| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536 |
- <?php
- require __DIR__ . '/auth.php';
- $dbPath = __DIR__ . '/_private/pl.db';
- $hasData = file_exists($dbPath) && filesize($dbPath) > 0;
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>P&L Viewer — ICG Magnetics</title>
- <style>
- *{box-sizing:border-box;margin:0;padding:0}
- html,body{height:100%;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;font-size:13px;background:#f1f5f9;color:#1e293b}
- /* ─── Layout ─── */
- #app{display:flex;height:100vh;overflow:hidden}
- #sidebar{width:220px;min-width:220px;background:#1e293b;color:#e2e8f0;display:flex;flex-direction:column;overflow:hidden;flex-shrink:0}
- #main{flex:1;display:flex;flex-direction:column;min-width:0;overflow:hidden}
- /* ─── Sidebar header ─── */
- #sb-head{padding:14px 14px 10px;border-bottom:1px solid #334155;flex-shrink:0}
- #sb-head h1{font-size:14px;font-weight:700;color:#f8fafc;letter-spacing:-.2px;line-height:1.3}
- #sb-head .sub{font-size:10px;color:#64748b;margin-top:2px;letter-spacing:.2px;text-transform:uppercase}
- .upload-link{display:flex;align-items:center;gap:6px;margin-top:10px;padding:7px 10px;background:#3b82f6;color:white;border-radius:5px;text-decoration:none;font-size:12px;font-weight:600;justify-content:center}
- .upload-link:hover{background:#2563eb}
- /* ─── Quick-select ─── */
- #qsel{padding:10px 12px 8px;border-bottom:1px solid #334155;flex-shrink:0}
- #qsel .qlabel{font-size:9px;text-transform:uppercase;letter-spacing:.6px;color:#64748b;margin-bottom:6px}
- .qrow{display:flex;gap:4px;flex-wrap:wrap}
- .qb{flex:1;min-width:calc(50% - 2px);padding:5px 2px;background:#334155;border:none;border-radius:4px;color:#cbd5e1;font-size:11px;cursor:pointer;text-align:center;line-height:1.2}
- .qb:hover{background:#475569;color:#f1f5f9}
- /* ─── Year/month scroll ─── */
- #yr-scroll{flex:1;overflow-y:auto;padding:6px 0}
- #yr-scroll::-webkit-scrollbar{width:3px}
- #yr-scroll::-webkit-scrollbar-thumb{background:#334155;border-radius:2px}
- .yr-item{}
- .yr-row{display:flex;align-items:center;padding:5px 12px;cursor:pointer;user-select:none;gap:0}
- .yr-row:hover{background:#27374d}
- .yr-cb{margin-right:7px;accent-color:#3b82f6;cursor:pointer;flex-shrink:0}
- .yr-lbl{flex:1;font-size:12px;font-weight:600;color:#cbd5e1}
- .yr-arrow{font-size:9px;color:#64748b;transition:transform .15s;display:inline-block}
- .yr-arrow.open{transform:rotate(90deg)}
- .mo-list{display:none;padding:1px 0 4px 32px}
- .mo-list.open{display:block}
- .mo-row{display:flex;align-items:center;padding:3px 6px;cursor:pointer;border-radius:3px}
- .mo-row:hover{background:#27374d}
- .mo-cb{margin-right:7px;accent-color:#3b82f6;cursor:pointer}
- .mo-lbl{font-size:11px;color:#94a3b8;cursor:pointer}
- .mo-lbl.partial{color:#f59e0b}
- /* ─── Top bar ─── */
- #top-bar{background:white;border-bottom:1px solid #e2e8f0;padding:10px 18px;display:flex;align-items:center;gap:12px;flex-shrink:0;min-height:46px}
- #top-bar h2{font-size:14px;font-weight:700;color:#0f172a;white-space:nowrap}
- #sel-info{font-size:12px;color:#64748b}
- #total-wrap{margin-left:auto;display:flex;align-items:center;gap:5px;font-size:12px;color:#475569;white-space:nowrap}
- #total-wrap input{accent-color:#3b82f6}
- /* ─── Table container ─── */
- #tbl-wrap{flex:1;overflow:auto;padding:12px 16px}
- #tbl-wrap.loading{opacity:.4;pointer-events:none;transition:opacity .1s}
- #empty-state{text-align:center;padding:60px 20px;color:#94a3b8}
- #empty-state h3{font-size:16px;color:#64748b;margin-bottom:8px}
- #empty-state a{color:#3b82f6}
- /* ─── P&L Table ─── */
- table.plt{border-collapse:collapse;white-space:nowrap;font-size:12px;table-layout:fixed}
- /* Sticky header */
- table.plt thead th{
- background:#1e293b;color:#e2e8f0;font-weight:600;
- text-align:right;position:sticky;top:0;z-index:3;
- padding:7px 10px;border-bottom:2px solid #0f172a;
- font-size:11px;letter-spacing:.2px;
- width:100px;overflow:hidden
- }
- table.plt thead th.col-name{
- text-align:left;position:sticky;left:0;z-index:4;
- width:220px
- }
- /* Year-total column header */
- table.plt thead th.col-ytotal{
- background:#0f172a;border-left:3px solid #3b82f6;color:#93c5fd;font-style:italic
- }
- /* Sticky name column */
- table.plt td.col-name{
- position:sticky;left:0;z-index:1;
- overflow:hidden;text-overflow:ellipsis;
- padding:5px 8px
- }
- /* Value cells */
- table.plt td.val{text-align:right;padding:5px 10px;font-variant-numeric:tabular-nums}
- table.plt td.val.neg{color:#ef4444}
- table.plt td.val.zero{color:#cbd5e1}
- /* Year-total value cells */
- table.plt td.col-ytotal{
- border-left:3px solid #3b82f6;font-weight:700;
- background:#eff6ff!important
- }
- tr.r-subtotal td.col-ytotal{background:#bfdbfe!important}
- tr.r-subtotal.L0 td.col-ytotal{background:#93c5fd!important}
- tr.r-total td.col-ytotal{background:#1e3a5f!important;color:#bfdbfe!important}
- /* indent */
- .i0{padding-left:8px!important}
- .i1{padding-left:18px!important}
- .i2{padding-left:30px!important}
- /* ── section header rows ── */
- tr.r-header td{
- background:#0f172a!important;color:#94a3b8;
- font-weight:700;font-size:10px;text-transform:uppercase;
- letter-spacing:.6px;padding:8px 8px 5px
- }
- tr.r-header.L0 td{background:#0f172a!important;color:#64748b;padding-top:12px}
- tr.r-header.L1 td{background:#1e293b!important;color:#94a3b8}
- /* ── item rows ── */
- tr.r-item td{background:#fff;border-bottom:1px solid #f1f5f9}
- tr.r-item:nth-child(even) td{background:#f8fafc}
- /* ── subtotal rows ── */
- tr.r-subtotal td{
- background:#dde3ed!important;font-weight:700;
- border-top:1px solid #c7d0e0;border-bottom:1px solid #c7d0e0
- }
- tr.r-subtotal.L0 td{background:#c7d0e0!important;font-size:13px}
- /* ── grand total row ── */
- tr.r-total td{
- background:#1e3a5f!important;color:#f0f9ff;
- font-weight:800;font-size:13px;
- border-top:3px solid #3b82f6
- }
- tr.r-total td.col-name{background:#1e3a5f!important;color:#f0f9ff}
- tr.r-total td.neg{color:#fca5a5!important}
- /* ─── Mobile hamburger toggle / backdrop (hidden on desktop) ─── */
- #sb-toggle{display:none}
- #sb-backdrop{display:none}
- /* ─── Mobile layout ─── */
- @media (max-width: 768px) {
- #sb-toggle{
- display:flex;align-items:center;justify-content:center;
- width:32px;height:32px;border:none;background:#1e293b;color:#f8fafc;
- border-radius:5px;font-size:16px;cursor:pointer;flex-shrink:0
- }
- #top-bar{padding:8px 10px;flex-wrap:wrap;gap:8px}
- #top-bar h2{font-size:13px}
- #sel-info{font-size:11px;flex-basis:100%;order:3;margin-left:40px}
- #total-wrap{margin-left:0;flex-wrap:wrap;font-size:11px;gap:4px}
- #app{position:relative}
- #sidebar{
- position:fixed;top:0;left:0;bottom:0;z-index:20;
- transform:translateX(-100%);transition:transform .2s ease;
- width:80vw;max-width:280px;box-shadow:2px 0 12px rgba(0,0,0,.3)
- }
- #sidebar.open{transform:translateX(0)}
- #sb-backdrop{
- display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:19
- }
- #sb-backdrop.open{display:block}
- #main{width:100%}
- #tbl-wrap{padding:8px 10px;-webkit-overflow-scrolling:touch}
- table.plt{font-size:11px}
- table.plt thead th{width:74px;padding:6px 6px;font-size:10px}
- table.plt thead th.col-name{width:150px}
- table.plt td.val{padding:5px 6px}
- table.plt td.col-name{padding:5px 6px}
- }
- </style>
- </head>
- <body>
- <div id="app">
- <!-- ═══ SIDEBAR ═══ -->
- <div id="sidebar">
- <div id="sb-head">
- <a href="upload.php" class="upload-link">↑ Upload New CSV</a>
- </div>
- <div id="qsel">
- <div class="qlabel">Quick Select</div>
- <div class="qrow">
- <button class="qb" onclick="qs('thisYear')">This Year</button>
- <button class="qb" onclick="qs('lastYear')">Last Year</button>
- <button class="qb" onclick="qs('ytd')">YTD</button>
- <button class="qb" onclick="qs('last12')">Last 12 Mo</button>
- <button class="qb" onclick="qs('none')">Clear</button>
- <button class="qb" onclick="qs('all')">All</button>
- </div>
- </div>
- <div id="yr-scroll">
- <div id="yr-list">
- <?php if (!$hasData): ?>
- <div style="padding:20px 14px;color:#475569;font-size:12px;line-height:1.6">
- No data yet.<br>
- <a href="upload.php" style="color:#3b82f6">Upload a CSV</a> to get started.
- </div>
- <?php else: ?>
- <div style="padding:16px;color:#475569;font-size:12px">Loading…</div>
- <?php endif; ?>
- </div>
- </div>
- </div><!-- /sidebar -->
- <div id="sb-backdrop" onclick="toggleSidebar()"></div>
- <!-- ═══ MAIN ═══ -->
- <div id="main">
- <div id="top-bar">
- <button id="sb-toggle" onclick="toggleSidebar()" aria-label="Toggle menu">☰</button>
- <h2>Profit & Loss Statement</h2>
- <span id="sel-info"></span>
- <div id="total-wrap">
- <input type="checkbox" id="show-total" onchange="render()">
- <label for="show-total">Show Year Totals</label>
- <span style="color:#cbd5e1;margin:0 4px">|</span>
- <input type="checkbox" id="totals-only" onchange="onTotalsOnly()">
- <label for="totals-only">Totals Only</label>
- <span style="color:#cbd5e1;margin:0 8px">|</span>
- <a href="logout.php" style="font-size:12px;color:#94a3b8;text-decoration:none">Sign out</a>
- </div>
- </div>
- <div id="tbl-wrap">
- <?php if (!$hasData): ?>
- <div id="empty-state">
- <h3>No Data Available</h3>
- <p>Please <a href="upload.php">upload a QuickBooks P&L CSV export</a> to get started.</p>
- </div>
- <?php endif; ?>
- </div>
- </div>
- </div><!-- /app -->
- <script>
- 'use strict';
- // ── State ──
- let allMonths = []; // flat array from API
- let yearMap = {}; // year -> [{id, label, month_num, is_partial}, ...]
- let selected = new Set(); // selected month IDs
- let plData = null; // last API /data response
- let debounce = null;
- const MO = ['','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
- // ── Boot ──
- <?php if ($hasData): ?>
- (async () => {
- try {
- const res = await fetch('api.php?action=months');
- if (!res.ok) throw new Error(res.status);
- allMonths = await res.json();
- if (allMonths.error) throw new Error(allMonths.error);
- buildSidebar();
- qs('thisYear');
- } catch(e) {
- document.getElementById('yr-list').innerHTML =
- '<div style="padding:14px;color:#f87171;font-size:12px">Error: '+esc(String(e.message))+'</div>';
- }
- })();
- <?php endif; ?>
- // ── Build sidebar ──
- function buildSidebar() {
- yearMap = {};
- allMonths.forEach(m => {
- if (m.is_total) return;
- (yearMap[m.year] = yearMap[m.year] || []).push(m);
- });
- const years = Object.keys(yearMap).map(Number).sort((a,b)=>b-a);
- const curY = new Date().getFullYear();
- let html = '';
- years.forEach(y => {
- const mos = yearMap[y];
- const open = y >= curY - 1;
- html += `<div class="yr-item" id="yi-${y}">
- <div class="yr-row" onclick="toggleYear(${y})">
- <input class="yr-cb" type="checkbox" id="yc-${y}"
- onclick="event.stopPropagation();toggleYearCb(${y})">
- <span class="yr-lbl">${y}</span>
- <span class="yr-arrow${open?' open':''}" id="ya-${y}">▶</span>
- </div>
- <div class="mo-list${open?' open':''}" id="ml-${y}">
- ${mos.map(m=>`
- <div class="mo-row">
- <input class="mo-cb" type="checkbox" id="mc-${m.id}" value="${m.id}" onchange="onMoCb()">
- <label class="mo-lbl${m.is_partial?' partial':''}" for="mc-${m.id}">${MO[m.month_num]}${m.is_partial?' <em>(partial)</em>':''}</label>
- </div>`).join('')}
- </div>
- </div>`;
- });
- document.getElementById('yr-list').innerHTML = html;
- }
- // ── Mobile sidebar toggle ──
- function toggleSidebar() {
- document.getElementById('sidebar').classList.toggle('open');
- document.getElementById('sb-backdrop').classList.toggle('open');
- }
- function closeMobileSidebar() {
- if (window.innerWidth <= 768) {
- document.getElementById('sidebar').classList.remove('open');
- document.getElementById('sb-backdrop').classList.remove('open');
- }
- }
- // ── Sidebar interactions ──
- function toggleYear(y) {
- document.getElementById('ml-'+y).classList.toggle('open');
- document.getElementById('ya-'+y).classList.toggle('open');
- }
- function toggleYearCb(y) {
- const cb = document.getElementById('yc-'+y);
- (yearMap[y]||[]).forEach(m => {
- const mcb = document.getElementById('mc-'+m.id);
- if (!mcb) return;
- mcb.checked = cb.checked;
- cb.checked ? selected.add(m.id) : selected.delete(m.id);
- });
- syncYearCb(y);
- schedule();
- }
- function onMoCb() {
- selected.clear();
- allMonths.forEach(m => {
- const cb = document.getElementById('mc-'+m.id);
- if (cb && cb.checked) selected.add(m.id);
- });
- Object.keys(yearMap).forEach(y => syncYearCb(+y));
- schedule();
- }
- function syncYearCb(y) {
- const cb = document.getElementById('yc-'+y);
- if (!cb) return;
- const mos = yearMap[y] || [];
- const n = mos.filter(m => selected.has(m.id)).length;
- cb.indeterminate = n > 0 && n < mos.length;
- cb.checked = n === mos.length && mos.length > 0;
- }
- // ── Quick selects ──
- function qs(mode) {
- const now = new Date();
- const curY = now.getFullYear();
- const curM = now.getMonth() + 1;
- allMonths.forEach(m => {
- if (m.is_total) return;
- let pick = false;
- if (mode==='all') pick = true;
- else if (mode==='thisYear') pick = m.year === curY;
- else if (mode==='lastYear') pick = m.year === curY - 1;
- else if (mode==='ytd') pick = m.year === curY && m.month_num <= curM;
- else if (mode==='last12') {
- const md = m.year*12 + m.month_num;
- const nd = curY*12 + curM;
- pick = md > nd-12 && md <= nd;
- }
- const cb = document.getElementById('mc-'+m.id);
- if (cb) cb.checked = pick;
- pick ? selected.add(m.id) : selected.delete(m.id);
- });
- Object.keys(yearMap).forEach(y => syncYearCb(+y));
- schedule();
- closeMobileSidebar();
- }
- // ── Data loading ──
- function schedule() {
- clearTimeout(debounce);
- debounce = setTimeout(load, 120);
- }
- async function load() {
- if (selected.size === 0) {
- document.getElementById('sel-info').textContent = '';
- document.getElementById('tbl-wrap').innerHTML =
- '<div style="padding:40px;text-align:center;color:#94a3b8;font-size:13px">Select months from the sidebar to view data.</div>';
- return;
- }
- const wrap = document.getElementById('tbl-wrap');
- wrap.classList.add('loading');
- // Year totals are computed client-side — only request selected months
- let ids = [...selected];
- try {
- const res = await fetch('api.php?action=data&ids='+encodeURIComponent(ids.join(',')));
- plData = await res.json();
- render();
- } catch(e) {
- wrap.innerHTML = '<div style="padding:40px;text-align:center;color:#ef4444">Error loading data: '+esc(e.message)+'</div>';
- } finally {
- wrap.classList.remove('loading');
- }
- }
- // ── Totals-only toggle: force show-total on when totals-only is enabled ──
- function onTotalsOnly() {
- const totalsOnly = document.getElementById('totals-only').checked;
- const showTotal = document.getElementById('show-total');
- if (totalsOnly) { showTotal.checked = true; showTotal.disabled = true; }
- else { showTotal.disabled = false; }
- render();
- }
- // ── Render table ──
- function render() {
- if (!plData || !plData.rows) return;
- const showTotal = document.getElementById('show-total').checked;
- const totalsOnly = document.getElementById('totals-only').checked;
- // Only real month columns (no DB TOTAL)
- const monthCols = (plData.columns || []).filter(c => !c.is_total);
- // Group month columns by year, preserving order
- const yearGroups = [];
- monthCols.forEach(c => {
- const last = yearGroups[yearGroups.length - 1];
- if (last && last.year === c.year) { last.cols.push(c); }
- else { yearGroups.push({ year: c.year, cols: [c] }); }
- });
- // Build flat display-column list.
- // In totals-only mode: one year-total sentinel per year, no individual months.
- // Otherwise: months interleaved with optional year-total sentinels.
- const dispCols = [];
- yearGroups.forEach(yg => {
- if (!totalsOnly) yg.cols.forEach(c => dispCols.push(c));
- if (totalsOnly || showTotal) dispCols.push({ isYTotal: true, year: yg.year, cols: yg.cols });
- });
- const selCount = selected.size;
- document.getElementById('sel-info').textContent =
- selCount + ' month' + (selCount !== 1 ? 's' : '') + ' selected';
- // Helper: sum row values across a set of columns
- function rowSum(row, cols) {
- return cols.reduce((s, c) => {
- const v = row.values[String(c.id)];
- return s + (v !== undefined && v !== null ? parseFloat(v) || 0 : 0);
- }, 0);
- }
- // Build header row
- let h = '<table class="plt"><thead><tr><th class="col-name">Account</th>';
- dispCols.forEach(dc => {
- if (dc.isYTotal) {
- h += `<th class="col-ytotal">${dc.year}</th>`;
- } else {
- h += `<th>${esc(dc.label)}</th>`;
- }
- });
- h += '</tr></thead><tbody>';
- // Render data rows — skip item rows with no data in any displayed month
- plData.rows.forEach(row => {
- if (row.type === 'item') {
- const hasData = monthCols.some(c => {
- const v = row.values[String(c.id)];
- return v !== undefined && v !== null && parseFloat(v) !== 0;
- });
- if (!hasData) return;
- }
- const L = row.indent;
- const rCls = 'r-' + row.type + (row.type === 'header' || row.type === 'subtotal' ? ' L' + L : '');
- const iCls = 'i' + L;
- if (row.type === 'header') {
- h += `<tr class="${rCls}"><td colspan="${dispCols.length + 1}" class="col-name ${iCls}">${esc(row.name)}</td></tr>`;
- return;
- }
- h += `<tr class="${rCls}"><td class="col-name ${iCls}">${esc(row.name)}</td>`;
- dispCols.forEach(dc => {
- if (dc.isYTotal) {
- const sum = rowSum(row, dc.cols);
- const vcls = 'val col-ytotal' + (sum < 0 ? ' neg' : sum === 0 ? ' zero' : '');
- h += `<td class="${vcls}">${fmt(sum)}</td>`;
- } else {
- const v = row.values[String(dc.id)];
- const num = (v === undefined || v === null) ? 0 : parseFloat(v);
- const vcls = 'val' + (num < 0 ? ' neg' : num === 0 ? ' zero' : '');
- h += `<td class="${vcls}">${fmt(num)}</td>`;
- }
- });
- h += '</tr>';
- });
- h += '</tbody></table>';
- document.getElementById('tbl-wrap').innerHTML = h;
- }
- // ── Helpers ──
- function fmt(n) {
- if (n === 0) return '—';
- const abs = Math.abs(n);
- const s = abs.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2});
- return (n < 0 ? '-' : '') + '$' + s;
- }
- function esc(s) {
- return String(s||'')
- .replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
- .replace(/"/g,'"');
- }
- </script>
- </body>
- </html>
|