index.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. <?php
  2. require __DIR__ . '/auth.php';
  3. $dbPath = __DIR__ . '/_private/pl.db';
  4. $hasData = file_exists($dbPath) && filesize($dbPath) > 0;
  5. ?>
  6. <!DOCTYPE html>
  7. <html lang="en">
  8. <head>
  9. <meta charset="UTF-8">
  10. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  11. <title>P&amp;L Viewer — ICG Magnetics</title>
  12. <style>
  13. *{box-sizing:border-box;margin:0;padding:0}
  14. html,body{height:100%;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;font-size:13px;background:#f1f5f9;color:#1e293b}
  15. /* ─── Layout ─── */
  16. #app{display:flex;height:100vh;overflow:hidden}
  17. #sidebar{width:220px;min-width:220px;background:#1e293b;color:#e2e8f0;display:flex;flex-direction:column;overflow:hidden;flex-shrink:0}
  18. #main{flex:1;display:flex;flex-direction:column;min-width:0;overflow:hidden}
  19. /* ─── Sidebar header ─── */
  20. #sb-head{padding:14px 14px 10px;border-bottom:1px solid #334155;flex-shrink:0}
  21. #sb-head h1{font-size:14px;font-weight:700;color:#f8fafc;letter-spacing:-.2px;line-height:1.3}
  22. #sb-head .sub{font-size:10px;color:#64748b;margin-top:2px;letter-spacing:.2px;text-transform:uppercase}
  23. .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}
  24. .upload-link:hover{background:#2563eb}
  25. /* ─── Quick-select ─── */
  26. #qsel{padding:10px 12px 8px;border-bottom:1px solid #334155;flex-shrink:0}
  27. #qsel .qlabel{font-size:9px;text-transform:uppercase;letter-spacing:.6px;color:#64748b;margin-bottom:6px}
  28. .qrow{display:flex;gap:4px;flex-wrap:wrap}
  29. .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}
  30. .qb:hover{background:#475569;color:#f1f5f9}
  31. /* ─── Year/month scroll ─── */
  32. #yr-scroll{flex:1;overflow-y:auto;padding:6px 0}
  33. #yr-scroll::-webkit-scrollbar{width:3px}
  34. #yr-scroll::-webkit-scrollbar-thumb{background:#334155;border-radius:2px}
  35. .yr-item{}
  36. .yr-row{display:flex;align-items:center;padding:5px 12px;cursor:pointer;user-select:none;gap:0}
  37. .yr-row:hover{background:#27374d}
  38. .yr-cb{margin-right:7px;accent-color:#3b82f6;cursor:pointer;flex-shrink:0}
  39. .yr-lbl{flex:1;font-size:12px;font-weight:600;color:#cbd5e1}
  40. .yr-arrow{font-size:9px;color:#64748b;transition:transform .15s;display:inline-block}
  41. .yr-arrow.open{transform:rotate(90deg)}
  42. .mo-list{display:none;padding:1px 0 4px 32px}
  43. .mo-list.open{display:block}
  44. .mo-row{display:flex;align-items:center;padding:3px 6px;cursor:pointer;border-radius:3px}
  45. .mo-row:hover{background:#27374d}
  46. .mo-cb{margin-right:7px;accent-color:#3b82f6;cursor:pointer}
  47. .mo-lbl{font-size:11px;color:#94a3b8;cursor:pointer}
  48. .mo-lbl.partial{color:#f59e0b}
  49. /* ─── Top bar ─── */
  50. #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}
  51. #top-bar h2{font-size:14px;font-weight:700;color:#0f172a;white-space:nowrap}
  52. #sel-info{font-size:12px;color:#64748b}
  53. #total-wrap{margin-left:auto;display:flex;align-items:center;gap:5px;font-size:12px;color:#475569;white-space:nowrap}
  54. #total-wrap input{accent-color:#3b82f6}
  55. /* ─── Table container ─── */
  56. #tbl-wrap{flex:1;overflow:auto;padding:12px 16px}
  57. #tbl-wrap.loading{opacity:.4;pointer-events:none;transition:opacity .1s}
  58. #empty-state{text-align:center;padding:60px 20px;color:#94a3b8}
  59. #empty-state h3{font-size:16px;color:#64748b;margin-bottom:8px}
  60. #empty-state a{color:#3b82f6}
  61. /* ─── P&L Table ─── */
  62. table.plt{border-collapse:collapse;white-space:nowrap;font-size:12px;table-layout:fixed}
  63. /* Sticky header */
  64. table.plt thead th{
  65. background:#1e293b;color:#e2e8f0;font-weight:600;
  66. text-align:right;position:sticky;top:0;z-index:3;
  67. padding:7px 10px;border-bottom:2px solid #0f172a;
  68. font-size:11px;letter-spacing:.2px;
  69. width:100px;overflow:hidden
  70. }
  71. table.plt thead th.col-name{
  72. text-align:left;position:sticky;left:0;z-index:4;
  73. width:220px
  74. }
  75. /* Year-total column header */
  76. table.plt thead th.col-ytotal{
  77. background:#0f172a;border-left:3px solid #3b82f6;color:#93c5fd;font-style:italic
  78. }
  79. /* Sticky name column */
  80. table.plt td.col-name{
  81. position:sticky;left:0;z-index:1;
  82. overflow:hidden;text-overflow:ellipsis;
  83. padding:5px 8px
  84. }
  85. /* Value cells */
  86. table.plt td.val{text-align:right;padding:5px 10px;font-variant-numeric:tabular-nums}
  87. table.plt td.val.neg{color:#ef4444}
  88. table.plt td.val.zero{color:#cbd5e1}
  89. /* Year-total value cells */
  90. table.plt td.col-ytotal{
  91. border-left:3px solid #3b82f6;font-weight:700;
  92. background:#eff6ff!important
  93. }
  94. tr.r-subtotal td.col-ytotal{background:#bfdbfe!important}
  95. tr.r-subtotal.L0 td.col-ytotal{background:#93c5fd!important}
  96. tr.r-total td.col-ytotal{background:#1e3a5f!important;color:#bfdbfe!important}
  97. /* indent */
  98. .i0{padding-left:8px!important}
  99. .i1{padding-left:18px!important}
  100. .i2{padding-left:30px!important}
  101. /* ── section header rows ── */
  102. tr.r-header td{
  103. background:#0f172a!important;color:#94a3b8;
  104. font-weight:700;font-size:10px;text-transform:uppercase;
  105. letter-spacing:.6px;padding:8px 8px 5px
  106. }
  107. tr.r-header.L0 td{background:#0f172a!important;color:#64748b;padding-top:12px}
  108. tr.r-header.L1 td{background:#1e293b!important;color:#94a3b8}
  109. /* ── item rows ── */
  110. tr.r-item td{background:#fff;border-bottom:1px solid #f1f5f9}
  111. tr.r-item:nth-child(even) td{background:#f8fafc}
  112. tr.r-item td.col-name{background:inherit}
  113. /* ── subtotal rows ── */
  114. tr.r-subtotal td{
  115. background:#dde3ed!important;font-weight:700;
  116. border-top:1px solid #c7d0e0;border-bottom:1px solid #c7d0e0
  117. }
  118. tr.r-subtotal.L0 td{background:#c7d0e0!important;font-size:13px}
  119. /* ── grand total row ── */
  120. tr.r-total td{
  121. background:#1e3a5f!important;color:#f0f9ff;
  122. font-weight:800;font-size:13px;
  123. border-top:3px solid #3b82f6
  124. }
  125. tr.r-total td.col-name{background:#1e3a5f!important;color:#f0f9ff}
  126. tr.r-total td.neg{color:#fca5a5!important}
  127. </style>
  128. </head>
  129. <body>
  130. <div id="app">
  131. <!-- ═══ SIDEBAR ═══ -->
  132. <div id="sidebar">
  133. <div id="sb-head">
  134. <a href="upload.php" class="upload-link">&#8593; Upload New CSV</a>
  135. </div>
  136. <div id="qsel">
  137. <div class="qlabel">Quick Select</div>
  138. <div class="qrow">
  139. <button class="qb" onclick="qs('thisYear')">This Year</button>
  140. <button class="qb" onclick="qs('lastYear')">Last Year</button>
  141. <button class="qb" onclick="qs('ytd')">YTD</button>
  142. <button class="qb" onclick="qs('last12')">Last 12 Mo</button>
  143. <button class="qb" onclick="qs('none')">Clear</button>
  144. <button class="qb" onclick="qs('all')">All</button>
  145. </div>
  146. </div>
  147. <div id="yr-scroll">
  148. <div id="yr-list">
  149. <?php if (!$hasData): ?>
  150. <div style="padding:20px 14px;color:#475569;font-size:12px;line-height:1.6">
  151. No data yet.<br>
  152. <a href="upload.php" style="color:#3b82f6">Upload a CSV</a> to get started.
  153. </div>
  154. <?php else: ?>
  155. <div style="padding:16px;color:#475569;font-size:12px">Loading…</div>
  156. <?php endif; ?>
  157. </div>
  158. </div>
  159. </div><!-- /sidebar -->
  160. <!-- ═══ MAIN ═══ -->
  161. <div id="main">
  162. <div id="top-bar">
  163. <h2>Profit &amp; Loss Statement</h2>
  164. <span id="sel-info"></span>
  165. <div id="total-wrap">
  166. <input type="checkbox" id="show-total" onchange="render()">
  167. <label for="show-total">Show Year Totals</label>
  168. <span style="color:#cbd5e1;margin:0 4px">|</span>
  169. <input type="checkbox" id="totals-only" onchange="onTotalsOnly()">
  170. <label for="totals-only">Totals Only</label>
  171. <span style="color:#cbd5e1;margin:0 8px">|</span>
  172. <a href="logout.php" style="font-size:12px;color:#94a3b8;text-decoration:none">Sign out</a>
  173. </div>
  174. </div>
  175. <div id="tbl-wrap">
  176. <?php if (!$hasData): ?>
  177. <div id="empty-state">
  178. <h3>No Data Available</h3>
  179. <p>Please <a href="upload.php">upload a QuickBooks P&amp;L CSV export</a> to get started.</p>
  180. </div>
  181. <?php endif; ?>
  182. </div>
  183. </div>
  184. </div><!-- /app -->
  185. <script>
  186. 'use strict';
  187. // ── State ──
  188. let allMonths = []; // flat array from API
  189. let yearMap = {}; // year -> [{id, label, month_num, is_partial}, ...]
  190. let selected = new Set(); // selected month IDs
  191. let plData = null; // last API /data response
  192. let debounce = null;
  193. const MO = ['','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  194. // ── Boot ──
  195. <?php if ($hasData): ?>
  196. (async () => {
  197. try {
  198. const res = await fetch('api.php?action=months');
  199. if (!res.ok) throw new Error(res.status);
  200. allMonths = await res.json();
  201. if (allMonths.error) throw new Error(allMonths.error);
  202. buildSidebar();
  203. qs('thisYear');
  204. } catch(e) {
  205. document.getElementById('yr-list').innerHTML =
  206. '<div style="padding:14px;color:#f87171;font-size:12px">Error: '+esc(String(e.message))+'</div>';
  207. }
  208. })();
  209. <?php endif; ?>
  210. // ── Build sidebar ──
  211. function buildSidebar() {
  212. yearMap = {};
  213. allMonths.forEach(m => {
  214. if (m.is_total) return;
  215. (yearMap[m.year] = yearMap[m.year] || []).push(m);
  216. });
  217. const years = Object.keys(yearMap).map(Number).sort((a,b)=>b-a);
  218. const curY = new Date().getFullYear();
  219. let html = '';
  220. years.forEach(y => {
  221. const mos = yearMap[y];
  222. const open = y >= curY - 1;
  223. html += `<div class="yr-item" id="yi-${y}">
  224. <div class="yr-row" onclick="toggleYear(${y})">
  225. <input class="yr-cb" type="checkbox" id="yc-${y}"
  226. onclick="event.stopPropagation();toggleYearCb(${y})">
  227. <span class="yr-lbl">${y}</span>
  228. <span class="yr-arrow${open?' open':''}" id="ya-${y}">&#9654;</span>
  229. </div>
  230. <div class="mo-list${open?' open':''}" id="ml-${y}">
  231. ${mos.map(m=>`
  232. <div class="mo-row">
  233. <input class="mo-cb" type="checkbox" id="mc-${m.id}" value="${m.id}" onchange="onMoCb()">
  234. <label class="mo-lbl${m.is_partial?' partial':''}" for="mc-${m.id}">${MO[m.month_num]}${m.is_partial?' <em>(partial)</em>':''}</label>
  235. </div>`).join('')}
  236. </div>
  237. </div>`;
  238. });
  239. document.getElementById('yr-list').innerHTML = html;
  240. }
  241. // ── Sidebar interactions ──
  242. function toggleYear(y) {
  243. document.getElementById('ml-'+y).classList.toggle('open');
  244. document.getElementById('ya-'+y).classList.toggle('open');
  245. }
  246. function toggleYearCb(y) {
  247. const cb = document.getElementById('yc-'+y);
  248. (yearMap[y]||[]).forEach(m => {
  249. const mcb = document.getElementById('mc-'+m.id);
  250. if (!mcb) return;
  251. mcb.checked = cb.checked;
  252. cb.checked ? selected.add(m.id) : selected.delete(m.id);
  253. });
  254. syncYearCb(y);
  255. schedule();
  256. }
  257. function onMoCb() {
  258. selected.clear();
  259. allMonths.forEach(m => {
  260. const cb = document.getElementById('mc-'+m.id);
  261. if (cb && cb.checked) selected.add(m.id);
  262. });
  263. Object.keys(yearMap).forEach(y => syncYearCb(+y));
  264. schedule();
  265. }
  266. function syncYearCb(y) {
  267. const cb = document.getElementById('yc-'+y);
  268. if (!cb) return;
  269. const mos = yearMap[y] || [];
  270. const n = mos.filter(m => selected.has(m.id)).length;
  271. cb.indeterminate = n > 0 && n < mos.length;
  272. cb.checked = n === mos.length && mos.length > 0;
  273. }
  274. // ── Quick selects ──
  275. function qs(mode) {
  276. const now = new Date();
  277. const curY = now.getFullYear();
  278. const curM = now.getMonth() + 1;
  279. allMonths.forEach(m => {
  280. if (m.is_total) return;
  281. let pick = false;
  282. if (mode==='all') pick = true;
  283. else if (mode==='thisYear') pick = m.year === curY;
  284. else if (mode==='lastYear') pick = m.year === curY - 1;
  285. else if (mode==='ytd') pick = m.year === curY && m.month_num <= curM;
  286. else if (mode==='last12') {
  287. const md = m.year*12 + m.month_num;
  288. const nd = curY*12 + curM;
  289. pick = md > nd-12 && md <= nd;
  290. }
  291. const cb = document.getElementById('mc-'+m.id);
  292. if (cb) cb.checked = pick;
  293. pick ? selected.add(m.id) : selected.delete(m.id);
  294. });
  295. Object.keys(yearMap).forEach(y => syncYearCb(+y));
  296. schedule();
  297. }
  298. // ── Data loading ──
  299. function schedule() {
  300. clearTimeout(debounce);
  301. debounce = setTimeout(load, 120);
  302. }
  303. async function load() {
  304. if (selected.size === 0) {
  305. document.getElementById('sel-info').textContent = '';
  306. document.getElementById('tbl-wrap').innerHTML =
  307. '<div style="padding:40px;text-align:center;color:#94a3b8;font-size:13px">Select months from the sidebar to view data.</div>';
  308. return;
  309. }
  310. const wrap = document.getElementById('tbl-wrap');
  311. wrap.classList.add('loading');
  312. // Year totals are computed client-side — only request selected months
  313. let ids = [...selected];
  314. try {
  315. const res = await fetch('api.php?action=data&ids='+encodeURIComponent(ids.join(',')));
  316. plData = await res.json();
  317. render();
  318. } catch(e) {
  319. wrap.innerHTML = '<div style="padding:40px;text-align:center;color:#ef4444">Error loading data: '+esc(e.message)+'</div>';
  320. } finally {
  321. wrap.classList.remove('loading');
  322. }
  323. }
  324. // ── Totals-only toggle: force show-total on when totals-only is enabled ──
  325. function onTotalsOnly() {
  326. const totalsOnly = document.getElementById('totals-only').checked;
  327. const showTotal = document.getElementById('show-total');
  328. if (totalsOnly) { showTotal.checked = true; showTotal.disabled = true; }
  329. else { showTotal.disabled = false; }
  330. render();
  331. }
  332. // ── Render table ──
  333. function render() {
  334. if (!plData || !plData.rows) return;
  335. const showTotal = document.getElementById('show-total').checked;
  336. const totalsOnly = document.getElementById('totals-only').checked;
  337. // Only real month columns (no DB TOTAL)
  338. const monthCols = (plData.columns || []).filter(c => !c.is_total);
  339. // Group month columns by year, preserving order
  340. const yearGroups = [];
  341. monthCols.forEach(c => {
  342. const last = yearGroups[yearGroups.length - 1];
  343. if (last && last.year === c.year) { last.cols.push(c); }
  344. else { yearGroups.push({ year: c.year, cols: [c] }); }
  345. });
  346. // Build flat display-column list.
  347. // In totals-only mode: one year-total sentinel per year, no individual months.
  348. // Otherwise: months interleaved with optional year-total sentinels.
  349. const dispCols = [];
  350. yearGroups.forEach(yg => {
  351. if (!totalsOnly) yg.cols.forEach(c => dispCols.push(c));
  352. if (totalsOnly || showTotal) dispCols.push({ isYTotal: true, year: yg.year, cols: yg.cols });
  353. });
  354. const selCount = selected.size;
  355. document.getElementById('sel-info').textContent =
  356. selCount + ' month' + (selCount !== 1 ? 's' : '') + ' selected';
  357. // Helper: sum row values across a set of columns
  358. function rowSum(row, cols) {
  359. return cols.reduce((s, c) => {
  360. const v = row.values[String(c.id)];
  361. return s + (v !== undefined && v !== null ? parseFloat(v) || 0 : 0);
  362. }, 0);
  363. }
  364. // Build header row
  365. let h = '<table class="plt"><thead><tr><th class="col-name">Account</th>';
  366. dispCols.forEach(dc => {
  367. if (dc.isYTotal) {
  368. h += `<th class="col-ytotal">${dc.year}</th>`;
  369. } else {
  370. h += `<th>${esc(dc.label)}</th>`;
  371. }
  372. });
  373. h += '</tr></thead><tbody>';
  374. // Render data rows — skip item rows with no data in any displayed month
  375. plData.rows.forEach(row => {
  376. if (row.type === 'item') {
  377. const hasData = monthCols.some(c => {
  378. const v = row.values[String(c.id)];
  379. return v !== undefined && v !== null && parseFloat(v) !== 0;
  380. });
  381. if (!hasData) return;
  382. }
  383. const L = row.indent;
  384. const rCls = 'r-' + row.type + (row.type === 'header' || row.type === 'subtotal' ? ' L' + L : '');
  385. const iCls = 'i' + L;
  386. if (row.type === 'header') {
  387. h += `<tr class="${rCls}"><td colspan="${dispCols.length + 1}" class="col-name ${iCls}">${esc(row.name)}</td></tr>`;
  388. return;
  389. }
  390. h += `<tr class="${rCls}"><td class="col-name ${iCls}">${esc(row.name)}</td>`;
  391. dispCols.forEach(dc => {
  392. if (dc.isYTotal) {
  393. const sum = rowSum(row, dc.cols);
  394. const vcls = 'val col-ytotal' + (sum < 0 ? ' neg' : sum === 0 ? ' zero' : '');
  395. h += `<td class="${vcls}">${fmt(sum)}</td>`;
  396. } else {
  397. const v = row.values[String(dc.id)];
  398. const num = (v === undefined || v === null) ? 0 : parseFloat(v);
  399. const vcls = 'val' + (num < 0 ? ' neg' : num === 0 ? ' zero' : '');
  400. h += `<td class="${vcls}">${fmt(num)}</td>`;
  401. }
  402. });
  403. h += '</tr>';
  404. });
  405. h += '</tbody></table>';
  406. document.getElementById('tbl-wrap').innerHTML = h;
  407. }
  408. // ── Helpers ──
  409. function fmt(n) {
  410. if (n === 0) return '—';
  411. const abs = Math.abs(n);
  412. const s = abs.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2});
  413. return (n < 0 ? '-' : '') + '$' + s;
  414. }
  415. function esc(s) {
  416. return String(s||'')
  417. .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
  418. .replace(/"/g,'&quot;');
  419. }
  420. </script>
  421. </body>
  422. </html>