← Demos
Web Pages · Templates

Business Accounting

by Shane Hadden Aug 4, 2026 11 views 250.2 KB
Sandbox · generic-business-accounting · no access to your account
View source — the whole page is this one file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Business Accounting</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">
<style>
:root{
  --ink:#14202A; --ink2:#1C2B37; --ink3:#2B3F4E; --ink-soft:#93A5B1;
  --paper:#FAF9F5; --card:#FFFFFF;
  --rule:#D7DCD4; --rule2:#EAEDE6;
  --green:#1D6B4A; --green-d:#155238; --green-lt:#E4EFE6; --greenbar:#F0F5EC;
  --red:#A5241D; --red-lt:#FBEAE8;
  --amber:#9C6608; --amber-lt:#FAF0DC;
  --blue:#265A73; --blue-lt:#E5EEF3;
  --text:#17202A; --muted:#68757F;
  --disp:'Space Grotesk',ui-sans-serif,system-ui,sans-serif;
  --body:'IBM Plex Sans',ui-sans-serif,system-ui,-apple-system,sans-serif;
  --mono:'IBM Plex Mono',ui-monospace,'SFMono-Regular',Menlo,monospace;
  --sh:0 1px 2px rgba(20,32,42,.06),0 8px 24px -12px rgba(20,32,42,.18);
}
*{box-sizing:border-box}
html,body{margin:0;padding:0}
body{background:var(--paper);color:var(--text);font-family:var(--body);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}
a{color:var(--blue)}
button,input,select,textarea{font-family:inherit;font-size:inherit;color:inherit}
::selection{background:#CFE3D5}

/* ---------- shell ---------- */
.app{display:grid;grid-template-columns:238px minmax(0,1fr);min-height:100vh}
.side{background:var(--ink);color:#C9D4DC;position:sticky;top:0;height:100vh;overflow-y:auto;overflow-x:hidden;display:flex;flex-direction:column}
.side::-webkit-scrollbar{width:8px}.side::-webkit-scrollbar-thumb{background:#2C4152;border-radius:8px}
.brand{padding:18px 18px 14px;display:flex;gap:11px;align-items:center;border-bottom:1px solid #24384A}
.brand-mark{width:32px;height:32px;flex:none}
.brand-name{font-family:var(--disp);font-weight:700;font-size:15px;letter-spacing:-.02em;color:#fff;line-height:1.15}
.brand-sub{font-family:var(--mono);font-size:9px;letter-spacing:.18em;text-transform:uppercase;color:#6F8797;margin-top:2px}
.navgrp{padding:14px 12px 2px}
.navgrp-t{font-family:var(--mono);font-size:9.5px;letter-spacing:.2em;text-transform:uppercase;color:#5E7686;padding:0 8px 7px}
.nav{display:flex;align-items:center;gap:9px;padding:7px 9px;border-radius:4px;color:#C4D0D8;cursor:pointer;font-size:13.5px;text-decoration:none;position:relative}
.nav:hover{background:#1E2F3D;color:#fff}
.nav.on{background:#22384A;color:#fff;font-weight:600}
.nav.on::before{content:"";position:absolute;left:-12px;top:5px;bottom:5px;width:3px;background:var(--green);border-radius:0 3px 3px 0}
.nav .ico{width:15px;height:15px;flex:none;opacity:.75}
.nav.on .ico{opacity:1}
.nav .cnt{margin-left:auto;font-family:var(--mono);font-size:10px;background:#2E4658;padding:1px 6px;border-radius:9px;color:#B9C9D4}
.nav .cnt.warn{background:var(--red);color:#fff}
.side-foot{margin-top:auto;padding:12px;border-top:1px solid #24384A;font-family:var(--mono);font-size:10px;color:#6F8797;display:flex;justify-content:space-between;align-items:center;gap:8px}
.side-foot b{color:#B9C9D4;font-weight:500}

main{min-width:0;display:flex;flex-direction:column}
.topbar{position:sticky;top:0;z-index:30;background:rgba(250,249,245,.94);backdrop-filter:blur(8px);border-bottom:1px solid var(--rule);padding:9px 22px;display:flex;gap:12px;align-items:center}
.burger{display:none}
.crumb{font-family:var(--mono);font-size:10.5px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
.crumb b{color:var(--text);font-weight:500}
.spacer{flex:1}
.searchbox{position:relative}
.searchbox input{width:230px;padding:7px 10px 7px 30px;border:1px solid var(--rule);border-radius:4px;background:#fff}
.searchbox svg{position:absolute;left:9px;top:8px;opacity:.45}
.searchbox kbd{position:absolute;right:8px;top:7px;font-family:var(--mono);font-size:10px;color:var(--muted);border:1px solid var(--rule);border-radius:3px;padding:0 4px;background:var(--paper)}
.period{display:flex;align-items:center;gap:6px;border:1px solid var(--rule);background:#fff;border-radius:4px;padding:4px 8px}
.period select,.period input{border:0;background:transparent;font-family:var(--mono);font-size:11.5px;outline:none}
.who{display:flex;align-items:center;gap:8px;padding-left:12px;border-left:1px solid var(--rule)}
.avatar{width:28px;height:28px;border-radius:50%;background:var(--ink3);color:#fff;display:grid;place-items:center;font-family:var(--mono);font-size:11px;font-weight:600}
.wrap{padding:20px 22px 64px;max-width:1420px;width:100%}

/* ---------- type ---------- */
h1{font-family:var(--disp);font-size:25px;font-weight:700;letter-spacing:-.025em;margin:0}
h2{font-family:var(--disp);font-size:16px;font-weight:600;letter-spacing:-.01em;margin:0}
h3{font-family:var(--disp);font-size:13.5px;font-weight:600;margin:0}
.lbl{font-family:var(--mono);font-size:9.5px;letter-spacing:.19em;text-transform:uppercase;color:var(--muted)}
.sub{color:var(--muted);font-size:13px}
.num{font-family:var(--mono);font-variant-numeric:tabular-nums;text-align:right;white-space:nowrap}
.neg{color:var(--red)}
.mono{font-family:var(--mono)}
.pagehead{display:flex;align-items:flex-end;gap:14px;flex-wrap:wrap;margin-bottom:16px}
.pagehead .acts{margin-left:auto;display:flex;gap:8px;flex-wrap:wrap}

/* ---------- controls ---------- */
.btn{border:1px solid var(--rule);background:#fff;padding:7px 13px;border-radius:4px;cursor:pointer;font-size:13px;font-weight:500;display:inline-flex;align-items:center;gap:6px;white-space:nowrap;transition:background .12s,border-color .12s,transform .06s}
.btn:hover{border-color:#B9C1B6;background:#fff}
.btn:active{transform:translateY(1px)}
.btn:focus-visible,.nav:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid var(--green);outline-offset:1px}
.btn.pri{background:var(--green);border-color:var(--green);color:#fff}
.btn.pri:hover{background:var(--green-d);border-color:var(--green-d)}
.btn.dark{background:var(--ink);border-color:var(--ink);color:#fff}
.btn.dark:hover{background:var(--ink2)}
.btn.danger{color:var(--red);border-color:#E3C7C4}
.btn.danger:hover{background:var(--red-lt)}
.btn.sm{padding:4px 9px;font-size:12px}
.btn.ico-only{padding:6px 8px}
.btn[disabled]{opacity:.45;cursor:not-allowed}
.seg{display:inline-flex;border:1px solid var(--rule);border-radius:4px;overflow:hidden;background:#fff}
.seg button{border:0;background:#fff;padding:6px 11px;cursor:pointer;font-size:12.5px;border-right:1px solid var(--rule2)}
.seg button:last-child{border-right:0}
.seg button.on{background:var(--ink);color:#fff}
input[type=text],input[type=number],input[type=date],input[type=email],input[type=month],select,textarea{border:1px solid var(--rule);border-radius:4px;padding:7px 9px;background:#fff;width:100%}
input[type=number],.f-money input{font-family:var(--mono);text-align:right}
textarea{resize:vertical;min-height:64px}
label.fl{display:block}
label.fl>span{display:block;font-family:var(--mono);font-size:9.5px;letter-spacing:.16em;text-transform:uppercase;color:var(--muted);margin-bottom:4px}
.chk{display:flex;align-items:center;gap:8px;font-size:13px}
.chk input{width:15px;height:15px;accent-color:var(--green)}

/* ---------- cards / grids ---------- */
.card{background:var(--card);border:1px solid var(--rule);border-radius:5px;box-shadow:var(--sh)}
.card-h{padding:12px 15px;border-bottom:1px solid var(--rule2);display:flex;align-items:center;gap:10px}
.card-h .acts{margin-left:auto;display:flex;gap:6px}
.card-b{padding:15px}
.grid{display:grid;gap:14px}
.g2{grid-template-columns:repeat(2,minmax(0,1fr))}
.g3{grid-template-columns:repeat(3,minmax(0,1fr))}
.g4{grid-template-columns:repeat(4,minmax(0,1fr))}
.g-2-1{grid-template-columns:2fr 1fr}
.g-1-2{grid-template-columns:1fr 2fr}
.kpi{padding:13px 15px;background:#fff;border:1px solid var(--rule);border-radius:5px;box-shadow:var(--sh)}
.kpi .v{font-family:var(--mono);font-size:23px;font-weight:600;letter-spacing:-.02em;margin-top:7px;font-variant-numeric:tabular-nums}
.kpi .d{font-family:var(--mono);font-size:11px;margin-top:5px;color:var(--muted)}
.kpi .d b{font-weight:500}
.up{color:var(--green)}.down{color:var(--red)}

/* ---------- tables (ledger) ---------- */
.tblwrap{overflow:auto;border-radius:0 0 5px 5px}
table.tbl{width:100%;border-collapse:collapse;font-size:13px}
table.tbl th{font-family:var(--mono);font-size:9.5px;letter-spacing:.15em;text-transform:uppercase;color:var(--muted);text-align:left;padding:8px 12px;border-bottom:1px solid var(--rule);background:#fff;position:sticky;top:0;z-index:2;white-space:nowrap;font-weight:500}
table.tbl th.num{text-align:right}
table.tbl td{padding:8px 12px;border-bottom:1px solid var(--rule2);vertical-align:middle}
table.tbl tbody tr:nth-child(even){background:var(--greenbar)}
table.tbl tbody tr.clickable{cursor:pointer}
table.tbl tbody tr.clickable:hover{background:var(--green-lt)}
table.tbl tfoot td{padding:9px 12px;font-family:var(--mono);font-weight:600;background:#fff}
.dbl{border-top:1px solid var(--text);border-bottom:3px double var(--text)}
.rowacts{display:flex;gap:5px;justify-content:flex-end;opacity:0;transition:opacity .1s}
tr:hover .rowacts,tr:focus-within .rowacts{opacity:1}
.iconbtn{border:1px solid var(--rule);background:#fff;border-radius:3px;padding:3px 5px;cursor:pointer;line-height:0}
.iconbtn:hover{border-color:var(--ink3)}
.empty{padding:44px 20px;text-align:center;color:var(--muted)}
.empty h3{margin-bottom:6px}

/* ---------- pills / stamp ---------- */
.pill{font-family:var(--mono);font-size:10px;letter-spacing:.08em;text-transform:uppercase;padding:2px 7px;border-radius:3px;border:1px solid;white-space:nowrap;display:inline-block}
.p-paid{color:var(--green);border-color:#BCD8C4;background:var(--green-lt)}
.p-open{color:var(--blue);border-color:#C3D8E2;background:var(--blue-lt)}
.p-over{color:var(--red);border-color:#E5C4C1;background:var(--red-lt)}
.p-draft{color:var(--muted);border-color:var(--rule);background:var(--paper)}
.p-part{color:var(--amber);border-color:#E8D6AF;background:var(--amber-lt)}
.stamp{display:inline-flex;align-items:center;gap:7px;border:2px solid var(--green);color:var(--green);padding:6px 13px;border-radius:3px;font-family:var(--mono);font-size:11px;letter-spacing:.18em;text-transform:uppercase;font-weight:600;transform:rotate(-2.5deg);background:rgba(255,255,255,.7)}
.stamp.bad{border-color:var(--red);color:var(--red)}
.tag{font-family:var(--mono);font-size:10px;color:var(--muted);border:1px solid var(--rule);padding:1px 5px;border-radius:3px}

/* ---------- modal ---------- */
.scrim{position:fixed;inset:0;background:rgba(17,28,37,.44);z-index:100;display:flex;align-items:flex-start;justify-content:center;padding:34px 16px;overflow:auto;backdrop-filter:blur(2px)}
.modal{background:#fff;border-radius:6px;width:100%;max-width:620px;box-shadow:0 24px 70px -18px rgba(10,20,28,.5);animation:pop .16s ease-out}
.modal.wide{max-width:1000px}
.modal.xl{max-width:1180px}
@keyframes pop{from{opacity:0;transform:translateY(-8px)}}
.modal-h{padding:14px 18px;border-bottom:1px solid var(--rule2);display:flex;align-items:center;gap:10px}
.modal-b{padding:18px;max-height:calc(100vh - 220px);overflow:auto}
.modal-f{padding:12px 18px;border-top:1px solid var(--rule2);display:flex;gap:8px;justify-content:flex-end;background:var(--paper);border-radius:0 0 6px 6px}
.x{margin-left:auto;border:0;background:transparent;cursor:pointer;font-size:19px;line-height:1;color:var(--muted);padding:2px 6px}
.x:hover{color:var(--text)}
.fields{display:grid;gap:13px;grid-template-columns:repeat(2,minmax(0,1fr))}
.fields .full{grid-column:1/-1}
.toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:var(--ink);color:#fff;padding:10px 16px;border-radius:5px;z-index:200;font-size:13px;box-shadow:0 12px 30px -8px rgba(0,0,0,.5);animation:pop .16s}
.toast.err{background:var(--red)}

/* ---------- line grid ---------- */
table.lines{width:100%;border-collapse:collapse;font-size:13px}
table.lines th{font-family:var(--mono);font-size:9px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted);text-align:left;padding:5px 6px;border-bottom:1px solid var(--rule);font-weight:500}
table.lines td{padding:3px 4px;border-bottom:1px solid var(--rule2)}
table.lines input,table.lines select{padding:5px 6px;border-color:var(--rule2)}
table.lines input:focus,table.lines select:focus{border-color:var(--green)}
.totbox{margin-left:auto;width:290px;font-family:var(--mono);font-size:13px}
.totrow{display:flex;justify-content:space-between;padding:4px 0}
.totrow.grand{border-top:1px solid var(--text);border-bottom:3px double var(--text);font-weight:600;font-size:15px;margin-top:5px;padding:7px 0}

/* ---------- misc ---------- */
.split{display:grid;grid-template-columns:260px minmax(0,1fr);gap:14px}
.listnav{border:1px solid var(--rule);border-radius:5px;background:#fff;overflow:hidden;box-shadow:var(--sh)}
.listnav button{display:block;width:100%;text-align:left;border:0;border-bottom:1px solid var(--rule2);background:#fff;padding:9px 12px;cursor:pointer;font-size:13px}
.listnav button:hover{background:var(--greenbar)}
.listnav button.on{background:var(--ink);color:#fff}
.bar{height:7px;background:var(--rule2);border-radius:4px;overflow:hidden}
.bar>i{display:block;height:100%;background:var(--green)}
.hint{background:var(--blue-lt);border:1px solid #CDDDE6;color:#1E4557;padding:9px 12px;border-radius:4px;font-size:12.5px}
.warnbox{background:var(--amber-lt);border:1px solid #E9D8B4;color:#7A5207;padding:9px 12px;border-radius:4px;font-size:12.5px}
.docpaper{background:#fff;border:1px solid var(--rule);border-radius:5px;padding:38px;box-shadow:var(--sh)}
.docgrid{display:grid;grid-template-columns:1fr 1fr;gap:24px}
.palette{position:fixed;inset:0;background:rgba(17,28,37,.4);z-index:150;display:flex;justify-content:center;padding-top:12vh}
.palette .box{background:#fff;width:min(560px,92vw);height:max-content;max-height:60vh;border-radius:7px;box-shadow:0 28px 70px -16px rgba(0,0,0,.5);overflow:hidden}
.palette input{border:0;border-bottom:1px solid var(--rule);border-radius:0;padding:14px 16px;font-size:15px}
.palette ul{list-style:none;margin:0;padding:6px;max-height:44vh;overflow:auto}
.palette li{padding:8px 11px;border-radius:4px;cursor:pointer;display:flex;gap:10px;align-items:center;font-size:13.5px}
.palette li.on{background:var(--green-lt)}
.palette li .k{margin-left:auto;font-family:var(--mono);font-size:10px;color:var(--muted)}
.sparkwrap{display:flex;align-items:flex-end;gap:3px;height:38px}
.sparkwrap i{flex:1;background:var(--green-lt);border-radius:2px 2px 0 0;display:block}
.scroll-x{overflow-x:auto}
.mt{margin-top:14px}.mb{margin-bottom:14px}
.flexrow{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.dot{width:8px;height:8px;border-radius:50%;display:inline-block}

@media (max-width:960px){
  .app{grid-template-columns:1fr}
  .side{position:fixed;left:0;top:0;z-index:60;width:250px;transform:translateX(-100%);transition:transform .2s}
  .side.open{transform:none;box-shadow:0 0 40px rgba(0,0,0,.4)}
  .burger{display:inline-flex}
  .g4,.g3,.g2,.g-2-1,.g-1-2,.split,.docgrid{grid-template-columns:1fr}
  .fields{grid-template-columns:1fr}
  .searchbox input{width:140px}
  .wrap{padding:14px 13px 60px}
  .docpaper{padding:20px}
}
.dropzone{border:1.5px dashed var(--rule);border-radius:8px;padding:22px 16px;text-align:center;cursor:pointer;
  background:var(--paper);transition:border-color .15s,background .15s;display:flex;flex-direction:column;gap:4px}
.dropzone:hover,.dropzone.over{border-color:var(--green);background:var(--green-lt)}
.dropzone b{font-family:var(--disp);font-size:14px;color:var(--green-d)}
.dropzone span{font-size:12px;color:var(--muted)}
details summary{cursor:pointer;font-size:12px;padding:4px 0}
@media (hover:none){.rowacts{opacity:1}}
@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
@media print{
  .side,.topbar,.noprint{display:none!important}
  .app{display:block}
  .wrap{padding:0;max-width:none}
  .docpaper{border:0;box-shadow:none;padding:0}
  body{background:#fff}
  table.tbl tbody tr:nth-child(even){background:#F3F3F3}
}
</style>
</head>
<body>
<div class="app">
  <aside class="side" id="side"></aside>
  <main>
    <div class="topbar">
      <button class="btn ico-only burger" id="burger" aria-label="Menu">☰</button>
      <div class="crumb" id="crumb"></div>
      <div class="spacer"></div>
      <div class="searchbox noprint">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
        <input id="gsearch" type="text" placeholder="Search everything" aria-label="Search">
        <kbd>⌘K</kbd>
      </div>
      <div class="period noprint" title="Reporting period">
        <span class="lbl">Period</span>
        <select id="periodSel"></select>
      </div>
      <div class="who noprint">
        <div class="avatar" id="avatar">—</div>
      </div>
    </div>
    <div class="wrap" id="view"></div>
  </main>
</div>
<script>
/* =========================================================================
   Business Accounting — application source
   ========================================================================= */
/* ------------------------------ utilities ------------------------------ */
const $ = (s, r) => (r || document).querySelector(s);
const $$ = (s, r) => Array.from((r || document).querySelectorAll(s));
const uid = (p) => (p || 'id') + '_' + Math.random().toString(36).slice(2, 9);
const r2 = (n) => Math.round((Number(n) || 0) * 100) / 100;
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const sum = (a, f) => a.reduce((t, x) => t + (f ? (Number(f(x)) || 0) : (Number(x) || 0)), 0);
const by = (k) => (a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0);
const clone = (o) => JSON.parse(JSON.stringify(o));

const CUR = { USD: '$', EUR: '€', GBP: '£', CAD: 'C$', AUD: 'A$', JPY: '¥', INR: '₹', MXN: 'MX$', CHF: 'CHF ', SGD: 'S$' };
function sym(c) { return CUR[c || DB.company.currency] || ((c || '') + ' '); }
function money(n, c) {
  n = r2(n);
  const s = sym(c);
  const v = Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return n < 0 ? '(' + s + v + ')' : s + v;
}
function moneyCell(n, c) { return '<span class="num' + (r2(n) < 0 ? ' neg' : '') + '">' + money(n, c) + '</span>'; }
function qty(n) { return (Number(n) || 0).toLocaleString('en-US', { maximumFractionDigits: 2 }); }
function pct(n) { return (Number(n) || 0).toFixed(1) + '%'; }

function today() { return new Date().toISOString().slice(0, 10); }
function iso(d) { return new Date(d).toISOString().slice(0, 10); }
function addDays(d, n) { const x = new Date(d + 'T00:00:00'); x.setDate(x.getDate() + n); return iso(x); }
function addMonths(d, n) { const x = new Date(d + 'T00:00:00'); x.setMonth(x.getMonth() + n); return iso(x); }
function monthStart(d) { return d.slice(0, 8) + '01'; }
function monthEnd(d) { const x = new Date(d.slice(0, 8) + '01T00:00:00'); x.setMonth(x.getMonth() + 1); x.setDate(0); return iso(x); }
function fmtDate(d) { if (!d) return ''; const x = new Date(d + 'T00:00:00'); return x.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' }); }
function fmtShort(d) { const x = new Date(d + 'T00:00:00'); return x.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); }
function monthLabel(d) { const x = new Date(d + 'T00:00:00'); return x.toLocaleDateString('en-US', { month: 'short', year: '2-digit' }); }
function daysBetween(a, b) { return Math.round((new Date(b) - new Date(a)) / 86400000); }
function monthsRange(from, to) { const out = []; let c = monthStart(from); while (c <= to) { out.push(c); c = addMonths(c, 1); } return out; }

/* deterministic pseudo-random for demo data */
let _seed = 20260804;
function rnd() { _seed = (_seed * 1103515245 + 12345) % 2147483648; return _seed / 2147483648; }
function pick(a) { return a[Math.floor(rnd() * a.length)]; }
function ri(a, b) { return Math.floor(rnd() * (b - a + 1)) + a; }

/* ------------------------------ storage ------------------------------ */
const KEY = 'business_accounting_db_v1';
let DB = null, MEM = {}, _saveT = null, DIRTY = false;

async function storeGet(k) {
  if (window.storage && window.storage.get) { const r = await window.storage.get(k); return r ? r.value : null; }
  return MEM[k] || null;
}
async function storeSet(k, v) {
  if (window.storage && window.storage.set) { await window.storage.set(k, v); return true; }
  MEM[k] = v; return false;
}
function save(reason) {
  DIRTY = true;
  clearTimeout(_saveT);
  _saveT = setTimeout(async () => {
    try { await storeSet(KEY, JSON.stringify(DB)); DIRTY = false; renderSide(); }
    catch (e) { console.warn('save failed', e); }
  }, 350);
  if (reason) logAudit(reason);
}
function logAudit(action, detail) {
  DB.audit.unshift({ id: uid('a'), ts: new Date().toISOString(), user: currentUser().name, action, detail: detail || '' });
  if (DB.audit.length > 600) DB.audit.length = 600;
}
function currentUser() { return DB.users.find(u => u.id === DB.session.userId) || DB.users[0]; }
function can(act) {
  const r = currentUser().role;
  if (r === 'Owner' || r === 'Accountant') return true;
  if (r === 'Viewer') return false;
  return act !== 'admin'; // Staff
}

/* ------------------------------ account types ------------------------------ */
const TYPES = {
  Asset: { normal: 'D', bs: 1, order: 1 },
  Liability: { normal: 'C', bs: 1, order: 2 },
  Equity: { normal: 'C', bs: 1, order: 3 },
  Income: { normal: 'C', bs: 0, order: 4 },
  COGS: { normal: 'D', bs: 0, order: 5 },
  Expense: { normal: 'D', bs: 0, order: 6 }
};
const A = { AR: '1100', AP: '2000', INV: '1200', BANK: '1010', CASH: '1000', SAVINGS: '1020', UNDEP: '1400', TAXPAY: '2200', TAXREC: '1600', CC: '2100', PRLIAB: '2300', LOAN: '2400', EQUIP: '1500', ACCDEP: '1510', OE: '3000', DRAW: '3100', RE: '3900', SALES: '4000', SERV: '4010', SHIP: '4100', DISC: '4200', OTHINC: '4900', COGS: '5000', PURCH: '5100', FREIGHT: '5200', WAGES: '6600', PRTAX: '6650', DEPR: '6700', WOFF: '6900' };

const COA = [
  ['1000', 'Cash on Hand', 'Asset', 'Bank'], ['1010', 'Business Checking', 'Asset', 'Bank'], ['1020', 'Business Savings', 'Asset', 'Bank'],
  ['1100', 'Accounts Receivable', 'Asset', 'Accounts Receivable'], ['1200', 'Inventory Asset', 'Asset', 'Current Asset'],
  ['1300', 'Prepaid Expenses', 'Asset', 'Current Asset'], ['1400', 'Undeposited Funds', 'Asset', 'Current Asset'],
  ['1500', 'Equipment & Fixtures', 'Asset', 'Fixed Asset'], ['1510', 'Accumulated Depreciation', 'Asset', 'Fixed Asset'],
  ['1600', 'Sales Tax Receivable', 'Asset', 'Current Asset'],
  ['2000', 'Accounts Payable', 'Liability', 'Accounts Payable'], ['2100', 'Company Credit Card', 'Liability', 'Credit Card'],
  ['2200', 'Sales Tax Payable', 'Liability', 'Current Liability'], ['2300', 'Payroll Liabilities', 'Liability', 'Current Liability'],
  ['2400', 'Equipment Loan', 'Liability', 'Long Term Liability'],
  ['3000', "Owner's Capital", 'Equity', 'Equity'], ['3100', "Owner's Draw", 'Equity', 'Equity'], ['3900', 'Retained Earnings', 'Equity', 'Equity'],
  ['4000', 'Product Sales', 'Income', 'Sales'], ['4010', 'Service Revenue', 'Income', 'Sales'], ['4100', 'Shipping & Handling', 'Income', 'Sales'],
  ['4200', 'Discounts Given', 'Income', 'Contra Sales'], ['4900', 'Other Income', 'Income', 'Other'],
  ['5000', 'Cost of Goods Sold', 'COGS', 'Cost of Sales'], ['5100', 'Materials & Purchases', 'COGS', 'Cost of Sales'], ['5200', 'Freight In', 'COGS', 'Cost of Sales'],
  ['6000', 'Advertising & Marketing', 'Expense', 'Operating'], ['6050', 'Bank & Merchant Fees', 'Expense', 'Operating'],
  ['6100', 'Insurance', 'Expense', 'Operating'], ['6150', 'Legal & Professional', 'Expense', 'Operating'],
  ['6200', 'Office Supplies', 'Expense', 'Operating'], ['6250', 'Rent & Lease', 'Expense', 'Operating'],
  ['6300', 'Repairs & Maintenance', 'Expense', 'Operating'], ['6350', 'Software & Subscriptions', 'Expense', 'Operating'],
  ['6400', 'Travel', 'Expense', 'Operating'], ['6450', 'Meals & Entertainment', 'Expense', 'Operating'],
  ['6500', 'Utilities & Telecom', 'Expense', 'Operating'], ['6550', 'Shipping & Postage', 'Expense', 'Operating'],
  ['6600', 'Wages & Salaries', 'Expense', 'Payroll'], ['6650', 'Payroll Taxes', 'Expense', 'Payroll'],
  ['6700', 'Depreciation Expense', 'Expense', 'Operating'], ['6800', 'Interest Expense', 'Expense', 'Other'],
  ['6900', 'Miscellaneous', 'Expense', 'Other']
];

function accByCode(code) { return DB.accounts.find(a => a.code === code); }
function accId(code) { const a = accByCode(code); return a ? a.id : null; }
function acc(id) { return DB.accounts.find(a => a.id === id) || { code: '????', name: 'Unknown', type: 'Expense' }; }
function accName(id) { const a = acc(id); return a.code + ' · ' + a.name; }
function accOpts(filter) {
  return DB.accounts.filter(a => a.active !== false).filter(filter || (() => true)).sort(by('code'))
    .map(a => ({ v: a.id, t: a.code + ' · ' + a.name }));
}
function bankAccounts() { return DB.accounts.filter(a => a.subtype === 'Bank' || a.subtype === 'Credit Card'); }

/* ------------------------------ seed data ------------------------------ */
function blankDB() {
  const accounts = COA.map(([code, name, type, subtype]) => ({ id: 'ac' + code, code, name, type, subtype, active: true, description: '' }));
  return {
    version: 1,
    company: {
      name: 'My Company', legal: '', taxId: '',
      email: '', phone: '', site: '',
      addr1: '', addr2: '', city: '', state: '', zip: '', country: '',
      currency: 'USD', fyStartMonth: 1, industry: ''
    },
    settings: {
      invoicePrefix: 'INV-', nextInvoice: 1001, billPrefix: 'BILL-', nextBill: 500, estPrefix: 'EST-', nextEst: 300,
      poPrefix: 'PO-', nextPO: 700, cnPrefix: 'CN-', nextCN: 100, nextJournal: 1,
      terms: 30, defaultTaxId: 't1', invoiceNote: 'Thank you for your business. Payment is due within terms shown above.',
      invoiceFooter: '', lateFeePct: 1.5, trackInventory: true, accrual: true
    },
    taxRates: [
      { id: 't1', name: 'No Tax', rate: 0, agency: '—' },
      { id: 't2', name: 'Sales Tax', rate: 7, agency: 'State revenue department' },
      { id: 't3', name: 'Reduced Rate', rate: 3.5, agency: 'State revenue department' },
      { id: 't4', name: 'VAT Standard', rate: 20, agency: 'Tax authority' }
    ],
    currencies: { USD: 1, EUR: 0.92, GBP: 0.79, CAD: 1.37, MXN: 17.1 },
    users: [
      { id: 'u1', name: 'Owner', email: '', role: 'Owner' }
    ],
    session: { userId: 'u1', period: 'ytd', from: '', to: '' },
    accounts, contacts: [], items: [], invoices: [], bills: [], estimates: [], pos: [], creditNotes: [],
    expenses: [], journal: [], bankTx: [], reconciliations: [], employees: [], payruns: [], assets: [],
    projects: [], timeEntries: [], budgets: {}, recurring: [], adjustments: [], audit: [], attachments: []
  };
}

function seed() {
  const d = blankDB();
  DB = d;
  const T = today();
  const start = addMonths(monthStart(T), -7);

  /* ---- demo company profile (the blank file above stays generic) ---- */
  d.company = {
    name: 'Northline Supply Co.', legal: 'Northline Supply Company LLC', taxId: '84-7719260',
    email: 'billing@northlinesupply.com', phone: '(217) 555-0148', site: 'northlinesupply.com',
    addr1: '1420 Kenyon Road', addr2: 'Suite 300', city: 'Urbana', state: 'IL', zip: '61801', country: 'United States',
    currency: 'USD', fyStartMonth: 1, industry: 'Wholesale & facility services'
  };
  d.settings.defaultTaxId = 't2';
  d.settings.invoiceFooter = 'Remit to: Northline Supply Co., 1420 Kenyon Road, Urbana IL 61801 \u00b7 ACH details on request.';
  d.taxRates = [
    { id: 't1', name: 'No Tax', rate: 0, agency: '\u2014' },
    { id: 't2', name: 'IL Sales Tax', rate: 8.25, agency: 'Illinois Dept. of Revenue' },
    { id: 't3', name: 'Reduced Rate', rate: 4, agency: 'Illinois Dept. of Revenue' },
    { id: 't4', name: 'VAT Standard', rate: 20, agency: 'HMRC' }
  ];
  d.users = [
    { id: 'u1', name: 'Dana Whitfield', email: 'dana@northlinesupply.com', role: 'Owner' },
    { id: 'u2', name: 'Marcus Ortiz', email: 'marcus@northlinesupply.com', role: 'Accountant' },
    { id: 'u3', name: 'Priya Raman', email: 'priya@northlinesupply.com', role: 'Staff' },
    { id: 'u4', name: 'External Auditor', email: 'audit@kmreview.com', role: 'Viewer' }
  ];
  d.session.userId = 'u1';

  /* ---- contacts ---- */
  const custs = [
    ['Cedarline Property Group', 'ap@cedarline.com', '(312) 555-0192', '88 W Monroe St', 'Chicago', 'IL', '60603', 30],
    ['Halcyon Medical Center', 'accounts@halcyonmed.org', '(217) 555-0110', '900 Curtis Rd', 'Savoy', 'IL', '61874', 45],
    ['Bright Fork Restaurants', 'pay@brightfork.co', '(773) 555-0177', '2210 N Milwaukee Ave', 'Chicago', 'IL', '60647', 15],
    ['Ridgeway School District', 'purchasing@ridgeway.k12.il.us', '(309) 555-0164', '15 School St', 'Peoria', 'IL', '61602', 60],
    ['Ambler Logistics', 'finance@amblerlog.com', '(314) 555-0133', '4400 Chouteau Ave', 'St. Louis', 'MO', '63110', 30],
    ['Vantage Fitness Clubs', 'ap@vantagefit.com', '(630) 555-0128', '75 Warrenville Rd', 'Naperville', 'IL', '60563', 30],
    ['Old Mill Hospitality', 'books@oldmillhosp.com', '(217) 555-0155', '312 Main St', 'Champaign', 'IL', '61820', 15],
    ['Quarry Ridge Apartments', 'manager@quarryridge.com', '(217) 555-0139', '2000 Quarry Rd', 'Urbana', 'IL', '61802', 30]
  ];
  custs.forEach((c, i) => d.contacts.push({
    id: 'c' + (i + 1), kind: 'customer', name: c[0], contact: pick(['Alex Nunez', 'Rae Coleman', 'Ivan Petrov', 'Suki Tan', 'Grace Bell', 'Tom Ridley']),
    email: c[1], phone: c[2], addr1: c[3], city: c[4], state: c[5], zip: c[6], country: 'United States',
    terms: c[7], currency: 'USD', taxId: d.settings.defaultTaxId, notes: '', active: true, creditLimit: ri(5, 40) * 1000
  }));
  const vends = [
    ['Fairbanks Paper & Packaging', 'orders@fairbankspkg.com', A.PURCH], ['Statewide Chemical Supply', 'ar@statewidechem.com', A.PURCH],
    ['Meridian Property Mgmt', 'rent@meridianpm.com', '6250'], ['Halcyon Utilities Co-op', 'billing@hucoop.com', '6500'],
    ['Bluewave Cloud Services', 'billing@bluewave.io', '6350'], ['Rockford Freight Lines', 'ap@rockfordfreight.com', A.FREIGHT],
    ['Kessler & Marsh CPA', 'invoices@kmreview.com', '6150'], ['Prairie Mutual Insurance', 'policy@prairiemutual.com', '6100']
  ];
  vends.forEach((v, i) => d.contacts.push({
    id: 'v' + (i + 1), kind: 'vendor', name: v[0], contact: pick(['Dale Munro', 'Nadia Reyes', 'Owen Park', 'Lena Hoff']),
    email: v[1], phone: '(800) 555-0' + ri(100, 199), addr1: ri(100, 999) + ' Industrial Pkwy', city: pick(['Rockford', 'Joliet', 'Decatur', 'Springfield']),
    state: 'IL', zip: '6' + ri(1000, 1999), country: 'United States', terms: pick([15, 30, 30, 45]),
    currency: 'USD', defaultAccount: 'ac' + v[2], notes: '', active: true, taxId: 't1'
  }));

  /* ---- items ---- */
  const items = [
    ['NL-100', 'Commercial Floor Cleaner (5 gal)', 'inventory', 84.00, 41.50, 120],
    ['NL-110', 'Microfiber Mop System', 'inventory', 139.00, 68.00, 45],
    ['NL-120', 'Nitrile Gloves — case of 1000', 'inventory', 96.50, 47.25, 210],
    ['NL-130', 'HEPA Vacuum — upright', 'inventory', 649.00, 372.00, 14],
    ['NL-140', 'Restroom Paper Bundle', 'inventory', 158.00, 79.00, 88],
    ['NL-150', 'Sanitizing Wipes — 12 pack', 'inventory', 72.00, 33.00, 160],
    ['SVC-01', 'Facility Deep Clean (per visit)', 'service', 850.00, 0, 0],
    ['SVC-02', 'Monthly Maintenance Contract', 'service', 1450.00, 0, 0],
    ['SVC-03', 'Equipment Servicing (hourly)', 'service', 115.00, 0, 0],
    ['SVC-04', 'On-site Staff Training', 'service', 620.00, 0, 0]
  ];
  items.forEach((it, i) => d.items.push({
    id: 'i' + (i + 1), sku: it[0], name: it[1], type: it[2], price: it[3], cost: it[4],
    opening: it[5], reorder: it[2] === 'inventory' ? 30 : 0, trackQty: it[2] === 'inventory',
    incomeAccount: it[2] === 'inventory' ? 'ac' + A.SALES : 'ac' + A.SERV,
    expenseAccount: 'ac' + A.COGS, assetAccount: 'ac' + A.INV, taxId: 't2', active: true,
    description: '', unit: it[2] === 'inventory' ? 'ea' : 'hr'
  }));

  /* ---- employees ---- */
  d.employees = [
    { id: 'e1', name: 'Priya Raman', title: 'Operations Lead', payType: 'salary', rate: 68000, freq: 'Monthly', taxRate: 22, benefits: 320, active: true, hired: addMonths(T, -26), email: 'priya@northlinesupply.com' },
    { id: 'e2', name: 'Cole Whitaker', title: 'Route Driver', payType: 'hourly', rate: 24.5, freq: 'Monthly', taxRate: 18, benefits: 190, active: true, hired: addMonths(T, -14), email: 'cole@northlinesupply.com' },
    { id: 'e3', name: 'Bianca Lorne', title: 'Account Manager', payType: 'salary', rate: 58000, freq: 'Monthly', taxRate: 20, benefits: 280, active: true, hired: addMonths(T, -9), email: 'bianca@northlinesupply.com' }
  ];

  /* ---- fixed assets ---- */
  d.assets = [
    { id: 'fa1', name: 'Delivery Van — Ford Transit', cost: 42800, date: addMonths(T, -22), life: 60, salvage: 6000, method: 'straight', account: 'ac' + A.EQUIP, accum: 0, disposed: false },
    { id: 'fa2', name: 'Warehouse Racking System', cost: 12400, date: addMonths(T, -16), life: 84, salvage: 0, method: 'straight', account: 'ac' + A.EQUIP, accum: 0, disposed: false },
    { id: 'fa3', name: 'Floor Scrubber — Tennant T300', cost: 9750, date: addMonths(T, -6), life: 60, salvage: 750, method: 'straight', account: 'ac' + A.EQUIP, accum: 0, disposed: false }
  ];

  /* ---- projects ---- */
  d.projects = [
    { id: 'p1', name: 'Halcyon Med — Facility Refresh', customerId: 'c2', budget: 24000, status: 'active', start: addMonths(T, -3), rate: 115 },
    { id: 'p2', name: 'Ridgeway Summer Deep Clean', customerId: 'c4', budget: 15500, status: 'active', start: addMonths(T, -1), rate: 105 },
    { id: 'p3', name: 'Cedarline Q1 Rollout', customerId: 'c1', budget: 31000, status: 'complete', start: addMonths(T, -6), rate: 120 }
  ];

  /* ---- opening balances ---- */
  const openCash = 68400, openInv = sum(d.items, it => it.opening * it.cost);
  d.journal.push({
    id: uid('j'), no: 'JE-0001', date: start, memo: 'Opening balances', source: 'opening', ref: 'opening', locked: true,
    lines: [
      { accountId: 'ac' + A.BANK, debit: openCash, credit: 0, memo: 'Opening cash' },
      { accountId: 'ac' + A.SAVINGS, debit: 25000, credit: 0, memo: 'Opening savings' },
      { accountId: 'ac' + A.INV, debit: openInv, credit: 0, memo: 'Opening inventory' },
      { accountId: 'ac' + A.EQUIP, debit: sum(d.assets, a => a.cost), credit: 0, memo: 'Fixed assets at cost' },
      { accountId: 'ac' + A.LOAN, debit: 0, credit: 28500, memo: 'Equipment loan' },
      { accountId: 'ac' + A.OE, debit: 0, credit: 0, memo: 'Owner capital' }
    ]
  });
  const je = d.journal[0];
  const dr = sum(je.lines, l => l.debit), cr = sum(je.lines, l => l.credit);
  je.lines.find(l => l.memo === 'Owner capital').credit = r2(dr - cr);
  d.settings.nextJournal = 2;

  /* ---- documents over the last 7 months ---- */
  const invItems = d.items.filter(i => i.type === 'inventory'), svcItems = d.items.filter(i => i.type === 'service');
  const months = monthsRange(start, T);
  months.forEach((m, mi) => {
    const last = mi === months.length - 1;
    const nInv = last ? 4 : ri(5, 8);
    for (let k = 0; k < nInv; k++) {
      const cust = pick(d.contacts.filter(c => c.kind === 'customer'));
      const date = addDays(m, ri(0, Math.min(26, daysBetween(m, monthEnd(m)))));
      if (date > T) continue;
      const lines = [];
      const nl = ri(1, 4);
      for (let l = 0; l < nl; l++) {
        const it = rnd() > .45 ? pick(invItems) : pick(svcItems);
        const q = it.type === 'inventory' ? ri(1, 12) : ri(1, 6);
        lines.push({ id: uid('l'), itemId: it.id, desc: it.name, qty: q, price: it.price, accountId: it.incomeAccount, taxId: it.taxId, discount: rnd() > .85 ? 5 : 0 });
      }
      const inv = {
        id: uid('inv'), no: d.settings.invoicePrefix + (d.settings.nextInvoice++), customerId: cust.id, date,
        due: addDays(date, cust.terms), currency: 'USD', rate: 1, lines, shipping: rnd() > .6 ? ri(20, 90) : 0,
        notes: d.settings.invoiceNote, terms: 'Net ' + cust.terms, status: 'sent', payments: [],
        projectId: rnd() > .8 ? pick(d.projects).id : '', po: rnd() > .7 ? 'PO' + ri(1000, 9999) : ''
      };
      const tot = docTotals(inv).total;
      const age = daysBetween(date, T);
      if (age > 12 && rnd() > .18) {
        const payDate = addDays(date, Math.min(age, ri(8, Math.max(9, cust.terms + 6))));
        if (payDate <= T) {
          const partial = rnd() > .88;
          inv.payments.push({ id: uid('pm'), date: payDate, amount: partial ? r2(tot * 0.5) : tot, accountId: 'ac' + A.BANK, method: pick(['ACH', 'Check', 'Card', 'Wire']), ref: 'REF' + ri(10000, 99999) });
        }
      }
      d.invoices.push(inv);
    }
    /* bills */
    const nB = ri(3, 5);
    for (let k = 0; k < nB; k++) {
      const vend = pick(d.contacts.filter(c => c.kind === 'vendor'));
      const date = addDays(m, ri(0, 25));
      if (date > T) continue;
      const isStock = vend.defaultAccount === 'ac' + A.PURCH;
      const lines = [];
      if (isStock) {
        const it = pick(invItems);
        lines.push({ id: uid('l'), itemId: it.id, desc: it.name + ' — restock', qty: ri(10, 40), price: it.cost, accountId: 'ac' + A.INV, taxId: 't1' });
      } else {
        lines.push({ id: uid('l'), itemId: '', desc: pick(['Monthly service', 'Quarterly charge', 'Standard billing', 'Contract fee']), qty: 1, price: ri(180, 2400), accountId: vend.defaultAccount, taxId: 't1' });
      }
      const bill = {
        id: uid('bl'), no: d.settings.billPrefix + (d.settings.nextBill++), vendorId: vend.id, date,
        due: addDays(date, vend.terms), ref: 'V' + ri(10000, 99999), currency: 'USD', rate: 1, lines,
        notes: '', status: 'open', payments: []
      };
      const bt = docTotals(bill).total;
      if (daysBetween(date, T) > 20 && rnd() > .3) {
        const pd = addDays(date, ri(10, vend.terms));
        if (pd <= T) bill.payments.push({ id: uid('pm'), date: pd, amount: bt, accountId: 'ac' + A.BANK, method: 'ACH', ref: 'ACH' + ri(1000, 9999) });
      }
      d.bills.push(bill);
    }
    /* expenses */
    const expDefs = [['6250', 'Meridian Property Mgmt', 4200, 'Warehouse rent'], ['6500', 'Halcyon Utilities Co-op', ri(280, 640), 'Electric & water'],
    ['6350', 'Bluewave Cloud Services', 289, 'Software subscriptions'], ['6050', '', ri(38, 96), 'Merchant processing fees'],
    ['6400', '', ri(120, 780), 'Travel — client visits'], ['6450', '', ri(40, 210), 'Client meals'],
    ['6200', '', ri(60, 340), 'Office supplies'], ['6000', '', ri(200, 1100), 'Local advertising'],
    ['6550', 'Rockford Freight Lines', ri(140, 520), 'Outbound shipping']];
    expDefs.forEach(ed => {
      if (rnd() > .28) {
        const date = addDays(m, ri(0, 25));
        if (date > T) return;
        const v = d.contacts.find(c => c.name === ed[1]);
        d.expenses.push({
          id: uid('ex'), date, vendorId: v ? v.id : '', payee: ed[1] || pick(['Amtrak', 'Shell', 'Staples', 'Meta Ads', 'Delta Air Lines', 'Local Cafe']),
          accountId: 'ac' + ed[0], payAccountId: rnd() > .5 ? 'ac' + A.BANK : 'ac' + A.CC, amount: r2(ed[2]),
          taxId: 't1', memo: ed[3], billable: false, customerId: '', method: pick(['Card', 'ACH', 'Card', 'Check'])
        });
      }
    });
    /* payroll for the last 5 months */
    if (mi >= months.length - 5 && monthEnd(m) <= T) {
      const pd = monthEnd(m);
      const lines = d.employees.filter(e => e.hired <= pd).map(e => {
        const gross = e.payType === 'salary' ? r2(e.rate / 12) : r2(e.rate * ri(150, 176));
        const tax = r2(gross * e.taxRate / 100);
        const ben = e.benefits;
        return { employeeId: e.id, gross, tax, benefits: ben, net: r2(gross - tax - ben), employerTax: r2(gross * .0765) };
      });
      d.payruns.push({ id: uid('pr'), no: 'PR-' + (100 + mi), period: monthLabel(m), start: monthStart(m), end: pd, payDate: pd, lines, status: 'posted', account: 'ac' + A.BANK });
    }
  });

  /* estimates, POs, credit notes, recurring, time entries */
  for (let i = 0; i < 5; i++) {
    const cust = pick(d.contacts.filter(c => c.kind === 'customer'));
    const date = addDays(T, -ri(2, 60));
    const it = pick(svcItems);
    d.estimates.push({
      id: uid('es'), no: d.settings.estPrefix + (d.settings.nextEst++), customerId: cust.id, date,
      expiry: addDays(date, 30), currency: 'USD', rate: 1,
      lines: [{ id: uid('l'), itemId: it.id, desc: it.name, qty: ri(2, 10), price: it.price, accountId: it.incomeAccount, taxId: 't2', discount: 0 }],
      shipping: 0, notes: 'Estimate valid 30 days.', status: pick(['draft', 'sent', 'sent', 'accepted', 'declined']), payments: [], convertedTo: ''
    });
  }
  for (let i = 0; i < 4; i++) {
    const vend = pick(d.contacts.filter(c => c.kind === 'vendor' && c.defaultAccount === 'ac' + A.PURCH));
    const it = pick(invItems);
    const date = addDays(T, -ri(1, 40));
    d.pos.push({
      id: uid('po'), no: d.settings.poPrefix + (d.settings.nextPO++), vendorId: vend.id, date,
      expected: addDays(date, 14), currency: 'USD', rate: 1,
      lines: [{ id: uid('l'), itemId: it.id, desc: it.name, qty: ri(20, 60), price: it.cost, accountId: 'ac' + A.INV, taxId: 't1' }],
      notes: '', status: pick(['open', 'open', 'sent', 'received']), payments: []
    });
  }
  const oldInv = d.invoices.filter(i => i.payments.length).slice(-1)[0];
  if (oldInv) {
    d.creditNotes.push({
      id: uid('cn'), no: d.settings.cnPrefix + (d.settings.nextCN++), customerId: oldInv.customerId, date: addDays(T, -9),
      currency: 'USD', rate: 1, appliedTo: oldInv.id, reason: 'Damaged goods returned',
      lines: [{ id: uid('l'), itemId: '', desc: 'Credit — damaged shipment', qty: 1, price: 240, accountId: 'ac' + A.SALES, taxId: 't2', discount: 0 }],
      shipping: 0, status: 'open', notes: '', payments: []
    });
  }
  d.recurring = [
    { id: uid('rc'), type: 'invoice', name: 'Vantage Fitness — monthly contract', customerId: 'c6', frequency: 'monthly', next: addMonths(monthStart(T), 1), active: true, lines: [{ id: uid('l'), itemId: 'i8', desc: 'Monthly Maintenance Contract', qty: 1, price: 1450, accountId: 'ac' + A.SERV, taxId: 't2', discount: 0 }] },
    { id: uid('rc'), type: 'invoice', name: 'Quarry Ridge — monthly contract', customerId: 'c8', frequency: 'monthly', next: addMonths(monthStart(T), 1), active: true, lines: [{ id: uid('l'), itemId: 'i8', desc: 'Monthly Maintenance Contract', qty: 1, price: 1450, accountId: 'ac' + A.SERV, taxId: 't2', discount: 0 }] },
    { id: uid('rc'), type: 'expense', name: 'Warehouse rent', vendorId: 'v3', frequency: 'monthly', next: addMonths(monthStart(T), 1), active: true, amount: 4200, accountId: 'ac6250', payAccountId: 'ac' + A.BANK }
  ];
  for (let i = 0; i < 22; i++) {
    const p = pick(d.projects), e = pick(d.employees);
    d.timeEntries.push({
      id: uid('te'), date: addDays(T, -ri(1, 70)), employeeId: e.id, projectId: p.id, customerId: p.customerId,
      hours: ri(1, 8), rate: p.rate, billable: rnd() > .2, invoiced: rnd() > .6, memo: pick(['Site visit', 'Deep clean crew', 'Equipment servicing', 'Client walkthrough', 'Training session'])
    });
  }
  /* budgets: this fiscal year */
  const y = new Date().getFullYear();
  d.budgets[y] = {};
  d.accounts.filter(a => ['Income', 'Expense', 'COGS'].includes(a.type)).forEach(a => {
    const base = a.type === 'Income' ? ri(6, 30) * 1000 : ri(1, 9) * 500;
    d.budgets[y][a.id] = Array.from({ length: 12 }, () => r2(base * (0.9 + rnd() * 0.25)));
  });
  /* bank feed */
  seedBankFeed(d, start, T);

  repostAll();
  logAudit('Company file created', 'Demo data generated');
  return d;
}

function seedBankFeed(d, start, T) {
  d.bankTx = [];
  d.invoices.forEach(i => i.payments.forEach(p => d.bankTx.push({
    id: uid('bt'), accountId: p.accountId, date: p.date, desc: 'DEPOSIT ' + (d.contacts.find(c => c.id === i.customerId) || {}).name + ' ' + p.ref,
    amount: p.amount, matched: 'invoice:' + i.id, reconciled: daysBetween(p.date, T) > 40
  })));
  d.bills.forEach(b => b.payments.forEach(p => d.bankTx.push({
    id: uid('bt'), accountId: p.accountId, date: p.date, desc: 'ACH DEBIT ' + (d.contacts.find(c => c.id === b.vendorId) || {}).name,
    amount: -p.amount, matched: 'bill:' + b.id, reconciled: daysBetween(p.date, T) > 40
  })));
  d.expenses.forEach(e => d.bankTx.push({
    id: uid('bt'), accountId: e.payAccountId, date: e.date, desc: (e.payee || 'PAYMENT').toUpperCase() + ' ' + e.memo,
    amount: -e.amount, matched: 'expense:' + e.id, reconciled: daysBetween(e.date, T) > 40
  }));
  /* a few unmatched feed items awaiting categorisation */
  const un = [['SQUARE INC TRANSFER', 1240.55], ['STRIPE PAYOUT 8841', 2610.20], ['USPS POSTAGE', -84.60], ['AMZN MKTPLACE OFFICE', -216.34], ['INTEREST EARNED', 18.42], ['MONTHLY SERVICE CHARGE', -22.00]];
  un.forEach((u, i) => d.bankTx.push({
    id: uid('bt'), accountId: 'ac' + A.BANK, date: addDays(T, -(i * 2 + 1)), desc: u[0], amount: u[1], matched: '', reconciled: false
  }));
  d.bankTx.sort((a, b) => a.date < b.date ? 1 : -1);
}

/* ============================ accounting engine ============================ */
function taxRate(id) { const t = (DB.taxRates || []).find(t => t.id === id); return t ? t.rate : 0; }
function taxName(id) { const t = (DB.taxRates || []).find(t => t.id === id); return t ? t.name : 'No Tax'; }

function lineAmount(l) { return r2((Number(l.qty) || 0) * (Number(l.price) || 0) * (1 - (Number(l.discount) || 0) / 100)); }
function docTotals(doc) {
  const lines = doc.lines || [];
  let sub = 0, tax = 0;
  lines.forEach(l => { const a = lineAmount(l); sub += a; tax += a * taxRate(l.taxId) / 100; });
  const ship = Number(doc.shipping) || 0;
  const total = r2(sub + tax + ship);
  const paid = r2(sum(doc.payments || [], p => p.amount));
  return { sub: r2(sub), tax: r2(tax), ship: r2(ship), total, paid, balance: r2(total - paid) };
}
function docStatus(doc, kind) {
  /* estimates and purchase orders have no payments, so their stored state is the status */
  if (kind === 'estimate' || kind === 'po') return doc.status || 'draft';
  if (doc.status === 'draft') return 'draft';
  if (doc.status === 'void') return 'void';
  const t = docTotals(doc);
  if (kind === 'creditnote') return t.balance <= 0.004 ? 'paid' : 'open';
  if (t.balance <= 0.004) return 'paid';
  if (t.paid > 0.004) return 'partial';
  const due = doc.due || doc.expiry;
  if (due && due < today()) return 'overdue';
  return kind === 'bill' ? 'open' : 'sent';
}
function statusPill(s) {
  const m = { paid: ['p-paid', 'Paid'], sent: ['p-open', 'Open'], open: ['p-open', 'Open'], overdue: ['p-over', 'Overdue'], draft: ['p-draft', 'Draft'], partial: ['p-part', 'Part paid'], void: ['p-draft', 'Void'], accepted: ['p-paid', 'Accepted'], declined: ['p-over', 'Declined'], received: ['p-paid', 'Received'], complete: ['p-paid', 'Complete'], active: ['p-open', 'Active'], posted: ['p-paid', 'Posted'], closed: ['p-draft', 'Closed'], 'on hold': ['p-part', 'On hold'] };
  const x = m[s] || ['p-draft', s];
  return '<span class="pill ' + x[0] + '">' + x[1] + '</span>';
}
function contact(id) { return DB.contacts.find(c => c.id === id) || { name: '—', kind: '', terms: 30 }; }
function item(id) { return DB.items.find(i => i.id === id) || null; }
function project(id) { return DB.projects.find(p => p.id === id) || null; }

function nextJnl() { const n = DB.settings.nextJournal++; return 'JE-' + String(n).padStart(4, '0'); }
function mkJ(source, ref, date, memo, lines, extra) {
  const L = lines.filter(l => r2(l.debit) !== 0 || r2(l.credit) !== 0)
    .map(l => ({ accountId: l.accountId, debit: r2(l.debit || 0), credit: r2(l.credit || 0), memo: l.memo || '' }));
  /* rounding plug: cents lost to per-line rounding are absorbed by the largest line
     so that every entry in the journal balances to the penny */
  const diff = r2(sum(L, l => l.debit) - sum(L, l => l.credit));
  if (diff && Math.abs(diff) <= 0.05 && L.length) {
    const big = L.slice().sort((a, b) => (b.debit + b.credit) - (a.debit + a.credit))[0];
    if (big.debit) big.debit = r2(big.debit - diff); else big.credit = r2(big.credit + diff);
  }
  return Object.assign({ id: uid('j'), no: nextJnl(), date, memo, source, ref, lines: L }, extra || {});
}
function clearPostings(source, ref) { DB.journal = DB.journal.filter(j => !(j.source === source && j.ref === ref)); }

/* ---- posting rules ---- */
function postInvoice(inv) {
  clearPostings('invoice', inv.id);
  clearPostings('invoice-pmt', inv.id);
  if (inv.status === 'draft' || inv.status === 'void') return;
  const fx = Number(inv.rate) || 1, L = [];
  const t = docTotals(inv);
  L.push({ accountId: accId(A.AR), debit: t.total * fx, credit: 0, memo: contact(inv.customerId).name });
  inv.lines.forEach(l => {
    const a = lineAmount(l);
    L.push({ accountId: l.accountId || accId(A.SALES), debit: 0, credit: a * fx, memo: l.desc });
    const tx = a * taxRate(l.taxId) / 100;
    if (tx) L.push({ accountId: accId(A.TAXPAY), debit: 0, credit: tx * fx, memo: taxName(l.taxId) });
  });
  if (t.ship) L.push({ accountId: accId(A.SHIP), debit: 0, credit: t.ship * fx, memo: 'Shipping' });
  /* cost of goods sold */
  let cogs = 0;
  inv.lines.forEach(l => { const it = item(l.itemId); if (it && it.trackQty) cogs += (Number(l.qty) || 0) * (Number(it.cost) || 0); });
  if (cogs > 0) {
    L.push({ accountId: accId(A.COGS), debit: cogs, credit: 0, memo: 'Cost of goods sold' });
    L.push({ accountId: accId(A.INV), debit: 0, credit: cogs, memo: 'Inventory relieved' });
  }
  DB.journal.push(mkJ('invoice', inv.id, inv.date, 'Invoice ' + inv.no + ' — ' + contact(inv.customerId).name, L));
  (inv.payments || []).forEach(p => {
    DB.journal.push(mkJ('invoice-pmt', inv.id, p.date, 'Payment received ' + inv.no + ' (' + p.method + ')', [
      { accountId: p.accountId, debit: p.amount * fx, credit: 0, memo: p.ref || '' },
      { accountId: accId(A.AR), debit: 0, credit: p.amount * fx, memo: contact(inv.customerId).name }
    ]));
  });
}
function postBill(b) {
  clearPostings('bill', b.id); clearPostings('bill-pmt', b.id);
  if (b.status === 'draft' || b.status === 'void') return;
  const fx = Number(b.rate) || 1, t = docTotals(b), L = [];
  b.lines.forEach(l => {
    const a = lineAmount(l);
    L.push({ accountId: l.accountId || accId(A.PURCH), debit: a * fx, credit: 0, memo: l.desc });
    const tx = a * taxRate(l.taxId) / 100;
    if (tx) L.push({ accountId: accId(A.TAXREC), debit: tx * fx, credit: 0, memo: taxName(l.taxId) });
  });
  if (t.ship) L.push({ accountId: accId(A.FREIGHT), debit: t.ship * fx, credit: 0, memo: 'Freight' });
  L.push({ accountId: accId(A.AP), debit: 0, credit: t.total * fx, memo: contact(b.vendorId).name });
  DB.journal.push(mkJ('bill', b.id, b.date, 'Bill ' + b.no + ' — ' + contact(b.vendorId).name, L));
  (b.payments || []).forEach(p => {
    DB.journal.push(mkJ('bill-pmt', b.id, p.date, 'Bill payment ' + b.no, [
      { accountId: accId(A.AP), debit: p.amount * fx, credit: 0, memo: contact(b.vendorId).name },
      { accountId: p.accountId, debit: 0, credit: p.amount * fx, memo: p.ref || '' }
    ]));
  });
}
function postExpense(e) {
  clearPostings('expense', e.id);
  const tx = r2(e.amount * taxRate(e.taxId) / 100);
  DB.journal.push(mkJ('expense', e.id, e.date, 'Expense — ' + (e.memo || acc(e.accountId).name), [
    { accountId: e.accountId, debit: e.amount, credit: 0, memo: e.payee || '' },
    { accountId: accId(A.TAXREC), debit: tx, credit: 0, memo: 'Recoverable tax' },
    { accountId: e.payAccountId, debit: 0, credit: e.amount + tx, memo: e.method || '' }
  ]));
}
function postCreditNote(cn) {
  clearPostings('credit', cn.id);
  if (cn.status === 'void') return;
  const t = docTotals(cn), fx = cn.rate || 1, L = [];
  cn.lines.forEach(l => {
    const a = lineAmount(l);
    L.push({ accountId: l.accountId || accId(A.SALES), debit: a * fx, credit: 0, memo: l.desc });
    const tx = a * taxRate(l.taxId) / 100;
    if (tx) L.push({ accountId: accId(A.TAXPAY), debit: tx * fx, credit: 0, memo: 'Tax adjustment' });
  });
  L.push({ accountId: accId(A.AR), debit: 0, credit: t.total * fx, memo: 'Credit to ' + contact(cn.customerId).name });
  DB.journal.push(mkJ('credit', cn.id, cn.date, 'Credit note ' + cn.no, L));
}
function postPayrun(pr) {
  clearPostings('payroll', pr.id);
  if (pr.status !== 'posted') return;
  const gross = sum(pr.lines, l => l.gross), tax = sum(pr.lines, l => l.tax), ben = sum(pr.lines, l => l.benefits),
    net = sum(pr.lines, l => l.net), er = sum(pr.lines, l => l.employerTax);
  DB.journal.push(mkJ('payroll', pr.id, pr.payDate, 'Payroll ' + pr.period, [
    { accountId: accId(A.WAGES), debit: gross, credit: 0, memo: 'Gross wages' },
    { accountId: accId(A.PRTAX), debit: er, credit: 0, memo: 'Employer taxes' },
    { accountId: accId(A.PRLIAB), debit: 0, credit: tax + er + ben, memo: 'Withholdings & employer liabilities' },
    { accountId: pr.account, debit: 0, credit: net, memo: 'Net pay' }
  ]));
}
function postAdjustment(adj) {
  clearPostings('adjust', adj.id);
  const it = item(adj.itemId); if (!it) return;
  const val = r2(adj.qty * it.cost);
  DB.journal.push(mkJ('adjust', adj.id, adj.date, 'Inventory adjustment — ' + it.name, [
    { accountId: accId(A.INV), debit: val > 0 ? val : 0, credit: val < 0 ? -val : 0, memo: adj.reason },
    { accountId: adj.offsetAccount || accId(A.WOFF), debit: val < 0 ? -val : 0, credit: val > 0 ? val : 0, memo: adj.reason }
  ]));
}
function repostAll() {
  DB.journal = DB.journal.filter(j => ['manual', 'opening', 'transfer', 'depreciation'].includes(j.source));
  DB.invoices.forEach(postInvoice);
  DB.bills.forEach(postBill);
  DB.expenses.forEach(postExpense);
  DB.creditNotes.forEach(postCreditNote);
  DB.payruns.forEach(postPayrun);
  (DB.adjustments || []).forEach(postAdjustment);
  DB.journal.sort((a, b) => a.date < b.date ? -1 : a.date > b.date ? 1 : 0);
}

/* ---- ledger queries ---- */
function jLines(from, to) {
  const out = [];
  DB.journal.forEach(j => {
    if (from && j.date < from) return;
    if (to && j.date > to) return;
    j.lines.forEach((l, i) => out.push({ ...l, date: j.date, jid: j.id, no: j.no, memo2: j.memo, source: j.source, ref: j.ref, idx: i }));
  });
  return out.sort((a, b) => a.date < b.date ? -1 : a.date > b.date ? 1 : 0);
}
function balance(accountId, from, to) {
  let d = 0, c = 0;
  DB.journal.forEach(j => {
    if (from && j.date < from) return; if (to && j.date > to) return;
    j.lines.forEach(l => { if (l.accountId === accountId) { d += l.debit; c += l.credit; } });
  });
  const a = acc(accountId);
  const nat = TYPES[a.type] ? TYPES[a.type].normal : 'D';
  return { debit: r2(d), credit: r2(c), balance: r2(nat === 'D' ? d - c : c - d), raw: r2(d - c) };
}
function balanceAll(from, to) {
  const map = {};
  DB.accounts.forEach(a => map[a.id] = { debit: 0, credit: 0 });
  DB.journal.forEach(j => {
    if (from && j.date < from) return; if (to && j.date > to) return;
    j.lines.forEach(l => { if (!map[l.accountId]) map[l.accountId] = { debit: 0, credit: 0 }; map[l.accountId].debit += l.debit; map[l.accountId].credit += l.credit; });
  });
  Object.keys(map).forEach(k => {
    const a = acc(k), nat = TYPES[a.type] ? TYPES[a.type].normal : 'D';
    map[k].debit = r2(map[k].debit); map[k].credit = r2(map[k].credit);
    map[k].balance = r2(nat === 'D' ? map[k].debit - map[k].credit : map[k].credit - map[k].debit);
  });
  return map;
}
function netIncome(from, to) {
  const m = balanceAll(from, to);
  let inc = 0, exp = 0;
  DB.accounts.forEach(a => {
    const b = m[a.id]; if (!b) return;
    if (a.type === 'Income') inc += b.balance;
    if (a.type === 'Expense' || a.type === 'COGS') exp += b.balance;
  });
  return { income: r2(inc), expense: r2(exp), net: r2(inc - exp) };
}
function fyStart(d) {
  d = d || today();
  const m = DB.company.fyStartMonth || 1;
  const y = Number(d.slice(0, 4)), mm = Number(d.slice(5, 7));
  const yy = mm >= m ? y : y - 1;
  return yy + '-' + String(m).padStart(2, '0') + '-01';
}
function period() {
  const s = DB.session;
  const T = today();
  const P = {
    'mtd': [monthStart(T), T], 'lastmonth': [monthStart(addMonths(T, -1)), monthEnd(addMonths(T, -1))],
    'qtd': [(() => { const m = Math.floor(Number(T.slice(5, 7) - 1) / 3) * 3 + 1; return T.slice(0, 4) + '-' + String(m).padStart(2, '0') + '-01'; })(), T],
    'ytd': [fyStart(T), T], 'last12': [addMonths(T, -11).slice(0, 8) + '01', T],
    'lastyear': [fyStart(addMonths(fyStart(T), -1)), addDays(fyStart(T), -1)],
    'all': ['1900-01-01', '2999-12-31'], 'custom': [s.from || fyStart(T), s.to || T]
  };
  const p = P[s.period] || P.ytd;
  return { from: p[0], to: p[1] };
}
function periodLabel() {
  const L = { mtd: 'This month', lastmonth: 'Last month', qtd: 'This quarter', ytd: 'Fiscal year to date', last12: 'Last 12 months', lastyear: 'Last fiscal year', all: 'All dates', custom: 'Custom' };
  return L[DB.session.period] || 'Custom';
}

/* ---- receivables / payables ---- */
function openInvoices() { return DB.invoices.filter(i => !['draft', 'void'].includes(i.status) && docTotals(i).balance > 0.004); }
function openBills() { return DB.bills.filter(b => !['draft', 'void'].includes(b.status) && docTotals(b).balance > 0.004); }
function agingBuckets(docs, dateKey) {
  const T = today(), b = { current: 0, d30: 0, d60: 0, d90: 0, d90p: 0, total: 0 };
  docs.forEach(x => {
    const bal = docTotals(x).balance, age = daysBetween(x[dateKey] || x.date, T);
    if (age <= 0) b.current += bal; else if (age <= 30) b.d30 += bal; else if (age <= 60) b.d60 += bal; else if (age <= 90) b.d90 += bal; else b.d90p += bal;
    b.total += bal;
  });
  Object.keys(b).forEach(k => b[k] = r2(b[k]));
  return b;
}
function customerBalance(cid) { return r2(sum(DB.invoices.filter(i => i.customerId === cid && !['draft', 'void'].includes(i.status)), i => docTotals(i).balance) - sum(DB.creditNotes.filter(c => c.customerId === cid && c.status !== 'void'), c => docTotals(c).balance)); }
function vendorBalance(vid) { return r2(sum(DB.bills.filter(b => b.vendorId === vid && !['draft', 'void'].includes(b.status)), b => docTotals(b).balance)); }

/* ---- inventory ---- */
function stockOf(itemId) {
  const it = item(itemId); if (!it || !it.trackQty) return 0;
  let q = Number(it.opening) || 0;
  DB.invoices.forEach(i => { if (['draft', 'void'].includes(i.status)) return; i.lines.forEach(l => { if (l.itemId === itemId) q -= Number(l.qty) || 0; }); });
  DB.bills.forEach(b => { if (['draft', 'void'].includes(b.status)) return; b.lines.forEach(l => { if (l.itemId === itemId) q += Number(l.qty) || 0; }); });
  (DB.adjustments || []).forEach(a => { if (a.itemId === itemId) q += Number(a.qty) || 0; });
  return r2(q);
}
function inventoryValue() { return r2(sum(DB.items.filter(i => i.trackQty), i => stockOf(i.id) * i.cost)); }
function lowStock() { return DB.items.filter(i => i.trackQty && i.active !== false && stockOf(i.id) <= (i.reorder || 0)); }

/* ---- fixed assets ---- */
function monthlyDep(a) { return a.method === 'straight' ? r2((a.cost - (a.salvage || 0)) / (a.life || 60)) : r2((a.cost - depTotal(a)) * (2 / ((a.life || 60) / 12)) / 12); }
function depTotal(a) { return r2(sum(DB.journal.filter(j => j.source === 'depreciation' && j.ref === a.id), j => sum(j.lines, l => l.debit))); }
function bookValue(a) { return r2(a.cost - depTotal(a)); }

/* ---- cash flow classification ---- */
function cashAccounts() { return DB.accounts.filter(a => a.subtype === 'Bank').map(a => a.id); }
function cashFlow(from, to) {
  const cash = cashAccounts(), out = { operating: {}, investing: {}, financing: {}, opening: 0, closing: 0 };
  let opening = 0;
  cash.forEach(id => opening += balance(id, null, addDays(from, -1)).raw);
  out.opening = r2(opening);
  DB.journal.forEach(j => {
    if (j.date < from || j.date > to) return;
    const cashLines = j.lines.filter(l => cash.includes(l.accountId));
    if (!cashLines.length) return;
    const delta = sum(cashLines, l => l.debit - l.credit);
    const others = j.lines.filter(l => !cash.includes(l.accountId));
    const tot = sum(others, l => Math.abs(l.debit - l.credit)) || 1;
    others.forEach(l => {
      const a = acc(l.accountId);
      let cat = 'operating';
      if (a.subtype === 'Fixed Asset') cat = 'investing';
      else if (a.type === 'Equity' || a.subtype === 'Long Term Liability') cat = 'financing';
      const share = delta * (Math.abs(l.debit - l.credit) / tot);
      const key = a.code + ' · ' + a.name;
      out[cat][key] = r2((out[cat][key] || 0) + share);
    });
  });
  out.closing = r2(out.opening + sum(cash, id => balance(id, from, to).raw));
  return out;
}

/* ============================ UI framework ============================ */
const ic = {
  home: '<path d="M3 10.5 12 3l9 7.5V21H3z"/>', doc: '<path d="M6 2h8l4 4v16H6z"/><path d="M14 2v5h5"/>',
  quote: '<path d="M4 4h16v12H8l-4 4z"/>', credit: '<path d="M3 6h18v12H3z"/><path d="M3 10h18"/>',
  users: '<circle cx="9" cy="8" r="3"/><path d="M3 20c0-3.3 2.7-6 6-6s6 2.7 6 6"/><circle cx="17" cy="9" r="2"/>',
  repeat: '<path d="M4 9a5 5 0 0 1 5-5h11"/><path d="m17 1 3 3-3 3"/><path d="M20 15a5 5 0 0 1-5 5H4"/><path d="m7 23-3-3 3-3"/>',
  bill: '<path d="M5 3h14v18l-3-2-2 2-2-2-2 2-2-2-3 2z"/><path d="M9 8h6M9 12h6"/>',
  cart: '<circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/><path d="M2 3h3l2.6 12h11L21 7H6"/>',
  card: '<rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/>',
  box: '<path d="M12 2 3 7v10l9 5 9-5V7z"/><path d="m3 7 9 5 9-5M12 12v10"/>',
  bank: '<path d="M3 10h18M5 10v9M19 10v9M9 10v9M15 10v9M2 21h20M12 3 3 8h18z"/>',
  check: '<path d="m4 12 5 5L20 6"/>', book: '<path d="M4 4h16v16H4z"/><path d="M9 4v16M4 10h16"/>',
  ledger: '<path d="M4 3h16v18H4z"/><path d="M8 7h8M8 11h8M8 15h5"/>',
  asset: '<path d="M3 20h18M6 20V9l6-5 6 5v11"/><path d="M10 20v-6h4v6"/>',
  target: '<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4"/>',
  people: '<circle cx="12" cy="7" r="4"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/>',
  clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
  chart: '<path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/>',
  gear: '<circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M19 5l-2 2M7 17l-2 2"/>',
  shield: '<path d="M12 2 4 6v6c0 5 3.4 8.6 8 10 4.6-1.4 8-5 8-10V6z"/>',
  plus: '<path d="M12 5v14M5 12h14"/>', edit: '<path d="M4 20h4l10-10-4-4L4 16z"/><path d="m14 6 4 4"/>',
  trash: '<path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13"/>', eye: '<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>',
  down: '<path d="M12 4v12M6 12l6 6 6-6M4 21h16"/>', mail: '<rect x="2" y="4" width="20" height="16"/><path d="m2 6 10 7 10-7"/>',
  print: '<path d="M6 9V3h12v6M6 18H4v-6h16v6h-2M8 14h8v7H8z"/>', money: '<circle cx="12" cy="12" r="9"/><path d="M12 7v10M9.5 9.5h4a1.5 1.5 0 0 1 0 3h-3a1.5 1.5 0 0 0 0 3h4"/>'
};
function svg(p, s) { return '<svg class="ico" width="' + (s || 15) + '" height="' + (s || 15) + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">' + p + '</svg>'; }

const NAV = [
  ['Overview', [['dashboard', 'Dashboard', ic.home]]],
  ['Sales', [['invoices', 'Invoices', ic.doc], ['estimates', 'Estimates', ic.quote], ['creditnotes', 'Credit notes', ic.credit], ['customers', 'Customers', ic.users], ['recurring', 'Recurring', ic.repeat]]],
  ['Purchases', [['bills', 'Bills', ic.bill], ['pos', 'Purchase orders', ic.cart], ['expenses', 'Expenses', ic.card], ['vendors', 'Vendors', ic.users]]],
  ['Inventory', [['items', 'Products & services', ic.box], ['stock', 'Stock control', ic.box]]],
  ['Banking', [['banking', 'Bank & cards', ic.bank], ['reconcile', 'Reconcile', ic.check]]],
  ['Accounting', [['coa', 'Chart of accounts', ic.book], ['journal', 'Journal entries', ic.ledger], ['ledger', 'General ledger', ic.ledger], ['assets', 'Fixed assets', ic.asset], ['budgets', 'Budgets', ic.target]]],
  ['Operations', [['payroll', 'Payroll', ic.people], ['projects', 'Projects & time', ic.clock]]],
  ['Insights', [['reports', 'Reports', ic.chart]]],
  ['Admin', [['settings', 'Settings', ic.gear], ['audit', 'Audit log', ic.shield]]]
];

let ROUTE = 'dashboard', SUB = '';

function renderSide() {
  const overdue = openInvoices().filter(i => docStatus(i) === 'overdue').length;
  const counts = { invoices: DB.invoices.length, bills: openBills().length, customers: DB.contacts.filter(c => c.kind === 'customer').length, vendors: DB.contacts.filter(c => c.kind === 'vendor').length, items: DB.items.length, reconcile: DB.bankTx.filter(t => !t.matched).length };
  let h = '<div class="brand"><svg class="brand-mark" viewBox="0 0 32 32" fill="none"><rect x="1" y="1" width="30" height="30" rx="5" fill="#1D6B4A"/><path d="M7 9h18M7 14h18M7 19h11" stroke="#EDF4EA" stroke-width="1.6" stroke-linecap="round"/><path d="M7 24h18M7 26.5h18" stroke="#FFF" stroke-width="1.4" stroke-linecap="round"/></svg><div><div class="brand-name">Business Accounting</div><div class="brand-sub">General Ledger</div></div></div>';
  NAV.forEach(([g, items]) => {
    h += '<div class="navgrp"><div class="navgrp-t">' + g + '</div>';
    items.forEach(([k, t, i]) => {
      const c = counts[k];
      const badge = k === 'invoices' && overdue ? '<span class="cnt warn">' + overdue + '</span>' : (c ? '<span class="cnt">' + c + '</span>' : '');
      h += '<a class="nav' + (ROUTE === k ? ' on' : '') + '" href="#/' + k + '">' + svg(i) + '<span>' + t + '</span>' + badge + '</a>';
    });
    h += '</div>';
  });
  h += '<div class="side-foot"><span>' + (DIRTY ? 'Saving…' : 'Saved') + '</span><b>' + esc(DB.company.name) + '</b></div>';
  $('#side').innerHTML = h;
}

function setCrumb(t, sub) {
  $('#crumb').innerHTML = '<b>' + esc(t) + '</b>' + (sub ? ' &nbsp;/&nbsp; ' + esc(sub) : '');
  document.title = (sub || t) + ' \u2014 Business Accounting';
}

/* ---------- tables ---------- */
function tableHTML(cols, rows, opts) {
  opts = opts || {};
  if (!rows.length) return '<div class="empty"><h3>' + (opts.emptyTitle || 'Nothing here yet') + '</h3><p class="sub">' + (opts.emptyMsg || 'Records you add will show up in this list.') + '</p>' + (opts.emptyAction || '') + '</div>';
  let h = '<div class="tblwrap"><table class="tbl"><thead><tr>';
  cols.forEach(c => h += '<th class="' + (c.cls || '') + '"' + (c.w ? ' style="width:' + c.w + '"' : '') + '>' + c.t + '</th>');
  h += '</tr></thead><tbody>';
  rows.forEach((r, i) => {
    h += '<tr' + (opts.rowClick ? ' class="clickable" data-row="' + i + '"' : '') + '>';
    cols.forEach(c => h += '<td class="' + (c.cls || '') + '">' + (c.fmt ? c.fmt(r, i) : esc(r[c.k])) + '</td>');
    h += '</tr>';
  });
  h += '</tbody>';
  if (opts.foot) {
    h += '<tfoot><tr>';
    cols.forEach((c, ci) => h += '<td class="' + (c.cls || '') + ' ' + (ci === 0 || c.cls ? 'dbl' : 'dbl') + '">' + (opts.foot[c.k] != null ? opts.foot[c.k] : '') + '</td>');
    h += '</tr></tfoot>';
  }
  return h + '</table></div>';
}
function bindRows(root, rows, fn) {
  $$('tr[data-row]', root).forEach(tr => tr.addEventListener('click', e => {
    if (e.target.closest('button,a,input')) return;
    fn(rows[Number(tr.dataset.row)]);
  }));
}
function rowActs(acts) {
  return '<div class="rowacts">' + acts.map(a => '<button class="iconbtn" data-act="' + a[0] + '" title="' + a[2] + '">' + svg(a[1], 13) + '</button>').join('') + '</div>';
}

/* ---------- modal ---------- */
let MODALS = [];
function openModal(o) {
  const el = document.createElement('div');
  el.className = 'scrim';
  el.innerHTML = '<div class="modal ' + (o.size || '') + '" role="dialog" aria-modal="true"><div class="modal-h"><h2>' + esc(o.title) + '</h2>' +
    (o.badge || '') + '<button class="x" aria-label="Close">×</button></div><div class="modal-b">' + o.body + '</div>' +
    (o.footer === null ? '' : '<div class="modal-f">' + (o.footer || '<button class="btn" data-close>Close</button>') + '</div>') + '</div>';
  document.body.appendChild(el);
  MODALS.push(el);
  el.addEventListener('mousedown', e => { if (e.target === el) closeModal(); });
  $('.x', el).addEventListener('click', closeModal);
  $$('[data-close]', el).forEach(b => b.addEventListener('click', closeModal));
  if (o.onOpen) o.onOpen(el);
  const f = $('input,select,textarea', el); if (f && !o.noFocus) setTimeout(() => f.focus(), 40);
  return el;
}
function closeModal() { const m = MODALS.pop(); if (m) m.remove(); }
function closeAllModals() { MODALS.forEach(m => m.remove()); MODALS = []; }
document.addEventListener('keydown', e => { if (e.key === 'Escape') { if (MODALS.length) closeModal(); else if ($('.palette')) $('.palette').remove(); } });

function toast(msg, err) {
  const t = document.createElement('div');
  t.className = 'toast' + (err ? ' err' : '');
  t.textContent = msg;
  document.body.appendChild(t);
  setTimeout(() => t.remove(), 2400);
}
function confirmDlg(title, msg, onYes, yesLabel) {
  openModal({
    title, body: '<p style="margin:0">' + esc(msg) + '</p>',
    footer: '<button class="btn" data-close>Cancel</button><button class="btn danger" id="cfy">' + (yesLabel || 'Delete') + '</button>',
    onOpen: el => $('#cfy', el).addEventListener('click', () => { closeModal(); onYes(); })
  });
}

/* ---------- forms ---------- */
function fieldHTML(f, v) {
  const val = v == null ? (f.def != null ? f.def : '') : v;
  const w = f.w === 'full' ? ' full' : '';
  let inner = '';
  if (f.type === 'select') {
    inner = '<select data-k="' + f.k + '"' + (f.attr || '') + '>' + (f.opts || []).map(o => {
      const ov = typeof o === 'object' ? o.v : o, ot = typeof o === 'object' ? o.t : o;
      return '<option value="' + esc(ov) + '"' + (String(ov) === String(val) ? ' selected' : '') + '>' + esc(ot) + '</option>';
    }).join('') + '</select>';
  } else if (f.type === 'textarea') {
    inner = '<textarea data-k="' + f.k + '"' + (f.attr || '') + '>' + esc(val) + '</textarea>';
  } else if (f.type === 'checkbox') {
    return '<label class="chk' + w + '"><input type="checkbox" data-k="' + f.k + '"' + (val ? ' checked' : '') + '><span>' + esc(f.t) + '</span></label>';
  } else if (f.type === 'static') {
    inner = '<div style="padding:7px 0" class="' + (f.cls || '') + '">' + (f.html || esc(val)) + '</div>';
  } else {
    const t = f.type === 'money' ? 'number' : (f.type || 'text');
    inner = '<input type="' + t + '" data-k="' + f.k + '" value="' + esc(val) + '"' + (f.type === 'money' ? ' step="0.01"' : '') + (f.attr || '') + (f.ph ? ' placeholder="' + esc(f.ph) + '"' : '') + '>';
  }
  return '<label class="fl' + w + '"><span>' + esc(f.t) + (f.req ? ' *' : '') + '</span>' + inner + (f.hint ? '<div class="sub" style="font-size:11.5px;margin-top:3px">' + f.hint + '</div>' : '') + '</label>';
}
function formHTML(fields, values) {
  return '<div class="fields">' + fields.map(f => f.type === 'divider' ? '<div class="full lbl" style="border-top:1px solid var(--rule2);padding-top:11px;margin-top:2px">' + esc(f.t) + '</div>' : fieldHTML(f, (values || {})[f.k])).join('') + '</div>';
}
function readForm(root) {
  const o = {};
  $$('[data-k]', root).forEach(el => {
    const k = el.dataset.k;
    if (el.type === 'checkbox') o[k] = el.checked;
    else if (el.type === 'number') o[k] = el.value === '' ? 0 : Number(el.value);
    else o[k] = el.value;
  });
  return o;
}
function formModal(title, fields, values, onSave, size) {
  openModal({
    title, size: size || '', body: formHTML(fields, values),
    footer: '<button class="btn" data-close>Cancel</button><button class="btn pri" id="fsave">Save</button>',
    onOpen: el => {
      const go = () => {
        const v = readForm(el);
        const missing = fields.filter(f => f.req && !String(v[f.k] || '').trim());
        if (missing.length) { toast('Fill in ' + missing[0].t, true); return; }
        closeModal(); onSave(v);
      };
      $('#fsave', el).addEventListener('click', go);
      el.addEventListener('keydown', e => { if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') go(); });
    }
  });
}

/* ---------- charts ---------- */
function barChart(data, o) {
  o = o || {};
  const h = o.h || 170, w = 100, max = Math.max(1, ...data.map(d => Math.abs(d.value)), ...(o.compare || []).map(d => Math.abs(d.value)));
  const n = data.length || 1, bw = w / n;
  let s = '<svg viewBox="0 0 100 ' + (h + 22) + '" preserveAspectRatio="none" style="width:100%;height:' + (h + 22) + 'px;overflow:visible">';
  [0, .25, .5, .75, 1].forEach(g => { const y = h - g * h; s += '<line x1="0" x2="100" y1="' + y + '" y2="' + y + '" stroke="#EAEDE6" stroke-width="0.5" vector-effect="non-scaling-stroke"/>'; });
  data.forEach((d, i) => {
    const bh = Math.abs(d.value) / max * h;
    const x = i * bw + bw * .18, ww = bw * (o.compare ? .3 : .64);
    s += '<rect x="' + x + '" y="' + (h - bh) + '" width="' + ww + '" height="' + Math.max(bh, .6) + '" fill="' + (o.color || '#1D6B4A') + '" rx="0.6"><title>' + esc(d.label) + ': ' + money(d.value) + '</title></rect>';
    if (o.compare && o.compare[i]) {
      const b2 = Math.abs(o.compare[i].value) / max * h;
      s += '<rect x="' + (x + ww + bw * .06) + '" y="' + (h - b2) + '" width="' + ww + '" height="' + Math.max(b2, .6) + '" fill="' + (o.color2 || '#A5241D') + '" opacity=".8" rx="0.6"><title>' + esc(o.compare[i].label) + ': ' + money(o.compare[i].value) + '</title></rect>';
    }
  });
  s += '</svg><div style="display:flex;font-family:var(--mono);font-size:9.5px;color:var(--muted);margin-top:-14px">' +
    data.map(d => '<div style="flex:1;text-align:center">' + esc(d.label) + '</div>').join('') + '</div>';
  return s;
}
function lineChart(pts, o) {
  o = o || {};
  const h = o.h || 150, w = 300;
  const vals = pts.map(p => p.value), max = Math.max(...vals, 1), min = Math.min(...vals, 0);
  const rng = (max - min) || 1;
  const X = i => (i / Math.max(1, pts.length - 1)) * w;
  const Y = v => h - ((v - min) / rng) * (h - 10) - 5;
  const d = pts.map((p, i) => (i ? 'L' : 'M') + X(i).toFixed(1) + ' ' + Y(p.value).toFixed(1)).join(' ');
  const area = d + ' L' + w + ' ' + h + ' L0 ' + h + ' Z';
  let s = '<svg viewBox="0 0 ' + w + ' ' + (h + 16) + '" style="width:100%;height:' + (h + 16) + 'px;overflow:visible">';
  s += '<defs><linearGradient id="lg" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#1D6B4A" stop-opacity=".22"/><stop offset="1" stop-color="#1D6B4A" stop-opacity="0"/></linearGradient></defs>';
  s += '<path d="' + area + '" fill="url(#lg)"/><path d="' + d + '" fill="none" stroke="#1D6B4A" stroke-width="1.8" vector-effect="non-scaling-stroke"/>';
  pts.forEach((p, i) => s += '<circle cx="' + X(i).toFixed(1) + '" cy="' + Y(p.value).toFixed(1) + '" r="2.4" fill="#fff" stroke="#1D6B4A" stroke-width="1.4"><title>' + esc(p.label) + ': ' + money(p.value) + '</title></circle>');
  s += '</svg><div style="display:flex;font-family:var(--mono);font-size:9.5px;color:var(--muted)">' + pts.map(p => '<div style="flex:1;text-align:center">' + esc(p.label) + '</div>').join('') + '</div>';
  return s;
}
function donut(segs, o) {
  o = o || {};
  const total = sum(segs, s => s.value) || 1, R = 42, C = 2 * Math.PI * R;
  let off = 0, s = '<svg viewBox="0 0 120 120" style="width:' + (o.size || 150) + 'px;height:' + (o.size || 150) + 'px">';
  segs.forEach(g => {
    const frac = g.value / total, len = frac * C;
    s += '<circle cx="60" cy="60" r="' + R + '" fill="none" stroke="' + g.color + '" stroke-width="15" stroke-dasharray="' + len.toFixed(2) + ' ' + (C - len).toFixed(2) + '" stroke-dashoffset="' + (-off).toFixed(2) + '" transform="rotate(-90 60 60)"><title>' + esc(g.label) + ': ' + money(g.value) + '</title></circle>';
    off += len;
  });
  s += '<text x="60" y="57" text-anchor="middle" font-family="IBM Plex Mono" font-size="9" fill="#68757F">' + esc(o.label || 'TOTAL') + '</text>';
  s += '<text x="60" y="70" text-anchor="middle" font-family="IBM Plex Mono" font-size="12.5" font-weight="600" fill="#17202A">' + money(total) + '</text></svg>';
  return s;
}

/* ---------- files ---------- */
function download(name, content, mime) {
  const b = new Blob([content], { type: mime || 'text/plain' });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(b); a.download = name; a.click();
  setTimeout(() => URL.revokeObjectURL(a.href), 3000);
}
function toCSV(cols, rows) {
  const q = v => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"';
  return [cols.map(c => q(c.t)).join(',')].concat(rows.map(r => cols.map(c => q(c.raw ? c.raw(r) : r[c.k])).join(','))).join('\n');
}
function exportCSV(name, cols, rows) { download(name + '.csv', toCSV(cols, rows), 'text/csv'); toast('Exported ' + name + '.csv'); }

/* ============================ document editor ============================ */
const DOCK = {
  invoice: { title: 'Invoice', coll: 'invoices', party: 'customerId', pkind: 'customer', prefix: 'invoicePrefix', next: 'nextInvoice', due: 'due', dueLabel: 'Due date', ship: true, disc: true, acct: a => a.type === 'Income', post: postInvoice, pay: true, route: 'invoices' },
  estimate: { title: 'Estimate', coll: 'estimates', party: 'customerId', pkind: 'customer', prefix: 'estPrefix', next: 'nextEst', due: 'expiry', dueLabel: 'Valid until', ship: true, disc: true, acct: a => a.type === 'Income', post: null, pay: false, route: 'estimates' },
  creditnote: { title: 'Credit note', coll: 'creditNotes', party: 'customerId', pkind: 'customer', prefix: 'cnPrefix', next: 'nextCN', due: '', dueLabel: '', ship: false, disc: true, acct: a => a.type === 'Income', post: postCreditNote, pay: false, route: 'creditnotes' },
  bill: { title: 'Bill', coll: 'bills', party: 'vendorId', pkind: 'vendor', prefix: 'billPrefix', next: 'nextBill', due: 'due', dueLabel: 'Due date', ship: true, disc: false, acct: a => ['Expense', 'COGS'].includes(a.type) || a.subtype === 'Current Asset' || a.subtype === 'Fixed Asset', post: postBill, pay: true, route: 'bills' },
  po: { title: 'Purchase order', coll: 'pos', party: 'vendorId', pkind: 'vendor', prefix: 'poPrefix', next: 'nextPO', due: 'expected', dueLabel: 'Expected', ship: false, disc: false, acct: a => ['Expense', 'COGS'].includes(a.type) || a.subtype === 'Current Asset', post: null, pay: false, route: 'pos' }
};
function nextNo(kind) { const c = DOCK[kind]; return DB.settings[c.prefix] + (DB.settings[c.next]++); }
function blankDoc(kind) {
  const c = DOCK[kind], T = today();
  const d = { id: '', no: '', date: T, currency: DB.company.currency, rate: 1, lines: [], shipping: 0, notes: DB.settings.invoiceNote, status: 'draft', payments: [], projectId: '', po: '', ref: '', reason: '' };
  d[c.party] = '';
  if (c.due) d[c.due] = addDays(T, DB.settings.terms);
  return d;
}

function docEditor(kind, docIn) {
  const c = DOCK[kind];
  const doc = clone(docIn || blankDoc(kind));
  if (!doc.lines.length) doc.lines = [newLine(kind)];
  const parties = DB.contacts.filter(x => x.kind === c.pkind && x.active !== false).map(x => ({ v: x.id, t: x.name }));
  const accts = accOpts(c.acct);
  const isNew = !doc.id;

  const body = `
  <div class="fields" style="grid-template-columns:repeat(4,minmax(0,1fr))">
    ${fieldHTML({ k: c.party, t: c.pkind === 'customer' ? 'Customer' : 'Vendor', type: 'select', opts: [{ v: '', t: '— select —' }].concat(parties), req: 1, w: 'full', attr: ' id="dParty"' }, doc[c.party])}
    ${fieldHTML({ k: 'no', t: 'Number', ph: 'auto' }, doc.no)}
    ${fieldHTML({ k: 'date', t: 'Date', type: 'date' }, doc.date)}
    ${c.due ? fieldHTML({ k: c.due, t: c.dueLabel, type: 'date' }, doc[c.due]) : fieldHTML({ k: 'reason', t: 'Reason' }, doc.reason)}
    ${fieldHTML({ k: 'currency', t: 'Currency', type: 'select', opts: Object.keys(DB.currencies).map(k => ({ v: k, t: k })), attr: ' id="dCur"' }, doc.currency)}
    ${kind === 'invoice' ? fieldHTML({ k: 'projectId', t: 'Project', type: 'select', opts: [{ v: '', t: '— none —' }].concat(DB.projects.map(p => ({ v: p.id, t: p.name }))) }, doc.projectId) : ''}
    ${kind === 'invoice' ? fieldHTML({ k: 'po', t: 'Customer PO' }, doc.po) : ''}
    ${kind === 'bill' ? fieldHTML({ k: 'ref', t: 'Vendor ref' }, doc.ref) : ''}
    ${fieldHTML({ k: 'status', t: 'Status', type: 'select', opts: kind === 'estimate' ? ['draft', 'sent', 'accepted', 'declined'] : kind === 'po' ? ['draft', 'open', 'sent', 'received', 'closed'] : ['draft', kind === 'bill' ? 'open' : 'sent', 'void'] }, doc.status)}
    <div class="full" id="fxNote"></div>
  </div>
  <div style="margin-top:16px" class="scroll-x">
    <table class="lines" id="lineTbl"><thead><tr>
      <th style="width:180px">Item</th><th>Description</th><th style="width:70px">Qty</th><th style="width:96px">Rate</th>
      <th style="width:180px">Account</th><th style="width:130px">Tax</th>${c.disc ? '<th style="width:62px">Disc %</th>' : ''}
      <th style="width:104px" class="num">Amount</th><th style="width:26px"></th></tr></thead><tbody></tbody></table>
    <button class="btn sm mt" id="addLine">+ Add line</button>
    <button class="btn sm mt" id="add4">+ Add 4 lines</button>
  </div>
  <div style="display:flex;gap:20px;margin-top:16px;flex-wrap:wrap">
    <div style="flex:1;min-width:240px">
      ${fieldHTML({ k: 'notes', t: 'Notes shown on the document', type: 'textarea' }, doc.notes)}
    </div>
    <div class="totbox" id="totBox"></div>
  </div>`;

  const el = openModal({
    title: (isNew ? 'New ' : 'Edit ') + c.title.toLowerCase(), size: 'xl', body,
    footer: '<button class="btn" data-close>Cancel</button>' + (c.pay && !isNew ? '<button class="btn" id="dPay">Record payment</button>' : '') +
      (doc.status === 'draft' ? '<button class="btn" id="dDraft">Save as draft</button><button class="btn pri" id="dSave">Save &amp; ' + (c.post ? 'post' : 'issue') + '</button>'
        : '<button class="btn pri" id="dSave">Save ' + c.title.toLowerCase() + '</button>'),
    onOpen: root => {
      const tb = $('#lineTbl tbody', root);
      function lineRow(l, i) {
        return `<tr data-i="${i}">
        <td><select data-l="itemId"><option value="">— none —</option>${DB.items.filter(x => x.active !== false).map(x => '<option value="' + x.id + '"' + (x.id === l.itemId ? ' selected' : '') + '>' + esc(x.sku + ' · ' + x.name) + '</option>').join('')}</select></td>
        <td><input data-l="desc" value="${esc(l.desc)}"></td>
        <td><input data-l="qty" type="number" step="0.01" value="${l.qty}"></td>
        <td><input data-l="price" type="number" step="0.01" value="${l.price}"></td>
        <td><select data-l="accountId">${accts.map(a => '<option value="' + a.v + '"' + (a.v === l.accountId ? ' selected' : '') + '>' + esc(a.t) + '</option>').join('')}</select></td>
        <td><select data-l="taxId">${DB.taxRates.map(t => '<option value="' + t.id + '"' + (t.id === l.taxId ? ' selected' : '') + '>' + esc(t.name) + '</option>').join('')}</select></td>
        ${c.disc ? '<td><input data-l="discount" type="number" step="1" value="' + (l.discount || 0) + '"></td>' : ''}
        <td class="num" data-amt>${money(lineAmount(l), doc.currency)}</td>
        <td><button class="iconbtn" data-del title="Remove line">×</button></td></tr>`;
      }
      function drawLines() { tb.innerHTML = doc.lines.map(lineRow).join(''); wire(); drawTotals(); }
      function drawTotals() {
        const t = docTotals(doc);
        $('#totBox', root).innerHTML =
          '<div class="totrow"><span>Subtotal</span><span>' + money(t.sub, doc.currency) + '</span></div>' +
          '<div class="totrow"><span>Tax</span><span>' + money(t.tax, doc.currency) + '</span></div>' +
          (c.ship ? '<div class="totrow"><span>Shipping</span><input type="number" step="0.01" id="shipIn" style="width:110px;text-align:right" value="' + (doc.shipping || 0) + '"></div>' : '') +
          '<div class="totrow grand"><span>Total</span><span>' + money(t.total, doc.currency) + '</span></div>' +
          (t.paid ? '<div class="totrow"><span>Paid</span><span>' + money(t.paid, doc.currency) + '</span></div><div class="totrow" style="font-weight:600"><span>Balance</span><span>' + money(t.balance, doc.currency) + '</span></div>' : '');
        const s = $('#shipIn', root);
        if (s) s.addEventListener('input', () => { doc.shipping = Number(s.value) || 0; drawTotals(); });
        const cur = $('#dCur', root).value, fx = DB.currencies[cur] || 1;
        $('#fxNote', root).innerHTML = cur === DB.company.currency ? '' :
          '<div class="hint">Foreign currency document. Posted to the ledger at ' + (1 / fx).toFixed(4) + ' ' + DB.company.currency + ' per ' + cur + ' — base total ' + money(t.total / fx) + '.</div>';
      }
      function wire() {
        $$('tr[data-i]', tb).forEach(tr => {
          const i = Number(tr.dataset.i);
          $$('[data-l]', tr).forEach(inp => inp.addEventListener('change', () => {
            const k = inp.dataset.l;
            doc.lines[i][k] = inp.type === 'number' ? Number(inp.value) : inp.value;
            if (k === 'itemId') {
              const it = item(inp.value);
              if (it) {
                doc.lines[i].desc = it.name;
                doc.lines[i].price = kind === 'bill' || kind === 'po' ? it.cost : it.price;
                doc.lines[i].accountId = (kind === 'bill' || kind === 'po') ? (it.trackQty ? accId(A.INV) : it.expenseAccount) : it.incomeAccount;
                doc.lines[i].taxId = it.taxId;
                if (!doc.lines[i].qty) doc.lines[i].qty = 1;
              }
              drawLines(); return;
            }
            $('[data-amt]', tr).textContent = money(lineAmount(doc.lines[i]), doc.currency);
            drawTotals();
          }));
          $$('[data-l]', tr).forEach(inp => { if (inp.tagName === 'INPUT') inp.addEventListener('input', () => { doc.lines[i][inp.dataset.l] = inp.type === 'number' ? Number(inp.value) : inp.value; $('[data-amt]', tr).textContent = money(lineAmount(doc.lines[i]), doc.currency); drawTotals(); }); });
          $('[data-del]', tr).addEventListener('click', () => { doc.lines.splice(i, 1); if (!doc.lines.length) doc.lines.push(newLine(kind)); drawLines(); });
        });
      }
      drawLines();
      $('#addLine', root).addEventListener('click', () => { doc.lines.push(newLine(kind)); drawLines(); });
      $('#add4', root).addEventListener('click', () => { for (let i = 0; i < 4; i++) doc.lines.push(newLine(kind)); drawLines(); });
      $('#dCur', root).addEventListener('change', () => { doc.currency = $('#dCur', root).value; drawTotals(); });
      const party = $('#dParty', root);
      party.addEventListener('change', () => {
        const p = contact(party.value);
        if (c.due && p.terms) { const de = $('[data-k="' + c.due + '"]', root); if (de) de.value = addDays($('[data-k="date"]', root).value, p.terms); }
        if (p.currency) { $('#dCur', root).value = p.currency; doc.currency = p.currency; drawTotals(); }
      });
      /* a draft is held out of the ledger; issuing it posts the entries */
      const LIVE = { invoice: 'sent', bill: 'open', creditnote: 'open', estimate: 'sent', po: 'open' };
      function commit(asDraft) {
        const v = readForm(root);
        Object.assign(doc, v);
        doc.rate = DB.currencies[doc.currency] ? 1 / DB.currencies[doc.currency] : 1;
        if (!doc[c.party]) { toast('Choose a ' + c.pkind, true); return; }
        doc.lines = doc.lines.filter(l => l.desc || lineAmount(l));
        if (!doc.lines.length) { toast('Add at least one line', true); return; }
        if (doc.status === 'draft' || asDraft) doc.status = asDraft ? 'draft' : (LIVE[kind] || 'open');
        if (!doc.no) doc.no = nextNo(kind);
        if (!doc.id) { doc.id = uid(kind); DB[c.coll].push(doc); }
        else { const idx = DB[c.coll].findIndex(x => x.id === doc.id); DB[c.coll][idx] = doc; }
        if (c.post) c.post(doc);
        save((isNew ? 'Created ' : 'Updated ') + c.title + ' ' + doc.no);
        closeModal(); render();
        toast(c.title + ' ' + doc.no + (asDraft ? ' saved as draft' : ' saved'));
      }
      $('#dSave', root).addEventListener('click', () => commit(false));
      const db2 = $('#dDraft', root); if (db2) db2.addEventListener('click', () => commit(true));
      const pb = $('#dPay', root);
      if (pb) pb.addEventListener('click', () => { closeModal(); paymentModal(kind, doc); });
    }
  });
  return el;
}
function newLine(kind) {
  return { id: uid('l'), itemId: '', desc: '', qty: 1, price: 0, discount: 0, taxId: DB.settings.defaultTaxId, accountId: (kind === 'bill' || kind === 'po') ? accId('6900') : accId(A.SALES) };
}

/* ---------- payments ---------- */
function paymentModal(kind, doc) {
  const c = DOCK[kind], t = docTotals(doc);
  const f = [
    { k: 'date', t: 'Payment date', type: 'date', def: today() },
    { k: 'amount', t: 'Amount', type: 'money', def: t.balance },
    { k: 'accountId', t: kind === 'bill' ? 'Paid from' : 'Deposit to', type: 'select', opts: accOpts(a => a.subtype === 'Bank' || a.subtype === 'Credit Card' || a.id === accId(A.UNDEP)), def: accId(A.BANK) },
    { k: 'method', t: 'Method', type: 'select', opts: ['ACH', 'Check', 'Card', 'Cash', 'Wire', 'Other'] },
    { k: 'ref', t: 'Reference', w: 'full', ph: 'Check no. / transaction id' }
  ];
  formModal('Record payment — ' + doc.no, f, {}, v => {
    if (!v.amount) { toast('Enter an amount', true); return; }
    doc.payments = doc.payments || [];
    doc.payments.push({ id: uid('pm'), date: v.date, amount: r2(v.amount), accountId: v.accountId, method: v.method, ref: v.ref });
    if (doc.status === 'draft') doc.status = kind === 'bill' ? 'open' : 'sent';
    DB.bankTx.push({ id: uid('bt'), accountId: v.accountId, date: v.date, desc: (kind === 'bill' ? 'PAYMENT ' : 'DEPOSIT ') + contact(doc[c.party]).name, amount: kind === 'bill' ? -r2(v.amount) : r2(v.amount), matched: kind + ':' + doc.id, reconciled: false });
    c.post(doc); save('Payment recorded on ' + doc.no); render();
    toast('Payment of ' + money(v.amount) + ' recorded');
  });
}

/* ---------- document view (printable) ---------- */
function docView(kind, doc) {
  const c = DOCK[kind], p = contact(doc[c.party]), t = docTotals(doc), st = docStatus(doc, kind);
  const co = DB.company;
  const rows = doc.lines.map(l => `<tr><td>${esc(l.desc)}${l.itemId && item(l.itemId) ? '<div class="sub" style="font-size:11.5px">' + esc(item(l.itemId).sku) + '</div>' : ''}</td>
    <td class="num">${qty(l.qty)}</td><td class="num">${money(l.price, doc.currency)}</td>
    ${c.disc ? '<td class="num">' + (l.discount || 0) + '%</td>' : ''}
    <td class="num">${taxRate(l.taxId) ? taxRate(l.taxId) + '%' : '—'}</td>
    <td class="num">${money(lineAmount(l), doc.currency)}</td></tr>`).join('');
  const body = `<div class="docpaper" id="printDoc">
    <div class="docgrid">
      <div>
        <div style="font-family:var(--disp);font-size:20px;font-weight:700">${esc(co.name)}</div>
        <div class="sub mono" style="font-size:12px;line-height:1.6;margin-top:6px">${esc(co.addr1)}<br>${esc(co.city)}, ${esc(co.state)} ${esc(co.zip)}<br>${esc(co.email)} · ${esc(co.phone)}<br>Tax ID ${esc(co.taxId)}</div>
      </div>
      <div style="text-align:right">
        <div class="lbl">${c.title}</div>
        <div style="font-family:var(--mono);font-size:26px;font-weight:600;letter-spacing:-.02em">${esc(doc.no)}</div>
        <div style="margin-top:8px">${statusPill(st)}</div>
        <div class="mono sub" style="font-size:12px;margin-top:10px;line-height:1.7">
          Issued ${fmtDate(doc.date)}${c.due && doc[c.due] ? '<br>' + c.dueLabel + ' ' + fmtDate(doc[c.due]) : ''}
          ${doc.po ? '<br>Your PO ' + esc(doc.po) : ''}${doc.ref ? '<br>Ref ' + esc(doc.ref) : ''}
        </div>
      </div>
    </div>
    <div class="docgrid" style="margin-top:26px">
      <div><div class="lbl">${c.pkind === 'customer' ? 'Bill to' : 'From'}</div>
        <div style="margin-top:6px;font-weight:600">${esc(p.name)}</div>
        <div class="sub" style="font-size:12.5px;line-height:1.6">${esc(p.contact || '')}<br>${esc(p.addr1 || '')}<br>${esc(p.city || '')}, ${esc(p.state || '')} ${esc(p.zip || '')}<br>${esc(p.email || '')}</div>
      </div>
      <div style="text-align:right">
        <div class="lbl">Amount ${st === 'paid' ? 'paid' : 'due'}</div>
        <div style="font-family:var(--mono);font-size:30px;font-weight:600;letter-spacing:-.02em;margin-top:4px">${money(st === 'paid' ? t.total : t.balance, doc.currency)}</div>
        ${doc.currency !== co.currency ? '<div class="sub mono" style="font-size:11px">Base equivalent ' + money(t.total * (doc.rate || 1)) + '</div>' : ''}
      </div>
    </div>
    <table class="tbl" style="margin-top:24px"><thead><tr><th>Description</th><th class="num">Qty</th><th class="num">Rate</th>${c.disc ? '<th class="num">Disc</th>' : ''}<th class="num">Tax</th><th class="num">Amount</th></tr></thead><tbody>${rows}</tbody></table>
    <div style="display:flex;margin-top:18px"><div style="flex:1"></div><div class="totbox">
      <div class="totrow"><span>Subtotal</span><span>${money(t.sub, doc.currency)}</span></div>
      <div class="totrow"><span>Tax</span><span>${money(t.tax, doc.currency)}</span></div>
      ${t.ship ? '<div class="totrow"><span>Shipping</span><span>' + money(t.ship, doc.currency) + '</span></div>' : ''}
      <div class="totrow grand"><span>Total</span><span>${money(t.total, doc.currency)}</span></div>
      ${t.paid ? '<div class="totrow"><span>Payments received</span><span>' + money(-t.paid, doc.currency) + '</span></div><div class="totrow" style="font-weight:600"><span>Balance due</span><span>' + money(t.balance, doc.currency) + '</span></div>' : ''}
    </div></div>
    ${(doc.payments || []).length ? '<div style="margin-top:20px"><div class="lbl">Payment history</div><table class="tbl" style="margin-top:6px"><tbody>' + doc.payments.map(pm => '<tr><td>' + fmtDate(pm.date) + '</td><td>' + esc(pm.method) + ' ' + esc(pm.ref || '') + '</td><td>' + esc(acc(pm.accountId).name) + '</td><td class="num">' + money(pm.amount, doc.currency) + '</td></tr>').join('') + '</tbody></table></div>' : ''}
    <div style="margin-top:24px;border-top:1px solid var(--rule2);padding-top:14px" class="sub">${esc(doc.notes || '')}<div style="margin-top:8px;font-size:11.5px">${esc(DB.settings.invoiceFooter)}</div></div>
  </div>`;
  const foot = '<button class="btn" data-close>Close</button>' +
    '<button class="btn" id="vPrint">Print / PDF</button>' +
    '<button class="btn" id="vCopy">Duplicate</button>' +
    (kind === 'estimate' ? '<button class="btn" id="vConv">Convert to invoice</button>' : '') +
    (kind === 'po' ? '<button class="btn" id="vConvB">Convert to bill</button>' : '') +
    (kind === 'invoice' ? '<button class="btn" id="vEmail">Send</button>' : '') +
    (c.pay && t.balance > 0.004 ? '<button class="btn pri" id="vPay">Record payment</button>' : '') +
    '<button class="btn" id="vEdit">Edit</button>';
  openModal({
    title: c.title + ' ' + doc.no, size: 'xl', body, footer: foot,
    onOpen: root => {
      $('#vEdit', root).addEventListener('click', () => { closeModal(); docEditor(kind, doc); });
      $('#vPrint', root).addEventListener('click', () => printNode(root));
      $('#vCopy', root).addEventListener('click', () => {
        const d2 = clone(doc); d2.id = ''; d2.no = ''; d2.date = today(); d2.payments = []; d2.status = 'draft';
        if (c.due) d2[c.due] = addDays(today(), DB.settings.terms);
        closeModal(); docEditor(kind, d2);
      });
      const pay = $('#vPay', root); if (pay) pay.addEventListener('click', () => { closeModal(); paymentModal(kind, doc); });
      const cv = $('#vConv', root);
      if (cv) cv.addEventListener('click', () => {
        const inv = clone(doc); inv.id = ''; inv.no = nextNo('invoice'); inv.date = today(); inv.due = addDays(today(), contact(doc.customerId).terms || 30);
        inv.status = 'sent'; inv.payments = []; inv.id = uid('inv');
        DB.invoices.push(inv); postInvoice(inv); doc.status = 'accepted'; doc.convertedTo = inv.no;
        save('Estimate ' + doc.no + ' converted to invoice ' + inv.no); closeModal(); go('invoices'); toast('Created ' + inv.no);
      });
      const cb = $('#vConvB', root);
      if (cb) cb.addEventListener('click', () => {
        const b = clone(doc); b.id = uid('bl'); b.no = nextNo('bill'); b.date = today(); b.due = addDays(today(), contact(doc.vendorId).terms || 30);
        b.status = 'open'; b.payments = [];
        DB.bills.push(b); postBill(b); doc.status = 'received';
        save('PO ' + doc.no + ' received into bill ' + b.no); closeModal(); go('bills'); toast('Created ' + b.no);
      });
      const em = $('#vEmail', root);
      if (em) em.addEventListener('click', () => {
        if (doc.status === 'draft') { doc.status = 'sent'; postInvoice(doc); save('Sent ' + doc.no); }
        const sub = encodeURIComponent(DB.company.name + ' — Invoice ' + doc.no);
        const bodyTxt = encodeURIComponent('Hello ' + (p.contact || p.name) + ',\n\nInvoice ' + doc.no + ' for ' + money(t.balance, doc.currency) + ' is attached, due ' + fmtDate(doc.due) + '.\n\nThank you,\n' + DB.company.name);
        window.open('mailto:' + (p.email || '') + '?subject=' + sub + '&body=' + bodyTxt);
        render();
      });
    }
  });
}
function printNode(root) {
  const node = $('#printDoc', root) || $('#printArea') || root;
  const w = window.open('', '_blank', 'width=900,height=1000');
  if (!w) { window.print(); return; }
  const css = Array.from(document.querySelectorAll('style,link[rel=stylesheet]')).map(n => n.outerHTML).join('');
  w.document.write('<html><head><title>' + document.title + '</title>' + css + '</head><body style="background:#fff;padding:28px">' + node.outerHTML + '</body></html>');
  w.document.close();
  setTimeout(() => { w.focus(); w.print(); }, 550);
}
function delDoc(kind, doc) {
  const c = DOCK[kind];
  confirmDlg('Delete ' + c.title.toLowerCase() + ' ' + doc.no, 'This removes the document and its ledger entries. This cannot be undone.', () => {
    DB[c.coll] = DB[c.coll].filter(x => x.id !== doc.id);
    clearPostings(kind === 'creditnote' ? 'credit' : kind, doc.id);
    clearPostings((kind === 'creditnote' ? 'credit' : kind) + '-pmt', doc.id);
    DB.bankTx = DB.bankTx.filter(t => t.matched !== kind + ':' + doc.id);
    save('Deleted ' + c.title + ' ' + doc.no); render(); toast(c.title + ' deleted');
  });
}

/* ============================ views: dashboard ============================ */
function page(title, sub, acts) {
  return '<div class="pagehead"><div><h1>' + esc(title) + '</h1>' + (sub ? '<div class="sub">' + sub + '</div>' : '') + '</div><div class="acts noprint">' + (acts || '') + '</div></div>';
}
function isEmptyFile() {
  return !DB.contacts.length && !DB.invoices.length && !DB.bills.length && !DB.expenses.length
    && !DB.items.length && !DB.journal.length && !DB.bankTx.length;
}
function view_welcome() {
  const steps = [
    ['Enter your company details', 'Name, address, tax number and the month your fiscal year starts. These print on every invoice.', 'Open settings', () => { LISTF.setTab = 'company'; go('settings'); }],
    ['Review the chart of accounts', '43 accounts are ready to go. Rename them, add your own, or deactivate the ones you will not use.', 'Chart of accounts', () => go('coa')],
    ['Add your bank accounts', 'Add an account for each bank or card, then import a statement or key transactions in by hand.', 'Banking', () => go('banking')],
    ['Enter opening balances', 'One journal entry dated the day before you start: what you own on the debit side, what you owe on the credit side.', 'New journal entry', () => journalModal()],
    ['Add customers, vendors and items', 'Anything you sell regularly becomes an item with a price and, for stock, a cost.', 'Add a customer', () => contactModal('customer')],
    ['Raise your first invoice', 'It posts to receivables and revenue automatically, and the books stay in balance.', 'New invoice', () => docEditor('invoice')]
  ];
  let h = page('Welcome', 'An empty company file, ready for your first entry', '');
  h += '<div class="card mb"><div class="card-b" style="display:flex;gap:22px;align-items:flex-start;flex-wrap:wrap">' +
    '<div style="flex:1;min-width:260px"><h2 style="font-family:var(--disp);font-size:19px;margin:0 0 6px">Set up ' + esc(DB.company.name) + '</h2>' +
    '<p class="sub" style="max-width:60ch">This is a full double-entry ledger. Every invoice, bill, expense and pay run posts debits and credits, so the trial balance and balance sheet always tie. Work through the steps below, or load the worked example to see what a running company file looks like.</p>' +
    '<div class="flexrow mt"><button class="btn pri" id="wCo">Enter company details</button><button class="btn" id="wDemo">Load demo company</button></div></div>' +
    '<div class="stamp" style="position:static;transform:rotate(-4deg);align-self:center">Books in balance</div>' +
    '</div></div>';
  h += '<div class="grid g2">' + steps.map((st, i) =>
    '<div class="card"><div class="card-b"><div class="lbl">Step ' + (i + 1) + '</div>' +
    '<h3 style="font-family:var(--disp);font-size:15px;margin:4px 0 6px">' + esc(st[0]) + '</h3>' +
    '<p class="sub">' + esc(st[1]) + '</p>' +
    '<button class="btn sm mt" data-w="' + i + '">' + esc(st[2]) + '</button></div></div>').join('') + '</div>';
  h += '<div class="hint mt">Everything is stored in this browser. Take a backup from Settings \u203a Data before you rely on it, and press \u2318K at any time to jump to a screen or start a document.</div>';
  $('#view').innerHTML = h;
  $('#wCo').addEventListener('click', () => { LISTF.setTab = 'company'; go('settings'); });
  $('#wDemo').addEventListener('click', () => confirmDlg('Load demo company',
    'Fills this file with a worked example \u2014 seven months of invoices, bills, payroll, projects and bank activity for a fictional supplier. You can wipe it again from Settings \u203a Data.',
    () => { DB = seed(); save('Loaded demo company'); render(); toast('Demo company loaded'); }, 'Load demo data'));
  $$('[data-w]').forEach(b => b.addEventListener('click', () => steps[Number(b.dataset.w)][3]()));
}
function view_dashboard() {
  if (isEmptyFile()) return view_welcome();
  const P = period(), T = today();
  const ni = netIncome(P.from, P.to);
  const cash = r2(sum(cashAccounts(), id => balance(id, null, T).balance));
  const ar = r2(sum(openInvoices(), i => docTotals(i).balance));
  const ap = r2(sum(openBills(), b => docTotals(b).balance));
  const od = openInvoices().filter(i => docStatus(i) === 'overdue');
  const months = monthsRange(addMonths(monthStart(T), -7), T);
  const inc = months.map(m => ({ label: monthLabel(m), value: netIncome(m, monthEnd(m)).income }));
  const exp = months.map(m => ({ label: monthLabel(m), value: netIncome(m, monthEnd(m)).expense }));
  const cashLine = months.map(m => ({ label: monthLabel(m), value: r2(sum(cashAccounts(), id => balance(id, null, monthEnd(m)).balance)) }));
  const aging = agingBuckets(openInvoices(), 'due');
  const margin = ni.income ? (ni.income - r2(sum(DB.accounts.filter(a => a.type === 'COGS'), a => balance(a.id, P.from, P.to).balance))) / ni.income * 100 : 0;
  const recent = jLines(addDays(T, -30), T).slice(-9).reverse();
  const topCust = DB.contacts.filter(c => c.kind === 'customer').map(c => ({
    c, v: r2(sum(DB.invoices.filter(i => i.customerId === c.id && i.date >= P.from && i.date <= P.to && !['draft', 'void'].includes(i.status)), i => docTotals(i).total))
  })).filter(x => x.v > 0).sort((a, b) => b.v - a.v).slice(0, 5);
  const low = lowStock();
  const unmatched = DB.bankTx.filter(t => !t.matched).length;

  let h = page('Dashboard', periodLabel() + ' &middot; ' + fmtDate(P.from) + ' – ' + fmtDate(P.to),
    '<button class="btn" id="dNewExp">New expense</button><button class="btn pri" id="dNewInv">New invoice</button>');

  h += '<div class="grid g4">' + [
    ['Cash on hand', cash, 'Across ' + cashAccounts().length + ' bank accounts'],
    ['Accounts receivable', ar, od.length ? '<b class="down">' + od.length + ' overdue</b> · ' + money(sum(od, i => docTotals(i).balance)) : 'All current'],
    ['Accounts payable', ap, openBills().length + ' unpaid bills'],
    ['Net income', ni.net, '<b class="' + (ni.net >= 0 ? 'up' : 'down') + '">' + pct(margin) + '</b> gross margin']
  ].map(k => '<div class="kpi"><div class="lbl">' + k[0] + '</div><div class="v' + (k[1] < 0 ? ' neg' : '') + '">' + money(k[1]) + '</div><div class="d">' + k[2] + '</div></div>').join('') + '</div>';

  const alerts = [];
  if (od.length) alerts.push(['over', od.length + ' overdue invoice' + (od.length > 1 ? 's' : '') + ' worth ' + money(sum(od, i => docTotals(i).balance)), 'invoices']);
  if (low.length) alerts.push(['low', low.length + ' item' + (low.length > 1 ? 's' : '') + ' at or below reorder point', 'stock']);
  if (unmatched) alerts.push(['bank', unmatched + ' bank transactions need categorising', 'banking']);
  const dueSoon = openBills().filter(b => b.due <= addDays(T, 7));
  if (dueSoon.length) alerts.push(['ap', dueSoon.length + ' bills due within 7 days (' + money(sum(dueSoon, b => docTotals(b).balance)) + ')', 'bills']);
  if (alerts.length) h += '<div class="grid mt" style="grid-template-columns:repeat(auto-fit,minmax(260px,1fr))">' +
    alerts.map(a => '<div class="warnbox" style="display:flex;gap:9px;align-items:center"><span class="dot" style="background:var(--amber)"></span><span style="flex:1">' + a[1] + '</span><a class="btn sm" href="#/' + a[2] + '">Open</a></div>').join('') + '</div>';

  h += '<div class="grid g-2-1 mt">' +
    '<div class="card"><div class="card-h"><h2>Income vs expenses</h2><div class="acts"><span class="tag"><span class="dot" style="background:var(--green);margin-right:5px"></span>Income</span><span class="tag"><span class="dot" style="background:var(--red);margin-right:5px"></span>Expense</span></div></div><div class="card-b">' +
    barChart(inc, { compare: exp, h: 180 }) + '</div></div>' +
    '<div class="card"><div class="card-h"><h2>Receivables ageing</h2></div><div class="card-b" style="display:flex;flex-direction:column;align-items:center;gap:10px">' +
    donut([{ label: 'Current', value: aging.current, color: '#1D6B4A' }, { label: '1–30 days', value: aging.d30, color: '#5C9E7E' }, { label: '31–60', value: aging.d60, color: '#C79A2E' }, { label: '61–90', value: aging.d90, color: '#C4703A' }, { label: '90+', value: aging.d90p, color: '#A5241D' }], { label: 'OUTSTANDING' }) +
    '<table class="tbl" style="font-size:12px"><tbody>' +
    [['Current', aging.current], ['1–30 days', aging.d30], ['31–60 days', aging.d60], ['61–90 days', aging.d90], ['Over 90 days', aging.d90p]].map(r => '<tr><td>' + r[0] + '</td><td class="num">' + money(r[1]) + '</td></tr>').join('') +
    '</tbody></table></div></div></div>';

  h += '<div class="grid g-1-2 mt">' +
    '<div class="card"><div class="card-h"><h2>Cash position</h2></div><div class="card-b">' + lineChart(cashLine, { h: 150 }) +
    '<table class="tbl mt" style="font-size:12.5px"><tbody>' + cashAccounts().map(id => '<tr><td>' + esc(acc(id).name) + '</td><td class="num">' + money(balance(id, null, T).balance) + '</td></tr>').join('') + '</tbody><tfoot><tr><td class="dbl">Total</td><td class="num dbl">' + money(cash) + '</td></tr></tfoot></table></div></div>' +
    '<div class="card"><div class="card-h"><h2>Recent ledger activity</h2><div class="acts"><a class="btn sm" href="#/journal">All entries</a></div></div>' +
    tableHTML([
      { t: 'Date', k: 'date', fmt: r => fmtDate(r.date), w: '110px' },
      { t: 'Entry', k: 'no', fmt: r => '<span class="mono" style="font-size:12px">' + esc(r.no) + '</span>' },
      { t: 'Account', k: 'accountId', fmt: r => esc(accName(r.accountId)) },
      { t: 'Memo', k: 'memo2', fmt: r => '<span class="sub">' + esc(r.memo2) + '</span>' },
      { t: 'Debit', k: 'debit', cls: 'num', fmt: r => r.debit ? money(r.debit) : '' },
      { t: 'Credit', k: 'credit', cls: 'num', fmt: r => r.credit ? money(r.credit) : '' }
    ], recent) + '</div></div>';

  h += '<div class="grid g2 mt">' +
    '<div class="card"><div class="card-h"><h2>Top customers</h2><div class="acts"><span class="lbl">' + periodLabel() + '</span></div></div>' +
    tableHTML([
      { t: 'Customer', k: 'n', fmt: r => esc(r.c.name) },
      { t: 'Revenue', k: 'v', cls: 'num', fmt: r => money(r.v) },
      { t: 'Share', k: 's', fmt: r => '<div class="bar"><i style="width:' + Math.min(100, r.v / (topCust[0] ? topCust[0].v : 1) * 100) + '%"></i></div>', w: '140px' }
    ], topCust, { emptyTitle: 'No sales in this period' }) + '</div>' +
    '<div class="card"><div class="card-h"><h2>Unpaid invoices</h2><div class="acts"><a class="btn sm" href="#/invoices">Open list</a></div></div>' +
    tableHTML([
      { t: 'Invoice', k: 'no', fmt: r => '<span class="mono">' + esc(r.no) + '</span>' },
      { t: 'Customer', k: 'c', fmt: r => esc(contact(r.customerId).name) },
      { t: 'Due', k: 'due', fmt: r => fmtDate(r.due) },
      { t: 'Status', k: 's', fmt: r => statusPill(docStatus(r)) },
      { t: 'Balance', k: 'b', cls: 'num', fmt: r => money(docTotals(r).balance) }
    ], openInvoices().sort(by('due')).slice(0, 7), { emptyTitle: 'Everything is paid', emptyMsg: 'No outstanding customer balances.' }) + '</div></div>';

  $('#view').innerHTML = h;
  $('#dNewInv').addEventListener('click', () => docEditor('invoice'));
  $('#dNewExp').addEventListener('click', () => expenseModal());
}

/* ============================ generic document list ============================ */
function docList(kind, cfg) {
  const c = DOCK[kind];
  const all = DB[c.coll].slice().sort((a, b) => a.date < b.date ? 1 : -1);
  const f = LISTF[kind] || (LISTF[kind] = { q: '', s: 'all' });
  let rows = all.filter(d => {
    if (f.s !== 'all' && docStatus(d, kind) !== f.s) return false;
    if (!f.q) return true;
    const q = f.q.toLowerCase();
    return (d.no + ' ' + contact(d[c.party]).name + ' ' + (d.po || '') + ' ' + (d.ref || '') + ' ' + d.lines.map(l => l.desc).join(' ')).toLowerCase().includes(q);
  });
  const tot = r2(sum(rows, d => docTotals(d).total * (d.rate || 1)));
  const bal = r2(sum(rows, d => docTotals(d).balance * (d.rate || 1)));
  const statuses = cfg.statuses || ['all', 'draft', 'sent', 'partial', 'overdue', 'paid'];

  let h = page(cfg.title, cfg.sub, '<button class="btn" id="lExp">Export CSV</button><button class="btn pri" id="lNew">New ' + c.title.toLowerCase() + '</button>');
  h += '<div class="flexrow mb noprint"><div class="seg">' + statuses.map(s => '<button data-s="' + s + '"' + (f.s === s ? ' class="on"' : '') + '>' + (s === 'all' ? 'All' : s[0].toUpperCase() + s.slice(1)) + '</button>').join('') + '</div>' +
    '<input id="lQ" type="text" placeholder="Filter by number, name or line" style="max-width:280px" value="' + esc(f.q) + '">' +
    '<div style="margin-left:auto" class="lbl">' + rows.length + ' documents · ' + money(tot) + ' total · ' + money(bal) + ' outstanding</div></div>';

  const cols = [
    { t: 'Number', k: 'no', w: '110px', fmt: d => '<span class="mono" style="font-weight:500">' + esc(d.no) + '</span>' },
    { t: 'Date', k: 'date', w: '110px', fmt: d => fmtDate(d.date) },
    { t: c.pkind === 'customer' ? 'Customer' : 'Vendor', k: 'p', fmt: d => esc(contact(d[c.party]).name) },
    { t: 'Reference', k: 'r', fmt: d => '<span class="sub">' + esc(d.po || d.ref || (d.lines[0] || {}).desc || '') + '</span>' },
    { t: c.due ? c.dueLabel : 'Reason', k: 'due', w: '110px', fmt: d => c.due ? fmtDate(d[c.due]) : esc(d.reason || '') },
    { t: 'Status', k: 's', w: '96px', fmt: d => statusPill(docStatus(d, kind)) },
    { t: 'Total', k: 't', cls: 'num', w: '110px', fmt: d => money(docTotals(d).total, d.currency) },
    { t: 'Balance', k: 'b', cls: 'num', w: '110px', fmt: d => moneyCell(docTotals(d).balance, d.currency) },
    { t: '', k: 'a', cls: 'num', w: '92px', fmt: () => rowActs([['view', ic.eye, 'View'], ['edit', ic.edit, 'Edit'], ['del', ic.trash, 'Delete']]) }
  ];
  h += '<div class="card">' + tableHTML(cols, rows, {
    rowClick: 1, foot: { no: 'Totals', t: money(tot), b: money(bal) },
    emptyTitle: 'No ' + c.title.toLowerCase() + 's yet',
    emptyMsg: 'Create your first ' + c.title.toLowerCase() + ' to get started.',
    emptyAction: '<button class="btn pri mt" onclick="docEditor(\'' + kind + '\')">New ' + c.title.toLowerCase() + '</button>'
  }) + '</div>';
  $('#view').innerHTML = h;

  bindRows($('#view'), rows, d => docView(kind, d));
  $$('#view tr[data-row]').forEach(tr => {
    const d = rows[Number(tr.dataset.row)];
    $$('[data-act]', tr).forEach(b => b.addEventListener('click', e => {
      e.stopPropagation();
      const a = b.dataset.act;
      if (a === 'view') docView(kind, d);
      if (a === 'edit') docEditor(kind, d);
      if (a === 'del') delDoc(kind, d);
    }));
  });
  $('#lNew').addEventListener('click', () => docEditor(kind));
  $('#lExp').addEventListener('click', () => exportCSV(kind + 's', [
    { t: 'Number', raw: d => d.no }, { t: 'Date', raw: d => d.date }, { t: 'Party', raw: d => contact(d[c.party]).name },
    { t: 'Due', raw: d => c.due ? d[c.due] : '' }, { t: 'Status', raw: d => docStatus(d, kind) },
    { t: 'Currency', raw: d => d.currency }, { t: 'Subtotal', raw: d => docTotals(d).sub }, { t: 'Tax', raw: d => docTotals(d).tax },
    { t: 'Total', raw: d => docTotals(d).total }, { t: 'Balance', raw: d => docTotals(d).balance }], rows));
  $$('#view .seg button').forEach(b => b.addEventListener('click', () => { f.s = b.dataset.s; render(); }));
  const q = $('#lQ');
  q.addEventListener('input', () => { f.q = q.value; render(); setTimeout(() => { const n = $('#lQ'); n.focus(); n.setSelectionRange(n.value.length, n.value.length); }, 0); });
}
const LISTF = {};

const view_invoices = () => docList('invoice', { title: 'Invoices', sub: 'Money owed to you by customers' });
const view_estimates = () => docList('estimate', { title: 'Estimates', sub: 'Quotes awaiting customer approval', statuses: ['all', 'draft', 'sent', 'accepted', 'declined'] });
const view_creditnotes = () => docList('creditnote', { title: 'Credit notes', sub: 'Credits issued against customer accounts', statuses: ['all', 'draft', 'open', 'void'] });
const view_bills = () => docList('bill', { title: 'Bills', sub: 'Money you owe suppliers', statuses: ['all', 'draft', 'open', 'partial', 'overdue', 'paid'] });
const view_pos = () => docList('po', { title: 'Purchase orders', sub: 'Committed orders not yet received', statuses: ['all', 'draft', 'open', 'sent', 'received', 'closed'] });

/* ============================ expenses ============================ */
function expenseModal(e) {
  const isNew = !e;
  const f = [
    { k: 'date', t: 'Date', type: 'date', def: today(), req: 1 },
    { k: 'payee', t: 'Payee', ph: 'Who was paid' },
    { k: 'vendorId', t: 'Linked vendor', type: 'select', opts: [{ v: '', t: '— none —' }].concat(DB.contacts.filter(c => c.kind === 'vendor').map(c => ({ v: c.id, t: c.name }))) },
    { k: 'accountId', t: 'Category', type: 'select', opts: accOpts(a => ['Expense', 'COGS'].includes(a.type) || a.subtype === 'Fixed Asset'), req: 1 },
    { k: 'amount', t: 'Amount', type: 'money', req: 1 },
    { k: 'taxId', t: 'Tax', type: 'select', opts: DB.taxRates.map(t => ({ v: t.id, t: t.name })) },
    { k: 'payAccountId', t: 'Paid from', type: 'select', opts: accOpts(a => a.subtype === 'Bank' || a.subtype === 'Credit Card'), def: accId(A.BANK) },
    { k: 'method', t: 'Method', type: 'select', opts: ['Card', 'ACH', 'Check', 'Cash', 'Other'] },
    { k: 'memo', t: 'Memo', w: 'full' },
    { k: 'billable', t: 'Billable to a customer', type: 'checkbox', w: 'full' },
    { k: 'customerId', t: 'Bill to customer', type: 'select', opts: [{ v: '', t: '— none —' }].concat(DB.contacts.filter(c => c.kind === 'customer').map(c => ({ v: c.id, t: c.name }))) }
  ];
  formModal(isNew ? 'New expense' : 'Edit expense', f, e || {}, v => {
    const rec = Object.assign({ id: e ? e.id : uid('ex') }, v);
    if (e) { const i = DB.expenses.findIndex(x => x.id === e.id); DB.expenses[i] = rec; }
    else { DB.expenses.push(rec); DB.bankTx.push({ id: uid('bt'), accountId: rec.payAccountId, date: rec.date, desc: (rec.payee || 'EXPENSE').toUpperCase() + ' ' + rec.memo, amount: -r2(rec.amount), matched: 'expense:' + rec.id, reconciled: false }); }
    postExpense(rec); save((e ? 'Updated' : 'Recorded') + ' expense ' + money(rec.amount)); render(); toast('Expense saved');
  });
}
function view_expenses() {
  const P = period();
  const f = LISTF.exp || (LISTF.exp = { q: '' });
  let rows = DB.expenses.filter(e => e.date >= P.from && e.date <= P.to).sort((a, b) => a.date < b.date ? 1 : -1);
  if (f.q) rows = rows.filter(e => ((e.payee || '') + ' ' + e.memo + ' ' + acc(e.accountId).name).toLowerCase().includes(f.q.toLowerCase()));
  const tot = r2(sum(rows, e => e.amount));
  const byCat = {};
  rows.forEach(e => byCat[e.accountId] = r2((byCat[e.accountId] || 0) + e.amount));
  const cats = Object.keys(byCat).map(k => ({ label: acc(k).name, value: byCat[k] })).sort((a, b) => b.value - a.value).slice(0, 6);

  let h = page('Expenses', 'Direct spend recorded outside of supplier bills · ' + periodLabel(),
    '<button class="btn" id="eExp">Export CSV</button><button class="btn pri" id="eNew">New expense</button>');
  h += '<div class="grid g4 mb">' +
    '<div class="kpi"><div class="lbl">Total this period</div><div class="v">' + money(tot) + '</div><div class="d">' + rows.length + ' transactions</div></div>' +
    cats.slice(0, 3).map(c => '<div class="kpi"><div class="lbl">' + esc(c.label) + '</div><div class="v">' + money(c.value) + '</div><div class="d">' + pct(c.value / (tot || 1) * 100) + ' of spend</div></div>').join('') + '</div>';
  h += '<div class="flexrow mb noprint"><input id="eQ" type="text" placeholder="Filter expenses" style="max-width:280px" value="' + esc(f.q) + '"></div>';
  h += '<div class="card">' + tableHTML([
    { t: 'Date', k: 'date', w: '110px', fmt: e => fmtDate(e.date) },
    { t: 'Payee', k: 'payee', fmt: e => esc(e.payee || contact(e.vendorId).name) },
    { t: 'Category', k: 'cat', fmt: e => esc(accName(e.accountId)) },
    { t: 'Memo', k: 'memo', fmt: e => '<span class="sub">' + esc(e.memo) + '</span>' },
    { t: 'Paid from', k: 'pa', fmt: e => esc(acc(e.payAccountId).name) },
    { t: 'Billable', k: 'bl', w: '80px', fmt: e => e.billable ? '<span class="pill p-open">Billable</span>' : '' },
    { t: 'Amount', k: 'amount', cls: 'num', w: '110px', fmt: e => money(e.amount) },
    { t: '', k: 'a', cls: 'num', w: '70px', fmt: () => rowActs([['edit', ic.edit, 'Edit'], ['del', ic.trash, 'Delete']]) }
  ], rows, { rowClick: 1, foot: { date: 'Total', amount: money(tot) }, emptyTitle: 'No expenses in this period' }) + '</div>';
  $('#view').innerHTML = h;
  bindRows($('#view'), rows, e => expenseModal(e));
  $$('#view tr[data-row]').forEach(tr => {
    const e = rows[Number(tr.dataset.row)];
    $$('[data-act]', tr).forEach(b => b.addEventListener('click', ev => {
      ev.stopPropagation();
      if (b.dataset.act === 'edit') expenseModal(e);
      else confirmDlg('Delete expense', 'Remove this expense and its ledger entry?', () => {
        DB.expenses = DB.expenses.filter(x => x.id !== e.id); clearPostings('expense', e.id);
        DB.bankTx = DB.bankTx.filter(t => t.matched !== 'expense:' + e.id);
        save('Deleted expense'); render();
      });
    }));
  });
  $('#eNew').addEventListener('click', () => expenseModal());
  $('#eExp').addEventListener('click', () => exportCSV('expenses', [{ t: 'Date', raw: e => e.date }, { t: 'Payee', raw: e => e.payee }, { t: 'Category', raw: e => accName(e.accountId) }, { t: 'Memo', raw: e => e.memo }, { t: 'Amount', raw: e => e.amount }], rows));
  const q = $('#eQ'); q.addEventListener('input', () => { f.q = q.value; render(); setTimeout(() => $('#eQ').focus(), 0); });
}

/* ============================ contacts ============================ */
function contactModal(kind, c) {
  const f = [
    { k: 'name', t: kind === 'customer' ? 'Customer name' : 'Vendor name', req: 1, w: 'full' },
    { k: 'contact', t: 'Primary contact' }, { k: 'email', t: 'Email', type: 'email' },
    { k: 'phone', t: 'Phone' }, { k: 'terms', t: 'Payment terms (days)', type: 'number', def: 30 },
    { k: 'addr1', t: 'Street', w: 'full' }, { k: 'city', t: 'City' }, { k: 'state', t: 'State' },
    { k: 'zip', t: 'Postcode' }, { k: 'country', t: 'Country', def: 'United States' },
    { k: 'currency', t: 'Currency', type: 'select', opts: Object.keys(DB.currencies) },
    { k: 'taxId', t: 'Default tax', type: 'select', opts: DB.taxRates.map(t => ({ v: t.id, t: t.name })) },
    kind === 'customer' ? { k: 'creditLimit', t: 'Credit limit', type: 'money' } : { k: 'defaultAccount', t: 'Default expense account', type: 'select', opts: accOpts(a => ['Expense', 'COGS'].includes(a.type)) },
    { k: 'notes', t: 'Notes', type: 'textarea', w: 'full' },
    { k: 'active', t: 'Active', type: 'checkbox', w: 'full' }
  ];
  formModal(c ? 'Edit ' + kind : 'New ' + kind, f, c || { active: true, terms: 30, currency: DB.company.currency }, v => {
    if (c) Object.assign(c, v);
    else DB.contacts.push(Object.assign({ id: uid(kind[0]), kind }, v));
    save((c ? 'Updated' : 'Added') + ' ' + kind + ' ' + v.name); render(); toast(kind[0].toUpperCase() + kind.slice(1) + ' saved');
  });
}
function contactView(c) {
  const isCust = c.kind === 'customer';
  const docs = isCust ? DB.invoices.filter(i => i.customerId === c.id) : DB.bills.filter(b => b.vendorId === c.id);
  const bal = isCust ? customerBalance(c.id) : vendorBalance(c.id);
  const lifetime = r2(sum(docs.filter(d => !['draft', 'void'].includes(d.status)), d => docTotals(d).total));
  const paidDocs = docs.filter(d => docTotals(d).balance <= 0 && d.payments.length);
  const avgDays = paidDocs.length ? Math.round(sum(paidDocs, d => daysBetween(d.date, d.payments[d.payments.length - 1].date)) / paidDocs.length) : null;
  const exps = isCust ? [] : DB.expenses.filter(e => e.vendorId === c.id);
  const body = `<div class="grid g4 mb">
    <div class="kpi"><div class="lbl">Open balance</div><div class="v">${money(bal)}</div></div>
    <div class="kpi"><div class="lbl">Lifetime ${isCust ? 'sales' : 'spend'}</div><div class="v">${money(lifetime + sum(exps, e => e.amount))}</div></div>
    <div class="kpi"><div class="lbl">Documents</div><div class="v">${docs.length}</div></div>
    <div class="kpi"><div class="lbl">Avg days to pay</div><div class="v">${avgDays == null ? '—' : avgDays}</div></div></div>
    <div class="grid g2 mb"><div class="card"><div class="card-h"><h3>Details</h3></div><div class="card-b sub" style="line-height:1.8">
      ${esc(c.contact || '')}<br>${esc(c.email || '')}<br>${esc(c.phone || '')}<br>${esc(c.addr1 || '')}<br>${esc(c.city || '')}, ${esc(c.state || '')} ${esc(c.zip || '')}<br>
      Terms: Net ${c.terms} · Currency ${esc(c.currency || DB.company.currency)}${c.creditLimit ? ' · Credit limit ' + money(c.creditLimit) : ''}</div></div>
    <div class="card"><div class="card-h"><h3>Notes</h3></div><div class="card-b sub">${esc(c.notes || 'No notes recorded.')}</div></div></div>
    <div class="card"><div class="card-h"><h3>Transaction history</h3></div>
    ${tableHTML([
    { t: 'Doc', k: 'no', fmt: d => '<span class="mono">' + esc(d.no) + '</span>' },
    { t: 'Date', k: 'date', fmt: d => fmtDate(d.date) },
    { t: 'Due', k: 'due', fmt: d => fmtDate(d.due) },
    { t: 'Status', k: 's', fmt: d => statusPill(docStatus(d, isCust ? 'invoice' : 'bill')) },
    { t: 'Total', k: 't', cls: 'num', fmt: d => money(docTotals(d).total, d.currency) },
    { t: 'Balance', k: 'b', cls: 'num', fmt: d => money(docTotals(d).balance, d.currency) }
  ], docs.slice().sort((a, b) => a.date < b.date ? 1 : -1), { emptyTitle: 'No transactions yet' })}</div>`;
  openModal({
    title: c.name, size: 'xl', body,
    footer: '<button class="btn" data-close>Close</button><button class="btn" id="cStmt">Statement</button><button class="btn" id="cEdit">Edit</button><button class="btn pri" id="cNew">New ' + (isCust ? 'invoice' : 'bill') + '</button>',
    onOpen: root => {
      $('#cEdit', root).addEventListener('click', () => { closeModal(); contactModal(c.kind, c); });
      $('#cNew', root).addEventListener('click', () => { closeModal(); const d = blankDoc(isCust ? 'invoice' : 'bill'); d[isCust ? 'customerId' : 'vendorId'] = c.id; docEditor(isCust ? 'invoice' : 'bill', d); });
      $('#cStmt', root).addEventListener('click', () => { closeModal(); statementModal(c); });
    }
  });
}
function statementModal(c) {
  const isCust = c.kind === 'customer';
  const docs = (isCust ? DB.invoices.filter(i => i.customerId === c.id) : DB.bills.filter(b => b.vendorId === c.id)).filter(d => !['draft', 'void'].includes(d.status));
  const ev = [];
  docs.forEach(d => {
    ev.push({ date: d.date, ref: d.no, desc: (isCust ? 'Invoice' : 'Bill') + ' ' + d.no, charge: docTotals(d).total, credit: 0 });
    (d.payments || []).forEach(p => ev.push({ date: p.date, ref: p.ref || p.method, desc: 'Payment — ' + p.method, charge: 0, credit: p.amount }));
  });
  ev.sort((a, b) => a.date < b.date ? -1 : 1);
  let run = 0;
  ev.forEach(e => { run = r2(run + e.charge - e.credit); e.bal = run; });
  const body = '<div class="docpaper" id="printDoc"><div class="docgrid"><div><div style="font-family:var(--disp);font-size:19px;font-weight:700">' + esc(DB.company.name) + '</div><div class="sub mono" style="font-size:12px">' + esc(DB.company.addr1) + '<br>' + esc(DB.company.city) + ', ' + esc(DB.company.state) + ' ' + esc(DB.company.zip) + '</div></div>' +
    '<div style="text-align:right"><div class="lbl">Statement of account</div><div style="font-family:var(--mono);font-size:15px;margin-top:4px">' + fmtDate(today()) + '</div><div style="margin-top:8px" class="lbl">Balance</div><div style="font-family:var(--mono);font-size:24px;font-weight:600">' + money(run) + '</div></div></div>' +
    '<div style="margin-top:20px"><div class="lbl">Account</div><div style="font-weight:600;margin-top:4px">' + esc(c.name) + '</div><div class="sub">' + esc(c.email || '') + '</div></div>' +
    tableHTML([{ t: 'Date', k: 'date', fmt: e => fmtDate(e.date) }, { t: 'Reference', k: 'ref' }, { t: 'Description', k: 'desc' },
    { t: 'Charges', k: 'charge', cls: 'num', fmt: e => e.charge ? money(e.charge) : '' },
    { t: 'Payments', k: 'credit', cls: 'num', fmt: e => e.credit ? money(e.credit) : '' },
    { t: 'Balance', k: 'bal', cls: 'num', fmt: e => money(e.bal) }], ev, { foot: { desc: 'Balance due', bal: money(run) } }) + '</div>';
  openModal({ title: 'Statement — ' + c.name, size: 'xl', body, footer: '<button class="btn" data-close>Close</button><button class="btn pri" id="sPrint">Print / PDF</button>', onOpen: r => $('#sPrint', r).addEventListener('click', () => printNode(r)) });
}
function contactsPage(kind) {
  const f = LISTF['ct_' + kind] || (LISTF['ct_' + kind] = { q: '' });
  let rows = DB.contacts.filter(c => c.kind === kind);
  if (f.q) rows = rows.filter(c => (c.name + ' ' + (c.email || '') + ' ' + (c.city || '')).toLowerCase().includes(f.q.toLowerCase()));
  rows.sort(by('name'));
  const isCust = kind === 'customer';
  const bal = r2(sum(rows, c => isCust ? customerBalance(c.id) : vendorBalance(c.id)));
  let h = page(isCust ? 'Customers' : 'Vendors', (isCust ? 'People who owe you money' : 'Suppliers you buy from') + ' · ' + money(bal) + ' outstanding',
    '<button class="btn" id="cExp">Export CSV</button><button class="btn pri" id="cNew">New ' + kind + '</button>');
  h += '<div class="flexrow mb noprint"><input id="cQ" type="text" placeholder="Search ' + kind + 's" style="max-width:300px" value="' + esc(f.q) + '"></div>';
  h += '<div class="card">' + tableHTML([
    { t: 'Name', k: 'name', fmt: c => '<b>' + esc(c.name) + '</b>' + (c.active === false ? ' <span class="tag">inactive</span>' : '') },
    { t: 'Contact', k: 'contact', fmt: c => esc(c.contact || '') },
    { t: 'Email', k: 'email', fmt: c => '<span class="sub">' + esc(c.email || '') + '</span>' },
    { t: 'Location', k: 'city', fmt: c => esc((c.city || '') + (c.state ? ', ' + c.state : '')) },
    { t: 'Terms', k: 'terms', fmt: c => 'Net ' + c.terms },
    { t: isCust ? 'Open receivable' : 'Open payable', k: 'b', cls: 'num', fmt: c => moneyCell(isCust ? customerBalance(c.id) : vendorBalance(c.id)) },
    { t: '', k: 'a', cls: 'num', w: '92px', fmt: () => rowActs([['view', ic.eye, 'Open'], ['edit', ic.edit, 'Edit'], ['del', ic.trash, 'Delete']]) }
  ], rows, { rowClick: 1, foot: { name: 'Total', b: money(bal) }, emptyTitle: 'No ' + kind + 's found' }) + '</div>';
  $('#view').innerHTML = h;
  bindRows($('#view'), rows, c => contactView(c));
  $$('#view tr[data-row]').forEach(tr => {
    const c = rows[Number(tr.dataset.row)];
    $$('[data-act]', tr).forEach(b => b.addEventListener('click', e => {
      e.stopPropagation();
      const a = b.dataset.act;
      if (a === 'view') contactView(c); if (a === 'edit') contactModal(kind, c);
      if (a === 'del') confirmDlg('Delete ' + c.name, 'Existing documents keep their history but will show an unknown party.', () => { DB.contacts = DB.contacts.filter(x => x.id !== c.id); save('Deleted ' + kind + ' ' + c.name); render(); });
    }));
  });
  $('#cNew').addEventListener('click', () => contactModal(kind));
  $('#cExp').addEventListener('click', () => exportCSV(kind + 's', [{ t: 'Name', k: 'name' }, { t: 'Contact', k: 'contact' }, { t: 'Email', k: 'email' }, { t: 'Phone', k: 'phone' }, { t: 'City', k: 'city' }, { t: 'Terms', k: 'terms' }, { t: 'Balance', raw: c => isCust ? customerBalance(c.id) : vendorBalance(c.id) }], rows));
  const q = $('#cQ'); q.addEventListener('input', () => { f.q = q.value; render(); setTimeout(() => $('#cQ').focus(), 0); });
}
const view_customers = () => contactsPage('customer');
const view_vendors = () => contactsPage('vendor');

/* ============================ items & inventory ============================ */
function itemModal(it) {
  const f = [
    { k: 'sku', t: 'SKU / code', req: 1 }, { k: 'name', t: 'Name', req: 1 },
    { k: 'type', t: 'Type', type: 'select', opts: [{ v: 'inventory', t: 'Inventory item' }, { v: 'service', t: 'Service' }, { v: 'noninventory', t: 'Non-inventory' }] },
    { k: 'unit', t: 'Unit', def: 'ea' },
    { k: 'price', t: 'Sale price', type: 'money' }, { k: 'cost', t: 'Cost', type: 'money' },
    { k: 'incomeAccount', t: 'Income account', type: 'select', opts: accOpts(a => a.type === 'Income') },
    { k: 'expenseAccount', t: 'Expense / COGS account', type: 'select', opts: accOpts(a => ['COGS', 'Expense'].includes(a.type)) },
    { k: 'taxId', t: 'Default tax', type: 'select', opts: DB.taxRates.map(t => ({ v: t.id, t: t.name })) },
    { k: 'reorder', t: 'Reorder point', type: 'number' },
    { k: 'opening', t: 'Opening quantity', type: 'number', hint: 'Only used before any transactions exist' },
    { k: 'description', t: 'Description', type: 'textarea', w: 'full' },
    { k: 'trackQty', t: 'Track quantity on hand', type: 'checkbox' },
    { k: 'active', t: 'Active', type: 'checkbox' }
  ];
  formModal(it ? 'Edit item' : 'New item', f, it || { active: true, trackQty: true, type: 'inventory', unit: 'ea', taxId: DB.settings.defaultTaxId, incomeAccount: accId(A.SALES), expenseAccount: accId(A.COGS) }, v => {
    v.assetAccount = accId(A.INV);
    if (it) Object.assign(it, v); else DB.items.push(Object.assign({ id: uid('i') }, v));
    repostAll(); save((it ? 'Updated' : 'Added') + ' item ' + v.name); render(); toast('Item saved');
  });
}
function view_items() {
  const rows = DB.items.slice().sort(by('sku'));
  const value = inventoryValue();
  let h = page('Products & services', 'Everything you sell, with cost, price and stock cover',
    '<button class="btn" id="iExp">Export CSV</button><button class="btn pri" id="iNew">New item</button>');
  h += '<div class="grid g4 mb">' +
    '<div class="kpi"><div class="lbl">Items</div><div class="v">' + rows.length + '</div><div class="d">' + rows.filter(i => i.trackQty).length + ' stocked</div></div>' +
    '<div class="kpi"><div class="lbl">Inventory value</div><div class="v">' + money(value) + '</div><div class="d">at average cost</div></div>' +
    '<div class="kpi"><div class="lbl">Below reorder</div><div class="v">' + lowStock().length + '</div><div class="d">needs purchasing</div></div>' +
    '<div class="kpi"><div class="lbl">Avg gross margin</div><div class="v">' + pct(sum(rows.filter(i => i.price), i => (i.price - i.cost) / i.price * 100) / Math.max(1, rows.filter(i => i.price).length)) + '</div><div class="d">across the catalogue</div></div></div>';
  h += '<div class="card">' + tableHTML([
    { t: 'SKU', k: 'sku', w: '92px', fmt: i => '<span class="mono">' + esc(i.sku) + '</span>' },
    { t: 'Name', k: 'name', fmt: i => '<b>' + esc(i.name) + '</b>' },
    { t: 'Type', k: 'type', w: '96px', fmt: i => '<span class="tag">' + esc(i.type) + '</span>' },
    { t: 'Income account', k: 'ia', fmt: i => '<span class="sub">' + esc(accName(i.incomeAccount)) + '</span>' },
    { t: 'Cost', k: 'cost', cls: 'num', fmt: i => money(i.cost) },
    { t: 'Price', k: 'price', cls: 'num', fmt: i => money(i.price) },
    { t: 'Margin', k: 'm', cls: 'num', fmt: i => i.price ? pct((i.price - i.cost) / i.price * 100) : '—' },
    { t: 'On hand', k: 'q', cls: 'num', fmt: i => i.trackQty ? '<b class="' + (stockOf(i.id) <= i.reorder ? 'neg' : '') + '">' + qty(stockOf(i.id)) + '</b>' : '—' },
    { t: 'Value', k: 'v', cls: 'num', fmt: i => i.trackQty ? money(stockOf(i.id) * i.cost) : '—' },
    { t: '', k: 'a', cls: 'num', w: '70px', fmt: () => rowActs([['edit', ic.edit, 'Edit'], ['del', ic.trash, 'Delete']]) }
  ], rows, { rowClick: 1, foot: { name: 'Inventory at cost', v: money(value) }, emptyTitle: 'No items yet' }) + '</div>';
  $('#view').innerHTML = h;
  bindRows($('#view'), rows, i => itemModal(i));
  $$('#view tr[data-row]').forEach(tr => {
    const i = rows[Number(tr.dataset.row)];
    $$('[data-act]', tr).forEach(b => b.addEventListener('click', e => {
      e.stopPropagation();
      if (b.dataset.act === 'edit') itemModal(i);
      else confirmDlg('Delete ' + i.name, 'Documents already using this item keep their lines.', () => { DB.items = DB.items.filter(x => x.id !== i.id); save('Deleted item ' + i.name); render(); });
    }));
  });
  $('#iNew').addEventListener('click', () => itemModal());
  $('#iExp').addEventListener('click', () => exportCSV('items', [{ t: 'SKU', k: 'sku' }, { t: 'Name', k: 'name' }, { t: 'Type', k: 'type' }, { t: 'Cost', k: 'cost' }, { t: 'Price', k: 'price' }, { t: 'On hand', raw: i => stockOf(i.id) }], rows));
}
function view_stock() {
  const rows = DB.items.filter(i => i.trackQty);
  let h = page('Stock control', 'Quantities on hand, movement history and adjustments',
    '<button class="btn" id="sAdj">New adjustment</button><button class="btn pri" id="sPO">Create purchase order</button>');
  h += '<div class="card mb"><div class="card-h"><h2>Stock on hand</h2><div class="acts"><span class="lbl">Valued at average cost</span></div></div>' + tableHTML([
    { t: 'SKU', k: 'sku', fmt: i => '<span class="mono">' + esc(i.sku) + '</span>' },
    { t: 'Item', k: 'name' },
    { t: 'On hand', k: 'q', cls: 'num', fmt: i => qty(stockOf(i.id)) },
    { t: 'Reorder at', k: 'reorder', cls: 'num' },
    { t: 'Cover', k: 'c', w: '160px', fmt: i => { const p = Math.min(100, stockOf(i.id) / Math.max(1, i.reorder * 3) * 100); return '<div class="bar"><i style="width:' + p + '%;background:' + (stockOf(i.id) <= i.reorder ? 'var(--red)' : 'var(--green)') + '"></i></div>'; } },
    { t: 'Unit cost', k: 'cost', cls: 'num', fmt: i => money(i.cost) },
    { t: 'Value', k: 'v', cls: 'num', fmt: i => money(stockOf(i.id) * i.cost) },
    { t: 'Status', k: 's', fmt: i => stockOf(i.id) <= 0 ? '<span class="pill p-over">Out of stock</span>' : stockOf(i.id) <= i.reorder ? '<span class="pill p-part">Reorder</span>' : '<span class="pill p-paid">OK</span>' }
  ], rows, { foot: { name: 'Total inventory asset', v: money(inventoryValue()) }, rowClick: 1 }) + '</div>';
  const adj = (DB.adjustments || []).slice().sort((a, b) => a.date < b.date ? 1 : -1);
  h += '<div class="card"><div class="card-h"><h2>Adjustments</h2></div>' + tableHTML([
    { t: 'Date', k: 'date', fmt: a => fmtDate(a.date) },
    { t: 'Item', k: 'i', fmt: a => esc((item(a.itemId) || {}).name || '—') },
    { t: 'Quantity', k: 'qty', cls: 'num', fmt: a => (a.qty > 0 ? '+' : '') + qty(a.qty) },
    { t: 'Reason', k: 'reason' },
    { t: 'Offset account', k: 'o', fmt: a => esc(accName(a.offsetAccount)) },
    { t: 'Value', k: 'v', cls: 'num', fmt: a => money(a.qty * (item(a.itemId) || { cost: 0 }).cost) }
  ], adj, { emptyTitle: 'No adjustments recorded' }) + '</div>';
  $('#view').innerHTML = h;
  bindRows($('#view'), rows, i => stockCard(i));
  $('#sAdj').addEventListener('click', () => adjustModal());
  $('#sPO').addEventListener('click', () => docEditor('po'));
}
function stockCard(it) {
  const mv = [];
  DB.bills.forEach(b => b.lines.forEach(l => { if (l.itemId === it.id && !['draft', 'void'].includes(b.status)) mv.push({ date: b.date, doc: b.no, type: 'Purchase', qty: Number(l.qty), rate: l.price }); }));
  DB.invoices.forEach(i => i.lines.forEach(l => { if (l.itemId === it.id && !['draft', 'void'].includes(i.status)) mv.push({ date: i.date, doc: i.no, type: 'Sale', qty: -Number(l.qty), rate: l.price }); }));
  (DB.adjustments || []).forEach(a => { if (a.itemId === it.id) mv.push({ date: a.date, doc: 'ADJ', type: 'Adjustment', qty: Number(a.qty), rate: it.cost }); });
  mv.sort((a, b) => a.date < b.date ? -1 : 1);
  let run = it.opening || 0;
  mv.forEach(m => { run += m.qty; m.bal = run; });
  openModal({
    title: it.sku + ' · ' + it.name, size: 'wide',
    body: '<div class="grid g4 mb"><div class="kpi"><div class="lbl">On hand</div><div class="v">' + qty(stockOf(it.id)) + '</div></div>' +
      '<div class="kpi"><div class="lbl">Value</div><div class="v">' + money(stockOf(it.id) * it.cost) + '</div></div>' +
      '<div class="kpi"><div class="lbl">Sold to date</div><div class="v">' + qty(-sum(mv.filter(m => m.type === 'Sale'), m => m.qty)) + '</div></div>' +
      '<div class="kpi"><div class="lbl">Margin</div><div class="v">' + (it.price ? pct((it.price - it.cost) / it.price * 100) : '—') + '</div></div></div>' +
      '<div class="card">' + tableHTML([{ t: 'Date', k: 'date', fmt: m => fmtDate(m.date) }, { t: 'Document', k: 'doc', fmt: m => '<span class="mono">' + esc(m.doc) + '</span>' },
      { t: 'Type', k: 'type' }, { t: 'Qty', k: 'qty', cls: 'num', fmt: m => (m.qty > 0 ? '+' : '') + qty(m.qty) },
      { t: 'Unit', k: 'rate', cls: 'num', fmt: m => money(m.rate) }, { t: 'Running', k: 'bal', cls: 'num', fmt: m => qty(m.bal) }], mv, { emptyTitle: 'No movement yet' }) + '</div>',
    footer: '<button class="btn" data-close>Close</button><button class="btn" id="skAdj">Adjust stock</button><button class="btn pri" id="skEdit">Edit item</button>',
    onOpen: r => { $('#skEdit', r).addEventListener('click', () => { closeModal(); itemModal(it); }); $('#skAdj', r).addEventListener('click', () => { closeModal(); adjustModal(it.id); }); }
  });
}
function adjustModal(itemId) {
  formModal('Inventory adjustment', [
    { k: 'date', t: 'Date', type: 'date', def: today() },
    { k: 'itemId', t: 'Item', type: 'select', opts: DB.items.filter(i => i.trackQty).map(i => ({ v: i.id, t: i.sku + ' · ' + i.name })), def: itemId },
    { k: 'qty', t: 'Quantity change', type: 'number', hint: 'Negative to write stock off' },
    { k: 'offsetAccount', t: 'Offset account', type: 'select', opts: accOpts(a => ['Expense', 'COGS'].includes(a.type)), def: accId(A.WOFF) },
    { k: 'reason', t: 'Reason', w: 'full', def: 'Stock count adjustment' }
  ], {}, v => {
    const a = Object.assign({ id: uid('adj') }, v);
    DB.adjustments = DB.adjustments || []; DB.adjustments.push(a); postAdjustment(a);
    save('Inventory adjusted'); render(); toast('Adjustment posted');
  });
}

/* ============================ banking ============================ */
function view_banking() {
  const accts = bankAccounts();
  const busiest = accts.slice().sort((a, b) => DB.bankTx.filter(t => t.accountId === b.id).length - DB.bankTx.filter(t => t.accountId === a.id).length)[0] || {};
  const sel = LISTF.bankSel && accts.find(a => a.id === LISTF.bankSel) ? LISTF.bankSel : busiest.id;
  LISTF.bankSel = sel;
  const tx = DB.bankTx.filter(t => t.accountId === sel).sort((a, b) => a.date < b.date ? 1 : -1);
  let run = balance(sel, null, '2999-12-31').raw;
  const rows = tx.map(t => { const o = Object.assign({}, t, { bal: run }); run = r2(run - t.amount); return o; });
  const uncat = DB.bankTx.filter(t => !t.matched).length;

  let h = page('Bank & cards', 'Feeds, registers and transfers · ' + uncat + ' transactions to categorise',
    '<button class="btn" id="bImp">Import CSV</button><button class="btn" id="bXfer">Transfer funds</button><button class="btn pri" id="bAdd">Add transaction</button>');
  h += '<div class="grid mb" style="grid-template-columns:repeat(auto-fit,minmax(210px,1fr))">' + accts.map(a => {
    const b = balance(a.id, null, today()).balance;
    const un = DB.bankTx.filter(t => t.accountId === a.id && !t.reconciled).length;
    return '<div class="kpi" style="cursor:pointer;border-color:' + (a.id === sel ? 'var(--green)' : 'var(--rule)') + '" data-bank="' + a.id + '">' +
      '<div class="lbl">' + esc(a.name) + '</div><div class="v">' + money(b) + '</div><div class="d">' + esc(a.subtype) + ' · <b>' + un + '</b> uncleared</div></div>';
  }).join('') + '</div>';
  h += '<div class="card"><div class="card-h"><h2>' + esc(acc(sel).name) + ' register</h2><div class="acts"><a class="btn sm" href="#/reconcile">Reconcile</a></div></div>' +
    tableHTML([
      { t: 'Date', k: 'date', w: '110px', fmt: t => fmtDate(t.date) },
      { t: 'Description', k: 'desc', fmt: t => esc(t.desc) },
      { t: 'Category', k: 'm', fmt: t => t.matched ? '<span class="tag">' + esc(t.matched.split(':')[0]) + '</span>' : '<button class="btn sm" data-cat>Categorise</button>' },
      { t: 'Cleared', k: 'r', w: '80px', fmt: t => t.reconciled ? '<span class="pill p-paid">R</span>' : '<span class="pill p-draft">—</span>' },
      { t: 'Deposit', k: 'd', cls: 'num', fmt: t => t.amount > 0 ? money(t.amount) : '' },
      { t: 'Withdrawal', k: 'w', cls: 'num', fmt: t => t.amount < 0 ? money(-t.amount) : '' },
      { t: 'Balance', k: 'bal', cls: 'num', fmt: t => moneyCell(t.bal) },
      { t: '', k: 'a', cls: 'num', w: '50px', fmt: () => rowActs([['del', ic.trash, 'Delete']]) }
    ], rows, { emptyTitle: 'No transactions on this account' }) + '</div>';
  $('#view').innerHTML = h;
  $$('[data-bank]').forEach(e => e.addEventListener('click', () => { LISTF.bankSel = e.dataset.bank; render(); }));
  $$('#view tbody tr').forEach((tr, i) => {
    const t = rows[i]; if (!t) return;
    const cat = $('[data-cat]', tr); if (cat) cat.addEventListener('click', () => categorise(t));
    const del = $('[data-act="del"]', tr); if (del) del.addEventListener('click', () => confirmDlg('Delete transaction', 'Remove this line from the register?', () => { DB.bankTx = DB.bankTx.filter(x => x.id !== t.id); clearPostings('manual', t.id); save('Deleted bank line'); render(); }));
  });
  $('#bAdd').addEventListener('click', () => bankTxModal(sel));
  $('#bXfer').addEventListener('click', () => transferModal());
  $('#bImp').addEventListener('click', () => importModal(sel));
}
function categorise(t) {
  formModal('Categorise — ' + t.desc, [
    { k: 'accountId', t: 'Account', type: 'select', opts: accOpts(a => a.type !== 'Equity' || true), def: t.amount < 0 ? accId('6900') : accId(A.OTHINC) },
    { k: 'memo', t: 'Memo', def: t.desc, w: 'full' },
    { k: 'contactId', t: 'Contact', type: 'select', opts: [{ v: '', t: '— none —' }].concat(DB.contacts.map(c => ({ v: c.id, t: c.name }))) }
  ], {}, v => {
    const L = t.amount < 0
      ? [{ accountId: v.accountId, debit: -t.amount, credit: 0, memo: v.memo }, { accountId: t.accountId, debit: 0, credit: -t.amount, memo: v.memo }]
      : [{ accountId: t.accountId, debit: t.amount, credit: 0, memo: v.memo }, { accountId: v.accountId, debit: 0, credit: t.amount, memo: v.memo }];
    DB.journal.push(mkJ('manual', t.id, t.date, v.memo, L));
    t.matched = 'manual:' + t.id;
    save('Categorised bank transaction'); render(); toast('Posted to ' + acc(v.accountId).name);
  });
}
function bankTxModal(accountId) {
  formModal('Add transaction', [
    { k: 'date', t: 'Date', type: 'date', def: today() },
    { k: 'accountId', t: 'Bank account', type: 'select', opts: bankAccounts().map(a => ({ v: a.id, t: a.name })), def: accountId },
    { k: 'desc', t: 'Description', w: 'full', req: 1 },
    { k: 'kind', t: 'Type', type: 'select', opts: [{ v: 'out', t: 'Money out' }, { v: 'in', t: 'Money in' }] },
    { k: 'amount', t: 'Amount', type: 'money', req: 1 },
    { k: 'category', t: 'Category', type: 'select', opts: accOpts(a => a.type !== 'Equity' || true) }
  ], {}, v => {
    const amt = v.kind === 'out' ? -Math.abs(v.amount) : Math.abs(v.amount);
    const t = { id: uid('bt'), accountId: v.accountId, date: v.date, desc: v.desc, amount: amt, matched: '', reconciled: false };
    DB.bankTx.push(t);
    const L = amt < 0 ? [{ accountId: v.category, debit: -amt, credit: 0, memo: v.desc }, { accountId: v.accountId, debit: 0, credit: -amt, memo: v.desc }]
      : [{ accountId: v.accountId, debit: amt, credit: 0, memo: v.desc }, { accountId: v.category, debit: 0, credit: amt, memo: v.desc }];
    DB.journal.push(mkJ('manual', t.id, v.date, v.desc, L));
    t.matched = 'manual:' + t.id;
    save('Added bank transaction'); render(); toast('Transaction added');
  });
}
function transferModal() {
  formModal('Transfer funds', [
    { k: 'date', t: 'Date', type: 'date', def: today() },
    { k: 'amount', t: 'Amount', type: 'money', req: 1 },
    { k: 'from', t: 'From account', type: 'select', opts: bankAccounts().map(a => ({ v: a.id, t: a.name })) },
    { k: 'to', t: 'To account', type: 'select', opts: bankAccounts().map(a => ({ v: a.id, t: a.name })) },
    { k: 'memo', t: 'Memo', w: 'full', def: 'Internal transfer' }
  ], {}, v => {
    if (v.from === v.to) { toast('Choose two different accounts', true); return; }
    const id = uid('tr');
    DB.journal.push(mkJ('transfer', id, v.date, v.memo, [
      { accountId: v.to, debit: v.amount, credit: 0, memo: v.memo },
      { accountId: v.from, debit: 0, credit: v.amount, memo: v.memo }
    ]));
    DB.bankTx.push({ id: uid('bt'), accountId: v.from, date: v.date, desc: 'TRANSFER TO ' + acc(v.to).name, amount: -v.amount, matched: 'transfer:' + id, reconciled: false });
    DB.bankTx.push({ id: uid('bt'), accountId: v.to, date: v.date, desc: 'TRANSFER FROM ' + acc(v.from).name, amount: v.amount, matched: 'transfer:' + id, reconciled: false });
    save('Transferred ' + money(v.amount)); render(); toast('Transfer recorded');
  });
}
function importModal(accountId) {
  openModal({
    title: 'Import bank statement',
    body: '<div class="hint mb">Paste CSV with columns <b>date, description, amount</b>. Negative amounts are money out. A header row is optional.</div>' +
      formHTML([{ k: 'accountId', t: 'Import into', type: 'select', opts: bankAccounts().map(a => ({ v: a.id, t: a.name })), w: 'full' },
      { k: 'csv', t: 'CSV data', type: 'textarea', w: 'full', attr: ' style="min-height:180px;font-family:var(--mono);font-size:12px"' }], { accountId }),
    footer: '<button class="btn" data-close>Cancel</button><button class="btn" id="impDemo">Paste sample</button><button class="btn pri" id="impGo">Import</button>',
    onOpen: root => {
      $('#impDemo', root).addEventListener('click', () => {
        $('[data-k="csv"]', root).value = 'date,description,amount\n' + today() + ',CUSTOMER DEPOSIT 8812,2450.00\n' + addDays(today(), -1) + ',OFFICE DEPOT,-142.19\n' + addDays(today(), -2) + ',FUEL STOP 221,-88.40';
      });
      $('#impGo', root).addEventListener('click', () => {
        const v = readForm(root);
        const lines = v.csv.split(/\r?\n/).filter(l => l.trim());
        let n = 0;
        lines.forEach(l => {
          const p = l.split(',').map(s => s.trim().replace(/^"|"$/g, ''));
          if (p.length < 3 || isNaN(Number(p[2]))) return;
          DB.bankTx.push({ id: uid('bt'), accountId: v.accountId, date: p[0], desc: p[1], amount: Number(p[2]), matched: '', reconciled: false });
          n++;
        });
        closeModal(); save('Imported ' + n + ' bank lines'); render(); toast(n + ' transactions imported — categorise them next');
      });
    }
  });
}
function view_reconcile() {
  const accts = bankAccounts();
  const busiest = accts.slice().sort((a, b) => DB.bankTx.filter(t => t.accountId === b.id && !t.reconciled).length - DB.bankTx.filter(t => t.accountId === a.id && !t.reconciled).length)[0] || {};
  const R = LISTF.rec || (LISTF.rec = { acct: busiest.id, end: today(), bal: 0, checked: {} });
  const tx = DB.bankTx.filter(t => t.accountId === R.acct && t.date <= R.end).sort(by('date'));
  const cleared = tx.filter(t => t.reconciled || R.checked[t.id]);
  const clearedTotal = r2(sum(cleared, t => t.amount));
  const opening = r2(sum(DB.bankTx.filter(t => t.accountId === R.acct && t.reconciled && t.date <= R.end), t => t.amount) - sum(tx.filter(t => t.reconciled), t => t.amount));
  const diff = r2(Number(R.bal) - clearedTotal);
  let h = page('Reconcile', 'Tick off items that appear on your statement until the difference is zero',
    '<button class="btn" id="rFinish">Finish reconciliation</button>');
  h += '<div class="grid g4 mb">' +
    '<div class="card"><div class="card-b">' + formHTML([{ k: 'acct', t: 'Account', type: 'select', opts: accts.map(a => ({ v: a.id, t: a.name })) }], R) + '</div></div>' +
    '<div class="card"><div class="card-b">' + formHTML([{ k: 'end', t: 'Statement date', type: 'date' }], R) + '</div></div>' +
    '<div class="card"><div class="card-b">' + formHTML([{ k: 'bal', t: 'Statement ending balance', type: 'money' }], R) + '</div></div>' +
    '<div class="kpi" style="display:flex;flex-direction:column;justify-content:center;align-items:center;gap:8px">' +
    (Math.abs(diff) < 0.005 ? '<span class="stamp">Reconciled</span>' : '<span class="stamp bad">Out ' + money(diff) + '</span>') +
    '<div class="d">Cleared ' + money(clearedTotal) + ' of ' + tx.length + ' lines</div></div></div>';
  h += '<div class="card">' + tableHTML([
    { t: '', k: 'c', w: '40px', fmt: t => '<input type="checkbox" data-tick="' + t.id + '"' + (t.reconciled || R.checked[t.id] ? ' checked' : '') + (t.reconciled ? ' disabled' : '') + '>' },
    { t: 'Date', k: 'date', fmt: t => fmtDate(t.date) },
    { t: 'Description', k: 'desc' },
    { t: 'Deposit', k: 'd', cls: 'num', fmt: t => t.amount > 0 ? money(t.amount) : '' },
    { t: 'Withdrawal', k: 'w', cls: 'num', fmt: t => t.amount < 0 ? money(-t.amount) : '' },
    { t: 'Status', k: 's', fmt: t => t.reconciled ? '<span class="pill p-paid">Previously cleared</span>' : '' }
  ], tx, { emptyTitle: 'Nothing to reconcile on this account' }) + '</div>';
  const prev = (DB.reconciliations || []).filter(x => x.accountId === R.acct);
  if (prev.length) h += '<div class="card mt"><div class="card-h"><h2>Completed reconciliations</h2></div>' + tableHTML([
    { t: 'Statement date', k: 'end', fmt: r => fmtDate(r.end) }, { t: 'Ending balance', k: 'bal', cls: 'num', fmt: r => money(r.bal) },
    { t: 'Items cleared', k: 'n', cls: 'num' }, { t: 'Completed', k: 'ts', fmt: r => fmtDate(r.ts.slice(0, 10)) }, { t: 'By', k: 'user' }], prev.slice().reverse()) + '</div>';
  $('#view').innerHTML = h;
  $$('[data-k]').forEach(el => el.addEventListener('change', () => { R[el.dataset.k] = el.type === 'number' ? Number(el.value) : el.value; render(); }));
  $$('[data-tick]').forEach(cb => cb.addEventListener('change', () => { R.checked[cb.dataset.tick] = cb.checked; render(); }));
  $('#rFinish').addEventListener('click', () => {
    if (Math.abs(diff) >= 0.005) { toast('Difference must be zero — currently ' + money(diff), true); return; }
    const ids = Object.keys(R.checked).filter(k => R.checked[k]);
    DB.bankTx.forEach(t => { if (ids.includes(t.id)) t.reconciled = true; });
    DB.reconciliations = DB.reconciliations || [];
    DB.reconciliations.push({ id: uid('rec'), accountId: R.acct, end: R.end, bal: Number(R.bal), n: ids.length, ts: new Date().toISOString(), user: currentUser().name });
    R.checked = {}; save('Reconciled ' + acc(R.acct).name + ' to ' + R.end); render(); toast('Reconciliation complete');
  });
}

/* ============================ chart of accounts / journal / ledger ============================ */
function accountModal(a) {
  formModal(a ? 'Edit account' : 'New account', [
    { k: 'code', t: 'Code', req: 1 }, { k: 'name', t: 'Name', req: 1 },
    { k: 'type', t: 'Type', type: 'select', opts: Object.keys(TYPES) },
    { k: 'subtype', t: 'Detail type', def: 'Operating' },
    { k: 'description', t: 'Description', type: 'textarea', w: 'full' },
    { k: 'active', t: 'Active', type: 'checkbox', w: 'full' }
  ], a || { active: true, type: 'Expense' }, v => {
    if (a) Object.assign(a, v); else DB.accounts.push(Object.assign({ id: uid('ac') }, v));
    save((a ? 'Updated' : 'Added') + ' account ' + v.code); render(); toast('Account saved');
  });
}
function view_coa() {
  const P = period();
  const bals = balanceAll(null, P.to);
  const rows = DB.accounts.slice().sort(by('code'));
  let h = page('Chart of accounts', DB.accounts.length + ' accounts · balances as at ' + fmtDate(P.to),
    '<button class="btn" id="aExp">Export CSV</button><button class="btn pri" id="aNew">New account</button>');
  const groups = Object.keys(TYPES).sort((a, b) => TYPES[a].order - TYPES[b].order);
  h += '<div class="card">' + '<div class="tblwrap"><table class="tbl"><thead><tr><th style="width:80px">Code</th><th>Account</th><th>Detail type</th><th>Status</th><th class="num" style="width:130px">Balance</th><th style="width:70px"></th></tr></thead><tbody>';
  groups.forEach(g => {
    const gr = rows.filter(a => a.type === g);
    if (!gr.length) return;
    const t = r2(sum(gr, a => (bals[a.id] || {}).balance || 0));
    h += '<tr style="background:var(--ink);color:#fff"><td colspan="4" class="mono" style="font-size:11px;letter-spacing:.16em;text-transform:uppercase">' + g + '</td><td class="num mono">' + money(t) + '</td><td></td></tr>';
    gr.forEach(a => {
      const b = (bals[a.id] || {}).balance || 0;
      h += '<tr data-acc="' + a.id + '" class="clickable"><td class="mono">' + esc(a.code) + '</td><td>' + esc(a.name) + '</td><td class="sub">' + esc(a.subtype || '') + '</td>' +
        '<td>' + (a.active === false ? '<span class="pill p-draft">Inactive</span>' : '<span class="pill p-paid">Active</span>') + '</td>' +
        '<td class="num">' + money(b) + '</td><td>' + rowActs([['edit', ic.edit, 'Edit'], ['led', ic.ledger, 'Ledger']]) + '</td></tr>';
    });
  });
  h += '</tbody></table></div></div>';
  $('#view').innerHTML = h;
  $$('#view tr[data-acc]').forEach(tr => {
    const a = DB.accounts.find(x => x.id === tr.dataset.acc);
    tr.addEventListener('click', e => { if (!e.target.closest('button')) { LISTF.ledgerAcc = a.id; go('ledger'); } });
    $$('[data-act]', tr).forEach(b => b.addEventListener('click', e => {
      e.stopPropagation();
      if (b.dataset.act === 'edit') accountModal(a); else { LISTF.ledgerAcc = a.id; go('ledger'); }
    }));
  });
  $('#aNew').addEventListener('click', () => accountModal());
  $('#aExp').addEventListener('click', () => exportCSV('chart-of-accounts', [{ t: 'Code', k: 'code' }, { t: 'Name', k: 'name' }, { t: 'Type', k: 'type' }, { t: 'Detail', k: 'subtype' }, { t: 'Balance', raw: a => (bals[a.id] || {}).balance || 0 }], rows));
}
function journalModal(j) {
  const lines = j ? clone(j.lines) : [{ accountId: accId(A.BANK), debit: 0, credit: 0, memo: '' }, { accountId: accId('6900'), debit: 0, credit: 0, memo: '' }];
  const opts = accOpts();
  const body = formHTML([{ k: 'date', t: 'Date', type: 'date' }, { k: 'no', t: 'Entry number', attr: ' readonly' }, { k: 'memo', t: 'Memo', w: 'full' }],
    { date: j ? j.date : today(), no: j ? j.no : 'auto', memo: j ? j.memo : '' }) +
    '<div class="mt scroll-x"><table class="lines" id="jl"><thead><tr><th style="width:240px">Account</th><th>Memo</th><th style="width:120px" class="num">Debit</th><th style="width:120px" class="num">Credit</th><th style="width:26px"></th></tr></thead><tbody></tbody></table>' +
    '<button class="btn sm mt" id="jAdd">+ Add line</button></div>' +
    '<div class="flexrow mt" style="justify-content:flex-end;gap:18px"><div id="jStamp"></div><div class="totbox" id="jTot"></div></div>';
  openModal({
    title: j ? 'Edit journal entry' : 'New journal entry', size: 'wide', body,
    footer: '<button class="btn" data-close>Cancel</button><button class="btn pri" id="jSave">Post entry</button>',
    onOpen: root => {
      const tb = $('#jl tbody', root);
      function draw() {
        tb.innerHTML = lines.map((l, i) => '<tr data-i="' + i + '"><td><select data-l="accountId">' + opts.map(o => '<option value="' + o.v + '"' + (o.v === l.accountId ? ' selected' : '') + '>' + esc(o.t) + '</option>').join('') + '</select></td>' +
          '<td><input data-l="memo" value="' + esc(l.memo || '') + '"></td>' +
          '<td><input data-l="debit" type="number" step="0.01" value="' + (l.debit || '') + '"></td>' +
          '<td><input data-l="credit" type="number" step="0.01" value="' + (l.credit || '') + '"></td>' +
          '<td><button class="iconbtn" data-del>×</button></td></tr>').join('');
        $$('tr[data-i]', tb).forEach(tr => {
          const i = Number(tr.dataset.i);
          $$('[data-l]', tr).forEach(inp => ['input', 'change'].forEach(ev => inp.addEventListener(ev, () => { lines[i][inp.dataset.l] = inp.type === 'number' ? Number(inp.value) : inp.value; tot(); })));
          $('[data-del]', tr).addEventListener('click', () => { lines.splice(i, 1); draw(); });
        });
        tot();
      }
      function tot() {
        const d = r2(sum(lines, l => l.debit)), c = r2(sum(lines, l => l.credit));
        $('#jTot', root).innerHTML = '<div class="totrow"><span>Total debits</span><span>' + money(d) + '</span></div><div class="totrow"><span>Total credits</span><span>' + money(c) + '</span></div><div class="totrow grand"><span>Difference</span><span>' + money(d - c) + '</span></div>';
        $('#jStamp', root).innerHTML = Math.abs(d - c) < 0.005 && d > 0 ? '<span class="stamp">In balance</span>' : '<span class="stamp bad">Out of balance</span>';
      }
      draw();
      $('#jAdd', root).addEventListener('click', () => { lines.push({ accountId: opts[0].v, debit: 0, credit: 0, memo: '' }); draw(); });
      $('#jSave', root).addEventListener('click', () => {
        const v = readForm(root);
        const d = r2(sum(lines, l => l.debit)), c = r2(sum(lines, l => l.credit));
        if (Math.abs(d - c) > 0.005 || !d) { toast('Debits must equal credits', true); return; }
        if (j) { j.date = v.date; j.memo = v.memo; j.lines = lines.map(l => ({ accountId: l.accountId, debit: r2(l.debit), credit: r2(l.credit), memo: l.memo })); }
        else DB.journal.push(mkJ('manual', uid('mj'), v.date, v.memo, lines));
        save((j ? 'Edited' : 'Posted') + ' journal entry'); closeModal(); render(); toast('Journal entry posted');
      });
    }
  });
}
function view_journal() {
  const P = period();
  const f = LISTF.jf || (LISTF.jf = { q: '', src: 'all' });
  let rows = DB.journal.filter(j => j.date >= P.from && j.date <= P.to);
  if (f.src !== 'all') rows = rows.filter(j => j.source === f.src);
  if (f.q) rows = rows.filter(j => (j.no + ' ' + j.memo + ' ' + j.lines.map(l => accName(l.accountId)).join(' ')).toLowerCase().includes(f.q.toLowerCase()));
  rows = rows.slice().sort((a, b) => a.date < b.date ? 1 : -1);
  const srcs = ['all'].concat(Array.from(new Set(DB.journal.map(j => j.source))));
  let h = page('Journal entries', 'Every posting in the general journal · ' + periodLabel(),
    '<button class="btn" id="jExp">Export CSV</button><button class="btn pri" id="jNew">New entry</button>');
  h += '<div class="flexrow mb noprint"><select id="jSrc" style="max-width:180px">' + srcs.map(s => '<option' + (f.src === s ? ' selected' : '') + '>' + s + '</option>').join('') + '</select>' +
    '<input id="jQ" type="text" placeholder="Search entries" style="max-width:280px" value="' + esc(f.q) + '"><div class="lbl" style="margin-left:auto">' + rows.length + ' entries</div></div>';
  h += '<div class="card"><div class="tblwrap"><table class="tbl"><thead><tr><th style="width:100px">Entry</th><th style="width:110px">Date</th><th>Memo / account</th><th style="width:110px">Source</th><th class="num" style="width:120px">Debit</th><th class="num" style="width:120px">Credit</th><th style="width:70px"></th></tr></thead><tbody>';
  rows.forEach((j, ji) => {
    const d = sum(j.lines, l => l.debit);
    h += '<tr data-j="' + j.id + '"><td class="mono">' + esc(j.no) + '</td><td>' + fmtDate(j.date) + '</td><td><b>' + esc(j.memo) + '</b></td><td><span class="tag">' + esc(j.source) + '</span></td><td class="num">' + money(d) + '</td><td class="num">' + money(sum(j.lines, l => l.credit)) + '</td><td>' + (j.source === 'manual' ? rowActs([['edit', ic.edit, 'Edit'], ['del', ic.trash, 'Delete']]) : '') + '</td></tr>';
    j.lines.forEach(l => h += '<tr style="background:#fff"><td></td><td></td><td style="padding-left:26px" class="sub">' + esc(accName(l.accountId)) + (l.memo ? ' — ' + esc(l.memo) : '') + '</td><td></td><td class="num sub">' + (l.debit ? money(l.debit) : '') + '</td><td class="num sub">' + (l.credit ? money(l.credit) : '') + '</td><td></td></tr>');
  });
  h += '</tbody></table></div></div>';
  $('#view').innerHTML = h;
  $$('#view tr[data-j]').forEach(tr => {
    const j = DB.journal.find(x => x.id === tr.dataset.j);
    $$('[data-act]', tr).forEach(b => b.addEventListener('click', e => {
      e.stopPropagation();
      if (b.dataset.act === 'edit') journalModal(j);
      else confirmDlg('Delete entry ' + j.no, 'This permanently removes the posting.', () => { DB.journal = DB.journal.filter(x => x.id !== j.id); save('Deleted journal entry ' + j.no); render(); });
    }));
  });
  $('#jNew').addEventListener('click', () => journalModal());
  $('#jSrc').addEventListener('change', e => { f.src = e.target.value; render(); });
  const q = $('#jQ'); q.addEventListener('input', () => { f.q = q.value; render(); setTimeout(() => $('#jQ').focus(), 0); });
  $('#jExp').addEventListener('click', () => {
    const flat = [];
    rows.forEach(j => j.lines.forEach(l => flat.push({ no: j.no, date: j.date, memo: j.memo, account: accName(l.accountId), debit: l.debit, credit: l.credit })));
    exportCSV('journal', [{ t: 'Entry', k: 'no' }, { t: 'Date', k: 'date' }, { t: 'Memo', k: 'memo' }, { t: 'Account', k: 'account' }, { t: 'Debit', k: 'debit' }, { t: 'Credit', k: 'credit' }], flat);
  });
}
function view_ledger() {
  const P = period();
  const id = LISTF.ledgerAcc && acc(LISTF.ledgerAcc).id ? LISTF.ledgerAcc : DB.accounts[0].id;
  LISTF.ledgerAcc = id;
  const a = acc(id);
  const open = balance(id, null, addDays(P.from, -1)).balance;
  const nat = TYPES[a.type].normal;
  let run = open;
  const rows = jLines(P.from, P.to).filter(l => l.accountId === id).map(l => {
    run = r2(run + (nat === 'D' ? l.debit - l.credit : l.credit - l.debit));
    return Object.assign({}, l, { run });
  });
  let h = page('General ledger', 'Transaction detail by account · ' + periodLabel(), '<button class="btn" id="gExp">Export CSV</button>');
  h += '<div class="split"><div class="listnav" style="max-height:70vh;overflow:auto">' +
    DB.accounts.slice().sort(by('code')).map(x => '<button data-a="' + x.id + '"' + (x.id === id ? ' class="on"' : '') + '><span class="mono" style="font-size:11px">' + esc(x.code) + '</span> ' + esc(x.name) + '</button>').join('') + '</div><div>';
  h += '<div class="card"><div class="card-h"><h2>' + esc(a.code + ' · ' + a.name) + '</h2><div class="acts"><span class="tag">' + esc(a.type) + '</span><span class="tag">Normal ' + (nat === 'D' ? 'debit' : 'credit') + '</span></div></div>' +
    tableHTML([
      { t: 'Date', k: 'date', w: '110px', fmt: l => fmtDate(l.date) },
      { t: 'Entry', k: 'no', w: '90px', fmt: l => '<span class="mono">' + esc(l.no) + '</span>' },
      { t: 'Memo', k: 'memo2', fmt: l => esc(l.memo2) + (l.memo ? ' <span class="sub">— ' + esc(l.memo) + '</span>' : '') },
      { t: 'Source', k: 'source', w: '100px', fmt: l => '<span class="tag">' + esc(l.source) + '</span>' },
      { t: 'Debit', k: 'debit', cls: 'num', fmt: l => l.debit ? money(l.debit) : '' },
      { t: 'Credit', k: 'credit', cls: 'num', fmt: l => l.credit ? money(l.credit) : '' },
      { t: 'Balance', k: 'run', cls: 'num', fmt: l => moneyCell(l.run) }
    ], rows, {
      foot: { date: 'Closing balance', debit: money(sum(rows, l => l.debit)), credit: money(sum(rows, l => l.credit)), run: money(run) },
      emptyTitle: 'No activity in this period'
    }) + '<div class="card-b sub">Opening balance ' + money(open) + ' at ' + fmtDate(P.from) + '</div></div></div></div>';
  $('#view').innerHTML = h;
  $$('[data-a]').forEach(b => b.addEventListener('click', () => { LISTF.ledgerAcc = b.dataset.a; render(); }));
  $('#gExp').addEventListener('click', () => exportCSV('ledger-' + a.code, [{ t: 'Date', k: 'date' }, { t: 'Entry', k: 'no' }, { t: 'Memo', k: 'memo2' }, { t: 'Debit', k: 'debit' }, { t: 'Credit', k: 'credit' }, { t: 'Balance', k: 'run' }], rows));
}

/* ============================ fixed assets ============================ */
function assetModal(a) {
  formModal(a ? 'Edit asset' : 'New fixed asset', [
    { k: 'name', t: 'Asset name', req: 1, w: 'full' },
    { k: 'date', t: 'Acquired', type: 'date', def: today() },
    { k: 'cost', t: 'Cost', type: 'money', req: 1 },
    { k: 'salvage', t: 'Salvage value', type: 'money' },
    { k: 'life', t: 'Useful life (months)', type: 'number', def: 60 },
    { k: 'method', t: 'Method', type: 'select', opts: [{ v: 'straight', t: 'Straight line' }, { v: 'ddb', t: 'Double declining' }] },
    { k: 'account', t: 'Asset account', type: 'select', opts: accOpts(x => x.subtype === 'Fixed Asset') }
  ], a || { method: 'straight', life: 60, account: accId(A.EQUIP) }, v => {
    if (a) Object.assign(a, v); else DB.assets.push(Object.assign({ id: uid('fa'), disposed: false }, v));
    save((a ? 'Updated' : 'Added') + ' asset ' + v.name); render(); toast('Asset saved');
  });
}
function view_assets() {
  const rows = DB.assets;
  const cost = r2(sum(rows, a => a.cost)), dep = r2(sum(rows, a => depTotal(a))), nbv = r2(cost - dep);
  let h = page('Fixed assets', 'Capital items, depreciation schedules and book values',
    '<button class="btn" id="fRun">Run depreciation</button><button class="btn pri" id="fNew">New asset</button>');
  h += '<div class="grid g4 mb">' +
    '<div class="kpi"><div class="lbl">Assets at cost</div><div class="v">' + money(cost) + '</div><div class="d">' + rows.length + ' items</div></div>' +
    '<div class="kpi"><div class="lbl">Accumulated depreciation</div><div class="v">' + money(dep) + '</div><div class="d">posted to 1510</div></div>' +
    '<div class="kpi"><div class="lbl">Net book value</div><div class="v">' + money(nbv) + '</div><div class="d">' + pct(cost ? nbv / cost * 100 : 0) + ' remaining</div></div>' +
    '<div class="kpi"><div class="lbl">Monthly charge</div><div class="v">' + money(sum(rows.filter(a => !a.disposed && bookValue(a) > a.salvage), a => monthlyDep(a))) + '</div><div class="d">at current schedule</div></div></div>';
  h += '<div class="card">' + tableHTML([
    { t: 'Asset', k: 'name', fmt: a => '<b>' + esc(a.name) + '</b>' + (a.disposed ? ' <span class="tag">disposed</span>' : '') },
    { t: 'Acquired', k: 'date', fmt: a => fmtDate(a.date) },
    { t: 'Method', k: 'method', fmt: a => a.method === 'straight' ? 'Straight line' : 'Declining' },
    { t: 'Life', k: 'life', cls: 'num', fmt: a => a.life + ' mo' },
    { t: 'Cost', k: 'cost', cls: 'num', fmt: a => money(a.cost) },
    { t: 'Monthly', k: 'm', cls: 'num', fmt: a => money(monthlyDep(a)) },
    { t: 'Accum. dep.', k: 'ad', cls: 'num', fmt: a => money(depTotal(a)) },
    { t: 'Book value', k: 'bv', cls: 'num', fmt: a => money(bookValue(a)) },
    { t: '', k: 'x', cls: 'num', w: '92px', fmt: () => rowActs([['edit', ic.edit, 'Edit'], ['disp', ic.money, 'Dispose'], ['del', ic.trash, 'Delete']]) }
  ], rows, { rowClick: 1, foot: { name: 'Totals', cost: money(cost), ad: money(dep), bv: money(nbv) }, emptyTitle: 'No fixed assets recorded' }) + '</div>';
  $('#view').innerHTML = h;
  bindRows($('#view'), rows, a => assetModal(a));
  $$('#view tr[data-row]').forEach(tr => {
    const a = rows[Number(tr.dataset.row)];
    $$('[data-act]', tr).forEach(b => b.addEventListener('click', e => {
      e.stopPropagation();
      const k = b.dataset.act;
      if (k === 'edit') assetModal(a);
      if (k === 'disp') disposeModal(a);
      if (k === 'del') confirmDlg('Delete ' + a.name, 'Depreciation already posted stays in the ledger.', () => { DB.assets = DB.assets.filter(x => x.id !== a.id); save('Deleted asset'); render(); });
    }));
  });
  $('#fNew').addEventListener('click', () => assetModal());
  $('#fRun').addEventListener('click', () => depreciationRun());
}
function depreciationRun() {
  formModal('Run depreciation', [
    { k: 'date', t: 'Post as at', type: 'date', def: monthEnd(today()) },
    { k: 'note', t: 'Memo', def: 'Monthly depreciation charge', w: 'full' }
  ], {}, v => {
    let n = 0, tot = 0;
    DB.assets.forEach(a => {
      if (a.disposed) return;
      const exists = DB.journal.some(j => j.source === 'depreciation' && j.ref === a.id && j.date === v.date);
      if (exists) return;
      const amt = Math.min(monthlyDep(a), Math.max(0, bookValue(a) - (a.salvage || 0)));
      if (amt <= 0) return;
      DB.journal.push(mkJ('depreciation', a.id, v.date, v.note + ' — ' + a.name, [
        { accountId: accId(A.DEPR), debit: amt, credit: 0, memo: a.name },
        { accountId: accId(A.ACCDEP), debit: 0, credit: amt, memo: a.name }
      ]));
      n++; tot += amt;
    });
    save('Depreciation run posted'); render();
    toast(n ? 'Posted ' + money(tot) + ' across ' + n + ' assets' : 'Nothing to post for that date');
  });
}
function disposeModal(a) {
  formModal('Dispose ' + a.name, [
    { k: 'date', t: 'Disposal date', type: 'date', def: today() },
    { k: 'proceeds', t: 'Sale proceeds', type: 'money' },
    { k: 'account', t: 'Proceeds to', type: 'select', opts: accOpts(x => x.subtype === 'Bank') }
  ], {}, v => {
    const nbv = bookValue(a), gain = r2(v.proceeds - nbv);
    DB.journal.push(mkJ('manual', uid('disp'), v.date, 'Disposal of ' + a.name, [
      { accountId: v.account, debit: v.proceeds, credit: 0, memo: 'Proceeds' },
      { accountId: accId(A.ACCDEP), debit: depTotal(a), credit: 0, memo: 'Remove accumulated depreciation' },
      { accountId: a.account, debit: 0, credit: a.cost, memo: 'Remove asset at cost' },
      { accountId: accId(A.OTHINC), debit: gain < 0 ? -gain : 0, credit: gain > 0 ? gain : 0, memo: gain >= 0 ? 'Gain on disposal' : 'Loss on disposal' }
    ]));
    a.disposed = true;
    save('Disposed asset ' + a.name); render(); toast((gain >= 0 ? 'Gain' : 'Loss') + ' of ' + money(Math.abs(gain)) + ' recorded');
  });
}

/* ============================ budgets ============================ */
function view_budgets() {
  const years = Object.keys(DB.budgets).length ? Object.keys(DB.budgets) : [String(new Date().getFullYear())];
  const y = LISTF.budgetYear || years[years.length - 1];
  LISTF.budgetYear = y;
  DB.budgets[y] = DB.budgets[y] || {};
  const B = DB.budgets[y];
  const accts = DB.accounts.filter(a => ['Income', 'COGS', 'Expense'].includes(a.type)).sort(by('code'));
  const mons = Array.from({ length: 12 }, (_, i) => y + '-' + String(i + 1).padStart(2, '0') + '-01');
  let h = page('Budgets', 'Plan by account and month, then track against the ledger',
    '<select id="byY" style="width:auto;display:inline-block">' + years.concat(years.includes(String(new Date().getFullYear() + 1)) ? [] : [String(new Date().getFullYear() + 1)]).map(v => '<option' + (v === y ? ' selected' : '') + '>' + v + '</option>').join('') + '</select>' +
    '<button class="btn" id="byFill">Copy actuals</button><button class="btn pri" id="byRep">Budget vs actual</button>');
  h += '<div class="card"><div class="tblwrap"><table class="tbl"><thead><tr><th style="min-width:220px">Account</th>' +
    mons.map(m => '<th class="num">' + monthLabel(m) + '</th>').join('') + '<th class="num">Year</th></tr></thead><tbody>';
  let colTot = Array(12).fill(0);
  accts.forEach(a => {
    const arr = B[a.id] || Array(12).fill(0);
    B[a.id] = arr;
    arr.forEach((v, i) => colTot[i] += Number(v) || 0);
    h += '<tr><td><span class="mono" style="font-size:11px">' + esc(a.code) + '</span> ' + esc(a.name) + '</td>' +
      arr.map((v, i) => '<td class="num"><input type="number" step="1" data-b="' + a.id + '" data-m="' + i + '" value="' + (Number(v) || 0) + '" style="width:88px;padding:3px 5px;border-color:transparent;background:transparent"></td>').join('') +
      '<td class="num"><b>' + money(sum(arr)) + '</b></td></tr>';
  });
  h += '</tbody><tfoot><tr><td class="dbl">Total</td>' + colTot.map(v => '<td class="num dbl">' + money(v) + '</td>').join('') + '<td class="num dbl">' + money(sum(colTot)) + '</td></tr></tfoot></table></div></div>';
  $('#view').innerHTML = h;
  $$('[data-b]').forEach(inp => inp.addEventListener('change', () => {
    DB.budgets[y][inp.dataset.b][Number(inp.dataset.m)] = Number(inp.value) || 0;
    save('Updated budget'); render();
  }));
  $('#byY').addEventListener('change', e => { LISTF.budgetYear = e.target.value; render(); });
  $('#byRep').addEventListener('click', () => { LISTF.report = 'budget'; go('reports'); });
  $('#byFill').addEventListener('click', () => confirmDlg('Copy actuals into budget', 'Replaces ' + y + ' budget figures with last year\'s actuals.', () => {
    accts.forEach(a => {
      DB.budgets[y][a.id] = mons.map(m => balance(a.id, addMonths(m, -12), monthEnd(addMonths(m, -12))).balance);
    });
    save('Budget seeded from actuals'); render(); toast('Budget updated from actuals');
  }, 'Copy'));
}

/* ============================ payroll ============================ */
function employeeModal(e) {
  formModal(e ? 'Edit employee' : 'New employee', [
    { k: 'name', t: 'Name', req: 1 }, { k: 'title', t: 'Job title' },
    { k: 'email', t: 'Email', type: 'email' }, { k: 'hired', t: 'Start date', type: 'date', def: today() },
    { k: 'payType', t: 'Pay type', type: 'select', opts: [{ v: 'salary', t: 'Salary (annual)' }, { v: 'hourly', t: 'Hourly' }] },
    { k: 'rate', t: 'Rate', type: 'money' },
    { k: 'freq', t: 'Frequency', type: 'select', opts: ['Monthly', 'Semi-monthly', 'Bi-weekly', 'Weekly'] },
    { k: 'taxRate', t: 'Withholding %', type: 'number', def: 20 },
    { k: 'benefits', t: 'Benefit deduction', type: 'money' },
    { k: 'active', t: 'Active', type: 'checkbox' }
  ], e || { active: true, payType: 'salary', freq: 'Monthly', taxRate: 20 }, v => {
    if (e) Object.assign(e, v); else DB.employees.push(Object.assign({ id: uid('e') }, v));
    save((e ? 'Updated' : 'Added') + ' employee ' + v.name); render(); toast('Employee saved');
  });
}
function view_payroll() {
  const emps = DB.employees;
  const runs = DB.payruns.slice().sort((a, b) => a.payDate < b.payDate ? 1 : -1);
  const ytdFrom = fyStart();
  const ytd = runs.filter(r => r.payDate >= ytdFrom);
  const gross = r2(sum(ytd, r => sum(r.lines, l => l.gross)));
  const taxes = r2(sum(ytd, r => sum(r.lines, l => l.tax + l.employerTax)));
  const net = r2(sum(ytd, r => sum(r.lines, l => l.net)));
  let h = page('Payroll', 'Employees, pay runs and the liabilities they create',
    '<button class="btn" id="pEmp">New employee</button><button class="btn pri" id="pRun">Run payroll</button>');
  h += '<div class="grid g4 mb">' +
    '<div class="kpi"><div class="lbl">Headcount</div><div class="v">' + emps.filter(e => e.active !== false).length + '</div><div class="d">active employees</div></div>' +
    '<div class="kpi"><div class="lbl">Gross pay YTD</div><div class="v">' + money(gross) + '</div><div class="d">' + ytd.length + ' pay runs</div></div>' +
    '<div class="kpi"><div class="lbl">Taxes & withholdings</div><div class="v">' + money(taxes) + '</div><div class="d">held in 2300</div></div>' +
    '<div class="kpi"><div class="lbl">Net paid</div><div class="v">' + money(net) + '</div><div class="d">cash out</div></div></div>';
  h += '<div class="card mb"><div class="card-h"><h2>Employees</h2></div>' + tableHTML([
    { t: 'Name', k: 'name', fmt: e => '<b>' + esc(e.name) + '</b>' },
    { t: 'Title', k: 'title' }, { t: 'Since', k: 'hired', fmt: e => fmtDate(e.hired) },
    { t: 'Pay', k: 'p', fmt: e => e.payType === 'salary' ? money(e.rate) + ' / yr' : money(e.rate) + ' / hr' },
    { t: 'Frequency', k: 'freq' }, { t: 'Withholding', k: 'taxRate', cls: 'num', fmt: e => e.taxRate + '%' },
    { t: 'Benefits', k: 'benefits', cls: 'num', fmt: e => money(e.benefits) },
    { t: 'Gross YTD', k: 'g', cls: 'num', fmt: e => money(sum(ytd, r => sum(r.lines.filter(l => l.employeeId === e.id), l => l.gross))) },
    { t: '', k: 'a', cls: 'num', w: '50px', fmt: () => rowActs([['edit', ic.edit, 'Edit']]) }
  ], emps, { rowClick: 1, emptyTitle: 'No employees yet' }) + '</div>';
  h += '<div class="card"><div class="card-h"><h2>Pay runs</h2></div>' + tableHTML([
    { t: 'Run', k: 'no', fmt: r => '<span class="mono">' + esc(r.no) + '</span>' },
    { t: 'Period', k: 'period' }, { t: 'Pay date', k: 'payDate', fmt: r => fmtDate(r.payDate) },
    { t: 'Employees', k: 'n', cls: 'num', fmt: r => r.lines.length },
    { t: 'Gross', k: 'g', cls: 'num', fmt: r => money(sum(r.lines, l => l.gross)) },
    { t: 'Withheld', k: 't', cls: 'num', fmt: r => money(sum(r.lines, l => l.tax)) },
    { t: 'Net', k: 'nt', cls: 'num', fmt: r => money(sum(r.lines, l => l.net)) },
    { t: 'Status', k: 's', fmt: r => statusPill(r.status) }
  ], runs, { rowClick: 1, emptyTitle: 'No pay runs yet' }) + '</div>';
  $('#view').innerHTML = h;
  const tables = $$('#view .card');
  bindRows(tables[0], emps, e => employeeModal(e));
  bindRows(tables[1], runs, r => payrunView(r));
  $('#pEmp').addEventListener('click', () => employeeModal());
  $('#pRun').addEventListener('click', () => payrunModal());
}
function payrunModal() {
  const emps = DB.employees.filter(e => e.active !== false);
  const T = today();
  const body = formHTML([
    { k: 'start', t: 'Period start', type: 'date', def: monthStart(T) },
    { k: 'end', t: 'Period end', type: 'date', def: monthEnd(T) },
    { k: 'payDate', t: 'Pay date', type: 'date', def: monthEnd(T) },
    { k: 'account', t: 'Pay from', type: 'select', opts: accOpts(a => a.subtype === 'Bank') }
  ], {}) +
    '<div class="mt scroll-x"><table class="lines" id="prl"><thead><tr><th>Employee</th><th class="num">Hours</th><th class="num">Gross</th><th class="num">Withholding</th><th class="num">Benefits</th><th class="num">Employer tax</th><th class="num">Net</th></tr></thead><tbody>' +
    emps.map(e => {
      const g = e.payType === 'salary' ? r2(e.rate / 12) : r2(e.rate * 160);
      return '<tr data-e="' + e.id + '"><td>' + esc(e.name) + '<div class="sub" style="font-size:11px">' + esc(e.title) + '</div></td>' +
        '<td><input data-p="hours" type="number" value="' + (e.payType === 'hourly' ? 160 : 0) + '"' + (e.payType === 'salary' ? ' disabled' : '') + '></td>' +
        '<td><input data-p="gross" type="number" step="0.01" value="' + g + '"></td>' +
        '<td><input data-p="tax" type="number" step="0.01" value="' + r2(g * e.taxRate / 100) + '"></td>' +
        '<td><input data-p="benefits" type="number" step="0.01" value="' + (e.benefits || 0) + '"></td>' +
        '<td><input data-p="employerTax" type="number" step="0.01" value="' + r2(g * .0765) + '"></td>' +
        '<td class="num" data-net>' + money(g - g * e.taxRate / 100 - (e.benefits || 0)) + '</td></tr>';
    }).join('') + '</tbody></table></div><div class="totbox mt" id="prTot"></div>';
  openModal({
    title: 'Run payroll', size: 'xl', body,
    footer: '<button class="btn" data-close>Cancel</button><button class="btn pri" id="prGo">Post pay run</button>',
    onOpen: root => {
      function calc() {
        let g = 0, t = 0, n = 0, er = 0;
        $$('tr[data-e]', root).forEach(tr => {
          const gv = Number($('[data-p="gross"]', tr).value) || 0, tv = Number($('[data-p="tax"]', tr).value) || 0,
            bv = Number($('[data-p="benefits"]', tr).value) || 0, ev = Number($('[data-p="employerTax"]', tr).value) || 0;
          const nv = r2(gv - tv - bv);
          $('[data-net]', tr).textContent = money(nv);
          g += gv; t += tv; n += nv; er += ev;
        });
        $('#prTot', root).innerHTML = '<div class="totrow"><span>Gross</span><span>' + money(g) + '</span></div>' +
          '<div class="totrow"><span>Withholdings</span><span>' + money(t) + '</span></div>' +
          '<div class="totrow"><span>Employer taxes</span><span>' + money(er) + '</span></div>' +
          '<div class="totrow grand"><span>Net to pay</span><span>' + money(n) + '</span></div>';
      }
      $$('[data-p]', root).forEach(i => i.addEventListener('input', () => {
        const tr = i.closest('tr');
        if (i.dataset.p === 'hours') {
          const e = DB.employees.find(x => x.id === tr.dataset.e);
          const g = r2((Number(i.value) || 0) * e.rate);
          $('[data-p="gross"]', tr).value = g;
          $('[data-p="tax"]', tr).value = r2(g * e.taxRate / 100);
          $('[data-p="employerTax"]', tr).value = r2(g * .0765);
        }
        calc();
      }));
      calc();
      $('#prGo', root).addEventListener('click', () => {
        const v = readForm(root);
        const lines = $$('tr[data-e]', root).map(tr => {
          const g = Number($('[data-p="gross"]', tr).value) || 0, t = Number($('[data-p="tax"]', tr).value) || 0,
            b = Number($('[data-p="benefits"]', tr).value) || 0, e = Number($('[data-p="employerTax"]', tr).value) || 0;
          return { employeeId: tr.dataset.e, gross: g, tax: t, benefits: b, employerTax: e, net: r2(g - t - b) };
        }).filter(l => l.gross > 0);
        if (!lines.length) { toast('Nothing to pay', true); return; }
        const pr = { id: uid('pr'), no: 'PR-' + (100 + DB.payruns.length + 1), period: monthLabel(v.start), start: v.start, end: v.end, payDate: v.payDate, lines, status: 'posted', account: v.account };
        DB.payruns.push(pr); postPayrun(pr);
        DB.bankTx.push({ id: uid('bt'), accountId: v.account, date: v.payDate, desc: 'PAYROLL ' + pr.no, amount: -r2(sum(lines, l => l.net)), matched: 'payroll:' + pr.id, reconciled: false });
        closeModal(); save('Posted payroll ' + pr.no); render(); toast('Payroll posted — ' + money(sum(lines, l => l.net)) + ' net');
      });
    }
  });
}
function payrunView(r) {
  openModal({
    title: 'Pay run ' + r.no + ' — ' + r.period, size: 'wide',
    body: '<div id="printDoc">' + tableHTML([
      { t: 'Employee', k: 'e', fmt: l => esc((DB.employees.find(e => e.id === l.employeeId) || {}).name || '—') },
      { t: 'Gross', k: 'gross', cls: 'num', fmt: l => money(l.gross) },
      { t: 'Withholding', k: 'tax', cls: 'num', fmt: l => money(l.tax) },
      { t: 'Benefits', k: 'benefits', cls: 'num', fmt: l => money(l.benefits) },
      { t: 'Employer tax', k: 'employerTax', cls: 'num', fmt: l => money(l.employerTax) },
      { t: 'Net pay', k: 'net', cls: 'num', fmt: l => money(l.net) }
    ], r.lines, {
      foot: {
        e: 'Totals', gross: money(sum(r.lines, l => l.gross)), tax: money(sum(r.lines, l => l.tax)),
        benefits: money(sum(r.lines, l => l.benefits)), employerTax: money(sum(r.lines, l => l.employerTax)), net: money(sum(r.lines, l => l.net))
      }
    }) + '</div>',
    footer: '<button class="btn" data-close>Close</button><button class="btn" id="prPrint">Print</button><button class="btn danger" id="prDel">Delete run</button>',
    onOpen: root => {
      $('#prPrint', root).addEventListener('click', () => printNode(root));
      $('#prDel', root).addEventListener('click', () => confirmDlg('Delete pay run', 'Removes the run and its ledger entries.', () => {
        DB.payruns = DB.payruns.filter(x => x.id !== r.id); clearPostings('payroll', r.id);
        closeAllModals(); save('Deleted pay run ' + r.no); render();
      }));
    }
  });
}

/* ============================ projects & time ============================ */
function projectModal(p) {
  formModal(p ? 'Edit project' : 'New project', [
    { k: 'name', t: 'Project name', req: 1, w: 'full' },
    { k: 'customerId', t: 'Customer', type: 'select', opts: DB.contacts.filter(c => c.kind === 'customer').map(c => ({ v: c.id, t: c.name })) },
    { k: 'budget', t: 'Budget', type: 'money' },
    { k: 'rate', t: 'Default billing rate', type: 'money' },
    { k: 'start', t: 'Start date', type: 'date', def: today() },
    { k: 'status', t: 'Status', type: 'select', opts: ['active', 'on hold', 'complete'] }
  ], p || { status: 'active' }, v => {
    if (p) Object.assign(p, v); else DB.projects.push(Object.assign({ id: uid('p') }, v));
    save((p ? 'Updated' : 'Created') + ' project ' + v.name); render(); toast('Project saved');
  });
}
function timeModal(t) {
  formModal(t ? 'Edit time entry' : 'Log time', [
    { k: 'date', t: 'Date', type: 'date', def: today() },
    { k: 'employeeId', t: 'Person', type: 'select', opts: DB.employees.map(e => ({ v: e.id, t: e.name })) },
    { k: 'projectId', t: 'Project', type: 'select', opts: DB.projects.map(p => ({ v: p.id, t: p.name })) },
    { k: 'hours', t: 'Hours', type: 'number' },
    { k: 'rate', t: 'Billing rate', type: 'money' },
    { k: 'memo', t: 'Notes', w: 'full' },
    { k: 'billable', t: 'Billable', type: 'checkbox' }
  ], t || { billable: true, hours: 1 }, v => {
    v.customerId = (project(v.projectId) || {}).customerId || '';
    if (t) Object.assign(t, v); else DB.timeEntries.push(Object.assign({ id: uid('te'), invoiced: false }, v));
    save('Logged time'); render(); toast('Time entry saved');
  });
}
function view_projects() {
  const rows = DB.projects.map(p => {
    const te = DB.timeEntries.filter(t => t.projectId === p.id);
    const hours = r2(sum(te, t => t.hours));
    const billed = r2(sum(DB.invoices.filter(i => i.projectId === p.id && !['draft', 'void'].includes(i.status)), i => docTotals(i).total));
    const wip = r2(sum(te.filter(t => t.billable && !t.invoiced), t => t.hours * t.rate));
    const cost = r2(sum(DB.expenses.filter(e => e.customerId === p.customerId && e.billable), e => e.amount));
    return { p, hours, billed, wip, cost, pctB: p.budget ? billed / p.budget * 100 : 0 };
  });
  const te = DB.timeEntries.slice().sort((a, b) => a.date < b.date ? 1 : -1);
  let h = page('Projects & time', 'Job costing, work in progress and billable hours',
    '<button class="btn" id="tNew">Log time</button><button class="btn" id="tBill">Invoice billable time</button><button class="btn pri" id="pNew">New project</button>');
  h += '<div class="grid g4 mb">' +
    '<div class="kpi"><div class="lbl">Active projects</div><div class="v">' + rows.filter(r => r.p.status === 'active').length + '</div></div>' +
    '<div class="kpi"><div class="lbl">Hours logged</div><div class="v">' + qty(sum(te, t => t.hours)) + '</div><div class="d">' + qty(sum(te.filter(t => t.billable), t => t.hours)) + ' billable</div></div>' +
    '<div class="kpi"><div class="lbl">Unbilled WIP</div><div class="v">' + money(sum(rows, r => r.wip)) + '</div><div class="d">ready to invoice</div></div>' +
    '<div class="kpi"><div class="lbl">Invoiced on projects</div><div class="v">' + money(sum(rows, r => r.billed)) + '</div></div></div>';
  h += '<div class="card mb"><div class="card-h"><h2>Projects</h2></div>' + tableHTML([
    { t: 'Project', k: 'n', fmt: r => '<b>' + esc(r.p.name) + '</b>' },
    { t: 'Customer', k: 'c', fmt: r => esc(contact(r.p.customerId).name) },
    { t: 'Status', k: 's', fmt: r => statusPill(r.p.status === 'on hold' ? 'draft' : r.p.status) },
    { t: 'Budget', k: 'b', cls: 'num', fmt: r => money(r.p.budget) },
    { t: 'Invoiced', k: 'i', cls: 'num', fmt: r => money(r.billed) },
    { t: 'Used', k: 'u', w: '140px', fmt: r => '<div class="bar"><i style="width:' + Math.min(100, r.pctB) + '%;background:' + (r.pctB > 100 ? 'var(--red)' : 'var(--green)') + '"></i></div>' },
    { t: 'Hours', k: 'h', cls: 'num', fmt: r => qty(r.hours) },
    { t: 'Unbilled WIP', k: 'w', cls: 'num', fmt: r => money(r.wip) }
  ], rows, { rowClick: 1, emptyTitle: 'No projects yet' }) + '</div>';
  h += '<div class="card"><div class="card-h"><h2>Time entries</h2></div>' + tableHTML([
    { t: 'Date', k: 'date', fmt: t => fmtDate(t.date) },
    { t: 'Person', k: 'e', fmt: t => esc((DB.employees.find(e => e.id === t.employeeId) || {}).name || '—') },
    { t: 'Project', k: 'p', fmt: t => esc((project(t.projectId) || {}).name || '—') },
    { t: 'Notes', k: 'memo', fmt: t => '<span class="sub">' + esc(t.memo || '') + '</span>' },
    { t: 'Hours', k: 'hours', cls: 'num', fmt: t => qty(t.hours) },
    { t: 'Rate', k: 'rate', cls: 'num', fmt: t => money(t.rate) },
    { t: 'Value', k: 'v', cls: 'num', fmt: t => money(t.hours * t.rate) },
    { t: 'Billing', k: 'b', fmt: t => t.invoiced ? '<span class="pill p-paid">Invoiced</span>' : t.billable ? '<span class="pill p-open">Billable</span>' : '<span class="pill p-draft">Internal</span>' }
  ], te, { rowClick: 1, emptyTitle: 'No time logged' }) + '</div>';
  $('#view').innerHTML = h;
  const cards = $$('#view .card');
  bindRows(cards[0], rows, r => projectModal(r.p));
  bindRows(cards[1], te, t => timeModal(t));
  $('#pNew').addEventListener('click', () => projectModal());
  $('#tNew').addEventListener('click', () => timeModal());
  $('#tBill').addEventListener('click', () => billTime());
}
function billTime() {
  const pend = DB.timeEntries.filter(t => t.billable && !t.invoiced);
  if (!pend.length) { toast('No unbilled billable time', true); return; }
  const byCust = {};
  pend.forEach(t => { (byCust[t.customerId] = byCust[t.customerId] || []).push(t); });
  const opts = Object.keys(byCust).map(k => ({ v: k, t: contact(k).name + ' — ' + qty(sum(byCust[k], t => t.hours)) + ' h · ' + money(sum(byCust[k], t => t.hours * t.rate)) }));
  formModal('Invoice billable time', [{ k: 'customerId', t: 'Customer', type: 'select', opts, w: 'full' }, { k: 'date', t: 'Invoice date', type: 'date', def: today() }], {}, v => {
    const list = byCust[v.customerId] || [];
    const inv = blankDoc('invoice');
    inv.customerId = v.customerId; inv.date = v.date; inv.due = addDays(v.date, contact(v.customerId).terms || 30);
    inv.status = 'sent'; inv.id = uid('inv'); inv.no = nextNo('invoice');
    inv.lines = list.map(t => ({ id: uid('l'), itemId: '', desc: (project(t.projectId) || {}).name + ' — ' + (t.memo || 'Services') + ' (' + fmtShort(t.date) + ')', qty: t.hours, price: t.rate, discount: 0, taxId: 't1', accountId: accId(A.SERV) }));
    DB.invoices.push(inv); postInvoice(inv);
    list.forEach(t => t.invoiced = true);
    save('Invoiced billable time'); render(); toast('Created ' + inv.no); docView('invoice', inv);
  });
}

/* ============================ recurring ============================ */
function recurringModal(r) {
  const isExp = r ? r.type === 'expense' : false;
  formModal(r ? 'Edit recurring' : 'New recurring template', [
    { k: 'name', t: 'Template name', req: 1, w: 'full' },
    { k: 'type', t: 'Type', type: 'select', opts: [{ v: 'invoice', t: 'Invoice' }, { v: 'expense', t: 'Expense' }] },
    { k: 'customerId', t: 'Customer (invoices)', type: 'select', opts: [{ v: '', t: '— none —' }].concat(DB.contacts.filter(c => c.kind === 'customer').map(c => ({ v: c.id, t: c.name }))) },
    { k: 'vendorId', t: 'Vendor (expenses)', type: 'select', opts: [{ v: '', t: '— none —' }].concat(DB.contacts.filter(c => c.kind === 'vendor').map(c => ({ v: c.id, t: c.name }))) },
    { k: 'amount', t: 'Amount', type: 'money', hint: 'Invoices use the single line below' },
    { k: 'accountId', t: 'Account', type: 'select', opts: accOpts() },
    { k: 'frequency', t: 'Frequency', type: 'select', opts: ['weekly', 'monthly', 'quarterly', 'annually'] },
    { k: 'next', t: 'Next run', type: 'date', def: addMonths(today(), 1) },
    { k: 'active', t: 'Active', type: 'checkbox' }
  ], r || { active: true, type: 'invoice', frequency: 'monthly' }, v => {
    if (r) Object.assign(r, v);
    else {
      const rec = Object.assign({ id: uid('rc') }, v);
      if (v.type === 'invoice') rec.lines = [{ id: uid('l'), itemId: '', desc: v.name, qty: 1, price: v.amount, discount: 0, taxId: DB.settings.defaultTaxId, accountId: v.accountId || accId(A.SERV) }];
      else { rec.payAccountId = accId(A.BANK); }
      DB.recurring.push(rec);
    }
    save('Saved recurring template'); render(); toast('Template saved');
  });
}
function runRecurring(r) {
  const step = { weekly: () => addDays(r.next, 7), monthly: () => addMonths(r.next, 1), quarterly: () => addMonths(r.next, 3), annually: () => addMonths(r.next, 12) };
  if (r.type === 'invoice') {
    const inv = blankDoc('invoice');
    inv.id = uid('inv'); inv.no = nextNo('invoice'); inv.customerId = r.customerId; inv.date = r.next;
    inv.due = addDays(r.next, contact(r.customerId).terms || 30); inv.status = 'sent';
    inv.lines = clone(r.lines).map(l => Object.assign(l, { id: uid('l') }));
    DB.invoices.push(inv); postInvoice(inv);
    toast('Created ' + inv.no);
  } else {
    const e = { id: uid('ex'), date: r.next, vendorId: r.vendorId, payee: contact(r.vendorId).name, accountId: r.accountId, payAccountId: r.payAccountId || accId(A.BANK), amount: r.amount, taxId: 't1', memo: r.name, method: 'ACH', billable: false, customerId: '' };
    DB.expenses.push(e); postExpense(e);
    DB.bankTx.push({ id: uid('bt'), accountId: e.payAccountId, date: e.date, desc: (e.payee || '').toUpperCase() + ' ' + e.memo, amount: -e.amount, matched: 'expense:' + e.id, reconciled: false });
    toast('Recorded ' + money(r.amount));
  }
  r.next = step[r.frequency]();
  save('Ran recurring template ' + r.name); render();
}
function view_recurring() {
  const rows = DB.recurring;
  const due = rows.filter(r => r.active && r.next <= today());
  let h = page('Recurring transactions', 'Templates that generate invoices and expenses on a schedule',
    (due.length ? '<button class="btn pri" id="rcAll">Run ' + due.length + ' due now</button>' : '') + '<button class="btn pri" id="rcNew">New template</button>');
  h += '<div class="card">' + tableHTML([
    { t: 'Template', k: 'name', fmt: r => '<b>' + esc(r.name) + '</b>' },
    { t: 'Type', k: 'type', fmt: r => '<span class="tag">' + esc(r.type) + '</span>' },
    { t: 'Party', k: 'p', fmt: r => esc(contact(r.customerId || r.vendorId).name) },
    { t: 'Frequency', k: 'frequency' },
    { t: 'Next run', k: 'next', fmt: r => fmtDate(r.next) + (r.next <= today() ? ' <span class="pill p-part">due</span>' : '') },
    { t: 'Amount', k: 'a', cls: 'num', fmt: r => money(r.type === 'invoice' ? sum(r.lines || [], l => lineAmount(l)) : r.amount) },
    { t: 'Status', k: 's', fmt: r => r.active ? '<span class="pill p-paid">Active</span>' : '<span class="pill p-draft">Paused</span>' },
    { t: '', k: 'x', cls: 'num', w: '110px', fmt: () => rowActs([['run', ic.repeat, 'Run now'], ['edit', ic.edit, 'Edit'], ['del', ic.trash, 'Delete']]) }
  ], rows, { rowClick: 1, emptyTitle: 'No recurring templates' }) + '</div>';
  $('#view').innerHTML = h;
  bindRows($('#view'), rows, r => recurringModal(r));
  $$('#view tr[data-row]').forEach(tr => {
    const r = rows[Number(tr.dataset.row)];
    $$('[data-act]', tr).forEach(b => b.addEventListener('click', e => {
      e.stopPropagation();
      const k = b.dataset.act;
      if (k === 'run') runRecurring(r);
      if (k === 'edit') recurringModal(r);
      if (k === 'del') confirmDlg('Delete template', 'Documents already generated are kept.', () => { DB.recurring = DB.recurring.filter(x => x.id !== r.id); save('Deleted recurring template'); render(); });
    }));
  });
  $('#rcNew').addEventListener('click', () => recurringModal());
  const all = $('#rcAll'); if (all) all.addEventListener('click', () => { due.forEach(runRecurring); });
}

/* ============================ reports ============================ */
const REPORTS = [
  ['pl', 'Profit & loss', 'Income statement for the period'],
  ['plmonth', 'P&L by month', 'Trend across the last twelve months'],
  ['bs', 'Balance sheet', 'Assets, liabilities and equity as at a date'],
  ['tb', 'Trial balance', 'Every account with debits and credits'],
  ['cf', 'Cash flow statement', 'Where the money actually moved'],
  ['ar', 'A/R ageing summary', 'Who owes you and for how long'],
  ['ap', 'A/P ageing summary', 'What you owe and when it falls due'],
  ['custbal', 'Customer balances', 'Open balance by customer'],
  ['vendbal', 'Vendor balances', 'Open balance by supplier'],
  ['salescust', 'Sales by customer', 'Revenue concentration'],
  ['salesitem', 'Sales by item', 'Units, revenue, cost and margin'],
  ['expcat', 'Expenses by category', 'Operating spend breakdown'],
  ['purchvend', 'Purchases by vendor', 'Supplier spend'],
  ['invval', 'Inventory valuation', 'Quantity and value on hand'],
  ['tax', 'Sales tax summary', 'Collected, paid and net owing'],
  ['budget', 'Budget vs actual', 'Variance by account'],
  ['proj', 'Profit by project', 'Job costing summary'],
  ['gl', 'General ledger detail', 'Every posting, every account'],
  ['audittrail', 'Transaction journal', 'Chronological posting list']
];
function view_reports() {
  const key = LISTF.report || 'pl';
  LISTF.report = key;
  const P = period();
  const rep = REPORTS.find(r => r[0] === key) || REPORTS[0];
  let h = page('Reports', rep[2] + ' · ' + fmtDate(P.from) + ' – ' + fmtDate(P.to),
    '<button class="btn" id="rPrint">Print / PDF</button><button class="btn" id="rCsv">Export CSV</button>');
  h += '<div class="split"><div class="listnav" style="max-height:74vh;overflow:auto">' +
    REPORTS.map(r => '<button data-r="' + r[0] + '"' + (r[0] === key ? ' class="on"' : '') + '><div>' + esc(r[1]) + '</div><div class="sub" style="font-size:11px;color:' + (r[0] === key ? '#B9C9D4' : 'var(--muted)') + '">' + esc(r[2]) + '</div></button>').join('') +
    '</div><div id="repBody"></div></div>';
  $('#view').innerHTML = h;
  $$('[data-r]').forEach(b => b.addEventListener('click', () => { LISTF.report = b.dataset.r; render(); }));
  const out = REP[key](P);
  $('#repBody').innerHTML = '<div class="card"><div class="card-h"><h2>' + esc(rep[1]) + '</h2><div class="acts lbl">' + esc(DB.company.name) + '</div></div><div id="printDoc" class="card-b">' +
    '<div class="mb" style="border-bottom:1px solid var(--rule2);padding-bottom:10px"><div style="font-family:var(--disp);font-size:17px;font-weight:600">' + esc(DB.company.name) + '</div>' +
    '<div class="lbl">' + esc(rep[1]) + ' · ' + fmtDate(P.from) + ' to ' + fmtDate(P.to) + ' · ' + (DB.settings.accrual ? 'Accrual basis' : 'Cash basis') + '</div></div>' + out.html + '</div></div>';
  $('#rPrint').addEventListener('click', () => printNode($('#repBody')));
  $('#rCsv').addEventListener('click', () => { if (out.csv) exportCSV(key + '-report', out.csv.cols, out.csv.rows); else toast('This report exports as PDF only'); });
}
function repTable(rows, opts) {
  opts = opts || {};
  let h = '<table class="tbl"><thead><tr><th>' + (opts.c1 || 'Account') + '</th>' + (opts.cols || ['Amount']).map(c => '<th class="num">' + c + '</th>').join('') + '</tr></thead><tbody>';
  rows.forEach(r => {
    if (r.head) { h += '<tr style="background:var(--ink);color:#fff"><td class="mono" style="font-size:11px;letter-spacing:.16em;text-transform:uppercase">' + esc(r.head) + '</td><td colspan="' + (opts.cols || ['x']).length + '"></td></tr>'; return; }
    if (r.total) { h += '<tr><td class="dbl"><b>' + esc(r.total) + '</b></td>' + r.values.map(v => '<td class="num dbl"><b>' + v + '</b></td>').join('') + '</tr>'; return; }
    if (r.sub) { h += '<tr><td style="font-weight:600;border-top:1px solid var(--rule)">' + esc(r.sub) + '</td>' + r.values.map(v => '<td class="num" style="font-weight:600;border-top:1px solid var(--rule)">' + v + '</td>').join('') + '</tr>'; return; }
    h += '<tr' + (r.link ? ' class="clickable" data-acc="' + r.link + '"' : '') + '><td style="padding-left:' + (r.indent ? 22 : 12) + 'px">' + esc(r.label) + '</td>' + r.values.map(v => '<td class="num">' + v + '</td>').join('') + '</tr>';
  });
  return h + '</tbody></table>';
}
const REP = {
  pl(P) {
    const b = balanceAll(P.from, P.to);
    const rows = [], grp = t => DB.accounts.filter(a => a.type === t && Math.abs((b[a.id] || {}).balance || 0) > 0.004).sort(by('code'));
    const inc = grp('Income'), cogs = grp('COGS'), exp = grp('Expense');
    const ti = r2(sum(inc, a => b[a.id].balance)), tc = r2(sum(cogs, a => b[a.id].balance)), te = r2(sum(exp, a => b[a.id].balance));
    rows.push({ head: 'Income' });
    inc.forEach(a => rows.push({ label: a.code + ' · ' + a.name, values: [money(b[a.id].balance)], indent: 1, link: a.id }));
    rows.push({ sub: 'Total income', values: [money(ti)] });
    rows.push({ head: 'Cost of sales' });
    cogs.forEach(a => rows.push({ label: a.code + ' · ' + a.name, values: [money(b[a.id].balance)], indent: 1, link: a.id }));
    rows.push({ sub: 'Total cost of sales', values: [money(tc)] });
    rows.push({ sub: 'Gross profit', values: [money(ti - tc)] });
    rows.push({ head: 'Operating expenses' });
    exp.forEach(a => rows.push({ label: a.code + ' · ' + a.name, values: [money(b[a.id].balance)], indent: 1, link: a.id }));
    rows.push({ sub: 'Total expenses', values: [money(te)] });
    rows.push({ total: 'Net income', values: [money(ti - tc - te)] });
    const gm = ti ? (ti - tc) / ti * 100 : 0, np = ti ? (ti - tc - te) / ti * 100 : 0;
    return {
      html: '<div class="grid g4 mb"><div class="kpi"><div class="lbl">Revenue</div><div class="v">' + money(ti) + '</div></div>' +
        '<div class="kpi"><div class="lbl">Gross profit</div><div class="v">' + money(ti - tc) + '</div><div class="d">' + pct(gm) + ' margin</div></div>' +
        '<div class="kpi"><div class="lbl">Operating expenses</div><div class="v">' + money(te) + '</div></div>' +
        '<div class="kpi"><div class="lbl">Net income</div><div class="v' + (ti - tc - te < 0 ? ' neg' : '') + '">' + money(ti - tc - te) + '</div><div class="d">' + pct(np) + ' net margin</div></div></div>' + repTable(rows),
      csv: { cols: [{ t: 'Account', k: 'a' }, { t: 'Amount', k: 'v' }], rows: inc.concat(cogs).concat(exp).map(a => ({ a: a.code + ' ' + a.name, v: b[a.id].balance })) }
    };
  },
  plmonth(P) {
    const T = today(), mons = monthsRange(addMonths(monthStart(T), -11), T);
    const accts = DB.accounts.filter(a => ['Income', 'COGS', 'Expense'].includes(a.type)).sort(by('code'));
    const data = {};
    accts.forEach(a => data[a.id] = mons.map(m => balance(a.id, m, monthEnd(m)).balance));
    const keep = accts.filter(a => sum(data[a.id].map(Math.abs)) > 0.004);
    let h = '<div class="tblwrap"><table class="tbl"><thead><tr><th>Account</th>' + mons.map(m => '<th class="num">' + monthLabel(m) + '</th>').join('') + '<th class="num">Total</th></tr></thead><tbody>';
    ['Income', 'COGS', 'Expense'].forEach(t => {
      h += '<tr style="background:var(--ink);color:#fff"><td class="mono" style="font-size:11px;letter-spacing:.16em;text-transform:uppercase">' + t + '</td><td colspan="' + (mons.length + 1) + '"></td></tr>';
      keep.filter(a => a.type === t).forEach(a => {
        h += '<tr><td>' + esc(a.code + ' · ' + a.name) + '</td>' + data[a.id].map(v => '<td class="num">' + (v ? money(v) : '—') + '</td>').join('') + '<td class="num"><b>' + money(sum(data[a.id])) + '</b></td></tr>';
      });
    });
    const net = mons.map((m, i) => r2(sum(keep.filter(a => a.type === 'Income'), a => data[a.id][i]) - sum(keep.filter(a => a.type !== 'Income'), a => data[a.id][i])));
    h += '<tr><td class="dbl"><b>Net income</b></td>' + net.map(v => '<td class="num dbl"><b>' + money(v) + '</b></td>').join('') + '<td class="num dbl"><b>' + money(sum(net)) + '</b></td></tr>';
    h += '</tbody></table></div><div class="mt">' + barChart(mons.map((m, i) => ({ label: monthLabel(m), value: net[i] })), { h: 150 }) + '</div>';
    return { html: h };
  },
  bs(P) {
    const asOf = P.to, b = balanceAll(null, asOf);
    const g = (type, sub) => DB.accounts.filter(a => a.type === type && (!sub || sub.includes(a.subtype)) && Math.abs((b[a.id] || {}).balance || 0) > 0.004).sort(by('code'));
    const curA = g('Asset', ['Bank', 'Accounts Receivable', 'Current Asset']), fixA = g('Asset', ['Fixed Asset']);
    const curL = g('Liability', ['Accounts Payable', 'Credit Card', 'Current Liability']), ltL = g('Liability', ['Long Term Liability']);
    const eq = g('Equity');
    const ni = netIncome(null, asOf).net;
    const tCurA = r2(sum(curA, a => b[a.id].balance)), tFixA = r2(sum(fixA, a => b[a.id].balance));
    const tCurL = r2(sum(curL, a => b[a.id].balance)), tLtL = r2(sum(ltL, a => b[a.id].balance));
    const tEq = r2(sum(eq, a => b[a.id].balance) + ni);
    const rows = [];
    rows.push({ head: 'Current assets' }); curA.forEach(a => rows.push({ label: a.code + ' · ' + a.name, values: [money(b[a.id].balance)], indent: 1, link: a.id }));
    rows.push({ sub: 'Total current assets', values: [money(tCurA)] });
    rows.push({ head: 'Fixed assets' }); fixA.forEach(a => rows.push({ label: a.code + ' · ' + a.name, values: [money(b[a.id].balance)], indent: 1, link: a.id }));
    rows.push({ sub: 'Total fixed assets', values: [money(tFixA)] });
    rows.push({ total: 'TOTAL ASSETS', values: [money(tCurA + tFixA)] });
    rows.push({ head: 'Current liabilities' }); curL.forEach(a => rows.push({ label: a.code + ' · ' + a.name, values: [money(b[a.id].balance)], indent: 1, link: a.id }));
    rows.push({ sub: 'Total current liabilities', values: [money(tCurL)] });
    rows.push({ head: 'Long-term liabilities' }); ltL.forEach(a => rows.push({ label: a.code + ' · ' + a.name, values: [money(b[a.id].balance)], indent: 1, link: a.id }));
    rows.push({ sub: 'Total liabilities', values: [money(tCurL + tLtL)] });
    rows.push({ head: 'Equity' }); eq.forEach(a => rows.push({ label: a.code + ' · ' + a.name, values: [money(b[a.id].balance)], indent: 1, link: a.id }));
    rows.push({ label: 'Current period earnings', values: [money(ni)], indent: 1 });
    rows.push({ sub: 'Total equity', values: [money(tEq)] });
    rows.push({ total: 'TOTAL LIABILITIES & EQUITY', values: [money(tCurL + tLtL + tEq)] });
    const diff = r2((tCurA + tFixA) - (tCurL + tLtL + tEq));
    return {
      html: '<div class="flexrow mb" style="justify-content:space-between"><div class="sub">As at ' + fmtDate(asOf) + '</div>' +
        (Math.abs(diff) < 0.02 ? '<span class="stamp">Balanced</span>' : '<span class="stamp bad">Out by ' + money(diff) + '</span>') + '</div>' + repTable(rows),
      csv: { cols: [{ t: 'Account', k: 'a' }, { t: 'Balance', k: 'v' }], rows: curA.concat(fixA, curL, ltL, eq).map(a => ({ a: a.code + ' ' + a.name, v: b[a.id].balance })) }
    };
  },
  tb(P) {
    const b = balanceAll(P.from, P.to);
    const rows = DB.accounts.filter(a => (b[a.id] || {}).debit || (b[a.id] || {}).credit).sort(by('code'));
    const td = r2(sum(rows, a => b[a.id].debit)), tc = r2(sum(rows, a => b[a.id].credit));
    let h = (Math.abs(td - tc) < 0.02 ? '<span class="stamp">In balance</span>' : '<span class="stamp bad">Out by ' + money(td - tc) + '</span>') +
      '<table class="tbl mt"><thead><tr><th>Code</th><th>Account</th><th>Type</th><th class="num">Debit</th><th class="num">Credit</th></tr></thead><tbody>' +
      rows.map(a => '<tr class="clickable" data-acc="' + a.id + '"><td class="mono">' + esc(a.code) + '</td><td>' + esc(a.name) + '</td><td class="sub">' + esc(a.type) + '</td><td class="num">' + money(b[a.id].debit) + '</td><td class="num">' + money(b[a.id].credit) + '</td></tr>').join('') +
      '</tbody><tfoot><tr><td class="dbl" colspan="3">Totals</td><td class="num dbl">' + money(td) + '</td><td class="num dbl">' + money(tc) + '</td></tr></tfoot></table>';
    return { html: h, csv: { cols: [{ t: 'Code', k: 'c' }, { t: 'Account', k: 'n' }, { t: 'Debit', k: 'd' }, { t: 'Credit', k: 'cr' }], rows: rows.map(a => ({ c: a.code, n: a.name, d: b[a.id].debit, cr: b[a.id].credit })) } };
  },
  cf(P) {
    const cf = cashFlow(P.from, P.to);
    const rows = [];
    let tot = 0;
    ['operating', 'investing', 'financing'].forEach(k => {
      rows.push({ head: k[0].toUpperCase() + k.slice(1) + ' activities' });
      const keys = Object.keys(cf[k]).filter(x => Math.abs(cf[k][x]) > 0.004).sort();
      keys.forEach(x => rows.push({ label: x, values: [money(cf[k][x])], indent: 1 }));
      const st = r2(sum(keys, x => cf[k][x]));
      tot += st;
      rows.push({ sub: 'Net cash from ' + k + ' activities', values: [money(st)] });
    });
    rows.push({ sub: 'Net change in cash', values: [money(tot)] });
    rows.push({ label: 'Cash at start of period', values: [money(cf.opening)] });
    rows.push({ total: 'Cash at end of period', values: [money(cf.closing)] });
    return { html: repTable(rows, { c1: 'Movement' }) };
  },
  ar(P) {
    const custs = DB.contacts.filter(c => c.kind === 'customer');
    const rows = custs.map(c => ({ c, b: agingBuckets(openInvoices().filter(i => i.customerId === c.id), 'due') })).filter(r => r.b.total > 0.004);
    const t = agingBuckets(openInvoices(), 'due');
    return {
      html: '<div class="mb">' + barChart([{ label: 'Current', value: t.current }, { label: '1–30', value: t.d30 }, { label: '31–60', value: t.d60 }, { label: '61–90', value: t.d90 }, { label: '90+', value: t.d90p }], { h: 130 }) + '</div>' +
        tableHTML([{ t: 'Customer', k: 'n', fmt: r => esc(r.c.name) },
        { t: 'Current', k: 'c', cls: 'num', fmt: r => money(r.b.current) }, { t: '1–30', k: 'a', cls: 'num', fmt: r => money(r.b.d30) },
        { t: '31–60', k: 'b2', cls: 'num', fmt: r => money(r.b.d60) }, { t: '61–90', k: 'c2', cls: 'num', fmt: r => money(r.b.d90) },
        { t: '90+', k: 'd', cls: 'num', fmt: r => '<span class="' + (r.b.d90p ? 'neg' : '') + '">' + money(r.b.d90p) + '</span>' },
        { t: 'Total', k: 't', cls: 'num', fmt: r => '<b>' + money(r.b.total) + '</b>' }], rows,
          { foot: { n: 'Total receivable', c: money(t.current), a: money(t.d30), b2: money(t.d60), c2: money(t.d90), d: money(t.d90p), t: money(t.total) }, emptyTitle: 'Nothing outstanding' }),
      csv: { cols: [{ t: 'Customer', raw: r => r.c.name }, { t: 'Current', raw: r => r.b.current }, { t: '1-30', raw: r => r.b.d30 }, { t: '31-60', raw: r => r.b.d60 }, { t: '61-90', raw: r => r.b.d90 }, { t: '90+', raw: r => r.b.d90p }, { t: 'Total', raw: r => r.b.total }], rows }
    };
  },
  ap(P) {
    const vs = DB.contacts.filter(c => c.kind === 'vendor');
    const rows = vs.map(c => ({ c, b: agingBuckets(openBills().filter(i => i.vendorId === c.id), 'due') })).filter(r => r.b.total > 0.004);
    const t = agingBuckets(openBills(), 'due');
    return {
      html: tableHTML([{ t: 'Vendor', k: 'n', fmt: r => esc(r.c.name) },
      { t: 'Current', k: 'c', cls: 'num', fmt: r => money(r.b.current) }, { t: '1–30', k: 'a', cls: 'num', fmt: r => money(r.b.d30) },
      { t: '31–60', k: 'b2', cls: 'num', fmt: r => money(r.b.d60) }, { t: '61–90', k: 'c2', cls: 'num', fmt: r => money(r.b.d90) },
      { t: '90+', k: 'd', cls: 'num', fmt: r => money(r.b.d90p) }, { t: 'Total', k: 't', cls: 'num', fmt: r => '<b>' + money(r.b.total) + '</b>' }], rows,
        { foot: { n: 'Total payable', t: money(t.total) }, emptyTitle: 'Nothing owing' })
    };
  },
  custbal() {
    const rows = DB.contacts.filter(c => c.kind === 'customer').map(c => ({ c, b: customerBalance(c.id), l: r2(sum(DB.invoices.filter(i => i.customerId === c.id), i => docTotals(i).total)) })).filter(r => r.b || r.l);
    return {
      html: tableHTML([{ t: 'Customer', k: 'n', fmt: r => esc(r.c.name) }, { t: 'Credit limit', k: 'cl', cls: 'num', fmt: r => r.c.creditLimit ? money(r.c.creditLimit) : '—' },
      { t: 'Lifetime billed', k: 'l', cls: 'num', fmt: r => money(r.l) }, { t: 'Open balance', k: 'b', cls: 'num', fmt: r => moneyCell(r.b) },
      { t: 'Utilisation', k: 'u', w: '150px', fmt: r => r.c.creditLimit ? '<div class="bar"><i style="width:' + Math.min(100, r.b / r.c.creditLimit * 100) + '%;background:' + (r.b > r.c.creditLimit ? 'var(--red)' : 'var(--green)') + '"></i></div>' : '' }],
        rows.sort((a, b) => b.b - a.b), { foot: { n: 'Total', b: money(sum(rows, r => r.b)) } })
    };
  },
  vendbal() {
    const rows = DB.contacts.filter(c => c.kind === 'vendor').map(c => ({ c, b: vendorBalance(c.id), l: r2(sum(DB.bills.filter(i => i.vendorId === c.id), i => docTotals(i).total) + sum(DB.expenses.filter(e => e.vendorId === c.id), e => e.amount)) }));
    return {
      html: tableHTML([{ t: 'Vendor', k: 'n', fmt: r => esc(r.c.name) }, { t: 'Terms', k: 't', fmt: r => 'Net ' + r.c.terms },
      { t: 'Lifetime spend', k: 'l', cls: 'num', fmt: r => money(r.l) }, { t: 'Open balance', k: 'b', cls: 'num', fmt: r => moneyCell(r.b) }],
        rows.sort((a, b) => b.l - a.l), { foot: { n: 'Total', l: money(sum(rows, r => r.l)), b: money(sum(rows, r => r.b)) } })
    };
  },
  salescust(P) {
    const rows = DB.contacts.filter(c => c.kind === 'customer').map(c => {
      const inv = DB.invoices.filter(i => i.customerId === c.id && i.date >= P.from && i.date <= P.to && !['draft', 'void'].includes(i.status));
      const t = r2(sum(inv, i => docTotals(i).sub * (i.rate || 1)));
      const cost = r2(sum(inv, i => sum(i.lines, l => { const it = item(l.itemId); return it && it.trackQty ? l.qty * it.cost : 0; })));
      return { c, n: inv.length, t, cost, gp: r2(t - cost) };
    }).filter(r => r.n).sort((a, b) => b.t - a.t);
    const tot = r2(sum(rows, r => r.t));
    return {
      html: tableHTML([{ t: 'Customer', k: 'n2', fmt: r => esc(r.c.name) }, { t: 'Invoices', k: 'n', cls: 'num' },
      { t: 'Net sales', k: 't', cls: 'num', fmt: r => money(r.t) }, { t: 'Cost', k: 'cost', cls: 'num', fmt: r => money(r.cost) },
      { t: 'Gross profit', k: 'gp', cls: 'num', fmt: r => money(r.gp) }, { t: 'Margin', k: 'm', cls: 'num', fmt: r => r.t ? pct(r.gp / r.t * 100) : '—' },
      { t: 'Share', k: 's', w: '130px', fmt: r => '<div class="bar"><i style="width:' + (tot ? r.t / tot * 100 : 0) + '%"></i></div>' }],
        rows, { foot: { n2: 'Total', t: money(tot), gp: money(sum(rows, r => r.gp)) } }),
      csv: { cols: [{ t: 'Customer', raw: r => r.c.name }, { t: 'Invoices', raw: r => r.n }, { t: 'Net sales', raw: r => r.t }, { t: 'Gross profit', raw: r => r.gp }], rows }
    };
  },
  salesitem(P) {
    const rows = DB.items.map(it => {
      let q = 0, rev = 0, cost = 0;
      DB.invoices.forEach(i => {
        if (i.date < P.from || i.date > P.to || ['draft', 'void'].includes(i.status)) return;
        i.lines.forEach(l => { if (l.itemId === it.id) { q += Number(l.qty) || 0; rev += lineAmount(l) * (i.rate || 1); cost += (Number(l.qty) || 0) * (it.trackQty ? it.cost : 0); } });
      });
      return { it, q, rev: r2(rev), cost: r2(cost), gp: r2(rev - cost) };
    }).filter(r => r.q).sort((a, b) => b.rev - a.rev);
    return {
      html: tableHTML([{ t: 'SKU', k: 's', fmt: r => '<span class="mono">' + esc(r.it.sku) + '</span>' }, { t: 'Item', k: 'n', fmt: r => esc(r.it.name) },
      { t: 'Qty sold', k: 'q', cls: 'num', fmt: r => qty(r.q) }, { t: 'Revenue', k: 'rev', cls: 'num', fmt: r => money(r.rev) },
      { t: 'Cost', k: 'cost', cls: 'num', fmt: r => money(r.cost) }, { t: 'Gross profit', k: 'gp', cls: 'num', fmt: r => money(r.gp) },
      { t: 'Margin', k: 'm', cls: 'num', fmt: r => r.rev ? pct(r.gp / r.rev * 100) : '—' }], rows,
        { foot: { n: 'Total', rev: money(sum(rows, r => r.rev)), cost: money(sum(rows, r => r.cost)), gp: money(sum(rows, r => r.gp)) } }),
      csv: { cols: [{ t: 'SKU', raw: r => r.it.sku }, { t: 'Item', raw: r => r.it.name }, { t: 'Qty', raw: r => r.q }, { t: 'Revenue', raw: r => r.rev }, { t: 'Gross profit', raw: r => r.gp }], rows }
    };
  },
  expcat(P) {
    const b = balanceAll(P.from, P.to);
    const rows = DB.accounts.filter(a => ['Expense', 'COGS'].includes(a.type) && Math.abs((b[a.id] || {}).balance || 0) > 0.004).sort((x, y) => b[y.id].balance - b[x.id].balance);
    const tot = r2(sum(rows, a => b[a.id].balance));
    return {
      html: '<div class="grid g2 mb"><div>' + donut(rows.slice(0, 6).map((a, i) => ({ label: a.name, value: b[a.id].balance, color: ['#1D6B4A', '#3F8A66', '#7FA98E', '#C79A2E', '#C4703A', '#A5241D'][i] })), { size: 190, label: 'SPEND' }) + '</div>' +
        '<div>' + rows.slice(0, 6).map((a, i) => '<div class="flexrow" style="justify-content:space-between;padding:5px 0;border-bottom:1px solid var(--rule2)"><span><span class="dot" style="background:' + ['#1D6B4A', '#3F8A66', '#7FA98E', '#C79A2E', '#C4703A', '#A5241D'][i] + ';margin-right:8px"></span>' + esc(a.name) + '</span><span class="mono">' + money(b[a.id].balance) + '</span></div>').join('') + '</div></div>' +
        tableHTML([{ t: 'Account', k: 'n', fmt: a => esc(a.code + ' · ' + a.name) }, { t: 'Type', k: 'type' },
        { t: 'Amount', k: 'v', cls: 'num', fmt: a => money(b[a.id].balance) },
        { t: '% of spend', k: 'p', cls: 'num', fmt: a => pct(tot ? b[a.id].balance / tot * 100 : 0) }], rows, { foot: { n: 'Total spend', v: money(tot) } }),
      csv: { cols: [{ t: 'Account', raw: a => a.code + ' ' + a.name }, { t: 'Amount', raw: a => b[a.id].balance }], rows }
    };
  },
  purchvend(P) {
    const rows = DB.contacts.filter(c => c.kind === 'vendor').map(c => {
      const bl = DB.bills.filter(b => b.vendorId === c.id && b.date >= P.from && b.date <= P.to && !['draft', 'void'].includes(b.status));
      const ex = DB.expenses.filter(e => e.vendorId === c.id && e.date >= P.from && e.date <= P.to);
      return { c, n: bl.length + ex.length, t: r2(sum(bl, b => docTotals(b).total) + sum(ex, e => e.amount)) };
    }).filter(r => r.t).sort((a, b) => b.t - a.t);
    return {
      html: tableHTML([{ t: 'Vendor', k: 'n2', fmt: r => esc(r.c.name) }, { t: 'Transactions', k: 'n', cls: 'num' },
      { t: 'Spend', k: 't', cls: 'num', fmt: r => money(r.t) },
      { t: 'Share', k: 's', w: '150px', fmt: r => '<div class="bar"><i style="width:' + (rows[0] ? r.t / rows[0].t * 100 : 0) + '%"></i></div>' }], rows,
        { foot: { n2: 'Total', t: money(sum(rows, r => r.t)) } })
    };
  },
  invval() {
    const rows = DB.items.filter(i => i.trackQty);
    return {
      html: tableHTML([{ t: 'SKU', k: 'sku', fmt: i => '<span class="mono">' + esc(i.sku) + '</span>' }, { t: 'Item', k: 'name' },
      { t: 'On hand', k: 'q', cls: 'num', fmt: i => qty(stockOf(i.id)) }, { t: 'Unit cost', k: 'cost', cls: 'num', fmt: i => money(i.cost) },
      { t: 'Value', k: 'v', cls: 'num', fmt: i => money(stockOf(i.id) * i.cost) },
      { t: 'Retail value', k: 'r', cls: 'num', fmt: i => money(stockOf(i.id) * i.price) },
      { t: 'Unrealised margin', k: 'm', cls: 'num', fmt: i => money(stockOf(i.id) * (i.price - i.cost)) }], rows,
        { foot: { name: 'Total inventory', v: money(inventoryValue()), r: money(sum(rows, i => stockOf(i.id) * i.price)), m: money(sum(rows, i => stockOf(i.id) * (i.price - i.cost))) } }),
      csv: { cols: [{ t: 'SKU', k: 'sku' }, { t: 'Item', k: 'name' }, { t: 'On hand', raw: i => stockOf(i.id) }, { t: 'Value', raw: i => stockOf(i.id) * i.cost }], rows }
    };
  },
  tax(P) {
    const rows = DB.taxRates.map(t => {
      let collected = 0, paid = 0, salesNet = 0, purchNet = 0;
      DB.invoices.forEach(i => { if (i.date < P.from || i.date > P.to || ['draft', 'void'].includes(i.status)) return; i.lines.forEach(l => { if (l.taxId === t.id) { salesNet += lineAmount(l); collected += lineAmount(l) * t.rate / 100; } }); });
      DB.bills.forEach(b => { if (b.date < P.from || b.date > P.to || ['draft', 'void'].includes(b.status)) return; b.lines.forEach(l => { if (l.taxId === t.id) { purchNet += lineAmount(l); paid += lineAmount(l) * t.rate / 100; } }); });
      DB.expenses.forEach(e => { if (e.date < P.from || e.date > P.to) return; if (e.taxId === t.id) { purchNet += e.amount; paid += e.amount * t.rate / 100; } });
      return { t, salesNet: r2(salesNet), collected: r2(collected), purchNet: r2(purchNet), paid: r2(paid), net: r2(collected - paid) };
    }).filter(r => r.t.rate > 0);
    const owed = r2(sum(rows, r => r.net));
    return {
      html: '<div class="grid g3 mb"><div class="kpi"><div class="lbl">Tax collected on sales</div><div class="v">' + money(sum(rows, r => r.collected)) + '</div></div>' +
        '<div class="kpi"><div class="lbl">Tax paid on purchases</div><div class="v">' + money(sum(rows, r => r.paid)) + '</div></div>' +
        '<div class="kpi"><div class="lbl">Net owing to agency</div><div class="v">' + money(owed) + '</div><div class="d">balance of 2200 less 1600</div></div></div>' +
        tableHTML([{ t: 'Tax', k: 'n', fmt: r => esc(r.t.name) + ' <span class="tag">' + r.t.rate + '%</span>' }, { t: 'Agency', k: 'ag', fmt: r => esc(r.t.agency || '') },
        { t: 'Net sales', k: 'sn', cls: 'num', fmt: r => money(r.salesNet) }, { t: 'Collected', k: 'c', cls: 'num', fmt: r => money(r.collected) },
        { t: 'Net purchases', k: 'pn', cls: 'num', fmt: r => money(r.purchNet) }, { t: 'Paid', k: 'p', cls: 'num', fmt: r => money(r.paid) },
        { t: 'Net due', k: 'net', cls: 'num', fmt: r => '<b>' + money(r.net) + '</b>' }], rows, { foot: { n: 'Total', net: money(owed) } })
    };
  },
  budget(P) {
    const y = LISTF.budgetYear || String(new Date().getFullYear());
    const B = DB.budgets[y] || {};
    const accts = DB.accounts.filter(a => ['Income', 'COGS', 'Expense'].includes(a.type)).sort(by('code'));
    const rows = accts.map(a => {
      const bud = r2(sum(B[a.id] || []));
      const act = balance(a.id, y + '-01-01', y + '-12-31').balance;
      return { a, bud, act, v: r2(act - bud), p: bud ? (act - bud) / bud * 100 : 0 };
    }).filter(r => r.bud || r.act);
    return {
      html: '<div class="hint mb">Comparing calendar year ' + y + '. Change the year on the Budgets page.</div>' +
        tableHTML([{ t: 'Account', k: 'n', fmt: r => esc(r.a.code + ' · ' + r.a.name) }, { t: 'Type', k: 't', fmt: r => r.a.type },
        { t: 'Budget', k: 'bud', cls: 'num', fmt: r => money(r.bud) }, { t: 'Actual', k: 'act', cls: 'num', fmt: r => money(r.act) },
        { t: 'Variance', k: 'v', cls: 'num', fmt: r => moneyCell(r.v) }, { t: '%', k: 'p', cls: 'num', fmt: r => r.bud ? pct(r.p) : '—' },
        { t: '', k: 'bar', w: '130px', fmt: r => '<div class="bar"><i style="width:' + Math.min(100, Math.abs(r.bud ? r.act / r.bud * 100 : 0)) + '%;background:' + (r.a.type === 'Income' ? (r.act >= r.bud ? 'var(--green)' : 'var(--amber)') : (r.act > r.bud ? 'var(--red)' : 'var(--green)')) + '"></i></div>' }], rows,
          { foot: { n: 'Total', bud: money(sum(rows, r => r.bud)), act: money(sum(rows, r => r.act)), v: money(sum(rows, r => r.v)) } })
    };
  },
  proj(P) {
    const rows = DB.projects.map(p => {
      const inv = DB.invoices.filter(i => i.projectId === p.id && !['draft', 'void'].includes(i.status));
      const rev = r2(sum(inv, i => docTotals(i).sub));
      const te = DB.timeEntries.filter(t => t.projectId === p.id);
      const laborCost = r2(sum(te, t => t.hours * t.rate * .55));
      const exp = r2(sum(DB.expenses.filter(e => e.customerId === p.customerId && e.billable), e => e.amount));
      return { p, rev, hours: r2(sum(te, t => t.hours)), cost: r2(laborCost + exp), gp: r2(rev - laborCost - exp) };
    });
    return {
      html: tableHTML([{ t: 'Project', k: 'n', fmt: r => esc(r.p.name) }, { t: 'Customer', k: 'c', fmt: r => esc(contact(r.p.customerId).name) },
      { t: 'Status', k: 's', fmt: r => statusPill(r.p.status === 'on hold' ? 'draft' : r.p.status) },
      { t: 'Budget', k: 'b', cls: 'num', fmt: r => money(r.p.budget) }, { t: 'Revenue', k: 'rev', cls: 'num', fmt: r => money(r.rev) },
      { t: 'Hours', k: 'h', cls: 'num', fmt: r => qty(r.hours) }, { t: 'Est. cost', k: 'cost', cls: 'num', fmt: r => money(r.cost) },
      { t: 'Profit', k: 'gp', cls: 'num', fmt: r => moneyCell(r.gp) }, { t: 'Margin', k: 'm', cls: 'num', fmt: r => r.rev ? pct(r.gp / r.rev * 100) : '—' }], rows,
        { foot: { n: 'Total', rev: money(sum(rows, r => r.rev)), cost: money(sum(rows, r => r.cost)), gp: money(sum(rows, r => r.gp)) } })
    };
  },
  gl(P) {
    const accts = DB.accounts.slice().sort(by('code'));
    let h = '';
    accts.forEach(a => {
      const ls = jLines(P.from, P.to).filter(l => l.accountId === a.id);
      if (!ls.length) return;
      let run = balance(a.id, null, addDays(P.from, -1)).balance;
      const nat = TYPES[a.type].normal;
      h += '<div style="margin-top:18px"><div class="lbl" style="background:var(--ink);color:#fff;padding:6px 10px;border-radius:3px">' + esc(a.code + ' · ' + a.name) + '</div>' +
        '<table class="tbl"><thead><tr><th style="width:110px">Date</th><th style="width:90px">Entry</th><th>Memo</th><th class="num">Debit</th><th class="num">Credit</th><th class="num">Balance</th></tr></thead><tbody>' +
        ls.map(l => { run = r2(run + (nat === 'D' ? l.debit - l.credit : l.credit - l.debit)); return '<tr><td>' + fmtDate(l.date) + '</td><td class="mono">' + esc(l.no) + '</td><td>' + esc(l.memo2) + '</td><td class="num">' + (l.debit ? money(l.debit) : '') + '</td><td class="num">' + (l.credit ? money(l.credit) : '') + '</td><td class="num">' + money(run) + '</td></tr>'; }).join('') +
        '</tbody><tfoot><tr><td class="dbl" colspan="3">Closing</td><td class="num dbl">' + money(sum(ls, l => l.debit)) + '</td><td class="num dbl">' + money(sum(ls, l => l.credit)) + '</td><td class="num dbl">' + money(run) + '</td></tr></tfoot></table></div>';
    });
    return { html: h || '<div class="empty"><h3>No postings in this period</h3></div>' };
  },
  audittrail(P) {
    const rows = DB.journal.filter(j => j.date >= P.from && j.date <= P.to).sort(by('date'));
    return {
      html: tableHTML([{ t: 'Date', k: 'date', fmt: j => fmtDate(j.date) }, { t: 'Entry', k: 'no', fmt: j => '<span class="mono">' + esc(j.no) + '</span>' },
      { t: 'Source', k: 'source', fmt: j => '<span class="tag">' + esc(j.source) + '</span>' }, { t: 'Memo', k: 'memo' },
      { t: 'Accounts', k: 'a', fmt: j => '<span class="sub">' + esc(j.lines.map(l => acc(l.accountId).code).join(' / ')) + '</span>' },
      { t: 'Amount', k: 'v', cls: 'num', fmt: j => money(sum(j.lines, l => l.debit)) }], rows,
        { foot: { date: rows.length + ' entries', v: money(sum(rows, j => sum(j.lines, l => l.debit))) } }),
      csv: { cols: [{ t: 'Date', k: 'date' }, { t: 'Entry', k: 'no' }, { t: 'Source', k: 'source' }, { t: 'Memo', k: 'memo' }, { t: 'Amount', raw: j => sum(j.lines, l => l.debit) }], rows }
    };
  }
};

/* ============================ save / open ============================ */
function persistent() { return !!(window.storage && window.storage.set); }
function slug(s) { return (s || 'company').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40); }
function backupNow() {
  const out = Object.assign({ _app: 'Business Accounting', _savedAt: new Date().toISOString() }, DB);
  download(slug(DB.company.name) + '-' + today() + '.json', JSON.stringify(out, null, 1), 'application/json');
  logAudit('Downloaded backup', DB.journal.length + ' journal entries');
  toast('Saved ' + slug(DB.company.name) + '-' + today() + '.json');
}
function restoreFromText(txt) {
  let o;
  try { o = JSON.parse(txt); } catch (e) { toast('That file is not valid JSON', true); return; }
  if (!o || !Array.isArray(o.accounts) || !Array.isArray(o.journal)) { toast('That does not look like a Business Accounting backup', true); return; }
  const label = (o.company && o.company.name) || 'company file';
  const stats = (o.invoices || []).length + ' invoices · ' + (o.journal || []).length + ' journal entries' +
    (o._savedAt ? ' · saved ' + fmtDate(o._savedAt.slice(0, 10)) : '');
  confirmDlg('Open ' + label + '?', 'Replaces everything currently in this file. ' + stats, () => {
    DB = o; migrate(); repostAll(); save('Opened backup: ' + label); render(); toast(label + ' opened');
  }, 'Open file');
}
function readBackupFile(file) {
  const fr = new FileReader();
  fr.onload = () => restoreFromText(String(fr.result));
  fr.onerror = () => toast('Could not read that file', true);
  fr.readAsText(file);
}
function openBackupPicker() {
  const inp = document.createElement('input');
  inp.type = 'file'; inp.accept = 'application/json,.json';
  inp.addEventListener('change', () => { if (inp.files[0]) readBackupFile(inp.files[0]); });
  inp.click();
}

/* ============================ settings ============================ */
function view_settings() {
  const tab = LISTF.setTab || 'company';
  LISTF.setTab = tab;
  const tabs = [['company', 'Company'], ['prefs', 'Preferences'], ['tax', 'Tax rates'], ['fx', 'Currencies'], ['users', 'Users & roles'], ['data', 'Data & backup']];
  let h = page('Settings', 'Company file configuration', '');
  h += '<div class="seg mb noprint">' + tabs.map(t => '<button data-t="' + t[0] + '"' + (tab === t[0] ? ' class="on"' : '') + '>' + t[1] + '</button>').join('') + '</div><div id="setBody"></div>';
  $('#view').innerHTML = h;
  $$('[data-t]').forEach(b => b.addEventListener('click', () => { LISTF.setTab = b.dataset.t; render(); }));
  const B = $('#setBody');
  if (tab === 'company') {
    B.innerHTML = '<div class="card"><div class="card-b">' + formHTML([
      { k: 'name', t: 'Trading name', w: 'full' }, { k: 'legal', t: 'Legal entity name', w: 'full' },
      { k: 'taxId', t: 'Tax / EIN' }, { k: 'industry', t: 'Industry' },
      { k: 'email', t: 'Billing email' }, { k: 'phone', t: 'Phone' }, { k: 'site', t: 'Website' },
      { k: 'currency', t: 'Base currency', type: 'select', opts: Object.keys(DB.currencies) },
      { k: 'addr1', t: 'Street', w: 'full' }, { k: 'city', t: 'City' }, { k: 'state', t: 'State' },
      { k: 'zip', t: 'Postcode' }, { k: 'country', t: 'Country' },
      { k: 'fyStartMonth', t: 'Fiscal year starts', type: 'select', opts: Array.from({ length: 12 }, (_, i) => ({ v: i + 1, t: new Date(2000, i, 1).toLocaleString('en-US', { month: 'long' }) })) }
    ], DB.company) + '<div class="mt"><button class="btn pri" id="setSave">Save company details</button></div></div></div>';
    $('#setSave').addEventListener('click', () => { Object.assign(DB.company, readForm(B)); save('Updated company details'); render(); toast('Company details saved'); });
  }
  if (tab === 'prefs') {
    B.innerHTML = '<div class="card"><div class="card-b">' + formHTML([
      { k: 'invoicePrefix', t: 'Invoice prefix' }, { k: 'nextInvoice', t: 'Next invoice number', type: 'number' },
      { k: 'billPrefix', t: 'Bill prefix' }, { k: 'nextBill', t: 'Next bill number', type: 'number' },
      { k: 'estPrefix', t: 'Estimate prefix' }, { k: 'nextEst', t: 'Next estimate number', type: 'number' },
      { k: 'poPrefix', t: 'PO prefix' }, { k: 'nextPO', t: 'Next PO number', type: 'number' },
      { k: 'cnPrefix', t: 'Credit note prefix' }, { k: 'nextCN', t: 'Next credit note number', type: 'number' },
      { k: 'terms', t: 'Default payment terms (days)', type: 'number' },
      { k: 'defaultTaxId', t: 'Default tax rate', type: 'select', opts: DB.taxRates.map(t => ({ v: t.id, t: t.name })) },
      { k: 'lateFeePct', t: 'Late fee % per month', type: 'number' },
      { k: 'invoiceNote', t: 'Default note on documents', type: 'textarea', w: 'full' },
      { k: 'invoiceFooter', t: 'Document footer', type: 'textarea', w: 'full' },
      { k: 'trackInventory', t: 'Track inventory quantities', type: 'checkbox' },
      { k: 'accrual', t: 'Accrual basis reporting', type: 'checkbox' }
    ], DB.settings) + '<div class="mt"><button class="btn pri" id="setSave2">Save preferences</button></div></div></div>';
    $('#setSave2').addEventListener('click', () => { Object.assign(DB.settings, readForm(B)); save('Updated preferences'); render(); toast('Preferences saved'); });
  }
  if (tab === 'tax') {
    B.innerHTML = '<div class="card"><div class="card-h"><h2>Tax rates</h2><div class="acts"><button class="btn pri" id="txNew">New rate</button></div></div>' +
      tableHTML([{ t: 'Name', k: 'name' }, { t: 'Rate', k: 'rate', cls: 'num', fmt: t => t.rate + '%' }, { t: 'Agency', k: 'agency' },
      { t: '', k: 'x', cls: 'num', w: '70px', fmt: () => rowActs([['edit', ic.edit, 'Edit'], ['del', ic.trash, 'Delete']]) }], DB.taxRates) + '</div>';
    $('#txNew').addEventListener('click', () => formModal('New tax rate', [{ k: 'name', t: 'Name', req: 1 }, { k: 'rate', t: 'Rate %', type: 'number' }, { k: 'agency', t: 'Agency', w: 'full' }], {}, v => { DB.taxRates.push(Object.assign({ id: uid('t') }, v)); save('Added tax rate'); render(); }));
    $$('#setBody tbody tr').forEach((tr, i) => {
      const t = DB.taxRates[i]; if (!t) return;
      $$('[data-act]', tr).forEach(b => b.addEventListener('click', () => {
        if (b.dataset.act === 'edit') formModal('Edit tax rate', [{ k: 'name', t: 'Name' }, { k: 'rate', t: 'Rate %', type: 'number' }, { k: 'agency', t: 'Agency', w: 'full' }], t, v => { Object.assign(t, v); repostAll(); save('Updated tax rate'); render(); });
        else confirmDlg('Delete tax rate', 'Documents using it fall back to zero.', () => { DB.taxRates = DB.taxRates.filter(x => x.id !== t.id); repostAll(); save('Deleted tax rate'); render(); });
      }));
    });
  }
  if (tab === 'fx') {
    const rows = Object.keys(DB.currencies).map(k => ({ code: k, rate: DB.currencies[k] }));
    B.innerHTML = '<div class="hint mb">Rates express how many units of the foreign currency equal one ' + DB.company.currency + '. Documents post to the ledger in base currency at the rate stored on the document.</div>' +
      '<div class="card"><div class="card-h"><h2>Currencies</h2><div class="acts"><button class="btn pri" id="fxNew">Add currency</button></div></div>' +
      tableHTML([{ t: 'Code', k: 'code', fmt: r => '<b class="mono">' + esc(r.code) + '</b>' }, { t: 'Symbol', k: 's', fmt: r => sym(r.code) },
      { t: 'Rate per ' + DB.company.currency, k: 'rate', cls: 'num', fmt: r => '<input type="number" step="0.0001" data-fx="' + r.code + '" value="' + r.rate + '" style="width:120px">' },
      { t: 'Documents', k: 'd', cls: 'num', fmt: r => DB.invoices.filter(i => i.currency === r.code).length }], rows) + '</div>';
    $$('[data-fx]').forEach(i => i.addEventListener('change', () => { DB.currencies[i.dataset.fx] = Number(i.value) || 1; save('Updated exchange rate'); toast('Rate saved'); }));
    $('#fxNew').addEventListener('click', () => formModal('Add currency', [{ k: 'code', t: 'Code (e.g. NZD)', req: 1 }, { k: 'rate', t: 'Rate per ' + DB.company.currency, type: 'number', def: 1 }], {}, v => { DB.currencies[v.code.toUpperCase()] = Number(v.rate) || 1; save('Added currency'); render(); }));
  }
  if (tab === 'users') {
    B.innerHTML = '<div class="hint mb">Roles are enforced in the interface: Owners and Accountants can post and edit, Staff can create documents, Viewers are read-only.</div>' +
      '<div class="card"><div class="card-h"><h2>Users</h2><div class="acts"><button class="btn pri" id="uNew">Invite user</button></div></div>' +
      tableHTML([{ t: 'Name', k: 'name', fmt: u => '<b>' + esc(u.name) + '</b>' + (u.id === DB.session.userId ? ' <span class="tag">signed in</span>' : '') },
      { t: 'Email', k: 'email' }, { t: 'Role', k: 'role', fmt: u => '<span class="pill p-open">' + esc(u.role) + '</span>' },
      { t: '', k: 'x', cls: 'num', w: '130px', fmt: u => '<div class="rowacts"><button class="btn sm" data-sw="' + u.id + '">Switch to</button></div>' }], DB.users) + '</div>';
    $('#uNew').addEventListener('click', () => formModal('Invite user', [{ k: 'name', t: 'Name', req: 1 }, { k: 'email', t: 'Email', type: 'email' }, { k: 'role', t: 'Role', type: 'select', opts: ['Owner', 'Accountant', 'Staff', 'Viewer'] }], {}, v => { DB.users.push(Object.assign({ id: uid('u') }, v)); save('Invited user ' + v.name); render(); }));
    $$('[data-sw]').forEach(b => b.addEventListener('click', () => { DB.session.userId = b.dataset.sw; save('Switched user'); render(); toast('Now working as ' + currentUser().name); }));
  }
  if (tab === 'data') {
    const sizeKb = Math.round(JSON.stringify(DB).length / 1024);
    B.innerHTML = '<div class="grid g2"><div class="card"><div class="card-h"><h2>Backup</h2></div><div class="card-b">' +
      '<p class="sub">Saves the whole company file — every contact, document, posting and setting — as one JSON file you can keep, back up, move to another machine, or open again later from the panel on the right.</p>' +
      '<div class="flexrow mt"><button class="btn pri" id="dExp">Save a copy to file</button><button class="btn" id="dExpCsv">Export all CSVs</button></div>' +
      '<div class="lbl mt">' + sizeKb + ' KB · ' + DB.journal.length + ' journal entries · ' + DB.invoices.length + ' invoices</div>' +
      '<div class="hint mt">' + (persistent()
        ? 'Changes are also saved automatically as you work, so this page picks up where you left off when you come back to it.'
        : '<b>No automatic saving here.</b> This copy is running without persistent storage, so anything you enter is lost when the tab closes. Save a file before you finish, and open it again when you return.') + '</div>' +
      '</div></div>' +
      '<div class="card"><div class="card-h"><h2>Restore</h2></div><div class="card-b">' +
      '<p class="sub">Open a backup file to replace everything in this company file.</p>' +
      '<div id="dDrop" class="dropzone"><b>Choose a backup file</b><span>or drag a .json backup here</span></div>' +
      '<input type="file" id="dFile" accept="application/json,.json" hidden>' +
      '<details class="mt"><summary class="sub">Paste the JSON instead</summary>' +
      '<textarea id="dImp" style="min-height:90px;font-family:var(--mono);font-size:11px" placeholder="Paste backup JSON"></textarea>' +
      '<div class="flexrow mt"><button class="btn" id="dImpGo">Restore from pasted JSON</button></div></details></div></div></div>' +
      '<div class="card mt"><div class="card-h"><h2>Maintenance</h2></div><div class="card-b flexrow">' +
      '<button class="btn" id="dRepost">Rebuild ledger from documents</button>' +
      '<button class="btn" id="dDemo">Load demo company</button>' +
      '<button class="btn danger" id="dWipe">Start an empty company file</button></div>' +
      '<div class="card-b sub" style="border-top:1px solid var(--rule2)">Rebuilding re-posts every invoice, bill, expense, credit note and pay run. Manual journal entries are preserved.</div></div>';
    $('#dExp').addEventListener('click', backupNow);
    $('#dExpCsv').addEventListener('click', () => {
      exportCSV('invoices', [{ t: 'No', k: 'no' }, { t: 'Date', k: 'date' }, { t: 'Customer', raw: i => contact(i.customerId).name }, { t: 'Total', raw: i => docTotals(i).total }], DB.invoices);
      setTimeout(() => exportCSV('journal', [{ t: 'No', k: 'no' }, { t: 'Date', k: 'date' }, { t: 'Memo', k: 'memo' }, { t: 'Amount', raw: j => sum(j.lines, l => l.debit) }], DB.journal), 400);
    });
    $('#dImpGo').addEventListener('click', () => restoreFromText($('#dImp').value));
    $('#dDrop').addEventListener('click', () => $('#dFile').click());
    $('#dFile').addEventListener('change', e => { if (e.target.files[0]) readBackupFile(e.target.files[0]); });
    const dz = $('#dDrop');
    ['dragenter', 'dragover'].forEach(ev => dz.addEventListener(ev, e => { e.preventDefault(); dz.classList.add('over'); }));
    ['dragleave', 'drop'].forEach(ev => dz.addEventListener(ev, e => { e.preventDefault(); dz.classList.remove('over'); }));
    dz.addEventListener('drop', e => { const f = e.dataTransfer.files[0]; if (f) readBackupFile(f); });
    $('#dRepost').addEventListener('click', () => { repostAll(); save('Rebuilt ledger'); render(); toast('Ledger rebuilt from source documents'); });
    $('#dDemo').addEventListener('click', () => confirmDlg('Load demo company', 'Replaces everything in this file with a fully worked example company \u2014 seven months of invoices, bills, payroll and bank activity. Download a backup first if you have entered your own data.', () => { _seed = Date.now() % 2147483647; DB = seed(); save('Loaded demo company'); render(); toast('Demo company loaded'); }, 'Load demo data'));
    $('#dWipe').addEventListener('click', () => confirmDlg('Start an empty company file', 'All customers, documents and postings are removed. Download a backup first if you need one.', () => {
      DB = blankDB(); DB.company.name = 'My Company'; save('Created empty company file'); render(); toast('Empty company file created');
    }, 'Erase everything'));
  }
}
function view_audit() {
  const rows = DB.audit;
  let h = page('Audit log', 'Every change made in this company file, newest first', '<button class="btn" id="auExp">Export CSV</button>');
  h += '<div class="card">' + tableHTML([
    { t: 'When', k: 'ts', w: '190px', fmt: a => new Date(a.ts).toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' }) },
    { t: 'User', k: 'user', w: '160px' },
    { t: 'Action', k: 'action' },
    { t: 'Detail', k: 'detail', fmt: a => '<span class="sub">' + esc(a.detail) + '</span>' }
  ], rows, { emptyTitle: 'No activity recorded yet' }) + '</div>';
  $('#view').innerHTML = h;
  $('#auExp').addEventListener('click', () => exportCSV('audit-log', [{ t: 'When', k: 'ts' }, { t: 'User', k: 'user' }, { t: 'Action', k: 'action' }, { t: 'Detail', k: 'detail' }], rows));
}

/* ============================ command palette ============================ */
function paletteActions() {
  const acts = [];
  NAV.forEach(([g, items]) => items.forEach(([k, t]) => acts.push({ t: t, s: g, run: () => go(k), k: '↵' })));
  acts.push({ t: 'New invoice', s: 'Create', run: () => docEditor('invoice') });
  acts.push({ t: 'New bill', s: 'Create', run: () => docEditor('bill') });
  acts.push({ t: 'New estimate', s: 'Create', run: () => docEditor('estimate') });
  acts.push({ t: 'New purchase order', s: 'Create', run: () => docEditor('po') });
  acts.push({ t: 'New credit note', s: 'Create', run: () => docEditor('creditnote') });
  acts.push({ t: 'New expense', s: 'Create', run: () => expenseModal() });
  acts.push({ t: 'New journal entry', s: 'Create', run: () => journalModal() });
  acts.push({ t: 'New customer', s: 'Create', run: () => contactModal('customer') });
  acts.push({ t: 'New vendor', s: 'Create', run: () => contactModal('vendor') });
  acts.push({ t: 'Transfer funds', s: 'Banking', run: () => transferModal() });
  acts.push({ t: 'Run payroll', s: 'Payroll', run: () => payrunModal() });
  acts.push({ t: 'Run depreciation', s: 'Accounting', run: () => depreciationRun() });
  acts.push({ t: 'Rebuild ledger', s: 'Accounting', run: () => { repostAll(); save('Rebuilt ledger'); render(); toast('Ledger rebuilt'); } });
  acts.push({ t: 'Save a copy to file', s: 'Data', run: () => backupNow() });
  acts.push({ t: 'Open a backup file', s: 'Data', run: () => openBackupPicker() });
  REPORTS.forEach(r => acts.push({ t: r[1], s: 'Report', run: () => { LISTF.report = r[0]; go('reports'); } }));
  return acts;
}
function searchRecords(q) {
  q = q.toLowerCase();
  const out = [];
  DB.invoices.forEach(i => { if ((i.no + ' ' + contact(i.customerId).name).toLowerCase().includes(q)) out.push({ t: i.no + ' — ' + contact(i.customerId).name, s: 'Invoice · ' + money(docTotals(i).total), run: () => docView('invoice', i) }); });
  DB.bills.forEach(b => { if ((b.no + ' ' + contact(b.vendorId).name).toLowerCase().includes(q)) out.push({ t: b.no + ' — ' + contact(b.vendorId).name, s: 'Bill · ' + money(docTotals(b).total), run: () => docView('bill', b) }); });
  DB.contacts.forEach(c => { if (c.name.toLowerCase().includes(q)) out.push({ t: c.name, s: c.kind === 'customer' ? 'Customer' : 'Vendor', run: () => contactView(c) }); });
  DB.items.forEach(i => { if ((i.sku + ' ' + i.name).toLowerCase().includes(q)) out.push({ t: i.sku + ' · ' + i.name, s: 'Item · ' + money(i.price), run: () => itemModal(i) }); });
  DB.accounts.forEach(a => { if ((a.code + ' ' + a.name).toLowerCase().includes(q)) out.push({ t: a.code + ' · ' + a.name, s: 'Account · ' + a.type, run: () => { LISTF.ledgerAcc = a.id; go('ledger'); } }); });
  return out.slice(0, 12);
}
function openPalette(initial) {
  if ($('.palette')) return;
  const el = document.createElement('div');
  el.className = 'palette';
  el.innerHTML = '<div class="box"><input type="text" placeholder="Jump to, create or search…" value="' + esc(initial || '') + '"><ul></ul></div>';
  document.body.appendChild(el);
  const inp = $('input', el), ul = $('ul', el);
  let list = [], sel = 0;
  function draw() {
    const q = inp.value.trim();
    const base = paletteActions();
    list = q ? base.filter(a => (a.t + ' ' + a.s).toLowerCase().includes(q.toLowerCase())).slice(0, 8).concat(searchRecords(q)) : base.slice(0, 10);
    sel = 0;
    ul.innerHTML = list.map((a, i) => '<li' + (i === sel ? ' class="on"' : '') + ' data-i="' + i + '"><span>' + esc(a.t) + '</span><span class="k">' + esc(a.s) + '</span></li>').join('') || '<li class="sub">No matches</li>';
    $$('li[data-i]', ul).forEach(li => li.addEventListener('click', () => { const a = list[Number(li.dataset.i)]; el.remove(); a.run(); }));
  }
  function move(d) {
    sel = Math.max(0, Math.min(list.length - 1, sel + d));
    $$('li[data-i]', ul).forEach((li, i) => li.className = i === sel ? 'on' : '');
    const cur = $$('li[data-i]', ul)[sel]; if (cur) cur.scrollIntoView({ block: 'nearest' });
  }
  inp.addEventListener('input', draw);
  inp.addEventListener('keydown', e => {
    if (e.key === 'ArrowDown') { e.preventDefault(); move(1); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); move(-1); }
    else if (e.key === 'Enter') { const a = list[sel]; if (a) { el.remove(); a.run(); } }
  });
  el.addEventListener('mousedown', e => { if (e.target === el) el.remove(); });
  draw(); inp.focus(); inp.select();
}

/* ============================ router & boot ============================ */
const VIEWS = {
  dashboard: view_dashboard, invoices: view_invoices, estimates: view_estimates, creditnotes: view_creditnotes,
  customers: view_customers, recurring: view_recurring, bills: view_bills, pos: view_pos, expenses: view_expenses,
  vendors: view_vendors, items: view_items, stock: view_stock, banking: view_banking, reconcile: view_reconcile,
  coa: view_coa, journal: view_journal, ledger: view_ledger, assets: view_assets, budgets: view_budgets,
  payroll: view_payroll, projects: view_projects, reports: view_reports, settings: view_settings, audit: view_audit
};
const TITLES = {};
NAV.forEach(([g, items]) => items.forEach(([k, t]) => TITLES[k] = [t, g]));

function go(route) {
  /* navigating to the page you are already on still re-renders, so palette
     actions like picking a different report take effect immediately */
  if (location.hash === '#/' + route) { ROUTE = route; render(); }
  else location.hash = '#/' + route;
}
function render() {
  if (!VIEWS[ROUTE]) ROUTE = 'dashboard';
  renderSide();
  setCrumb((TITLES[ROUTE] || ['Dashboard', ''])[1], (TITLES[ROUTE] || ['Dashboard'])[0]);
  $('#avatar').textContent = currentUser().name.split(' ').map(s => s[0]).join('').slice(0, 2);
  $('#avatar').title = currentUser().name + ' · ' + currentUser().role;
  try { VIEWS[ROUTE](); } catch (e) { console.error(e); $('#view').innerHTML = '<div class="empty"><h3>That page hit a snag</h3><p class="sub">' + esc(e.message) + '</p><button class="btn mt" onclick="go(\'dashboard\')">Back to dashboard</button></div>'; }
  $$('#view [data-acc]').forEach(el => el.addEventListener('click', () => { LISTF.ledgerAcc = el.dataset.acc; go('ledger'); }));
  window.scrollTo({ top: 0 });
  $('#side').classList.remove('open');
}
function routeFromHash() {
  const h = location.hash.replace(/^#\/?/, '') || 'dashboard';
  ROUTE = h.split('/')[0] || 'dashboard';
  render();
}
window.addEventListener('hashchange', routeFromHash);

function migrate() {
  const b = blankDB();
  Object.keys(b).forEach(k => { if (DB[k] === undefined) DB[k] = b[k]; });
  ['adjustments', 'reconciliations', 'audit', 'attachments', 'recurring', 'projects', 'timeEntries'].forEach(k => { if (!Array.isArray(DB[k])) DB[k] = []; });
  if (!DB.session) DB.session = { userId: DB.users[0].id, period: 'ytd', from: '', to: '' };
}
async function boot() {
  let raw = null;
  try { raw = await storeGet(KEY); } catch (e) { }
  if (raw) { try { DB = JSON.parse(raw); migrate(); } catch (e) { DB = blankDB(); } }
  else { DB = blankDB(); logAudit('Created company file', 'Empty chart of accounts loaded'); await storeSet(KEY, JSON.stringify(DB)); }

  /* period selector */
  const opts = [['mtd', 'This month'], ['lastmonth', 'Last month'], ['qtd', 'This quarter'], ['ytd', 'Fiscal year to date'], ['last12', 'Last 12 months'], ['lastyear', 'Last fiscal year'], ['all', 'All dates']];
  $('#periodSel').innerHTML = opts.map(o => '<option value="' + o[0] + '"' + (DB.session.period === o[0] ? ' selected' : '') + '>' + o[1] + '</option>').join('');
  $('#periodSel').addEventListener('change', e => { DB.session.period = e.target.value; save(); render(); });
  $('#gsearch').addEventListener('focus', () => { openPalette(''); $('#gsearch').blur(); });
  $('#burger').addEventListener('click', () => $('#side').classList.toggle('open'));
  $('#avatar').addEventListener('click', () => { LISTF.setTab = 'users'; go('settings'); });
  document.addEventListener('keydown', e => {
    if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); openPalette(''); }
    if (e.key === '/' && !/input|textarea|select/i.test(document.activeElement.tagName)) { e.preventDefault(); openPalette(''); }
    if (e.key.toLowerCase() === 'n' && e.altKey) { e.preventDefault(); docEditor('invoice'); }
    if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); backupNow(); }
    if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'o') { e.preventDefault(); openBackupPicker(); }
  });
  routeFromHash();
}

/* Small scripting surface — handy from the browser console:
   BS.db returns the live company file, BS.report('pl') opens a report. */
window.BS = {
  get db() { return DB; }, set db(v) { DB = v; save('Replaced company file'); render(); },
  go, render, save, repostAll, seed, blankDB, LISTF, VIEWS, REPORTS, REP, DOCK,
  report(k) { LISTF.report = k; go('reports'); },
  totals: docTotals, balance, balanceAll, netIncome, period
};

boot();

</script>
</body>
</html>

Reaches out to

Websites this page contacts when it runs — fonts, chart libraries, data. Found by reading its source.

  • fonts.googleapis.com
  • fonts.gstatic.com

Licence

Published on Globefin under the MIT License. You may copy, change, and reuse this page, including commercially — just keep the notice below with it.

Copyright © 2026 Shane Hadden. Licensed under the MIT License. Published on Globefin.

Provided as is, without warranty. Any external libraries it loads keep their own licences. Terms →

Sandbox

Scripts run, but the demo has its own throwaway origin. It can't read your session or cookies, can't reach the page around it, and can't navigate your tab. Don't enter real passwords or personal data into any demo.