/** * BookKeeping System & Mini App API Client Library: LOCAL STORAGE edition * * Same global name, method names, arguments and return shapes as the HTTP edition * (bookkeeping-api.js), but nothing goes to a server. The backend logic (account rules, * ledger filtering, same-day edit rules, trial balance / balance sheet / income statement / * cash flow, settings, mini-app data) is implemented here and the data lives in the browser. * Load ONE of the two files; the rest of the app can't tell which it got. * * Storage: localStorage by default (one JSON document per business). Browsers cap localStorage * at roughly 5 MB per origin, so this suits personal-scale ledgers; the adapter below is the * only thing to replace if you later want IndexedDB. If localStorage isn't available (e.g. a * sandboxed iframe) it falls back to memory and data is lost on reload: check * api.getStorageInfo().persistent. * * @param {string} baseURL ignored (kept so the signature matches the HTTP edition) * @param {string} initialBusiness optional; pins this instance to a business * @param {object} options { storage?: adapter, namespace?: string, enforceZeroBalanceOnArchive?: boolean } * adapter = { keys(): string[], get(k): string|null, set(k, v), remove(k) } (all synchronous) */ const initializeBookKeepingAPI = (baseURL = '', initialBusiness = null, options = {}) => { const NS = options.namespace || 'bookkeeping'; const SYSTEM_VERSION = '1'; const DEFAULT_BUSINESS = 'default'; const ARCHIVE_MARKER = '_deleted_'; const ENFORCE_ZERO_ON_ARCHIVE = options.enforceZeroBalanceOnArchive !== false; // documented AppContext behaviour // ── Errors ─────────────────────────────────────────────────────────────── // The HTTP edition either surfaces the server's message (serverError) or throws a generic // ".::token::." (tokenError). Same here; tokenError also carries the specific reason in .detail. const serverError = (msg) => new Error(msg); const tokenError = (token, detail) => { const e = new Error(token); if (detail) e.detail = detail; return e; }; const asDetail = (e) => (e && e.message) || String(e); // ── Storage adapter ────────────────────────────────────────────────────── const localStorageAdapter = () => { try { const probe = `${NS}:__probe__`; window.localStorage.setItem(probe, '1'); window.localStorage.removeItem(probe); } catch { return null; } const ls = window.localStorage; return { persistent: true, keys: () => Array.from({ length: ls.length }, (_, i) => ls.key(i)), get: (k) => ls.getItem(k), set: (k, v) => ls.setItem(k, v), remove: (k) => ls.removeItem(k) }; }; const memoryAdapter = () => { const m = new Map(); return { persistent: false, keys: () => Array.from(m.keys()), get: (k) => (m.has(k) ? m.get(k) : null), set: (k, v) => { m.set(k, v); }, remove: (k) => { m.delete(k); } }; }; let store = options.storage || localStorageAdapter(); if (!store) { console.warn('[BookKeeping] localStorage unavailable; using in-memory storage. Data will be lost on reload.'); store = memoryAdapter(); } const DB_PREFIX = `${NS}:db:`; const GLOBAL_KEY = `${NS}:global`; // ── Small helpers ──────────────────────────────────────────────────────── const r8 = (n) => Math.round(n * 1e8) / 1e8; // tame float noise (server used decimal) const sum = (xs) => r8(xs.reduce((a, b) => a + b, 0)); const pad = (n) => String(n).padStart(2, '0'); const fmtLocal = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; const todayDay = () => fmtLocal(new Date()).slice(0, 10); const dayOf = (iso) => String(iso).slice(0, 10); const localDayOfISO = (iso) => fmtLocal(new Date(iso)).slice(0, 10); const realDate = (y, m, d) => { const dt = new Date(y, m - 1, d); return dt.getFullYear() === y && dt.getMonth() === m - 1 && dt.getDate() === d; }; // → 'YYYY-MM-DDTHH:mm:ss' (the shape the server returns) or null const parseDateInput = (v) => { if (v instanceof Date) return isNaN(v) ? null : fmtLocal(v); const s = String(v ?? '').trim(); if (!s) return null; let m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s); if (m) return realDate(+m[1], +m[2], +m[3]) ? `${s}T00:00:00` : null; m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?$/.exec(s); if (m) return realDate(+m[1], +m[2], +m[3]) ? `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6] || '00'}` : null; const d = new Date(s); return isNaN(d) ? null : fmtLocal(d); }; const asReportDate = (v) => { const c = parseDateInput(v); return c ? `${dayOf(c)}T00:00:00` : null; }; // ── Business naming (mirrors BusinessName.TryNormalize on the server) ──── const normalizeName = (n) => String(n ?? '').trim().replace(/\s+/g, '_'); const sameName = (a, b) => String(a).toLowerCase() === String(b).toLowerCase(); const validBusinessName = (raw, allowMarker = false) => { const n = normalizeName(raw); if (!n || n.length > 100 || n.startsWith('.') || n.includes('..')) return null; if (/[\\/:*?"<>|\u0000-\u001f]/.test(n)) return null; if (!allowMarker && n.includes(ARCHIVE_MARKER)) return null; return n; }; // ── Database documents ─────────────────────────────────────────────────── const newDb = () => ({ schema: 1, seq: { account: 0, entry: 0, info: 0 }, accounts: [], // { id, name, type, subType, archivedAt, createdAt } entries: [], // { id, description, date, createdAt, debits:[{accountId,amount}], credits:[...] } info: [], // { id, information, createdAt } kv: { business_currency: 'USD', business_closing_month: '12', business_closing_day: '31', quick_views: '', dashboard_metrics: '', account_groups: '', mini_apps: '[]', version: SYSTEM_VERSION } }); const cache = new Map(); // key -> { raw, db } const dbKey = (name) => DB_PREFIX + name; const dbExists = (name) => store.get(dbKey(name)) !== null; const writeDoc = (key, obj) => { const raw = JSON.stringify(obj); try { store.set(key, raw); } catch (e) { cache.delete(key); const quota = e && (e.name === 'QuotaExceededError' || e.code === 22 || e.code === 1014); throw new Error(quota ? 'Browser storage is full. Export this business and free some space.' : `Could not save data: ${asDetail(e)}`); } cache.set(key, { raw, db: obj }); }; const loadDb = (name) => { const key = dbKey(name); const raw = store.get(key); if (raw === null) throw new Error(`Business '${name}' not found`); const hit = cache.get(key); if (hit && hit.raw === raw) return hit.db; // another tab's write changes raw, so we re-parse const db = JSON.parse(raw); cache.set(key, { raw, db }); return db; }; const saveDb = (name, db) => writeDoc(dbKey(name), db); const cloneDb = (db) => JSON.parse(JSON.stringify(db)); const ensureBusinessDb = (name) => { if (!dbExists(name)) saveDb(name, newDb()); }; // ── Global (server-global in the HTTP edition: config + translations) ──── const loadGlobal = () => { const raw = store.get(GLOBAL_KEY); if (raw) { try { return JSON.parse(raw); } catch { /* fall through to defaults */ } } return { config: { dark_mode: 'false', version: SYSTEM_VERSION }, translations: {} }; }; const saveGlobal = (g) => writeDoc(GLOBAL_KEY, g); // ── Client-side "current business" (same behaviour as the HTTP edition) ── const STORAGE_KEY = 'bookkeeping.currentBusiness'; const readStored = () => { try { return sessionStorage.getItem(STORAGE_KEY); } catch { return null; } }; const writeStored = (n) => { try { n ? sessionStorage.setItem(STORAGE_KEY, n) : sessionStorage.removeItem(STORAGE_KEY); } catch { } }; let currentBusiness = initialBusiness ? normalizeName(initialBusiness) : null; const setCurrent = (name) => { currentBusiness = name; writeStored(name); }; const listBusinesses = () => store.keys().filter(k => k.startsWith(DB_PREFIX)).map(k => k.slice(DB_PREFIX.length)); const activeBusinesses = () => listBusinesses().filter(n => !n.includes(ARCHIVE_MARKER) && !n.startsWith('.')) .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); const archivedBusinesses = () => listBusinesses().filter(n => n.includes(ARCHIVE_MARKER)); ensureBusinessDb(DEFAULT_BUSINESS); const resolveCurrent = () => { const list = activeBusinesses(); const canonical = (n) => n && list.find(b => sameName(b, n)); const chosen = canonical(currentBusiness) || canonical(readStored()) || canonical(DEFAULT_BUSINESS) || DEFAULT_BUSINESS; ensureBusinessDb(chosen); if (!currentBusiness || !sameName(chosen, currentBusiness)) setCurrent(chosen); else currentBusiness = chosen; return currentBusiness; }; const biz = () => resolveCurrent(); // ── Accounting rules ───────────────────────────────────────────────────── const ALLOWED_SUBTYPES = { asset: ['', 'current', 'non-current', 'cash', 'receivable'], liability: ['', 'current', 'non-current', 'payable'], equity: [''], revenue: [''], expense: [''] }; const validateAccountTypeAndSubType = (type, subType) => { const t = String(type ?? '').trim().toLowerCase(); const s = String(subType ?? '').trim().toLowerCase(); if (!ALLOWED_SUBTYPES[t]) throw new Error(`Invalid Account Type: ${type}`); if (!ALLOWED_SUBTYPES[t].includes(s)) throw new Error(`Invalid subType '${subType}' for account type '${t}'`); return { type: t, subType: s }; }; const validateAmount = (amount, label) => { if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) throw new Error(`Invalid ${label}: amount must be a number greater than zero`); }; const debitNormal = (type) => type === 'asset' || type === 'expense'; const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0); // SQLite BINARY ordering // accountId -> { debits:[{amount, day}], credits:[...] }, built in one pass over the ledger const ledgerIndex = (db) => { const idx = new Map(); const slot = (id) => { if (!idx.has(id)) idx.set(id, { debits: [], credits: [] }); return idx.get(id); }; for (const e of db.entries) { const day = dayOf(e.date); for (const d of e.debits) slot(d.accountId).debits.push({ amount: d.amount, day }); for (const c of e.credits) slot(c.accountId).credits.push({ amount: c.amount, day }); } return idx; }; // Mirrors FilteredBalance: with no dates it is the full balance; with dates only in-range lines count. const balanceOf = (acct, idx, start, end) => { const l = idx.get(acct.id) || { debits: [], credits: [] }; const inRange = (x) => (!start || x.day >= start) && (!end || x.day <= end); const useAll = !start && !end; const d = sum(l.debits.filter(x => useAll || inRange(x)).map(x => x.amount)); const c = sum(l.credits.filter(x => useAll || inRange(x)).map(x => x.amount)); if (debitNormal(acct.type)) return d >= c ? { amount: r8(d - c), side: 'debit' } : { amount: r8(c - d), side: 'credit' }; return c >= d ? { amount: r8(c - d), side: 'credit' } : { amount: r8(d - c), side: 'debit' }; }; const sameDayOrThrow = (e, verb) => { const created = localDayOfISO(e.createdAt); if (created !== todayDay()) throw new Error(`GeneralLedgerEntry with Id ${e.id} was created on ${created} and can only be ${verb} on the same day.`); }; // Accepts [{accountID|accountId, amount}] and returns normalised lines, or throws. const normaliseLines = (lines, label) => { if (!Array.isArray(lines) || lines.length === 0) throw new Error(`${label}s must be a non-empty array.`); return lines.map((l, i) => { if (l === null || typeof l !== 'object') throw new Error(`Invalid format for ${label} at index ${i}: Must be an object.`); const id = Number(l.accountID ?? l.accountId); const amount = typeof l.amount === 'string' ? Number(l.amount) : l.amount; if (!Number.isInteger(id)) throw new Error(`Invalid account id for ${label} at index ${i}`); validateAmount(amount, `${label} amount for account '${id}'`); return { accountId: id, amount }; }); }; const CMP_OPS = new Set(['=', '!=', '<>', '>', '<', '>=', '<=']); const cmpAmount = (lineAmount, op, target) => { const a = r8(lineAmount), b = r8(target); switch (CMP_OPS.has(op) ? op : '=') { case '=': return a === b; case '!=': case '<>': return a !== b; case '>': return a > b; case '<': return a < b; case '>=': return a >= b; case '<=': return a <= b; } }; // Mirrors BuildFilters + AppendDetailFilter: each filter is its own "some line matches" clause, ANDed. const buildDetailFilters = (ids, comparison, amount) => { const parsed = (ids || []).map(s => parseInt(s, 10)).filter(n => Number.isFinite(n)); if (parsed.length > 0) return parsed.map(id => ({ id, comparison, amount })); if (amount !== null) return [{ id: null, comparison, amount }]; return null; }; const entryMatchesFilter = (entry, f, side) => { const lines = side === 'debit' ? entry.debits : side === 'credit' ? entry.credits : [...entry.debits, ...entry.credits]; return lines.some(l => (f.id === null || l.accountId === f.id) && (f.amount === null || cmpAmount(l.amount, f.comparison || '=', f.amount))); }; const toArray = (v) => (v === undefined || v === null || v === '' ? [] : Array.isArray(v) ? v : [v]); const toNum = (v) => { const n = parseFloat(v); return Number.isFinite(n) ? n : null; }; const queryLedger = (db, fetchAll, offset, size, q) => { const nameOf = new Map(db.accounts.map(a => [a.id, a.name])); const idQ = parseInt(q.id, 10); const desc = String(q.description ?? '').trim().toLowerCase(); const from = parseDateInput(q.fromDate), to = parseDateInput(q.toDate); const cmp = (k) => (q[k] === undefined || q[k] === null || q[k] === '' ? null : String(q[k])); const groups = [ ['debit', buildDetailFilters(toArray(q.debitAccountIds), cmp('debitAccountComparison'), toNum(q.debitAccountAmount))], ['credit', buildDetailFilters(toArray(q.creditAccountIds), cmp('creditAccountComparison'), toNum(q.creditAccountAmount))], [null, buildDetailFilters(toArray(q.anyAccountIds), cmp('anyAccountComparison'), toNum(q.anyAccountAmount))] ]; const matches = db.entries.filter(e => { if (Number.isFinite(idQ) && e.id !== idQ) return false; if (desc && !String(e.description ?? '').toLowerCase().includes(desc)) return false; if (from && dayOf(e.date) < dayOf(from)) return false; if (to && dayOf(e.date) > dayOf(to)) return false; for (const [side, filters] of groups) if (filters && !filters.every(f => entryMatchesFilter(e, f, side))) return false; return true; }); matches.sort((a, b) => a.date < b.date ? 1 : a.date > b.date ? -1 : a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : b.id - a.id); const page = fetchAll ? matches : matches.slice(offset, offset + size); const line = (l) => ({ accountId: l.accountId, accountName: nameOf.get(l.accountId) ?? '', amount: l.amount }); return { transactions: page.map(e => ({ id: e.id, date: e.date, description: e.description ?? null, debits: e.debits.map(line), credits: e.credits.map(line) })), transactionCount: matches.length }; }; // ── Reports (ports of TrialBalance / BalanceSheet / IncomeStatement / CashFlowStatement) ── const reportContext = (filters = {}) => { const db = loadDb(biz()); const startISO = asReportDate(filters.startDate), endISO = asReportDate(filters.endDate); const idx = ledgerIndex(db); const accounts = [...db.accounts].sort(byName); // includes archived, like the server const rows = accounts.map(a => ({ a, bal: balanceOf(a, idx, startISO && dayOf(startISO), endISO && dayOf(endISO)) })); return { rows, startISO, endISO }; }; const signed = (bal, positiveSide) => (bal.side === positiveSide ? bal.amount : -bal.amount); // ── Business-scoped data access ────────────────────────────────────────── const readDb = () => loadDb(biz()); const mutate = (fn) => { // atomic: edit a clone, then commit const name = biz(); const work = cloneDb(loadDb(name)); const out = fn(work); saveDb(name, work); return out; }; const kvGet = (db, key, fallback) => { const v = db.kv[key]; return v === undefined || v === null || String(v).trim() === '' ? fallback : String(v); }; // ── Public API ─────────────────────────────────────────────────────────── return { // Mini Apps async getMiniApps() { try { return JSON.parse(kvGet(readDb(), 'mini_apps', '[]')) || []; } catch (e) { throw tokenError('.::Failed to load mini apps::.', asDetail(e)); } }, async saveMiniApps(apps) { try { if (!Array.isArray(apps)) throw new Error('Data must be a JSON array'); for (const item of apps) if (!item || item.id === undefined || item.id === null || String(item.id).trim() === '') throw new Error("Every mini-app must have an 'id' property"); mutate(db => { db.kv.mini_apps = JSON.stringify(apps); }); return true; } catch (e) { throw tokenError('.::Failed to save mini apps::.', asDetail(e)); } }, async getAppData(appId) { try { return JSON.parse(kvGet(readDb(), `app_data:${appId}`, '{}')); } catch (e) { throw tokenError('.::Failed to load app data::.', asDetail(e)); } }, async deleteAppData(appId) { try { mutate(db => { delete db.kv[`app_data:${appId}`]; }); return true; } catch (e) { throw tokenError('.::Failed to delete app data::.', asDetail(e)); } }, async saveAppData(appId, data) { const body = JSON.stringify(data); if (body === undefined || body.trim() === '') throw serverError('Empty body'); try { mutate(db => { db.kv[`app_data:${appId}`] = body.trim(); }); return true; } catch (e) { throw serverError(asDetail(e) || '.::Failed to save app data.::.'); } }, async deleteLocale(code) { try { const g = loadGlobal(); delete g.translations[String(code).toLowerCase()]; saveGlobal(g); return true; } catch (e) { throw tokenError('.::Failed to delete locale::.', asDetail(e)); } }, // These three talk to external services in the HTTP edition (via the server). Here the // browser calls them directly, so they only work if the remote allows cross-origin requests. async getStoreApps() { const r = await fetch('https://tenseri.com/app-store-list'); if (!r.ok) throw new Error(`.::Store returned ${r.status}::.`); return await r.json(); }, async downloadAppFile(url) { if (!url) throw new Error('.::App has no uploaded file yet. The developer needs to upload it via the admin panel.::.'); let r; try { r = await fetch(url); } catch (e) { throw tokenError('.::Download failed (network)::.', asDetail(e)); } if (!r.ok) throw new Error(`.::Download failed (${r.status})::.`); return await r.text(); }, getAppNotification: async () => { try { const res = await fetch('https://tenseri.com/notifications/v1'); if (!res.ok) return; return await res.json(); } catch { return; } }, // Account Groups async getAccountGroups() { try { return JSON.parse(kvGet(readDb(), 'account_groups', '[]')); } catch (e) { throw tokenError('.::Failed to load account groups::.', asDetail(e)); } }, async saveAccountGroups(groups) { try { const body = JSON.stringify(groups); if (body === undefined) throw new Error('Empty body'); mutate(db => { db.kv.account_groups = body.trim(); }); return true; } catch (e) { throw tokenError('.::Failed to save account groups::.', asDetail(e)); } }, // Businesses / Entities (each business is one JSON document in storage) async getBusinesses() { const current = resolveCurrent(); return { defaultBusiness: DEFAULT_BUSINESS, localBusinesses: activeBusinesses(), remoteBusinesses: [], archivedBusinesses: archivedBusinesses(), currentBusiness: current }; }, async getCurrentBusiness() { return resolveCurrent(); }, async createBusiness(businessData) { const name = validBusinessName(businessData && businessData.name); if (!name) throw serverError('Invalid business name'); if (activeBusinesses().some(b => sameName(b, name))) throw serverError(`A business named '${name}' already exists.`); saveDb(name, newDb()); setCurrent(name); // creating switches to the new business, as before return true; }, async renameBusiness(oldName, newName) { const from = validBusinessName(oldName), to = validBusinessName(newName); if (!from || !to) throw serverError('Invalid business name'); if (sameName(from, to) || activeBusinesses().some(b => sameName(b, to))) throw serverError(`A business named '${to}' already exists.`); if (!dbExists(from)) throw serverError(`Business '${from}' not found.`); writeDoc(dbKey(to), loadDb(from)); store.remove(dbKey(from)); cache.delete(dbKey(from)); if (currentBusiness && sameName(currentBusiness, from)) setCurrent(to); return { message: 'Business renamed', newName: to }; }, async deleteBusiness(name) { // archives, never destroys const n = validBusinessName(name); if (!n || !dbExists(n)) throw tokenError('.::Failed to archive entity::.', `Database file not found: ${name}`); const stamp = fmtLocal(new Date()).replace(/[-:]/g, '').replace('T', '_'); writeDoc(dbKey(`${n}${ARCHIVE_MARKER}${stamp}`), loadDb(n)); store.remove(dbKey(n)); cache.delete(dbKey(n)); if (currentBusiness && sameName(currentBusiness, n)) setCurrent(null); return true; }, async restoreBusiness(name) { const archived = validBusinessName(name, true); const parts = archived ? archived.split(ARCHIVE_MARKER) : []; if (!archived || parts.length < 2 || !dbExists(archived)) throw tokenError('.::Failed to restore entity::.', 'Archived database not found or invalid name'); let restored = parts[0]; if (dbExists(restored)) { let c = 1; while (dbExists(`${parts[0]}_restored${c}`)) c++; restored = `${parts[0]}_restored${c}`; } writeDoc(dbKey(restored), loadDb(archived)); store.remove(dbKey(archived)); cache.delete(dbKey(archived)); return true; }, async switchBusiness(name) { const match = activeBusinesses().find(b => sameName(b, normalizeName(name))); if (!match) throw new Error('.::Failed to select entity::.'); setCurrent(match); return true; }, // Export is a JSON document (not a SQLite .db): it round-trips with importBusinessFile here. async exportBusinessBlob(name) { const n = validBusinessName(name); if (!n || !dbExists(n)) throw new Error('.::Export failed::.'); return new Blob([JSON.stringify(loadDb(n), null, 2)], { type: 'application/json' }); }, async importBusinessFile(formData) { const file = formData && formData.get && formData.get('file'); if (!file) throw serverError('No file provided'); let doc; try { doc = JSON.parse(await file.text()); } catch (e) { throw serverError(`Failed to read or validate the imported database structure: ${asDetail(e)}`); } if (!doc || !Array.isArray(doc.accounts) || !Array.isArray(doc.entries) || !doc.kv || typeof doc.kv !== 'object') throw serverError('Failed to read or validate the imported database structure: not a business export.'); const version = doc.kv.version === undefined ? 'unknown' : String(doc.kv.version); if (version !== SYSTEM_VERSION) throw serverError(`Version mismatch. System version is '${SYSTEM_VERSION}', but imported database version is '${version}'.`); const base = String(file.name || 'imported').replace(/\.[^.]*$/, '').replace(/ /g, '_').toLowerCase().replace(/[^a-z0-9_-]/g, ''); if (!base) throw serverError('Invalid file name'); let name = base, c = 1; while (dbExists(name)) name = `${base}_${c++}`; doc.info = doc.info || []; doc.seq = doc.seq || { account: 0, entry: 0, info: 0 }; saveDb(name, doc); return { name }; }, // Accounts async getAccounts() { const db = readDb(); const idx = ledgerIndex(db); return db.accounts.filter(a => !a.archivedAt).sort(byName).map(a => { const bal = balanceOf(a, idx); return { id: a.id, name: a.name, type: a.type, subType: a.subType || '', balance: bal.amount, balanceSide: bal.side }; }); }, async getArchivedAccounts() { return readDb().accounts.filter(a => a.archivedAt).sort(byName) .map(a => ({ id: a.id, name: a.name, type: a.type, subType: a.subType || '' })); }, async createAccount(accountData) { try { const name = String(accountData && accountData.name !== undefined ? accountData.name : '').trim(); if (!name) throw new Error('Account name cannot be empty'); const { type, subType } = validateAccountTypeAndSubType(accountData.type, accountData.subType ?? ''); return mutate(db => { const clash = db.accounts.find(a => a.name.toLowerCase() === name.toLowerCase()); if (clash) throw new Error(clash.archivedAt ? `Account '${name}' already exists (archived)` : `Account '${name}' already exists`); const id = ++db.seq.account; db.accounts.push({ id, name, type, subType, archivedAt: null, createdAt: new Date().toISOString() }); return id; }); } catch (e) { throw serverError(asDetail(e) || '.::Failed to create account.::.'); } }, async updateAccount(id, newName) { try { const accountId = parseInt(id, 10); const name = String(newName ?? '').trim(); if (!Number.isFinite(accountId)) throw new Error('Missing or invalid account id'); if (!name) throw new Error('Account name cannot be empty'); mutate(db => { const target = db.accounts.find(a => a.id === accountId); if (!target) throw new Error(`Account with id '${accountId}' not found`); if (db.accounts.some(a => a.id !== accountId && a.name.toLowerCase() === name.toLowerCase())) throw new Error(`Account '${name}' already exists`); target.name = name; }); return true; } catch (e) { throw serverError(asDetail(e) || '.::Failed to update account::.'); } }, async archiveAccount(accountId) { try { const id = parseInt(accountId, 10); if (!Number.isFinite(id)) throw new Error('Missing or invalid account id'); mutate(db => { const a = db.accounts.find(x => x.id === id && !x.archivedAt); if (!a) throw new Error(`Account with id '${id}' not found`); if (ENFORCE_ZERO_ON_ARCHIVE && balanceOf(a, ledgerIndex(db)).amount !== 0) throw new Error(`Account '${a.name}' has a non-zero balance and cannot be archived`); a.archivedAt = new Date().toISOString(); }); return true; } catch (e) { throw serverError(asDetail(e) || '.::Unknown error::.'); } }, async restoreAccount(accountId) { try { const id = parseInt(accountId, 10); if (!Number.isFinite(id)) throw new Error('Missing or invalid account id'); mutate(db => { const a = db.accounts.find(x => x.id === id); if (a) a.archivedAt = null; }); return true; } catch (e) { throw serverError(asDetail(e) || '.::Unknown error::.'); } }, // Transactions async getTransactions(offset = 0, size = 10, queryParams = {}, fetchAll = false) { const allowedKeys = [ 'id', 'fromDate', 'toDate', 'description', 'debitAccountNames', 'debitAccountComparison', 'debitAccountAmount', 'creditAccountIds', 'creditAccountComparison', 'creditAccountAmount', 'debitAccountIds', 'creditAccountNames', 'anyAccountIds', 'anyAccountComparison', 'anyAccountAmount' ]; for (const key of Object.keys(queryParams)) { if (!allowedKeys.includes(key)) { throw new Error( `.::Invalid parameter provided: "${key}". Acceptable parameters are: ${allowedKeys.join(', ')}::.` ); } } try { return queryLedger(readDb(), !!fetchAll, Number(offset) || 0, Number(size) || 10, queryParams); } catch (e) { throw tokenError('.::Failed to fetch transactions::.', asDetail(e)); } }, async getAllTransactions() { return await this.getTransactions(0, 10, {}, true); }, async postTransaction(txData) { try { const date = parseDateInput(txData && txData.date); if (!date) throw new Error('Invalid date provided.'); const debits = normaliseLines(txData.debits, 'debit'); const credits = normaliseLines(txData.credits, 'credit'); const description = String(txData.description ?? ''); const totalD = sum(debits.map(l => l.amount)), totalC = sum(credits.map(l => l.amount)); if (Math.abs(totalD - totalC) > 0.001) throw new Error(`Transaction Error: ${description}! Debits (${totalD}) and credits (${totalC}) must be equal`); mutate(db => { const active = new Set(db.accounts.filter(a => !a.archivedAt).map(a => a.id)); for (const l of [...debits, ...credits]) if (!active.has(l.accountId)) throw new Error(`Account '${l.accountId}' not found`); db.entries.push({ id: ++db.seq.entry, description, date, createdAt: new Date().toISOString(), debits, credits }); }); return true; } catch (e) { throw serverError(asDetail(e) || '.::Transaction failed::.'); } }, async getTodayTransactions() { try { const db = readDb(); const nameOf = new Map(db.accounts.map(a => [a.id, a.name])); const today = todayDay(); const line = (l) => ({ accountName: nameOf.get(l.accountId) ?? '', amount: l.amount }); const transactions = db.entries .filter(e => localDayOfISO(e.createdAt) === today) .sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : a.id - b.id)) .map(e => ({ id: e.id, date: e.date, description: e.description ?? null, debits: e.debits.map(line), credits: e.credits.map(line) })); return { transactions }; } catch (e) { throw tokenError('.::Failed to load todays transactions::.', asDetail(e)); } }, async updateTodayTransactions(payload) { try { const txs = payload && payload.transactions; if (!Array.isArray(txs)) throw new Error('transactions must be an array'); mutate(db => { const idByName = new Map(db.accounts.map(a => [a.name, a.id])); const lines = (arr, label) => { if (!Array.isArray(arr)) throw new Error(`${label}s must be an array`); return arr.map(l => { validateAmount(l.amount, `${label} amount for '${l.accountName}'`); const accountId = idByName.get(l.accountName); if (accountId === undefined) throw new Error(`Account '${l.accountName}' not found`); return { accountId, amount: l.amount }; }); }; for (const tx of txs) { const id = Number(tx.id); const desc = String(tx.description ?? ''); const date = parseDateInput(tx.date); if (!date) throw new Error('Invalid date provided.'); const debits = lines(tx.debits, 'debit'), credits = lines(tx.credits, 'credit'); const totalD = sum(debits.map(l => l.amount)), totalC = sum(credits.map(l => l.amount)); if (Math.abs(totalD - totalC) > 0.001) throw new Error(`Transaction '${desc}' is not balanced! Debits (${totalD}) and credits (${totalC}) must be equal`); const entry = db.entries.find(e => e.id === id); if (!entry) throw new Error(`No GeneralLedgerEntry found with Id ${id}.`); sameDayOrThrow(entry, 'updated'); Object.assign(entry, { description: desc, date, debits, credits }); } }); return true; } catch (e) { throw tokenError('.::Failed to update todays transactions::.', asDetail(e)); } }, async deleteTransaction(txId) { try { const id = Number(txId); mutate(db => { const i = db.entries.findIndex(e => e.id === id); if (i < 0) throw new Error(`No GeneralLedgerEntry found with Id ${id}.`); sameDayOrThrow(db.entries[i], 'deleted'); db.entries.splice(i, 1); }); return true; } catch (e) { throw tokenError('.::Failed to delete transaction::.', asDetail(e)); } }, // Financial Reports async getTrialBalance(filters = {}) { try { const { rows, startISO, endISO } = reportContext(filters); let totalDebit = 0, totalCredit = 0; const accounts = []; for (const { a, bal } of rows) { if (bal.amount <= 0) continue; const debit = bal.side === 'debit' ? bal.amount : 0; const credit = bal.side === 'credit' ? bal.amount : 0; totalDebit += debit; totalCredit += credit; accounts.push({ name: a.name, type: a.type, debit, credit }); } totalDebit = r8(totalDebit); totalCredit = r8(totalCredit); return { accounts, totalDebit, totalCredit, isBalanced: Math.abs(totalDebit - totalCredit) < 0.01, startDate: startISO, endDate: endISO }; } catch (e) { throw tokenError('.::Failed to load trial balance::.', asDetail(e)); } }, async getBalanceSheet(filters = {}) { try { const { rows, startISO, endISO } = reportContext(filters); const assets = [], liabilities = [], equity = []; let totalAssets = 0, totalLiabilities = 0, totalEquity = 0, totalRevenue = 0, totalExpense = 0; for (const { a, bal } of rows) { const subType = a.subType || ''; if (a.type === 'asset') { const v = signed(bal, 'debit'); assets.push({ name: a.name, amount: v, subType }); totalAssets += v; } else if (a.type === 'liability') { const v = signed(bal, 'credit'); liabilities.push({ name: a.name, amount: v, subType }); totalLiabilities += v; } else if (a.type === 'revenue') totalRevenue += signed(bal, 'credit'); else if (a.type === 'expense') totalExpense += signed(bal, 'debit'); else if (a.type === 'equity') { const v = signed(bal, 'credit'); equity.push({ name: a.name, amount: v, subType }); totalEquity += v; } } const netProfit = r8(totalRevenue - totalExpense); if (netProfit !== 0) { equity.push({ name: netProfit > 0 ? 'Net Profit' : 'Net Loss', amount: netProfit, subType: '' }); totalEquity += netProfit; } totalAssets = r8(totalAssets); totalLiabilities = r8(totalLiabilities); totalEquity = r8(totalEquity); const bySub = (list, s) => sum(list.filter(x => x.subType === s).map(x => x.amount)); return { assets, totalAssets, totalCurrentAssets: bySub(assets, 'current'), totalNonCurrentAssets: bySub(assets, 'non-current'), liabilities, totalLiabilities, totalCurrentLiabilities: bySub(liabilities, 'current'), totalNonCurrentLiabilities: bySub(liabilities, 'non-current'), equity, totalEquity, isBalanced: Math.abs(totalAssets - (totalLiabilities + totalEquity)) < 0.01, startDate: startISO, endDate: endISO }; } catch (e) { throw tokenError('.::Failed to load balance sheet::.', asDetail(e)); } }, async getIncomeStatement(filters = {}) { try { const { rows, startISO, endISO } = reportContext(filters); const revenues = [], expenses = []; let totalRevenue = 0, totalExpenses = 0; for (const { a, bal } of rows) { if (a.type === 'revenue') { const v = signed(bal, 'credit'); revenues.push({ name: a.name, amount: v }); totalRevenue += v; } else if (a.type === 'expense') { const v = signed(bal, 'debit'); expenses.push({ name: a.name, amount: v }); totalExpenses += v; } } totalRevenue = r8(totalRevenue); totalExpenses = r8(totalExpenses); return { revenues, totalRevenue, expenses, totalExpenses, netIncome: r8(totalRevenue - totalExpenses), startDate: startISO, endDate: endISO }; } catch (e) { throw tokenError('.::Failed to load income statement::.', asDetail(e)); } }, async getCashFlow(filters = {}) { try { const { rows, startISO, endISO } = reportContext(filters); let totalRevenue = 0, totalExpenses = 0, netInvesting = 0, netFinancing = 0, closingCash = 0; const adjustments = [], investing = [], financing = []; for (const { a, bal } of rows) { const subType = a.subType || '', name = a.name; switch (a.type) { case 'revenue': totalRevenue += signed(bal, 'credit'); break; case 'expense': totalExpenses += signed(bal, 'debit'); break; case 'asset': { const v = signed(bal, 'debit'); if (subType === 'cash') closingCash += v; else if (subType === 'current' || subType === 'receivable') adjustments.push({ name, amount: -v, category: subType === 'receivable' ? 'Receivable' : 'Current Asset', direction: 'increaseDecrease' }); else if (subType === 'non-current') { investing.push({ name, amount: -v, direction: 'purchaseDisposal' }); netInvesting -= v; } break; } case 'liability': { const v = signed(bal, 'credit'); if (subType === 'current' || subType === 'payable') adjustments.push({ name, amount: v, category: subType === 'payable' ? 'Payable' : 'Current Liability', direction: 'increaseDecrease' }); else if (subType === 'non-current') { financing.push({ name, amount: v, direction: 'proceedsRepayment' }); netFinancing += v; } break; } case 'equity': { const v = signed(bal, 'credit'); financing.push({ name, amount: v, direction: 'movement' }); netFinancing += v; break; } } } const netIncome = r8(totalRevenue - totalExpenses); const totalAdjustments = sum(adjustments.map(x => x.amount)); netInvesting = r8(netInvesting); netFinancing = r8(netFinancing); return { netIncome, adjustments, netOperating: r8(netIncome + totalAdjustments), investing, netInvesting, financing, netFinancing, netChange: r8(netIncome + totalAdjustments + netInvesting + netFinancing), closingCash: r8(closingCash), start_date: startISO, end_date: endISO }; } catch (e) { throw tokenError('.::Failed to load cash flow statement::.', asDetail(e)); } }, // Information Notes async getLatestNote() { const list = [...readDb().info].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1)); const n = list[0]; return n ? { information: n.information, date: n.createdAt } : { information: '', date: '' }; }, async getOldNotes() { const list = [...readDb().info].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1)).slice(1); return Object.fromEntries(list.map(n => [n.id, n.createdAt])); }, async getNoteById(id) { const n = readDb().info.find(x => x.id === Number(id)); return n ? { information: n.information, date: n.createdAt } : { information: '', date: '' }; }, async createNote(information) { try { if (information === undefined || information === null) throw new Error('information is required'); mutate(db => { db.info.push({ id: ++db.seq.info, information: String(information), createdAt: new Date().toISOString() }); }); return true; } catch (e) { throw tokenError('.::Failed to save note::.', asDetail(e)); } }, async deleteNote(id) { try { mutate(db => { db.info = db.info.filter(n => n.id !== Number(id)); }); return true; } catch (e) { throw tokenError('.::Failed to delete note::.', asDetail(e)); } }, // Business settings (per business) getCurrency: async () => kvGet(readDb(), 'business_currency', 'USD'), updateCurrency: async (currency) => { try { const value = String(currency ?? '').trim(); if (!/^[A-Za-z]{3}$/.test(value)) throw new Error(`'${currency}' is not a valid currency code`); mutate(db => { db.kv.business_currency = value; }); return true; } catch (e) { throw tokenError('.::Failed to update currency settings::.', asDetail(e)); } }, getPinnedApps: async () => { const text = kvGet(readDb(), 'pinned_apps', ''); if (!text) return ''; try { return JSON.parse(text); } catch { return text; } }, setPinnedApps: async (payload) => { const isObject = payload !== null && typeof payload === 'object'; const body = isObject ? JSON.stringify(payload) : payload; if (body === undefined || body === null || String(body).trim() === '') throw tokenError('.::Failed to save pinned apps::.', 'Request body is empty.'); try { mutate(db => { db.kv.pinned_apps = String(body); }); return true; } catch (e) { throw tokenError('.::Failed to save pinned apps::.', asDetail(e)); } }, getClosingDate: async () => { const db = readDb(); return { closingDay: parseInt(kvGet(db, 'business_closing_day', '31'), 10), closingMonth: parseInt(kvGet(db, 'business_closing_month', '12'), 10) }; }, updateClosingDate: async (day, month) => { try { const d = parseInt(day, 10), m = parseInt(month, 10); if (!Number.isInteger(m) || m < 1 || m > 12) throw new Error('Invalid month value. Must be between 1 and 12.'); const daysInMonth = new Date(new Date().getFullYear(), m, 0).getDate(); if (!Number.isInteger(d) || d < 1 || d > daysInMonth) { const monthName = new Date(2000, m - 1, 1).toLocaleString('en-US', { month: 'long' }); throw new Error(`Invalid day value. ${monthName} has ${daysInMonth} days.`); } mutate(db => { db.kv.business_closing_month = String(m); db.kv.business_closing_day = String(d); }); return true; } catch (e) { throw tokenError('.::Failed to update closing month::.', asDetail(e)); } }, getMiniAppUpdate: async (appId, updateURL) => { try { if (!updateURL) throw new Error('updateURL is required'); const apps = JSON.parse(kvGet(readDb(), 'mini_apps', '[]')); const app = Array.isArray(apps) ? apps.find(a => a && String(a.id) === String(appId)) : null; if (!app) return { message: 'No updates found' }; const r = await fetch(updateURL); // browser fetch: needs CORS on the remote if (!r.ok) return { message: 'No updates found' }; const updated = await r.text(); return updated === String(app.htmlCode ?? '') ? { message: 'No updates found' } : { message: 'Found an update', updatedApp: updated }; } catch (e) { throw tokenError('.::Failed to fetch app update::.', asDetail(e)); } }, // Global System Config & Settings (shared by all businesses on this browser) getGlobalConfig: async (key) => { const g = loadGlobal(); const text = key ? String(g.config[key] ?? '') : JSON.stringify(g.config); if (!text) return null; try { return JSON.parse(text); } catch { return text; } }, saveGlobalConfig: async (key, config) => { try { const isObject = config !== null && typeof config === 'object'; const body = isObject ? JSON.stringify(config) : String(config); const g = loadGlobal(); g.config[key] = body; saveGlobal(g); return true; } catch (e) { throw tokenError(`.::Failed to save ${key} settings::.`, asDetail(e)); } }, setGlobalConfig: async (key, config) => { try { const isObject = config !== null && typeof config === 'object'; const body = isObject ? JSON.stringify(config) : String(config); const g = loadGlobal(); g.config[key] = body; saveGlobal(g); return true; } catch (e) { throw tokenError(`.::Failed to save ${key} settings::.`, asDetail(e)); } }, getAvailablelanguages: async () => Object.entries(loadGlobal().translations).map(([code, t]) => ({ name: t.name, code })), getDashboardMetrics: async () => kvGet(readDb(), 'dashboard_metrics', ''), saveDashboardMetrics: async (metricsString) => { try { mutate(db => { db.kv.dashboard_metrics = String(metricsString ?? '').trim(); }); return true; } catch (e) { throw tokenError('.::Failed to update dashboard fields::.', asDetail(e)); } }, async addLocaleTranslation(name, code, translation) { try { const n = String(name ?? '').trim(), c = String(code ?? '').trim(); const body = translation === undefined || translation === null ? '' : (typeof translation === 'string' ? translation : JSON.stringify(translation)); if (!n || !c || !body.trim()) throw new Error('Name, code, and translation cannot be empty.'); const g = loadGlobal(); g.translations[c.toLowerCase()] = { name: n, translation: body }; saveGlobal(g); return true; } catch (e) { throw tokenError('.::Failed to save translation::.', asDetail(e)); } }, // Extras that only exist in the local edition async getTranslation(code) { const t = loadGlobal().translations[String(code).toLowerCase()]; return t ? t.translation : ''; }, getStorageInfo() { const keys = store.keys().filter(k => k.startsWith(`${NS}:`)); const chars = keys.reduce((n, k) => n + k.length + (store.get(k) || '').length, 0); return { persistent: !!store.persistent, keys: keys.length, approxBytes: chars * 2, approxLimitBytes: 5 * 1024 * 1024 }; } }; };