equals-wd-card-expense-proc.../templates/financial_reports/index.html

1493 lines
68 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Financial Reports — Undo Designs</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--navy: #0C1A3A;
--navy-2: #12244C;
--navy-3: #1a2f5e;
--navy-4: #0a1428;
--cyan: #00D4FF;
--cyan-dim: rgba(0,212,255,.12);
--cyan-glow: rgba(0,212,255,.06);
--blue: #1B8EF8;
--green: #10D98A;
--green-dim: rgba(16,217,138,.12);
--red: #F04438;
--red-dim: rgba(240,68,56,.12);
--amber: #F79009;
--w1: rgba(255,255,255,.95);
--w2: rgba(255,255,255,.65);
--w3: rgba(255,255,255,.35);
--w4: rgba(255,255,255,.10);
--w5: rgba(255,255,255,.05);
--border: rgba(255,255,255,.07);
--border-c: rgba(0,212,255,.18);
--mono: 'JetBrains Mono', monospace;
--disp: 'Space Grotesk', sans-serif;
--body: 'Inter', sans-serif;
--radius: 10px;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: var(--body);
background: var(--navy-4);
color: var(--w1);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
}
body::before {
content: '';
position: fixed; inset: 0; pointer-events: none; z-index: 0;
background-image: radial-gradient(circle, rgba(0,212,255,.07) 1px, transparent 1px);
background-size: 28px 28px;
}
header {
position: sticky; top: 0; z-index: 100;
background: rgba(12,26,58,.85);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
padding: 0 32px;
height: 60px;
display: flex; align-items: center; justify-content: space-between;
}
.logo {
display: flex; align-items: center; gap: 10px;
font-family: var(--disp); font-size: 15px; font-weight: 600;
color: var(--w1); text-decoration: none;
}
.logo-icon {
width: 30px; height: 30px;
background: linear-gradient(135deg, var(--navy-3), var(--navy-2));
border: 1px solid var(--border-c);
border-radius: 7px;
display: flex; align-items: center; justify-content: center;
}
.logo-icon svg { width: 16px; height: 16px; }
.logo span { color: var(--cyan); }
main {
position: relative; z-index: 1;
flex: 1;
max-width: 1140px;
width: 100%;
margin: 0 auto;
padding: 48px 24px 80px;
}
.page-title { margin-bottom: 40px; }
.eyebrow {
font-family: var(--mono); font-size: 10px;
letter-spacing: .16em; text-transform: uppercase;
color: var(--cyan); margin-bottom: 10px;
}
.page-title h1 {
font-family: var(--disp); font-size: 28px; font-weight: 700;
color: var(--w1); line-height: 1.2; margin-bottom: 8px;
}
.page-title p { font-size: 14px; color: var(--w2); line-height: 1.6; max-width: 560px; }
.card {
background: var(--navy-2);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
margin-bottom: 16px;
}
.card-label {
font-family: var(--mono); font-size: 9.5px; letter-spacing: .14em;
text-transform: uppercase; color: var(--w3); margin-bottom: 14px;
}
.file-zone {
border: 1.5px dashed var(--border);
border-radius: 8px;
padding: 28px 20px;
text-align: center;
cursor: default;
transition: all .2s;
position: relative;
}
.file-zone:hover, .file-zone.drag-over { border-color: var(--cyan); background: var(--cyan-glow); }
.file-zone-icon {
width: 36px; height: 36px; margin: 0 auto 10px;
background: var(--w5); border-radius: 8px;
display: flex; align-items: center; justify-content: center;
}
.file-zone-icon svg { width: 18px; height: 18px; color: var(--w3); }
.file-zone-label { font-size: 13px; color: var(--w2); }
.file-zone-label strong { color: var(--cyan); }
.file-zone-sub { font-size: 11px; color: var(--w3); margin-top: 4px; }
.tb-file-list { list-style: none; margin-top: 12px; }
.tb-file-list li {
display: flex; align-items: center; justify-content: space-between;
padding: 8px 12px; border: 1px solid var(--border);
border-radius: 6px; margin-bottom: 6px;
font-family: var(--mono); font-size: 11px; color: var(--w2);
background: var(--w5);
}
.tb-file-list li span { color: var(--cyan); margin-right: 8px; }
.tb-remove { background: none; border: none; cursor: pointer; color: var(--w3); font-size: 14px; padding: 0 4px; transition: color .15s; }
.tb-remove:hover { color: var(--red); }
.field-row { display: flex; gap: 12px; margin-bottom: 14px; flex-wrap: wrap; }
.field { flex: 1; min-width: 200px; }
.field label { display: block; font-size: 11px; color: var(--w3); margin-bottom: 6px; }
.field input[type="text"], .field input[type="date"] {
width: 100%; background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px;
padding: 9px 12px; font-family: var(--body); font-size: 13px; color: var(--w1);
outline: none; transition: border-color .2s;
}
.field input:focus { border-color: var(--cyan); }
.check-row { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; cursor: pointer; user-select: none; }
.checkbox {
width: 18px; height: 18px; border-radius: 5px; border: 1px solid var(--border);
background: var(--w5); display: flex; align-items: center; justify-content: center;
flex-shrink: 0; transition: all .15s;
}
.checkbox.checked { background: var(--cyan-dim); border-color: var(--border-c); }
.checkbox svg { width: 11px; height: 11px; color: var(--cyan); display: none; }
.checkbox.checked svg { display: block; }
.check-label { font-size: 13px; color: var(--w2); }
.check-label strong { color: var(--w1); }
.budget-file-panel {
margin: 0 0 14px 30px;
padding: 10px 12px;
background: var(--w5);
border: 1px solid var(--border);
border-radius: 8px;
display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;
}
.budget-file-status { font-size: 12px; color: var(--w2); }
.budget-file-status .filename { color: var(--w1); font-weight: 500; }
.budget-file-status.none { color: var(--w3); font-style: italic; }
.btn-link {
background: none; border: 1px solid var(--border-c); color: var(--cyan);
font-size: 11.5px; font-family: var(--disp); font-weight: 600;
padding: 6px 12px; border-radius: 6px; cursor: pointer; transition: all .15s;
}
.btn-link:hover { background: var(--cyan-glow); }
.btn-link:disabled { opacity: .4; cursor: not-allowed; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
padding: 11px 22px; border-radius: 8px; border: none;
font-family: var(--disp); font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .2s; text-decoration: none;
width: 100%; margin-top: 6px;
}
.btn-primary { background: linear-gradient(135deg, var(--cyan), var(--blue)); color: var(--navy); }
.btn-primary:hover { filter: brightness(1.08); }
.btn-primary:disabled { opacity: .4; cursor: not-allowed; filter: none; }
.spinner {
display: none;
align-items: center; gap: 8px;
font-family: var(--mono); font-size: 11px; color: var(--w3);
margin-top: 12px;
}
.spinner.visible { display: flex; }
.spinner-dot {
width: 6px; height: 6px; border-radius: 50%; background: var(--cyan);
animation: pulse 1s infinite ease-in-out;
}
@keyframes pulse { 0%,100% { opacity: .3; } 50% { opacity: 1; } }
.error-note {
display: none;
font-size: 12px; color: var(--red); background: var(--red-dim);
border: 1px solid rgba(240,68,56,.2); border-radius: 8px;
padding: 12px 14px; margin-top: 12px;
}
.error-note.visible { display: block; }
.result-card { display: none; }
.result-card.visible { display: block; }
.result-header { display: flex; align-items: center; gap: 10px; margin-bottom: 18px; }
.result-icon {
width: 32px; height: 32px; border-radius: 8px;
display: flex; align-items: center; justify-content: center;
}
.result-icon.ok { background: var(--green-dim); }
.result-icon.warn { background: var(--red-dim); }
.result-icon svg { width: 16px; height: 16px; }
.result-title { font-family: var(--disp); font-size: 15px; font-weight: 600; color: var(--w1); }
.result-sub { font-size: 12px; color: var(--w3); margin-top: 2px; }
.stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 16px; }
.stat-box { background: var(--w5); border: 1px solid var(--border); border-radius: 8px; padding: 12px; }
.stat-value { font-family: var(--mono); font-size: 17px; font-weight: 500; color: var(--cyan); line-height: 1; }
.stat-value.positive { color: var(--green); }
.stat-value.negative { color: var(--red); }
.stat-label { font-size: 10px; color: var(--w3); margin-top: 4px; text-transform: uppercase; letter-spacing: .08em; }
.recon-row {
display: flex; align-items: center; justify-content: space-between;
padding: 8px 0; border-bottom: 1px solid var(--w5);
font-family: var(--mono); font-size: 11px; color: var(--w2);
}
.recon-row:last-child { border-bottom: none; }
.recon-badge { padding: 3px 9px; border-radius: 20px; font-size: 10px; font-weight: 500; }
.recon-badge.ok { background: var(--green-dim); color: var(--green); }
.recon-badge.warn { background: var(--red-dim); color: var(--red); }
.compare-table { margin-bottom: 16px; }
.compare-row {
display: grid; grid-template-columns: 1.15fr 1fr 1fr 76px; gap: 10px; align-items: center;
padding: 9px 0; border-bottom: 1px solid var(--w5);
}
.compare-row:last-child { border-bottom: none; }
.compare-row.compare-header {
border-bottom: 1px solid var(--border); padding-bottom: 8px;
font-family: var(--mono); font-size: 9.5px; letter-spacing: .08em;
text-transform: uppercase; color: var(--w3);
}
.compare-label { font-size: 12px; color: var(--w2); }
.compare-value { font-family: var(--mono); font-size: 12px; color: var(--w1); text-align: right; }
.compare-header .compare-value { text-align: right; }
.acct-recon-table {
border: 1px solid var(--border); border-radius: 8px; overflow: hidden;
max-height: 280px; overflow-y: auto;
}
.acct-recon-row {
display: grid; grid-template-columns: 1fr 92px 92px 72px 62px; gap: 8px;
padding: 7px 10px; font-family: var(--mono); font-size: 10.5px; color: var(--w2);
border-bottom: 1px solid var(--w5); align-items: center;
}
.acct-recon-row:last-child { border-bottom: none; }
.acct-recon-row.head {
background: var(--w5); color: var(--w3); text-transform: uppercase;
letter-spacing: .06em; font-size: 9px; position: sticky; top: 0;
}
.acct-recon-row .num { text-align: right; }
.acct-recon-row.mismatch { background: var(--red-dim); }
.acct-recon-row.mismatch .num, .acct-recon-row.mismatch span:first-child { color: var(--w1); }
.diagnostic-note {
display: flex; gap: 10px; align-items: flex-start;
font-size: 12px; color: var(--w2); background: var(--amber-dim, rgba(247,144,9,.12));
border: 1px solid rgba(247,144,9,.25); border-radius: 8px;
padding: 12px 14px; margin-bottom: 10px; line-height: 1.55;
}
.diagnostic-note svg { width: 15px; height: 15px; color: var(--amber, #F79009); flex-shrink: 0; margin-top: 1px; }
.diagnostic-note strong { color: var(--w1); display: block; margin-bottom: 3px; }
.review-intro { font-size: 12.5px; color: var(--w2); line-height: 1.55; margin-bottom: 16px; }
.review-step-badge {
display: inline-block; margin-left: 10px; padding: 2px 9px; border-radius: 20px;
background: var(--cyan-dim); border: 1px solid var(--border-c); color: var(--cyan);
font-family: var(--mono); font-size: 9.5px; font-weight: 500; letter-spacing: .04em;
text-transform: none; vertical-align: middle;
}
.review-next-note {
display: flex; gap: 8px; align-items: flex-start;
font-size: 11.5px; color: var(--w3); line-height: 1.5;
background: var(--w5); border: 1px solid var(--border); border-radius: 8px;
padding: 10px 12px; margin: -6px 0 16px;
}
.review-next-note::before { content: '→'; color: var(--cyan); flex-shrink: 0; }
.review-row {
display: grid; grid-template-columns: 20px 1fr 1.4fr 100px 150px; gap: 10px; align-items: center;
padding: 10px 0; border-bottom: 1px solid var(--w5);
}
.review-row:last-child { border-bottom: none; }
.review-row input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--cyan); cursor: pointer; }
.review-account-code { font-family: var(--mono); font-size: 11px; color: var(--w1); }
.review-account-sub { font-size: 10.5px; color: var(--w3); margin-top: 2px; }
.review-row input[type="text"], .review-row select {
width: 100%; background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px;
padding: 7px 9px; font-family: var(--body); font-size: 12.5px; color: var(--w1);
outline: none; transition: border-color .2s;
}
.review-row input:focus, .review-row select:focus { border-color: var(--cyan); }
.review-row.excluded input[type="text"], .review-row.excluded select { opacity: .35; pointer-events: none; }
.review-row.excluded .review-account-code, .review-row.excluded .review-account-sub { opacity: .35; }
.review-row-budget { grid-template-columns: 20px 1.2fr 1fr 1fr; }
.review-row-mapping { grid-template-columns: 1fr 240px; }
.review-row-project-first { grid-template-columns: 1fr 320px 200px; }
.review-row-category-first { grid-template-columns: 1fr 200px 320px; }
.mapping-list { list-style: none; margin-bottom: 4px; }
.mapping-list li {
display: flex; flex-direction: column; align-items: stretch; gap: 6px;
padding: 8px 12px; border: 1px solid var(--border);
border-radius: 6px; margin-bottom: 6px;
font-family: var(--mono); font-size: 11px; color: var(--w2);
background: var(--w5);
}
.mapping-primary-row { display: flex; align-items: center; gap: 10px; }
.mapping-row-info { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.mapping-list li .mapping-account { color: var(--cyan); margin-right: 8px; }
.mapping-list li .mapping-arrow { color: var(--w3); margin: 0 6px; }
.mapping-list li .mapping-leave { color: var(--w3); font-style: italic; }
.mapping-target-select {
flex-shrink: 0; max-width: 240px;
background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px;
padding: 5px 8px; font-family: var(--body); font-size: 11.5px; color: var(--w1);
outline: none; transition: border-color .2s;
}
.mapping-target-select:focus { border-color: var(--cyan); }
.mapping-target-select:disabled { opacity: .5; }
.mapping-paired-row {
display: flex; align-items: center; gap: 8px;
padding-top: 6px; border-top: 1px dashed var(--border);
}
.mapping-paired-label { color: var(--w3); font-size: 10px; white-space: nowrap; flex-shrink: 0; }
.mapping-paired-source {
flex: 1; min-width: 0;
background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px;
padding: 5px 8px; font-family: var(--body); font-size: 11.5px; color: var(--w1);
outline: none; transition: border-color .2s;
}
.mapping-paired-source:focus { border-color: var(--cyan); }
.mapping-paired-row .mapping-target-select { max-width: 200px; }
.mapping-empty { font-size: 12px; color: var(--w3); font-style: italic; padding: 4px 0 10px; }
.mapping-subhead {
font-family: var(--mono); font-size: 10px; letter-spacing: .1em; text-transform: uppercase;
color: var(--w3); margin: 18px 0 8px;
}
.mapping-subhead:first-child { margin-top: 0; }
footer { position: relative; z-index: 1; text-align: center; padding: 20px; font-size: 11px; color: var(--w3); border-top: 1px solid var(--border); }
footer a { color: var(--cyan); text-decoration: none; }
</style>
</head>
<body>
<header>
<a class="logo" href="/">
<div class="logo-icon">
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4h12M2 8h8M2 12h5" stroke="#00D4FF" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</div>
Financial <span>Reports</span>
</a>
</header>
<main>
<div class="page-title">
<div class="eyebrow">Planeterra International Foundation</div>
<h1>Financial Reports</h1>
<p>Upload the revenue and expense trial balances to generate a Category Summary and Balance Sheet snapshot.</p>
</div>
<div class="card">
<div class="card-label">Trial Balance Files</div>
<div class="file-zone" id="tbZone">
<input type="file" id="tbFileInput" accept=".xlsx,.xls" multiple style="display:none">
<div class="file-zone-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14,2 14,8 20,8"/>
</svg>
</div>
<div class="file-zone-label" id="tbDropLabel"><strong>Drop trial balance files here</strong> or <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">browse</span></div>
<div class="file-zone-sub">Revenue trial balance + expense trial balance (.xlsx) — plus an optional GL Dump for Balance Sheet supporting schedules, and/or a Budget file to use for just this one run (see Report Options below to store one permanently)</div>
</div>
<ul class="tb-file-list" id="tbFileList"></ul>
</div>
<div class="card">
<div class="card-label">Report Options</div>
<div class="check-row" id="checkCategorySummary">
<div class="checkbox checked">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20,6 9,17 4,12"/></svg>
</div>
<div class="check-label"><strong>Category Summary</strong> — Revenue &amp; Expense by Account/Category/Project Code</div>
</div>
<div class="check-row" id="checkBalanceSheet">
<div class="checkbox checked">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20,6 9,17 4,12"/></svg>
</div>
<div class="check-label"><strong>Balance Sheet</strong> — Assets / Liabilities / Net Assets snapshot</div>
</div>
<div class="check-row" id="checkSchedules">
<div class="checkbox checked">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20,6 9,17 4,12"/></svg>
</div>
<div class="check-label"><strong>Supporting Schedules</strong> — one per Balance Sheet account, requires a GL Dump upload</div>
</div>
<div class="check-row" id="checkBudget">
<div class="checkbox checked">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20,6 9,17 4,12"/></svg>
</div>
<div class="check-label"><strong>Budget vs Actual</strong> — uses the stored Budget file below (or one dropped into Trial Balance Files above, just for this run)</div>
</div>
<div class="budget-file-panel">
<div class="budget-file-status none" id="budgetFileStatus">Checking stored Budget file…</div>
<input type="file" id="budgetFileInput" accept=".xlsx,.xls" style="display:none">
<button type="button" class="btn-link" id="budgetFileReplaceBtn">Upload / Replace Budget File</button>
</div>
<div class="spinner" id="budgetUploadSpinner" style="margin: -4px 0 14px 30px">
<div class="spinner-dot"></div>
Uploading…
</div>
<div class="error-note" id="budgetUploadError" style="margin: -4px 0 14px 30px"></div>
<div class="check-row" id="checkCents" style="margin-top:14px">
<div class="checkbox">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20,6 9,17 4,12"/></svg>
</div>
<div class="check-label">Show cents (default: whole dollars)</div>
</div>
<div class="field-row" style="margin-top:16px">
<div class="field">
<label for="reportDate">Report Date</label>
<input type="date" id="reportDate">
</div>
<div class="field">
<label for="reportTitle">Report Title</label>
<input type="text" id="reportTitle" value="Planeterra International Foundation (Group Consolidated)">
</div>
</div>
<button class="btn btn-primary" id="processBtn" disabled>Generate Report</button>
<div class="spinner" id="spinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="errorNote"></div>
</div>
<div class="card" id="reviewCard" style="display:none">
<div class="card-label">New Balance Sheet Accounts Found</div>
<p class="review-intro">These accounts have activity in the uploaded trial balance but aren't yet mapped to a Balance Sheet line item — left as-is, they'd be silently excluded from the Balance Sheet total. Review each one below, then confirm to add the checked accounts and generate the report.</p>
<div id="reviewRows"></div>
<button class="btn btn-primary" id="confirmAccountsBtn">Confirm &amp; Generate Report</button>
<div class="spinner" id="reviewSpinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="reviewErrorNote"></div>
</div>
<div class="card" id="reviewBudgetCard" style="display:none">
<div class="card-label">New Budget Lines Found</div>
<p class="review-intro">These budget lines don't have a matching entry in the budget key map yet — left as-is, they'd be silently excluded from the Budget vs Actual report. Type in the account (and project, if this line is project-specific) each one should count towards, then confirm.</p>
<div id="reviewBudgetRows"></div>
<button class="btn btn-primary" id="confirmBudgetLinesBtn">Confirm &amp; Generate Report</button>
<div class="spinner" id="reviewBudgetSpinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="reviewBudgetErrorNote"></div>
</div>
<div class="card" id="reviewBudgetProjectsCard" style="display:none">
<div class="card-label">Budget File Issues Found</div>
<p class="review-intro" id="reviewBudgetProjectsSummary"></p>
<button type="button" class="btn-link" id="toggleBudgetProjectsDetailsBtn" style="margin-bottom:14px">Show details</button>
<div id="reviewBudgetProjectsRows" style="display:none"></div>
<button class="btn btn-primary" id="confirmBudgetProjectsBtn">Continue &amp; Generate Report</button>
<div class="spinner" id="reviewBudgetProjectsSpinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="reviewBudgetProjectsErrorNote"></div>
</div>
<div class="card" id="reviewCategoryMappingCard" style="display:none">
<div class="card-label">Categories Not Found In The Budget <span class="review-step-badge">Review step 1 of up to 3</span></div>
<p class="review-intro">These TB categories have real actual activity but no matching category in the Budget file for that account. Fold one into an existing budget category to merge its actuals into that category's row (its project code stays the same), or leave it as-is. Either choice is remembered for future runs — edit it any time in Category &amp; Project Mappings below.</p>
<p class="review-next-note">After you confirm here, project codes not found in the budget are checked next, then any remaining budget file issues — before the report finally generates.</p>
<div id="reviewCategoryMappingRows"></div>
<button class="btn btn-primary" id="confirmCategoryMappingBtn">Confirm &amp; Continue</button>
<div class="spinner" id="reviewCategoryMappingSpinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="reviewCategoryMappingErrorNote"></div>
</div>
<div class="card" id="reviewProjectMappingCard" style="display:none">
<div class="card-label">Project Codes Not Found In The Budget <span class="review-step-badge">Review step 2 of up to 3</span></div>
<p class="review-intro">These TB project codes (often "(No project)") have real actual activity but no matching project in the Budget file for that account. Fold one into an existing budget project to merge its actuals into that project's row, or leave it as-is — remembered for future runs the same way as category mappings.</p>
<p class="review-next-note">After you confirm here, any remaining budget file issues are checked next, then the report generates.</p>
<div id="reviewProjectMappingRows"></div>
<button class="btn btn-primary" id="confirmProjectMappingBtn">Confirm &amp; Continue</button>
<div class="spinner" id="reviewProjectMappingSpinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="reviewProjectMappingErrorNote"></div>
</div>
<div class="card">
<div class="card-label">Category &amp; Project Mappings</div>
<p class="review-intro">Every reassignment decision on record — made just now above, or added directly here — applied automatically on every future run. A blank target means "leave as is, don't ask again".</p>
<div class="mapping-subhead">Category Mappings</div>
<div id="categoryMappingsList"></div>
<div class="field-row" style="margin-top:4px">
<div class="field"><input type="text" id="newCategoryAccountCode" placeholder="Account code (e.g. 43000)"></div>
<div class="field"><input type="text" id="newCategorySource" placeholder="TB category"></div>
<div class="field"><input type="text" id="newCategoryTarget" placeholder="Target (blank = leave as is)"></div>
</div>
<button class="btn-link" id="addCategoryMappingBtn">Add Mapping</button>
<div class="mapping-subhead">Project Mappings</div>
<div id="projectMappingsList"></div>
<div class="field-row" style="margin-top:4px">
<div class="field"><input type="text" id="newProjectAccountCode" placeholder="Account code (e.g. 68030)"></div>
<div class="field"><input type="text" id="newProjectSource" placeholder="TB project code"></div>
<div class="field"><input type="text" id="newProjectTarget" placeholder="Target (blank = leave as is)"></div>
</div>
<button class="btn-link" id="addProjectMappingBtn">Add Mapping</button>
</div>
<div class="card result-card" id="resultCard">
<div class="result-header">
<div class="result-icon" id="resultIcon">
<svg viewBox="0 0 24 24" fill="none" stroke="#10D98A" stroke-width="2.5">
<polyline points="20,6 9,17 4,12"/>
</svg>
</div>
<div>
<div class="result-title" id="resultTitle">Report generated</div>
<div class="result-sub" id="resultSub"></div>
</div>
</div>
<div class="stats-grid">
<div class="stat-box">
<div class="stat-value" id="statRevenue">—</div>
<div class="stat-label">Total Revenue</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statExpense">—</div>
<div class="stat-label">Total Expense</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statSurplus">—</div>
<div class="stat-label">Surplus / (Deficit)</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statBalanceCheck">—</div>
<div class="stat-label">Balance Sheet Check</div>
</div>
</div>
<div id="headlineCompareSection" style="display:none">
<div class="card-label" style="margin-top:4px">Report vs. Source Files</div>
<div class="compare-table">
<div class="compare-row compare-header">
<span></span><span class="compare-value">Report</span><span class="compare-value">Source Files</span><span></span>
</div>
<div class="compare-row">
<span class="compare-label">Total Income</span>
<span class="compare-value" id="cmpIncomeReport">—</span>
<span class="compare-value" id="cmpIncomeSource">—</span>
<span class="recon-badge" id="cmpIncomeBadge">—</span>
</div>
<div class="compare-row">
<span class="compare-label">Total Expenses</span>
<span class="compare-value" id="cmpExpensesReport">—</span>
<span class="compare-value" id="cmpExpensesSource">—</span>
<span class="recon-badge" id="cmpExpensesBadge">—</span>
</div>
<div class="compare-row">
<span class="compare-label">Surplus / (Deficit)</span>
<span class="compare-value" id="cmpSurplusReport">—</span>
<span class="compare-value" id="cmpSurplusSource">—</span>
<span class="recon-badge" id="cmpSurplusBadge">—</span>
</div>
</div>
</div>
<div id="reconSection" style="display:none">
<div class="card-label" style="margin-top:4px">Reconciliation to Uploaded Files</div>
<div id="reconRows"></div>
</div>
<div id="scheduleReconSection" style="display:none; margin-top:16px">
<div class="card-label" id="scheduleReconLabel">Supporting Schedules vs. Trial Balance</div>
<div id="scheduleDiagnostics"></div>
<div class="acct-recon-table" id="scheduleReconTable"></div>
</div>
<div id="budgetSection" style="display:none; margin-top:16px">
<div class="card-label" id="budgetLabel">Budget vs Actual</div>
<div id="budgetUnbudgetedNote"></div>
</div>
<button class="btn btn-primary" id="downloadBtn" style="margin-top:16px">Download Report</button>
</div>
</main>
<footer>
Built by <a href="https://undodesigns.com" target="_blank">Undo Designs</a> · Financial Reports v1
</footer>
<script>
const $ = id => document.getElementById(id);
$('reportDate').valueAsDate = new Date();
// ── Stored Budget file (see /api/upload-budget, /api/budget-status) ────────
function fmtStoredDate(iso) {
const d = new Date(iso);
return d.toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'})
+ ' ' + d.toLocaleTimeString('en-US', {hour: 'numeric', minute: '2-digit'});
}
async function refreshBudgetStatus() {
try {
const r = await fetch('/financial-reports/api/budget-status');
const d = await r.json();
const el = $('budgetFileStatus');
if (d.exists) {
el.classList.remove('none');
el.innerHTML = `<span class="filename">Budget file stored</span> — uploaded ${fmtStoredDate(d.uploaded_at)}`;
} else {
el.classList.add('none');
el.textContent = 'No Budget file stored yet — upload one to enable Budget vs Actual';
}
} catch (e) {
$('budgetFileStatus').textContent = 'Could not check stored Budget file status';
}
}
refreshBudgetStatus();
$('budgetFileReplaceBtn').addEventListener('click', () => $('budgetFileInput').click());
$('budgetFileInput').addEventListener('change', async () => {
const file = $('budgetFileInput').files[0];
if (!file) return;
$('budgetUploadError').classList.remove('visible');
$('budgetFileReplaceBtn').disabled = true;
$('budgetUploadSpinner').classList.add('visible');
const fd = new FormData();
fd.append('budget_file', file);
try {
const r = await fetch('/financial-reports/api/upload-budget', { method: 'POST', body: fd });
const d = await r.json();
if (r.ok && d.status === 'ok') {
await refreshBudgetStatus();
// A new Budget file means new category/project options for the
// Manage Mappings panel's inline dropdowns (see refreshBudgetOptions).
await refreshBudgetOptions();
refreshCategoryMappings();
refreshProjectMappings();
} else {
$('budgetUploadError').textContent = d.error || 'Unexpected error';
$('budgetUploadError').classList.add('visible');
}
} catch (e) {
$('budgetUploadError').textContent = 'Network error: ' + e.message;
$('budgetUploadError').classList.add('visible');
}
$('budgetUploadSpinner').classList.remove('visible');
$('budgetFileReplaceBtn').disabled = false;
$('budgetFileInput').value = '';
});
// ── Checkboxes ──────────────────────────────────────────────────────────────
function toggleCheck(rowId) {
$(rowId).querySelector('.checkbox').classList.toggle('checked');
}
$('checkCategorySummary').addEventListener('click', () => toggleCheck('checkCategorySummary'));
$('checkBalanceSheet').addEventListener('click', () => toggleCheck('checkBalanceSheet'));
$('checkSchedules').addEventListener('click', () => toggleCheck('checkSchedules'));
$('checkBudget').addEventListener('click', () => toggleCheck('checkBudget'));
$('checkCents').addEventListener('click', () => toggleCheck('checkCents'));
function isChecked(rowId) { return $(rowId).querySelector('.checkbox').classList.contains('checked'); }
// ── Multi-file upload ──────────────────────────────────────────────────────
const tbFiles = [];
function renderFileList() {
const list = $('tbFileList');
list.innerHTML = '';
tbFiles.forEach((file, idx) => {
const li = document.createElement('li');
li.innerHTML = `<span>${idx + 1}</span>${file.name}
<button class="tb-remove" data-idx="${idx}" title="Remove">✕</button>`;
list.appendChild(li);
});
list.querySelectorAll('.tb-remove').forEach(btn => {
btn.addEventListener('click', () => {
tbFiles.splice(+btn.dataset.idx, 1);
renderFileList();
$('processBtn').disabled = tbFiles.length === 0;
});
});
$('tbDropLabel').innerHTML = tbFiles.length
? `<strong>${tbFiles.length} file${tbFiles.length > 1 ? 's' : ''} selected</strong> — <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">add more</span>`
: `<strong>Drop trial balance files here</strong> or <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">browse</span>`;
document.getElementById('tbBrowseBtn')?.addEventListener('click', () => $('tbFileInput').click());
}
$('tbBrowseBtn').addEventListener('click', () => $('tbFileInput').click());
$('tbFileInput').addEventListener('change', () => {
Array.from($('tbFileInput').files).forEach(f => {
if (!tbFiles.find(x => x.name === f.name)) tbFiles.push(f);
});
$('tbFileInput').value = '';
$('processBtn').disabled = tbFiles.length === 0;
renderFileList();
});
const zone = $('tbZone');
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
e.preventDefault(); zone.classList.remove('drag-over');
Array.from(e.dataTransfer.files)
.filter(f => f.name.endsWith('.xlsx') || f.name.endsWith('.xls'))
.forEach(f => { if (!tbFiles.find(x => x.name === f.name)) tbFiles.push(f); });
$('processBtn').disabled = tbFiles.length === 0;
renderFileList();
});
// ── Process ───────────────────────────────────────────────────────────────
let lastFilename = '';
function escapeHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function fmtMoney(n) {
const sign = n < 0 ? '-' : '';
return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
function renderReportResult(d) {
lastFilename = d.filename;
$('resultSub').textContent = d.filename;
$('statRevenue').textContent = 'revenue_total' in d ? fmtMoney(d.revenue_total) : '—';
$('statExpense').textContent = 'expense_total' in d ? fmtMoney(d.expense_total) : '—';
const surplusEl = $('statSurplus');
if ('surplus_deficit' in d) {
surplusEl.textContent = fmtMoney(d.surplus_deficit);
surplusEl.className = 'stat-value ' + (d.surplus_deficit >= 0 ? 'positive' : 'negative');
} else {
surplusEl.textContent = '—'; surplusEl.className = 'stat-value';
}
const balEl = $('statBalanceCheck');
if ('balance_check' in d) {
balEl.textContent = fmtMoney(d.balance_check);
balEl.className = 'stat-value ' + (d.balance_sheet_balanced ? 'positive' : 'negative');
} else {
balEl.textContent = 'n/a'; balEl.className = 'stat-value';
}
if (d.headline_comparison) {
$('headlineCompareSection').style.display = '';
for (const [key, prefix] of [['income', 'cmpIncome'], ['expenses', 'cmpExpenses'], ['surplus', 'cmpSurplus']]) {
const m = d.headline_comparison[key];
$(prefix + 'Report').textContent = fmtMoney(m.report);
$(prefix + 'Source').textContent = fmtMoney(m.source);
const badge = $(prefix + 'Badge');
badge.textContent = m.match ? 'MATCH' : 'MISMATCH';
badge.className = 'recon-badge ' + (m.match ? 'ok' : 'warn');
}
} else {
$('headlineCompareSection').style.display = 'none';
}
if (d.reconciliation) {
$('reconSection').style.display = '';
const rows = [];
for (const [label, entity] of [['Canada', d.reconciliation.canada], ['US', d.reconciliation.us]]) {
const ok = Math.abs(entity.report - entity.source) < 0.01;
rows.push(`<div class="recon-row"><span>${label}: report ${fmtMoney(entity.report)} vs source ${fmtMoney(entity.source)}</span>
<span class="recon-badge ${ok ? 'ok' : 'warn'}">${ok ? 'MATCH' : 'MISMATCH'}</span></div>`);
}
$('reconRows').innerHTML = rows.join('');
} else {
$('reconSection').style.display = 'none';
}
if (d.schedules && d.schedules.length) {
$('scheduleReconSection').style.display = '';
const diagnostics = d.schedule_diagnostics || [];
$('scheduleDiagnostics').innerHTML = diagnostics.map(diag => `
<div class="diagnostic-note">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></svg>
<div><strong>${escapeHtml(diag.title)}</strong>${escapeHtml(diag.detail)}</div>
</div>
`).join('');
const sch = d.schedules;
const mismatches = sch.filter(s => !s.matches).length;
$('scheduleReconLabel').textContent = mismatches
? `Supporting Schedules vs. Trial Balance — ${mismatches} of ${sch.length} account${sch.length === 1 ? '' : 's'} MISMATCH`
: `Supporting Schedules vs. Trial Balance — all ${sch.length} accounts match`;
const rows = ['<div class="acct-recon-row head"><span>Account</span><span class="num">Trial Balance</span><span class="num">Schedule</span><span class="num">Diff</span><span>Status</span></div>'];
sch.forEach(s => {
rows.push(`<div class="acct-recon-row${s.matches ? '' : ' mismatch'}">
<span>${s.account}</span>
<span class="num">${fmtMoney(s.tb_total)}</span>
<span class="num">${fmtMoney(s.schedule_total)}</span>
<span class="num">${fmtMoney(s.diff)}</span>
<span class="recon-badge ${s.matches ? 'ok' : 'warn'}">${s.matches ? 'OK' : 'MISMATCH'}</span>
</div>`);
});
$('scheduleReconTable').innerHTML = rows.join('');
} else {
$('scheduleReconSection').style.display = 'none';
$('scheduleDiagnostics').innerHTML = '';
}
if (d.budget_vs_actual) {
$('budgetSection').style.display = '';
const bva = d.budget_vs_actual;
$('budgetLabel').textContent = `Budget vs Actual — ${bva.lines} line${bva.lines === 1 ? '' : 's'} · `
+ `Budget ${fmtMoney(bva.total_budget)} · Actual ${fmtMoney(bva.total_actual)}`;
const unbudgeted = bva.unbudgeted_actuals || [];
if (unbudgeted.length) {
const total = unbudgeted.reduce((s, u) => s + u.actual_ytd, 0);
const rows = unbudgeted.map(u =>
`<div class="recon-row"><span>${escapeHtml(u.account_code)}${u.category ? ' — ' + escapeHtml(u.category) : ''}${u.project ? ' — ' + escapeHtml(u.project) : ''}</span>
<span>${fmtMoney(u.actual_ytd)}</span></div>`).join('');
$('budgetUnbudgetedNote').innerHTML = `
<div class="diagnostic-note">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></svg>
<div><strong>${unbudgeted.length} account/project combination${unbudgeted.length === 1 ? '' : 's'} with actual activity but no budget line (${fmtMoney(total)} total)</strong>${rows}</div>
</div>`;
} else {
$('budgetUnbudgetedNote').innerHTML = '';
}
} else {
$('budgetSection').style.display = 'none';
$('budgetUnbudgetedNote').innerHTML = '';
}
const icon = $('resultIcon');
if (d.reconciled) {
icon.className = 'result-icon ok';
$('resultTitle').textContent = 'Report generated — reconciled';
} else {
icon.className = 'result-icon warn';
$('resultTitle').textContent = 'Report generated — check reconciliation';
}
$('resultCard').classList.add('visible');
}
// ── Shared dispatcher: a response can be a finished report, either review
// gate (see routes.py's _check_gates_and_respond - confirming one gate can
// chain straight into needing the other), or an error. ────────────────────
function hideAllReviewCards() {
$('reviewCard').style.display = 'none';
$('reviewBudgetCard').style.display = 'none';
$('reviewBudgetProjectsCard').style.display = 'none';
$('reviewCategoryMappingCard').style.display = 'none';
$('reviewProjectMappingCard').style.display = 'none';
}
function handleProcessResponse(d, errorNoteId) {
if (d.status === 'ok') {
hideAllReviewCards();
renderReportResult(d);
refreshCategoryMappings();
refreshProjectMappings();
} else if (d.status === 'needs_review' && d.review_type === 'accounts') {
hideAllReviewCards();
pendingToken = d.token;
pendingUnmapped = d.unmapped_accounts;
renderReviewRows();
$('reviewCard').style.display = '';
} else if (d.status === 'needs_review' && d.review_type === 'budget_lines') {
hideAllReviewCards();
pendingBudgetToken = d.token;
pendingUnmappedBudgetLines = d.unmapped_budget_lines;
renderReviewBudgetRows();
$('reviewBudgetCard').style.display = '';
} else if (d.status === 'needs_review' && d.review_type === 'category_mapping') {
hideAllReviewCards();
pendingCategoryMappingToken = d.token;
pendingUnmappedCategories = d.unmapped_categories;
renderReviewCategoryMappingRows();
$('reviewCategoryMappingCard').style.display = '';
} else if (d.status === 'needs_review' && d.review_type === 'project_mapping') {
hideAllReviewCards();
pendingProjectMappingToken = d.token;
pendingUnmappedProjects = d.unmapped_projects;
renderReviewProjectMappingRows();
$('reviewProjectMappingCard').style.display = '';
} else if (d.status === 'needs_review' && d.review_type === 'budget_projects') {
hideAllReviewCards();
pendingBudgetProjectsToken = d.token;
pendingUnmatchedBudgetProjects = d.unmatched_budget_projects;
pendingMissingAccountRows = d.missing_account_rows || [];
renderReviewBudgetProjectsRows();
$('reviewBudgetProjectsCard').style.display = '';
} else {
$(errorNoteId).textContent = d.error || 'Unexpected error';
$(errorNoteId).classList.add('visible');
}
}
// ── Unmapped-account review (see /api/process's "needs_review" status) ─────
let pendingToken = null;
let pendingUnmapped = [];
const SECTION_LABELS = { Assets: 'Assets', Liabilities: 'Liabilities', NetAssets: 'Net Assets' };
function renderReviewRows() {
$('reviewRows').innerHTML = pendingUnmapped.map((a, i) => `
<div class="review-row" data-idx="${i}">
<input type="checkbox" class="review-include" data-idx="${i}" checked>
<div>
<div class="review-account-code">${escapeHtml(a.account_label)}</div>
<div class="review-account-sub">${fmtMoney(a.tb_total)} on the trial balance</div>
</div>
<input type="text" class="review-line-item" data-idx="${i}" placeholder="Line item name (e.g. Accounts receivable)">
<select class="review-section" data-idx="${i}">
${Object.entries(SECTION_LABELS).map(([val, label]) =>
`<option value="${val}" ${a.suggested_section === val ? 'selected' : ''}>${label}</option>`).join('')}
</select>
<select class="review-sign" data-idx="${i}">
<option value="1" ${a.suggested_sign === 1 ? 'selected' : ''}>+ (increases section)</option>
<option value="-1" ${a.suggested_sign === -1 ? 'selected' : ''}>− (decreases section)</option>
</select>
</div>
`).join('');
$('reviewRows').querySelectorAll('.review-include').forEach(cb => {
cb.addEventListener('change', () => {
cb.closest('.review-row').classList.toggle('excluded', !cb.checked);
});
});
}
$('confirmAccountsBtn').addEventListener('click', async () => {
$('reviewErrorNote').classList.remove('visible');
const mappings = [];
let missingLabel = false;
$('reviewRows').querySelectorAll('.review-row').forEach(row => {
const idx = +row.dataset.idx;
if (!row.querySelector('.review-include').checked) return;
const lineItem = row.querySelector('.review-line-item').value.trim();
if (!lineItem) { missingLabel = true; return; }
mappings.push({
account_code: pendingUnmapped[idx].account_code,
line_item: lineItem,
section: row.querySelector('.review-section').value,
sign: parseInt(row.querySelector('.review-sign').value, 10),
});
});
if (missingLabel) {
$('reviewErrorNote').textContent = 'Give every checked account a line item name, or uncheck it to leave it unmapped for now.';
$('reviewErrorNote').classList.add('visible');
return;
}
$('confirmAccountsBtn').disabled = true;
$('reviewSpinner').classList.add('visible');
try {
const r = await fetch('/financial-reports/api/confirm-accounts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: pendingToken, mappings }),
});
const d = await r.json();
handleProcessResponse(d, 'reviewErrorNote');
} catch (e) {
$('reviewErrorNote').textContent = 'Network error: ' + e.message;
$('reviewErrorNote').classList.add('visible');
}
$('reviewSpinner').classList.remove('visible');
$('confirmAccountsBtn').disabled = false;
});
// ── Unmapped-budget-line review (see /api/process's "needs_review" status,
// review_type "budget_lines") ───────────────────────────────────────────────
let pendingBudgetToken = null;
let pendingUnmappedBudgetLines = [];
function renderReviewBudgetRows() {
$('reviewBudgetRows').innerHTML = pendingUnmappedBudgetLines.map((b, i) => `
<div class="review-row review-row-budget" data-idx="${i}">
<input type="checkbox" class="review-include" data-idx="${i}" checked>
<div>
<div class="review-account-code">${escapeHtml(b.budget_gl_name)}${b.budget_no ? ' <span style="color:var(--w3)">(No. ' + escapeHtml(b.budget_no) + ')</span>' : ''}</div>
<div class="review-account-sub">${fmtMoney(b.ytd_budget)} YTD budget</div>
</div>
<input type="text" class="review-target-account" data-idx="${i}" placeholder="Account (e.g. 72800:Visas and Other dues)">
<input type="text" class="review-target-project" data-idx="${i}" placeholder="Project (leave blank if account-level)">
</div>
`).join('');
$('reviewBudgetRows').querySelectorAll('.review-include').forEach(cb => {
cb.addEventListener('change', () => {
cb.closest('.review-row').classList.toggle('excluded', !cb.checked);
});
});
}
$('confirmBudgetLinesBtn').addEventListener('click', async () => {
$('reviewBudgetErrorNote').classList.remove('visible');
const mappings = [];
let missingAccount = false;
$('reviewBudgetRows').querySelectorAll('.review-row').forEach(row => {
const idx = +row.dataset.idx;
if (!row.querySelector('.review-include').checked) return;
const account = row.querySelector('.review-target-account').value.trim();
if (!account) { missingAccount = true; return; }
mappings.push({
budget_gl_name: pendingUnmappedBudgetLines[idx].budget_gl_name,
budget_no: pendingUnmappedBudgetLines[idx].budget_no,
summary_account: account,
summary_project: row.querySelector('.review-target-project').value.trim(),
});
});
if (missingAccount) {
$('reviewBudgetErrorNote').textContent = 'Give every checked budget line a target account, or uncheck it to leave it unmapped for now.';
$('reviewBudgetErrorNote').classList.add('visible');
return;
}
$('confirmBudgetLinesBtn').disabled = true;
$('reviewBudgetSpinner').classList.add('visible');
try {
const r = await fetch('/financial-reports/api/confirm-budget-lines', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: pendingBudgetToken, mappings }),
});
const d = await r.json();
handleProcessResponse(d, 'reviewBudgetErrorNote');
} catch (e) {
$('reviewBudgetErrorNote').textContent = 'Network error: ' + e.message;
$('reviewBudgetErrorNote').classList.add('visible');
}
$('reviewBudgetSpinner').classList.remove('visible');
$('confirmBudgetLinesBtn').disabled = false;
});
// ── Unmatched-budget-project review (see /api/process's "needs_review"
// status, review_type "budget_projects") - acknowledge-only, nothing to
// type in: a detailed-format budget file already carries its own
// account/category/project mapping (see routes.py's api_confirm_budget_projects).
let pendingBudgetProjectsToken = null;
let pendingUnmatchedBudgetProjects = [];
let pendingMissingAccountRows = [];
function renderReviewBudgetProjectsRows() {
const unmatchedHtml = pendingUnmatchedBudgetProjects.map(p => `
<div class="review-row review-row-budget">
<div>
<div class="review-account-code">${escapeHtml(p.category)} — ${escapeHtml(p.project)}</div>
<div class="review-account-sub">${escapeHtml(p.account)} · ${fmtMoney(p.ytd_budget)} YTD budget</div>
</div>
</div>
`).join('');
const missingAccountHtml = pendingMissingAccountRows.map(m => `
<div class="review-row review-row-budget">
<div>
<div class="review-account-code">${escapeHtml(m.gl_name || m.category)} — ${escapeHtml(m.category)} / ${escapeHtml(m.project)}</div>
<div class="review-account-sub" style="color:var(--red)">No Account at all in the Budget file${m.no ? ' (No. ' + escapeHtml(String(m.no)) + ')' : ''} · ${fmtMoney(m.amount)} — currently excluded from every Budget/Variance total until fixed in the source workbook</div>
</div>
</div>
`).join('');
let html = '';
if (pendingMissingAccountRows.length) {
html += `<div class="card-label" style="color:var(--red)">Missing Account entirely (${pendingMissingAccountRows.length}) — fix in the source Budget workbook and re-upload</div>${missingAccountHtml}`;
}
if (pendingUnmatchedBudgetProjects.length) {
html += `<div class="card-label" style="margin-top:${pendingMissingAccountRows.length ? '14px' : '0'}">No matching TB activity (${pendingUnmatchedBudgetProjects.length})</div>${unmatchedHtml}`;
}
$('reviewBudgetProjectsRows').innerHTML = html;
const total = pendingMissingAccountRows.length + pendingUnmatchedBudgetProjects.length;
const parts = [];
if (pendingMissingAccountRows.length) parts.push(`${pendingMissingAccountRows.length} missing an Account entirely (worth fixing in the source workbook)`);
if (pendingUnmatchedBudgetProjects.length) parts.push(`${pendingUnmatchedBudgetProjects.length} with no matching TB activity (usually fine to continue past)`);
$('reviewBudgetProjectsSummary').textContent = `${total} budget file issue${total === 1 ? '' : 's'} found — ${parts.join(', ')}. Nothing needs to be filled in either way.`;
$('reviewBudgetProjectsRows').style.display = 'none';
$('toggleBudgetProjectsDetailsBtn').textContent = 'Show details';
}
$('toggleBudgetProjectsDetailsBtn').addEventListener('click', () => {
const rows = $('reviewBudgetProjectsRows');
const hidden = rows.style.display === 'none';
rows.style.display = hidden ? '' : 'none';
$('toggleBudgetProjectsDetailsBtn').textContent = hidden ? 'Hide details' : 'Show details';
});
$('confirmBudgetProjectsBtn').addEventListener('click', async () => {
$('reviewBudgetProjectsErrorNote').classList.remove('visible');
$('confirmBudgetProjectsBtn').disabled = true;
$('reviewBudgetProjectsSpinner').classList.add('visible');
try {
const r = await fetch('/financial-reports/api/confirm-budget-projects', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: pendingBudgetProjectsToken }),
});
const d = await r.json();
handleProcessResponse(d, 'reviewBudgetProjectsErrorNote');
} catch (e) {
$('reviewBudgetProjectsErrorNote').textContent = 'Network error: ' + e.message;
$('reviewBudgetProjectsErrorNote').classList.add('visible');
}
$('reviewBudgetProjectsSpinner').classList.remove('visible');
$('confirmBudgetProjectsBtn').disabled = false;
});
// ── Unmapped-TB-category review (see /api/process's "needs_review" status,
// review_type "category_mapping") - each row either folds into an existing
// budget category (a real merge - see logic.py's _apply_reassignment) or is
// left as-is, either way remembered via category_reassignment_map.csv. ────
let pendingCategoryMappingToken = null;
let pendingUnmappedCategories = [];
function renderReviewCategoryMappingRows() {
$('reviewCategoryMappingRows').innerHTML = pendingUnmappedCategories.map((c, i) => `
<div class="review-row review-row-category-first" data-idx="${i}">
<div>
<div class="review-account-code">${escapeHtml(c.category)}</div>
<div class="review-account-sub">${escapeHtml(c.account_name)} · ${escapeHtml(c.project)} · ${fmtMoney(c.amount)} YTD actual</div>
</div>
<select class="review-target-category" data-idx="${i}">
<option value="">Leave category as is</option>
${c.budget_categories.map(bc => `<option value="${escapeHtml(bc)}">${escapeHtml(bc)}</option>`).join('')}
</select>
<select class="review-target-project" data-idx="${i}">
<option value="">Keep project: ${escapeHtml(c.project)}</option>
${c.budget_projects.map(bp => `<option value="${escapeHtml(bp)}">Move to: ${escapeHtml(bp)}</option>`).join('')}
</select>
</div>
`).join('');
}
$('confirmCategoryMappingBtn').addEventListener('click', async () => {
$('reviewCategoryMappingErrorNote').classList.remove('visible');
const decisions = pendingUnmappedCategories.map((c, i) => {
const targetCategory = $('reviewCategoryMappingRows').querySelector(`.review-target-category[data-idx="${i}"]`).value;
const targetProject = $('reviewCategoryMappingRows').querySelector(`.review-target-project[data-idx="${i}"]`).value;
const decision = targetCategory
? { account_code: c.account_code, source: c.category, action: 'map', target_category: targetCategory }
: { account_code: c.account_code, source: c.category, action: 'leave_as_is' };
decision.project = c.project;
if (targetProject) {
decision.project_action = 'map';
decision.target_project = targetProject;
} else {
decision.project_action = 'keep';
}
return decision;
});
$('confirmCategoryMappingBtn').disabled = true;
$('reviewCategoryMappingSpinner').classList.add('visible');
try {
const r = await fetch('/financial-reports/api/confirm-category-mapping', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: pendingCategoryMappingToken, decisions }),
});
const d = await r.json();
handleProcessResponse(d, 'reviewCategoryMappingErrorNote');
} catch (e) {
$('reviewCategoryMappingErrorNote').textContent = 'Network error: ' + e.message;
$('reviewCategoryMappingErrorNote').classList.add('visible');
}
$('reviewCategoryMappingSpinner').classList.remove('visible');
$('confirmCategoryMappingBtn').disabled = false;
});
// ── Unmapped-TB-project review (see /api/process's "needs_review" status,
// review_type "project_mapping") - same mechanics as category mapping. ─────
let pendingProjectMappingToken = null;
let pendingUnmappedProjects = [];
function renderReviewProjectMappingRows() {
$('reviewProjectMappingRows').innerHTML = pendingUnmappedProjects.map((p, i) => `
<div class="review-row review-row-project-first" data-idx="${i}">
<div>
<div class="review-account-code">${escapeHtml(p.project)}</div>
<div class="review-account-sub">${escapeHtml(p.account_name)} · ${escapeHtml(p.category)} · ${fmtMoney(p.amount)} YTD actual</div>
</div>
<select class="review-target-project" data-idx="${i}">
<option value="">Leave project as is</option>
${p.budget_projects.map(bp => `<option value="${escapeHtml(bp)}">${escapeHtml(bp)}</option>`).join('')}
</select>
<select class="review-target-category" data-idx="${i}">
<option value="">Keep category: ${escapeHtml(p.category)}</option>
${p.budget_categories.map(bc => `<option value="${escapeHtml(bc)}">Move to: ${escapeHtml(bc)}</option>`).join('')}
</select>
</div>
`).join('');
}
$('confirmProjectMappingBtn').addEventListener('click', async () => {
$('reviewProjectMappingErrorNote').classList.remove('visible');
const decisions = pendingUnmappedProjects.map((p, i) => {
const targetProject = $('reviewProjectMappingRows').querySelector(`.review-target-project[data-idx="${i}"]`).value;
const targetCategory = $('reviewProjectMappingRows').querySelector(`.review-target-category[data-idx="${i}"]`).value;
const decision = targetProject
? { account_code: p.account_code, source: p.project, action: 'map', target_project: targetProject }
: { account_code: p.account_code, source: p.project, action: 'leave_as_is' };
decision.category = p.category;
if (targetCategory) {
decision.category_action = 'map';
decision.target_category = targetCategory;
} else {
decision.category_action = 'keep';
}
return decision;
});
$('confirmProjectMappingBtn').disabled = true;
$('reviewProjectMappingSpinner').classList.add('visible');
try {
const r = await fetch('/financial-reports/api/confirm-project-mapping', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: pendingProjectMappingToken, decisions }),
});
const d = await r.json();
handleProcessResponse(d, 'reviewProjectMappingErrorNote');
} catch (e) {
$('reviewProjectMappingErrorNote').textContent = 'Network error: ' + e.message;
$('reviewProjectMappingErrorNote').classList.add('visible');
}
$('reviewProjectMappingSpinner').classList.remove('visible');
$('confirmProjectMappingBtn').disabled = false;
});
// ── Manage Mappings panel (independent of any run - see
// /api/category-mappings, /api/project-mappings) - each existing mapping's
// target is a live dropdown (options from /api/budget-options, the stored
// Budget file's own categories/projects for that account), reassigned by
// picking a new option rather than deleting and waiting for a fresh run to
// re-flag it. ────────────────────────────────────────────────────────────
let budgetOptionsByAccount = {};
async function refreshBudgetOptions() {
try {
const r = await fetch('/financial-reports/api/budget-options');
const d = await r.json();
budgetOptionsByAccount = d.by_account || {};
} catch (e) { /* dropdowns just fall back to "Leave as is" + the current value */ }
}
function buildMappingTargetOptions(accountCode, currentTarget, kind, placeholderLabel) {
const opts = budgetOptionsByAccount[accountCode];
const list = opts ? (kind === 'category' ? opts.categories : opts.projects) : [];
const html = [`<option value="">${escapeHtml(placeholderLabel || 'Leave as is')}</option>`];
if (currentTarget && !list.includes(currentTarget)) {
html.push(`<option value="${escapeHtml(currentTarget)}" selected>${escapeHtml(currentTarget)} (current)</option>`);
}
list.forEach(v => {
html.push(`<option value="${escapeHtml(v)}" ${v === currentTarget ? 'selected' : ''}>${escapeHtml(v)}</option>`);
});
return html.join('');
}
// kind's mapping list also gets a secondary "also reassign <the other kind>"
// row per entry, mirroring the review gates' combined category+project
// decision - unlike a flagged review-gate row, a saved mapping doesn't
// carry a specific project (or category) of its own, so this writes an
// independent companion entry to the OTHER file, keyed by whatever source
// text is typed in here (see api_confirm_category_mapping/_project_mapping
// for the review-gate equivalent, which already knows the source).
function renderMappingsList(containerId, mappings, kind, upsertUrl, onDelete) {
const el = $(containerId);
if (!mappings.length) {
el.innerHTML = '<div class="mapping-empty">None yet</div>';
return;
}
const pairedKind = kind === 'category' ? 'project' : 'category';
const pairedUpsertUrl = kind === 'category' ? '/financial-reports/api/project-mappings' : '/financial-reports/api/category-mappings';
const pairedLabel = kind === 'category' ? '+ project:' : '+ category:';
const pairedPlaceholder = kind === 'category' ? 'Project code to also reassign' : 'Category to also reassign';
el.innerHTML = '<ul class="mapping-list">' + mappings.map(m => `
<li>
<div class="mapping-primary-row">
<span class="mapping-row-info"><span class="mapping-account">${escapeHtml(m.account_code)}</span>${escapeHtml(m.source)}</span>
<span class="mapping-arrow">→</span>
<select class="mapping-target-select" data-account="${escapeHtml(m.account_code)}" data-source="${escapeHtml(m.source)}">
${buildMappingTargetOptions(m.account_code, m.target, kind)}
</select>
<button class="tb-remove" data-account="${escapeHtml(m.account_code)}" data-source="${escapeHtml(m.source)}" title="Remove">✕</button>
</div>
<div class="mapping-paired-row">
<span class="mapping-paired-label">${pairedLabel}</span>
<input type="text" class="mapping-paired-source" placeholder="${pairedPlaceholder} (optional)">
<select class="mapping-target-select mapping-paired-target">
${buildMappingTargetOptions(m.account_code, '', pairedKind, 'Select target…')}
</select>
<button type="button" class="btn-link mapping-paired-apply" data-account="${escapeHtml(m.account_code)}">Apply</button>
</div>
</li>`).join('') + '</ul>';
el.querySelectorAll('.mapping-target-select:not(.mapping-paired-target)').forEach(sel => {
sel.addEventListener('change', async () => {
sel.disabled = true;
try {
await fetch(upsertUrl, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_code: sel.dataset.account, source: sel.dataset.source, target: sel.value }),
});
} finally {
if (kind === 'category') refreshCategoryMappings(); else refreshProjectMappings();
}
});
});
el.querySelectorAll('.tb-remove').forEach(btn => {
btn.addEventListener('click', () => onDelete(btn.dataset.account, btn.dataset.source));
});
el.querySelectorAll('.mapping-paired-apply').forEach(btn => {
btn.addEventListener('click', async () => {
const row = btn.closest('.mapping-paired-row');
const sourceInput = row.querySelector('.mapping-paired-source');
const targetSelect = row.querySelector('.mapping-paired-target');
const source = sourceInput.value.trim();
if (!source) { sourceInput.focus(); return; }
btn.disabled = true;
try {
await fetch(pairedUpsertUrl, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_code: btn.dataset.account, source, target: targetSelect.value }),
});
} finally {
if (pairedKind === 'category') refreshCategoryMappings(); else refreshProjectMappings();
}
});
});
}
async function refreshCategoryMappings() {
try {
const r = await fetch('/financial-reports/api/category-mappings');
const d = await r.json();
renderMappingsList('categoryMappingsList', d.mappings || [], 'category', '/financial-reports/api/category-mappings', deleteCategoryMappingRow);
} catch (e) { /* Manage Mappings panel is a convenience, fail quietly */ }
}
async function deleteCategoryMappingRow(account_code, source) {
await fetch('/financial-reports/api/category-mappings/delete', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_code, source }),
});
refreshCategoryMappings();
}
$('addCategoryMappingBtn').addEventListener('click', async () => {
const account_code = $('newCategoryAccountCode').value.trim();
const source = $('newCategorySource').value.trim();
const target = $('newCategoryTarget').value.trim();
if (!account_code || !source) return;
await fetch('/financial-reports/api/category-mappings', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_code, source, target }),
});
$('newCategoryAccountCode').value = ''; $('newCategorySource').value = ''; $('newCategoryTarget').value = '';
refreshCategoryMappings();
});
async function refreshProjectMappings() {
try {
const r = await fetch('/financial-reports/api/project-mappings');
const d = await r.json();
renderMappingsList('projectMappingsList', d.mappings || [], 'project', '/financial-reports/api/project-mappings', deleteProjectMappingRow);
} catch (e) { /* Manage Mappings panel is a convenience, fail quietly */ }
}
async function deleteProjectMappingRow(account_code, source) {
await fetch('/financial-reports/api/project-mappings/delete', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_code, source }),
});
refreshProjectMappings();
}
$('addProjectMappingBtn').addEventListener('click', async () => {
const account_code = $('newProjectAccountCode').value.trim();
const source = $('newProjectSource').value.trim();
const target = $('newProjectTarget').value.trim();
if (!account_code || !source) return;
await fetch('/financial-reports/api/project-mappings', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_code, source, target }),
});
$('newProjectAccountCode').value = ''; $('newProjectSource').value = ''; $('newProjectTarget').value = '';
refreshProjectMappings();
});
refreshBudgetOptions().then(() => {
refreshCategoryMappings();
refreshProjectMappings();
});
// ── Process ───────────────────────────────────────────────────────────────
$('processBtn').addEventListener('click', async () => {
if (tbFiles.length === 0) return;
$('processBtn').disabled = true;
$('spinner').classList.add('visible');
$('errorNote').classList.remove('visible');
$('resultCard').classList.remove('visible');
hideAllReviewCards();
const fd = new FormData();
tbFiles.forEach((f, i) => fd.append(`trial_balance_file_${i}`, f));
fd.append('include_category_summary', isChecked('checkCategorySummary'));
fd.append('include_balance_sheet', isChecked('checkBalanceSheet'));
fd.append('include_schedules', isChecked('checkSchedules'));
fd.append('include_budget', isChecked('checkBudget'));
fd.append('use_cents', isChecked('checkCents'));
fd.append('report_date', $('reportDate').value);
fd.append('title', $('reportTitle').value);
try {
const r = await fetch('/financial-reports/api/process', { method: 'POST', body: fd });
const d = await r.json();
handleProcessResponse(d, 'errorNote');
} catch (e) {
$('errorNote').textContent = 'Network error: ' + e.message;
$('errorNote').classList.add('visible');
}
$('spinner').classList.remove('visible');
$('processBtn').disabled = false;
});
$('downloadBtn').addEventListener('click', () => {
if (lastFilename) window.location.href = '/financial-reports/api/download/' + encodeURIComponent(lastFilename);
});
</script>
</body>
</html>