index.php 17 KB

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