index.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. </div>
  170. </div>
  171. <div id="tbl-wrap">
  172. <?php if (!$hasData): ?>
  173. <div id="empty-state">
  174. <h3>No Data Available</h3>
  175. <p>Please <a href="upload.php">upload a QuickBooks P&amp;L CSV export</a> to get started.</p>
  176. </div>
  177. <?php endif; ?>
  178. </div>
  179. </div>
  180. </div><!-- /app -->
  181. <script>
  182. 'use strict';
  183. // ── State ──
  184. let allMonths = []; // flat array from API
  185. let yearMap = {}; // year -> [{id, label, month_num, is_partial}, ...]
  186. let selected = new Set(); // selected month IDs
  187. let plData = null; // last API /data response
  188. let debounce = null;
  189. const MO = ['','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  190. // ── Boot ──
  191. <?php if ($hasData): ?>
  192. (async () => {
  193. try {
  194. const res = await fetch('api.php?action=months');
  195. if (!res.ok) throw new Error(res.status);
  196. allMonths = await res.json();
  197. if (allMonths.error) throw new Error(allMonths.error);
  198. buildSidebar();
  199. qs('thisYear');
  200. } catch(e) {
  201. document.getElementById('yr-list').innerHTML =
  202. '<div style="padding:14px;color:#f87171;font-size:12px">Error: '+esc(String(e.message))+'</div>';
  203. }
  204. })();
  205. <?php endif; ?>
  206. // ── Build sidebar ──
  207. function buildSidebar() {
  208. yearMap = {};
  209. allMonths.forEach(m => {
  210. if (m.is_total) return;
  211. (yearMap[m.year] = yearMap[m.year] || []).push(m);
  212. });
  213. const years = Object.keys(yearMap).map(Number).sort((a,b)=>b-a);
  214. const curY = new Date().getFullYear();
  215. let html = '';
  216. years.forEach(y => {
  217. const mos = yearMap[y];
  218. const open = y >= curY - 1;
  219. html += `<div class="yr-item" id="yi-${y}">
  220. <div class="yr-row" onclick="toggleYear(${y})">
  221. <input class="yr-cb" type="checkbox" id="yc-${y}"
  222. onclick="event.stopPropagation();toggleYearCb(${y})">
  223. <span class="yr-lbl">${y}</span>
  224. <span class="yr-arrow${open?' open':''}" id="ya-${y}">&#9654;</span>
  225. </div>
  226. <div class="mo-list${open?' open':''}" id="ml-${y}">
  227. ${mos.map(m=>`
  228. <div class="mo-row">
  229. <input class="mo-cb" type="checkbox" id="mc-${m.id}" value="${m.id}" onchange="onMoCb()">
  230. <label class="mo-lbl${m.is_partial?' partial':''}" for="mc-${m.id}">${MO[m.month_num]}${m.is_partial?' <em>(partial)</em>':''}</label>
  231. </div>`).join('')}
  232. </div>
  233. </div>`;
  234. });
  235. document.getElementById('yr-list').innerHTML = html;
  236. }
  237. // ── Sidebar interactions ──
  238. function toggleYear(y) {
  239. document.getElementById('ml-'+y).classList.toggle('open');
  240. document.getElementById('ya-'+y).classList.toggle('open');
  241. }
  242. function toggleYearCb(y) {
  243. const cb = document.getElementById('yc-'+y);
  244. (yearMap[y]||[]).forEach(m => {
  245. const mcb = document.getElementById('mc-'+m.id);
  246. if (!mcb) return;
  247. mcb.checked = cb.checked;
  248. cb.checked ? selected.add(m.id) : selected.delete(m.id);
  249. });
  250. syncYearCb(y);
  251. schedule();
  252. }
  253. function onMoCb() {
  254. selected.clear();
  255. allMonths.forEach(m => {
  256. const cb = document.getElementById('mc-'+m.id);
  257. if (cb && cb.checked) selected.add(m.id);
  258. });
  259. Object.keys(yearMap).forEach(y => syncYearCb(+y));
  260. schedule();
  261. }
  262. function syncYearCb(y) {
  263. const cb = document.getElementById('yc-'+y);
  264. if (!cb) return;
  265. const mos = yearMap[y] || [];
  266. const n = mos.filter(m => selected.has(m.id)).length;
  267. cb.indeterminate = n > 0 && n < mos.length;
  268. cb.checked = n === mos.length && mos.length > 0;
  269. }
  270. // ── Quick selects ──
  271. function qs(mode) {
  272. const now = new Date();
  273. const curY = now.getFullYear();
  274. const curM = now.getMonth() + 1;
  275. allMonths.forEach(m => {
  276. if (m.is_total) return;
  277. let pick = false;
  278. if (mode==='all') pick = true;
  279. else if (mode==='thisYear') pick = m.year === curY;
  280. else if (mode==='lastYear') pick = m.year === curY - 1;
  281. else if (mode==='ytd') pick = m.year === curY && m.month_num <= curM;
  282. else if (mode==='last12') {
  283. const md = m.year*12 + m.month_num;
  284. const nd = curY*12 + curM;
  285. pick = md > nd-12 && md <= nd;
  286. }
  287. const cb = document.getElementById('mc-'+m.id);
  288. if (cb) cb.checked = pick;
  289. pick ? selected.add(m.id) : selected.delete(m.id);
  290. });
  291. Object.keys(yearMap).forEach(y => syncYearCb(+y));
  292. schedule();
  293. }
  294. // ── Data loading ──
  295. function schedule() {
  296. clearTimeout(debounce);
  297. debounce = setTimeout(load, 120);
  298. }
  299. async function load() {
  300. if (selected.size === 0) {
  301. document.getElementById('sel-info').textContent = '';
  302. document.getElementById('tbl-wrap').innerHTML =
  303. '<div style="padding:40px;text-align:center;color:#94a3b8;font-size:13px">Select months from the sidebar to view data.</div>';
  304. return;
  305. }
  306. const wrap = document.getElementById('tbl-wrap');
  307. wrap.classList.add('loading');
  308. // Year totals are computed client-side — only request selected months
  309. let ids = [...selected];
  310. try {
  311. const res = await fetch('api.php?action=data&ids='+encodeURIComponent(ids.join(',')));
  312. plData = await res.json();
  313. render();
  314. } catch(e) {
  315. wrap.innerHTML = '<div style="padding:40px;text-align:center;color:#ef4444">Error loading data: '+esc(e.message)+'</div>';
  316. } finally {
  317. wrap.classList.remove('loading');
  318. }
  319. }
  320. // ── Render table ──
  321. function render() {
  322. if (!plData || !plData.rows) return;
  323. const showTotal = document.getElementById('show-total').checked;
  324. // Only real month columns (no DB TOTAL)
  325. const monthCols = (plData.columns || []).filter(c => !c.is_total);
  326. // Group month columns by year, preserving order
  327. const yearGroups = [];
  328. monthCols.forEach(c => {
  329. const last = yearGroups[yearGroups.length - 1];
  330. if (last && last.year === c.year) { last.cols.push(c); }
  331. else { yearGroups.push({ year: c.year, cols: [c] }); }
  332. });
  333. // Build flat display-column list: months interleaved with optional year-total sentinels
  334. // sentinel: { isYTotal: true, year, cols: [...month cols for this year] }
  335. const dispCols = [];
  336. yearGroups.forEach(yg => {
  337. yg.cols.forEach(c => dispCols.push(c));
  338. if (showTotal) dispCols.push({ isYTotal: true, year: yg.year, cols: yg.cols });
  339. });
  340. const selCount = selected.size;
  341. document.getElementById('sel-info').textContent =
  342. selCount + ' month' + (selCount !== 1 ? 's' : '') + ' selected';
  343. // Helper: sum row values across a set of columns
  344. function rowSum(row, cols) {
  345. return cols.reduce((s, c) => {
  346. const v = row.values[String(c.id)];
  347. return s + (v !== undefined && v !== null ? parseFloat(v) || 0 : 0);
  348. }, 0);
  349. }
  350. // Build header row
  351. let h = '<table class="plt"><thead><tr><th class="col-name">Account</th>';
  352. dispCols.forEach(dc => {
  353. if (dc.isYTotal) {
  354. h += `<th class="col-ytotal">${dc.year}</th>`;
  355. } else {
  356. h += `<th>${esc(dc.label)}</th>`;
  357. }
  358. });
  359. h += '</tr></thead><tbody>';
  360. // Render data rows — skip item rows with no data in any displayed month
  361. plData.rows.forEach(row => {
  362. if (row.type === 'item') {
  363. const hasData = monthCols.some(c => {
  364. const v = row.values[String(c.id)];
  365. return v !== undefined && v !== null && parseFloat(v) !== 0;
  366. });
  367. if (!hasData) return;
  368. }
  369. const L = row.indent;
  370. const rCls = 'r-' + row.type + (row.type === 'header' || row.type === 'subtotal' ? ' L' + L : '');
  371. const iCls = 'i' + L;
  372. if (row.type === 'header') {
  373. h += `<tr class="${rCls}"><td colspan="${dispCols.length + 1}" class="col-name ${iCls}">${esc(row.name)}</td></tr>`;
  374. return;
  375. }
  376. h += `<tr class="${rCls}"><td class="col-name ${iCls}">${esc(row.name)}</td>`;
  377. dispCols.forEach(dc => {
  378. if (dc.isYTotal) {
  379. const sum = rowSum(row, dc.cols);
  380. const vcls = 'val col-ytotal' + (sum < 0 ? ' neg' : sum === 0 ? ' zero' : '');
  381. h += `<td class="${vcls}">${fmt(sum)}</td>`;
  382. } else {
  383. const v = row.values[String(dc.id)];
  384. const num = (v === undefined || v === null) ? 0 : parseFloat(v);
  385. const vcls = 'val' + (num < 0 ? ' neg' : num === 0 ? ' zero' : '');
  386. h += `<td class="${vcls}">${fmt(num)}</td>`;
  387. }
  388. });
  389. h += '</tr>';
  390. });
  391. h += '</tbody></table>';
  392. document.getElementById('tbl-wrap').innerHTML = h;
  393. }
  394. // ── Helpers ──
  395. function fmt(n) {
  396. if (n === 0) return '—';
  397. const abs = Math.abs(n);
  398. const s = abs.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2});
  399. return (n < 0 ? '-' : '') + '$' + s;
  400. }
  401. function esc(s) {
  402. return String(s||'')
  403. .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
  404. .replace(/"/g,'&quot;');
  405. }
  406. </script>
  407. </body>
  408. </html>