YummyPastry

Enhanced Costco Analyzer

Nov 23rd, 2025
1,398
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.24 KB | None | 1 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Costco Receipt Dashboard</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1" />
  7.  
  8. <!-- Chart.js Library -->
  9. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  10.  
  11. <style>
  12. :root {
  13. --bg: #f5f7fb;
  14. --card-bg: #ffffff;
  15. --accent: #2563eb;
  16. --accent-soft: #e0edff;
  17. --gas-accent: #dc2626;
  18. --gas-soft: #fee2e2;
  19. --gold: #d97706;
  20. --gold-soft: #fef3c7;
  21. --refund-accent: #7c3aed;
  22. --refund-soft: #f3e8ff;
  23. --text-main: #111827;
  24. --text-muted: #6b7280;
  25. --border: #e5e7eb;
  26. --success: #16a34a;
  27. --danger: #ef4444;
  28. --radius-lg: 18px;
  29. --shadow-soft: 0 10px 25px rgba(15, 23, 42, 0.05);
  30. }
  31.  
  32. * { box-sizing: border-box; }
  33.  
  34. body {
  35. margin: 0;
  36. font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  37. background: var(--bg);
  38. color: var(--text-main);
  39. padding-bottom: 60px;
  40. }
  41.  
  42. .page {
  43. max-width: 1200px;
  44. margin: 0 auto;
  45. padding: 24px 16px;
  46. }
  47.  
  48. /* HEADER */
  49. header {
  50. display: flex;
  51. flex-wrap: wrap;
  52. align-items: center;
  53. justify-content: space-between;
  54. gap: 16px;
  55. margin-bottom: 30px;
  56. }
  57.  
  58. header h1 {
  59. margin: 0;
  60. font-size: 1.8rem;
  61. display: flex;
  62. align-items: center;
  63. gap: 10px;
  64. }
  65.  
  66. .date-badge {
  67. background: #e5e7eb;
  68. color: var(--text-main);
  69. font-size: 0.9rem;
  70. padding: 4px 12px;
  71. border-radius: 12px;
  72. font-weight: 500;
  73. }
  74.  
  75. /* UPLOADER */
  76. .uploader {
  77. padding: 10px 16px;
  78. background: var(--card-bg);
  79. border-radius: 999px;
  80. border: 1px solid var(--border);
  81. box-shadow: var(--shadow-soft);
  82. display: flex;
  83. align-items: center;
  84. gap: 12px;
  85. font-size: 0.9rem;
  86. }
  87.  
  88. .status {
  89. font-size: 0.85rem;
  90. color: var(--text-muted);
  91. margin-top: 6px;
  92. text-align: right;
  93. }
  94.  
  95. /* SECTIONS */
  96. .section-header {
  97. font-size: 1.4rem;
  98. font-weight: 700;
  99. margin: 40px 0 16px;
  100. display: flex;
  101. align-items: center;
  102. gap: 8px;
  103. padding-bottom: 8px;
  104. border-bottom: 2px solid var(--border);
  105. }
  106.  
  107. /* GRIDS */
  108. .summary-grid {
  109. display: grid;
  110. grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  111. gap: 16px;
  112. margin-bottom: 24px;
  113. }
  114.  
  115. .grid-2 {
  116. display: grid;
  117. grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  118. gap: 20px;
  119. margin-bottom: 24px;
  120. }
  121.  
  122. .grid-3 {
  123. display: grid;
  124. grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  125. gap: 20px;
  126. margin-bottom: 24px;
  127. }
  128.  
  129. /* CARDS */
  130. .summary-card {
  131. background: var(--card-bg);
  132. border-radius: var(--radius-lg);
  133. padding: 16px;
  134. box-shadow: var(--shadow-soft);
  135. border: 1px solid var(--border);
  136. }
  137.  
  138. .summary-card.gold { border-left: 4px solid var(--gold); }
  139. .summary-card.gas { border-left: 4px solid var(--gas-accent); }
  140. .summary-card.refund { border-left: 4px solid var(--refund-accent); }
  141.  
  142. .summary-card .label {
  143. font-size: 0.75rem;
  144. text-transform: uppercase;
  145. letter-spacing: 0.05em;
  146. color: var(--text-muted);
  147. font-weight: 600;
  148. }
  149.  
  150. .summary-card .value {
  151. margin-top: 6px;
  152. font-size: 1.4rem;
  153. font-weight: 700;
  154. }
  155.  
  156. .summary-card .sub {
  157. margin-top: 4px;
  158. font-size: 0.8rem;
  159. color: var(--text-muted);
  160. }
  161.  
  162. .card {
  163. background: var(--card-bg);
  164. border-radius: var(--radius-lg);
  165. padding: 20px;
  166. box-shadow: var(--shadow-soft);
  167. border: 1px solid var(--border);
  168. }
  169.  
  170. .card.gas-container { border-top: 4px solid var(--gas-accent); }
  171.  
  172. .card h2 {
  173. margin: 0 0 4px;
  174. font-size: 1.1rem;
  175. display: flex;
  176. align-items: center;
  177. gap: 8px;
  178. }
  179.  
  180. .card .subtitle {
  181. margin: 0 0 16px;
  182. font-size: 0.85rem;
  183. color: var(--text-muted);
  184. }
  185.  
  186. /* TABLES */
  187. table {
  188. width: 100%;
  189. border-collapse: collapse;
  190. font-size: 0.85rem;
  191. }
  192.  
  193. thead { background: var(--accent-soft); }
  194. .gold-table thead { background: var(--gold-soft); color: #92400e; }
  195.  
  196. th, td {
  197. padding: 8px 10px;
  198. text-align: left;
  199. border-bottom: 1px solid var(--border);
  200. }
  201.  
  202. th:first-child, td:first-child { width: 1%; white-space: nowrap; }
  203. th:last-child, td:last-child { text-align: right; }
  204. tbody tr:nth-child(even) { background: #f9fafb; }
  205.  
  206. .money { font-variant-numeric: tabular-nums; font-weight: 600; }
  207. .pos { color: var(--success); }
  208. .neg { color: var(--danger); }
  209.  
  210. .chart-wrapper {
  211. position: relative;
  212. height: 300px;
  213. width: 100%;
  214. }
  215.  
  216. @media (max-width: 640px) {
  217. .uploader { width: 100%; flex-wrap: wrap; justify-content: center; }
  218. .date-badge { margin-top: 5px; }
  219. }
  220. </style>
  221. </head>
  222. <body>
  223.  
  224. <div class="page">
  225. <header>
  226. <div>
  227. <h1>
  228. <span class="icon">๐Ÿงพ</span>Enhanced Costco Analyzer
  229. <span id="dateRangeTitle" class="date-badge">Waiting for file...</span>
  230. </h1>
  231. <p>Upload your JSON receipts to see spending insights.</p>
  232. </div>
  233. <div>
  234. <div class="uploader">
  235. <label for="fileInput">Select JSON:</label>
  236. <input id="fileInput" type="file" accept="application/json,.json" />
  237. </div>
  238. <div id="status" class="status"></div>
  239. </div>
  240. </header>
  241.  
  242. <!-- MERCHANDISE SECTION -->
  243. <div class="section-header"><span class="icon">๐Ÿ›’</span> Warehouse Merchandise</div>
  244.  
  245. <section class="summary-grid">
  246. <div class="summary-card">
  247. <div class="label">Net Spent (Merch)</div>
  248. <div class="value" id="totalSpent">โ€“</div>
  249. <div class="sub">Purchases - Refunds</div>
  250. </div>
  251. <div class="summary-card">
  252. <div class="label">Net Items</div>
  253. <div class="value" id="totalPurchases">โ€“</div>
  254. <div class="sub">Unique Codes: <span id="uniqueItems">0</span></div>
  255. </div>
  256. <div class="summary-card">
  257. <div class="label">Merch Visits</div>
  258. <div class="value" id="receiptCount">โ€“</div>
  259. <div class="sub">Avg <span id="avgPerReceipt"></span> / trip</div>
  260. </div>
  261. <div class="summary-card refund">
  262. <div class="label" style="color:var(--refund-accent)">Total Refunded</div>
  263. <div class="value" id="refundTotal" style="color:var(--refund-accent)">โ€“</div>
  264. <div class="sub">Returns Count: <span id="refundCount">0</span></div>
  265. </div>
  266. <div class="summary-card">
  267. <div class="label">Merch Locations</div>
  268. <div class="value" id="uniqueWarehouses">โ€“</div>
  269. <div class="sub">Unique Warehouses</div>
  270. </div>
  271. <div class="summary-card gold">
  272. <div class="label" style="color:#b45309">Est. Executive Reward</div>
  273. <div class="value" id="totalRewards" style="color:#b45309">โ€“</div>
  274. <div class="sub">2% of Annual Subtotals</div>
  275. </div>
  276. </section>
  277.  
  278. <section class="grid-2">
  279. <div class="card">
  280. <h2><span class="icon">๐Ÿ†</span> 2% Reward Tracker</h2>
  281. <p class="subtitle">Estimated cashback based on annual pre-tax merchandise subtotals.</p>
  282. <table class="gold-table">
  283. <thead>
  284. <tr>
  285. <th>Year</th>
  286. <th>Qualifying Spend</th>
  287. <th>2% Cashback</th>
  288. </tr>
  289. </thead>
  290. <tbody id="rewardsBody"></tbody>
  291. </table>
  292. </div>
  293. <div class="card">
  294. <h2><span class="icon">๐Ÿ“Š</span> Merchandise Spending Trend</h2>
  295. <p class="subtitle">Total spent per month (Tax included).</p>
  296. <div class="chart-wrapper">
  297. <canvas id="merchChart"></canvas>
  298. </div>
  299. </div>
  300. </section>
  301.  
  302. <!-- NEW ITEM LISTS -->
  303. <section class="grid-3">
  304. <div class="card">
  305. <h2><span class="icon">๐Ÿ’Ž</span> Most Expensive</h2>
  306. <p class="subtitle">Items with highest recorded price.</p>
  307. <table>
  308. <thead>
  309. <tr><th>Item</th><th>Max Price</th><th>Avg</th></tr>
  310. </thead>
  311. <tbody id="mostExpensiveBody"></tbody>
  312. </table>
  313. </div>
  314. <div class="card">
  315. <h2><span class="icon">๐Ÿ“ˆ</span> Price Increases</h2>
  316. <p class="subtitle">Latest price > First price recorded.</p>
  317. <table>
  318. <thead>
  319. <tr><th>Item</th><th>Old &rarr; New</th><th>Diff</th></tr>
  320. </thead>
  321. <tbody id="priceIncreaseBody"></tbody>
  322. </table>
  323. </div>
  324. <div class="card">
  325. <h2><span class="icon">๐Ÿ“‰</span> Price Drops</h2>
  326. <p class="subtitle">Latest price < First price recorded.</p>
  327. <table>
  328. <thead>
  329. <tr><th>Item</th><th>Old &rarr; New</th><th>Diff</th></tr>
  330. </thead>
  331. <tbody id="priceDecreaseBody"></tbody>
  332. </table>
  333. </div>
  334. </section>
  335.  
  336. <section class="grid-2">
  337. <div class="card">
  338. <h2><span class="icon">๐Ÿ’ฐ</span> Most Total Spent</h2>
  339. <p class="subtitle">Highest cumulative spend items.</p>
  340. <table>
  341. <thead>
  342. <tr>
  343. <th>#</th><th>Item</th><th>Total</th><th>Cnt</th><th>Avg</th>
  344. </tr>
  345. </thead>
  346. <tbody id="mostTotalSpentBody"></tbody>
  347. </table>
  348. </div>
  349. <div class="card">
  350. <h2><span class="icon">๐Ÿ”ฅ</span> Most Frequently Bought</h2>
  351. <p class="subtitle">Items purchased most often.</p>
  352. <table>
  353. <thead>
  354. <tr>
  355. <th>#</th><th>Item</th><th>Cnt</th><th>Avg</th><th>Change</th>
  356. </tr>
  357. </thead>
  358. <tbody id="mostPurchasedBody"></tbody>
  359. </table>
  360. </div>
  361. </section>
  362.  
  363. <!-- GAS SECTION -->
  364. <div class="section-header" style="color:#b91c1c; border-color:#fecaca;">
  365. <span class="icon">โ›ฝ</span> Gas Station Stats
  366. </div>
  367.  
  368. <section class="summary-grid">
  369. <div class="summary-card gas">
  370. <div class="label">Total Gas Spent</div>
  371. <div class="value" id="gasTotalSpent">โ€“</div>
  372. </div>
  373. <div class="summary-card">
  374. <div class="label">Total Gallons</div>
  375. <div class="value" id="gasTotalGallons">โ€“</div>
  376. </div>
  377. <div class="summary-card">
  378. <div class="label">Avg Price/Gal</div>
  379. <div class="value" id="gasAvgPrice">โ€“</div>
  380. <div class="sub">Weighted Average</div>
  381. </div>
  382. <div class="summary-card">
  383. <div class="label">Gas Visits</div>
  384. <div class="value" id="gasVisits">โ€“</div>
  385. </div>
  386. <div class="summary-card">
  387. <div class="label">Gas Locations</div>
  388. <div class="value" id="gasLocationsCount">โ€“</div>
  389. <div class="sub">Unique Stations</div>
  390. </div>
  391. </section>
  392.  
  393. <section class="grid-2">
  394. <div class="card gas-container">
  395. <h2><span class="icon">๐Ÿ“‰</span> Price Per Gallon History</h2>
  396. <p class="subtitle">Average price paid per month by grade.</p>
  397. <div class="chart-wrapper">
  398. <canvas id="gasPriceHistoryChart"></canvas>
  399. </div>
  400. </div>
  401. <div class="card gas-container">
  402. <h2><span class="icon">๐Ÿ’ณ</span> Gas Spend by Grade</h2>
  403. <p class="subtitle">Total monthly spend split by fuel type.</p>
  404. <div class="chart-wrapper">
  405. <canvas id="gasSpendBreakdownChart"></canvas>
  406. </div>
  407. </div>
  408. </section>
  409.  
  410. <section class="card gas-container" style="margin-top:20px;">
  411. <h2><span class="icon">๐Ÿ“Š</span> Total Monthly Gas Spending</h2>
  412. <p class="subtitle">Combined fuel expenses over time.</p>
  413. <div class="chart-wrapper">
  414. <canvas id="gasChart"></canvas>
  415. </div>
  416. </section>
  417.  
  418. <section class="summary-grid" style="margin-top: 40px; opacity: 0.9;">
  419. <div class="summary-card">
  420. <div class="label">Total Unique Locations</div>
  421. <div class="value" id="totalAllLocations">โ€“</div>
  422. <div class="sub">Gas + Merchandise combined</div>
  423. </div>
  424. </section>
  425.  
  426. </div>
  427.  
  428. <script>
  429. // --- 1. CONFIGURATION & FORMATTERS ---
  430. const currencyFormatter = new Intl.NumberFormat("en-US", {
  431. style: "currency",
  432. currency: "USD",
  433. minimumFractionDigits: 2,
  434. maximumFractionDigits: 2,
  435. });
  436. const numFormatter = new Intl.NumberFormat("en-US", { maximumFractionDigits: 1 });
  437.  
  438. function formatMoney(v) { return currencyFormatter.format(v || 0); }
  439. function formatNum(v) { return numFormatter.format(v || 0); }
  440.  
  441. function getMonthAbbr(dateObj) {
  442. const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  443. const y = dateObj.getFullYear().toString().slice(-2);
  444. return `${months[dateObj.getMonth()]} '${y}`;
  445. }
  446.  
  447. // Helper to generate "YYYY-MM" keys for sorting
  448. function getSortableMonthKey(dateObj) {
  449. const y = dateObj.getFullYear();
  450. const m = String(dateObj.getMonth() + 1).padStart(2, '0');
  451. return `${y}-${m}`;
  452. }
  453.  
  454. // Global chart instances
  455. let merchChartInstance = null;
  456. let gasChartInstance = null;
  457. let gasPriceChartInstance = null;
  458. let gasSpendBreakdownInstance = null;
  459.  
  460. // --- 2. DATA PROCESSING ---
  461. function processData(receipts) {
  462. // Sort receipts by date ascending
  463. receipts.sort((a, b) => new Date(a.transactionDate) - new Date(b.transactionDate));
  464.  
  465. // Determine Date Range
  466. const dates = receipts.map(r => new Date(r.transactionDate));
  467. const minDate = new Date(Math.min(...dates));
  468. const maxDate = new Date(Math.max(...dates));
  469. const dateRangeStr = `${minDate.getFullYear()} - ${maxDate.getFullYear()}`;
  470.  
  471. // Data Containers
  472. const merch = {
  473. receipts: [],
  474. itemStats: new Map(),
  475. monthly: new Map(),
  476. subtotalByYear: new Map(),
  477. totalSpent: 0,
  478. totalUnits: 0,
  479. refundCount: 0,
  480. refundTotal: 0,
  481. locations: new Set()
  482. };
  483.  
  484. const gas = {
  485. receipts: [],
  486. monthly: new Map(),
  487. totalSpent: 0,
  488. totalGallons: 0,
  489. priceSum: 0,
  490. count: 0,
  491. locations: new Set()
  492. };
  493.  
  494. const allLocations = new Set();
  495.  
  496. receipts.forEach(r => {
  497. const date = new Date(r.transactionDate);
  498. const monthKey = getSortableMonthKey(date);
  499. const year = date.getFullYear();
  500. const locName = (r.warehouseName || "Unknown").trim();
  501. const total = Number(r.total) || 0;
  502.  
  503. allLocations.add(locName);
  504.  
  505. // Identify Gas Receipts (Type or Item Codes 800877/800599)
  506. const isGas = r.receiptType === "Gas Station" ||
  507. r.documentType === "FuelReceipts" ||
  508. (r.itemArray && r.itemArray.some(i => ["800877", "800599"].includes(i.itemNumber)));
  509.  
  510. if (isGas) {
  511. // GAS LOGIC
  512. gas.receipts.push(r);
  513. gas.locations.add(locName);
  514. gas.totalSpent += total;
  515. gas.count++;
  516.  
  517. // Initialize monthly map if needed
  518. if (!gas.monthly.has(monthKey)) gas.monthly.set(monthKey, { spent: 0 });
  519. gas.monthly.get(monthKey).spent += total;
  520.  
  521. // Process Gas Items (Gallons, Price)
  522. if (r.itemArray) {
  523. r.itemArray.forEach(item => {
  524. const gals = Number(item.fuelUnitQuantity) || 0;
  525. const price = Number(item.itemUnitPriceAmount) || 0;
  526. if (gals > 0) {
  527. gas.totalGallons += gals;
  528. gas.priceSum += (price * gals); // Weighted sum for avg calc
  529. }
  530. });
  531. }
  532.  
  533. } else {
  534. // MERCH LOGIC
  535. merch.receipts.push(r);
  536. merch.locations.add(locName);
  537.  
  538. // Net Spend Logic
  539. merch.totalSpent += total;
  540.  
  541. // Refund Tracking
  542. if (total < 0 || r.transactionType === "Refund") {
  543. merch.refundCount++;
  544. merch.refundTotal += Math.abs(total);
  545. }
  546.  
  547. // Subtotal Logic (Pre-tax, for rewards)
  548. const subTotal = Number(r.subTotal) || 0;
  549. merch.subtotalByYear.set(year, (merch.subtotalByYear.get(year) || 0) + subTotal);
  550.  
  551. if (!merch.monthly.has(monthKey)) merch.monthly.set(monthKey, { spent: 0 });
  552. merch.monthly.get(monthKey).spent += total;
  553.  
  554. // Item Stats
  555. if (r.itemArray) {
  556. r.itemArray.forEach(item => {
  557. const unit = Number(item.unit) || 0;
  558. const amount = Number(item.amount) || 0;
  559.  
  560. if (!item.itemNumber || unit <= 0 || amount <= 0) return;
  561.  
  562. // Item Key
  563. const key = item.itemNumber;
  564. const name = (item.itemDescription01 || "").trim();
  565. const unitPrice = amount / unit;
  566.  
  567. if (!merch.itemStats.has(key)) {
  568. merch.itemStats.set(key, {
  569. name, itemNumber: key,
  570. totalSpent: 0,
  571. totalUnits: 0,
  572. purchases: 0,
  573. priceHistory: [] // Array of {date, price}
  574. });
  575. }
  576. const stat = merch.itemStats.get(key);
  577. stat.totalSpent += amount;
  578. stat.totalUnits += unit;
  579.  
  580. merch.totalUnits += unit;
  581.  
  582. // Only track positive purchases as "Visits" and "Price History"
  583. // We exclude returns from price history to avoid skewed min/max stats
  584. if (unit > 0 && amount > 0) {
  585. stat.purchases += 1;
  586. stat.priceHistory.push({ date: date, price: unitPrice });
  587. }
  588. });
  589. }
  590. }
  591. });
  592.  
  593. // Post-process itemStats to sort price history
  594. merch.itemStats.forEach(stat => {
  595. stat.priceHistory.sort((a, b) => a.date - b.date);
  596. if (stat.priceHistory.length > 0) {
  597. stat.firstPrice = stat.priceHistory[0].price;
  598. stat.lastPrice = stat.priceHistory[stat.priceHistory.length - 1].price;
  599. stat.maxPrice = Math.max(...stat.priceHistory.map(p => p.price));
  600. stat.minPrice = Math.min(...stat.priceHistory.map(p => p.price));
  601. } else {
  602. stat.firstPrice = 0; stat.lastPrice = 0; stat.maxPrice = 0; stat.minPrice = 0;
  603. }
  604. });
  605.  
  606. return { merch, gas, allLocations, dateRangeStr };
  607. }
  608.  
  609. // --- 3. RENDERING DASHBOARD ---
  610. function renderDashboard(data) {
  611. const { merch, gas, allLocations, dateRangeStr } = data;
  612.  
  613. // Update Header
  614. document.getElementById("dateRangeTitle").textContent = dateRangeStr;
  615.  
  616. // --- MERCH STATS ---
  617. document.getElementById("totalSpent").textContent = formatMoney(merch.totalSpent);
  618. document.getElementById("totalPurchases").textContent = formatNum(merch.totalUnits);
  619. document.getElementById("uniqueItems").textContent = formatNum(merch.itemStats.size);
  620. document.getElementById("receiptCount").textContent = formatNum(merch.receipts.length);
  621. document.getElementById("uniqueWarehouses").textContent = merch.locations.size;
  622. document.getElementById("refundCount").textContent = formatNum(merch.refundCount);
  623. document.getElementById("refundTotal").textContent = formatMoney(merch.refundTotal);
  624.  
  625. const avgPerReceipt = merch.receipts.length ? merch.totalSpent / merch.receipts.length : 0;
  626. document.getElementById("avgPerReceipt").textContent = formatMoney(avgPerReceipt);
  627.  
  628. // --- EXECUTIVE REWARDS (2%) ---
  629. const rewardsBody = document.getElementById("rewardsBody");
  630. rewardsBody.innerHTML = "";
  631. let grandTotalRewards = 0;
  632. const years = Array.from(merch.subtotalByYear.keys()).sort((a,b) => b - a);
  633.  
  634. years.forEach(year => {
  635. const sub = merch.subtotalByYear.get(year);
  636. const reward = sub * 0.02;
  637. grandTotalRewards += reward;
  638. rewardsBody.innerHTML += `
  639. <tr>
  640. <td><strong>${year}</strong></td>
  641. <td>${formatMoney(sub)}</td>
  642. <td class="money pos">+${formatMoney(reward)}</td>
  643. </tr>
  644. `;
  645. });
  646. document.getElementById("totalRewards").textContent = formatMoney(grandTotalRewards);
  647.  
  648. // --- TABLES ---
  649. renderMerchTables(merch.itemStats);
  650.  
  651. // --- GAS STATS ---
  652. document.getElementById("gasTotalSpent").textContent = formatMoney(gas.totalSpent);
  653. document.getElementById("gasTotalGallons").textContent = formatNum(gas.totalGallons) + " gal";
  654. const weightedAvgPrice = gas.totalGallons > 0 ? (gas.priceSum / gas.totalGallons) : 0;
  655. document.getElementById("gasAvgPrice").textContent = formatMoney(weightedAvgPrice);
  656. document.getElementById("gasVisits").textContent = gas.count;
  657. document.getElementById("gasLocationsCount").textContent = gas.locations.size;
  658. document.getElementById("totalAllLocations").textContent = allLocations.size;
  659.  
  660. // --- CHART 1: MERCH SPEND ---
  661. renderSimpleBarChart("merchChart", merch.monthly, "Merchandise Spend ($)", "#2563eb", merchChartInstance, (i)=>merchChartInstance=i);
  662.  
  663. // --- CHART 2: TOTAL GAS SPEND ---
  664. renderSimpleBarChart("gasChart", gas.monthly, "Total Gas Spend ($)", "#dc2626", gasChartInstance, (i)=>gasChartInstance=i);
  665.  
  666. // --- GAS SPECIFIC LOGIC FOR GRADE SPLIT ---
  667. const gasGrades = new Map(); // Key: "YYYY-MM" -> { pSpend:0, pGal:0, rSpend:0, rGal:0 }
  668.  
  669. gas.receipts.forEach(r => {
  670. const monthKey = getSortableMonthKey(new Date(r.transactionDate));
  671. if (!gasGrades.has(monthKey)) {
  672. gasGrades.set(monthKey, { pSpend: 0, pGal: 0, rSpend: 0, rGal: 0 });
  673. }
  674. const entry = gasGrades.get(monthKey);
  675.  
  676. if(r.itemArray) {
  677. r.itemArray.forEach(item => {
  678. const amt = Number(item.amount) || 0;
  679. const gal = Number(item.fuelUnitQuantity) || 0;
  680.  
  681. if (item.itemNumber === "800877") { // Premium
  682. entry.pSpend += amt;
  683. entry.pGal += gal;
  684. } else if (item.itemNumber === "800599") { // Regular
  685. entry.rSpend += amt;
  686. entry.rGal += gal;
  687. }
  688. });
  689. }
  690. });
  691.  
  692. // Prepare Data for Gas Breakdown Charts
  693. const sortedGasKeys = Array.from(gasGrades.keys()).sort();
  694. const gasLabels = sortedGasKeys.map(k => {
  695. const [y, m] = k.split('-');
  696. return getMonthAbbr(new Date(y, m - 1));
  697. });
  698.  
  699. const pPrices = [];
  700. const rPrices = [];
  701. const pSpends = [];
  702. const rSpends = [];
  703.  
  704. sortedGasKeys.forEach(k => {
  705. const d = gasGrades.get(k);
  706. pPrices.push(d.pGal > 0 ? d.pSpend / d.pGal : null);
  707. rPrices.push(d.rGal > 0 ? d.rSpend / d.rGal : null);
  708. pSpends.push(d.pSpend);
  709. rSpends.push(d.rSpend);
  710. });
  711.  
  712. // --- CHART 3: GAS PRICE HISTORY (LINE) ---
  713. const ctxPrice = document.getElementById("gasPriceHistoryChart").getContext("2d");
  714. if (gasPriceChartInstance) gasPriceChartInstance.destroy();
  715. gasPriceChartInstance = new Chart(ctxPrice, {
  716. type: 'line',
  717. data: {
  718. labels: gasLabels,
  719. datasets: [
  720. {
  721. label: 'Premium ($/gal)',
  722. data: pPrices,
  723. borderColor: '#dc2626',
  724. backgroundColor: '#dc2626',
  725. tension: 0.3,
  726. spanGaps: true
  727. },
  728. {
  729. label: 'Regular ($/gal)',
  730. data: rPrices,
  731. borderColor: '#4b5563',
  732. backgroundColor: '#4b5563',
  733. tension: 0.3,
  734. spanGaps: true
  735. }
  736. ]
  737. },
  738. options: {
  739. responsive: true,
  740. maintainAspectRatio: false,
  741. scales: { y: { beginAtZero: false } }
  742. }
  743. });
  744.  
  745. // --- CHART 4: GAS SPEND BREAKDOWN (STACKED BAR) ---
  746. const ctxBreakdown = document.getElementById("gasSpendBreakdownChart").getContext("2d");
  747. if (gasSpendBreakdownInstance) gasSpendBreakdownInstance.destroy();
  748. gasSpendBreakdownInstance = new Chart(ctxBreakdown, {
  749. type: 'bar',
  750. data: {
  751. labels: gasLabels,
  752. datasets: [
  753. {
  754. label: 'Premium Spend',
  755. data: pSpends,
  756. backgroundColor: '#dc2626',
  757. },
  758. {
  759. label: 'Regular Spend',
  760. data: rSpends,
  761. backgroundColor: '#9ca3af',
  762. }
  763. ]
  764. },
  765. options: {
  766. responsive: true,
  767. maintainAspectRatio: false,
  768. scales: {
  769. x: { stacked: true },
  770. y: { stacked: true, beginAtZero: true }
  771. }
  772. }
  773. });
  774. }
  775.  
  776. // --- 4. HELPER RENDER FUNCTIONS ---
  777. function renderMerchTables(itemStats) {
  778. const items = Array.from(itemStats.values());
  779.  
  780. // 1. Most Expensive (Max Price) - Filter out "0" prices from erroneous data
  781. const byMaxPrice = [...items]
  782. .filter(i => i.maxPrice > 0)
  783. .sort((a,b) => b.maxPrice - a.maxPrice)
  784. .slice(0, 10);
  785.  
  786. const expBody = document.getElementById("mostExpensiveBody");
  787. expBody.innerHTML = "";
  788. byMaxPrice.forEach(row => {
  789. expBody.innerHTML += `<tr><td>${row.name}</td><td class="money">${formatMoney(row.maxPrice)}</td><td class="money">${formatMoney(row.totalSpent/row.totalUnits)}</td></tr>`;
  790. });
  791.  
  792. // 2. Price Increases (Latest > First)
  793. const byIncrease = [...items]
  794. .filter(i => i.lastPrice > i.firstPrice)
  795. .sort((a,b) => (b.lastPrice - b.firstPrice) - (a.lastPrice - a.firstPrice))
  796. .slice(0, 10);
  797.  
  798. const incBody = document.getElementById("priceIncreaseBody");
  799. incBody.innerHTML = "";
  800. byIncrease.forEach(row => {
  801. const diff = row.lastPrice - row.firstPrice;
  802. incBody.innerHTML += `<tr><td>${row.name}</td><td>${formatMoney(row.firstPrice)} &rarr; ${formatMoney(row.lastPrice)}</td><td class="money pos">+${formatMoney(diff)}</td></tr>`;
  803. });
  804.  
  805. // 3. Price Decreases (Latest < First)
  806. const byDecrease = [...items]
  807. .filter(i => i.lastPrice < i.firstPrice)
  808. .sort((a,b) => (a.lastPrice - a.firstPrice) - (b.lastPrice - b.firstPrice))
  809. .slice(0, 10);
  810.  
  811. const decBody = document.getElementById("priceDecreaseBody");
  812. decBody.innerHTML = "";
  813. byDecrease.forEach(row => {
  814. const diff = row.lastPrice - row.firstPrice;
  815. decBody.innerHTML += `<tr><td>${row.name}</td><td>${formatMoney(row.firstPrice)} &rarr; ${formatMoney(row.lastPrice)}</td><td class="money neg">${formatMoney(diff)}</td></tr>`;
  816. });
  817.  
  818. // 4. Top Spend
  819. const bySpend = [...items].sort((a,b) => b.totalSpent - a.totalSpent).slice(0, 10);
  820. const spendBody = document.getElementById("mostTotalSpentBody");
  821. spendBody.innerHTML = "";
  822. bySpend.forEach((row, i) => {
  823. spendBody.innerHTML += `
  824. <tr>
  825. <td>${i+1}</td>
  826. <td><strong>${row.name}</strong></td>
  827. <td class="money">${formatMoney(row.totalSpent)}</td>
  828. <td>${row.totalUnits}</td>
  829. <td class="money">${formatMoney(row.totalSpent/row.totalUnits)}</td>
  830. </tr>
  831. `;
  832. });
  833.  
  834. // 5. Most Frequent
  835. const byCount = [...items].sort((a,b) => b.totalUnits - a.totalUnits).slice(0, 10);
  836. const countBody = document.getElementById("mostPurchasedBody");
  837. countBody.innerHTML = "";
  838. byCount.forEach((row, i) => {
  839. const change = row.maxPrice - row.minPrice;
  840. const changeStr = change > 0.01 ? `<span class="pos">+${formatMoney(change)}</span>` : "-";
  841. countBody.innerHTML += `
  842. <tr>
  843. <td>${i+1}</td>
  844. <td><strong>${row.name}</strong></td>
  845. <td>${row.totalUnits}</td>
  846. <td class="money">${formatMoney(row.totalSpent/row.totalUnits)}</td>
  847. <td>${changeStr}</td>
  848. </tr>
  849. `;
  850. });
  851. }
  852.  
  853. function renderSimpleBarChart(canvasId, monthlyMap, label, color, instance, setInstance) {
  854. const ctx = document.getElementById(canvasId).getContext('2d');
  855. const sortedKeys = Array.from(monthlyMap.keys()).sort();
  856.  
  857. const labels = sortedKeys.map(k => {
  858. const [y, m] = k.split('-');
  859. return getMonthAbbr(new Date(y, m - 1));
  860. });
  861. const data = sortedKeys.map(k => monthlyMap.get(k).spent);
  862.  
  863. if (instance) instance.destroy();
  864.  
  865. const newChart = new Chart(ctx, {
  866. type: 'bar',
  867. data: {
  868. labels,
  869. datasets: [{
  870. label: label,
  871. data: data,
  872. backgroundColor: color,
  873. borderRadius: 4
  874. }]
  875. },
  876. options: {
  877. responsive: true,
  878. maintainAspectRatio: false,
  879. plugins: { legend: { display: false } },
  880. scales: { y: { beginAtZero: true } }
  881. }
  882. });
  883. setInstance(newChart);
  884. }
  885.  
  886. // --- 5. EVENT LISTENER ---
  887. document.getElementById("fileInput").addEventListener("change", (e) => {
  888. const file = e.target.files[0];
  889. if (!file) return;
  890. const reader = new FileReader();
  891. reader.onload = (ev) => {
  892. try {
  893. const json = JSON.parse(ev.target.result);
  894. if (!Array.isArray(json)) throw new Error("File must be a JSON array of receipts.");
  895. document.getElementById("status").textContent = `Success! Loaded ${json.length} receipts.`;
  896.  
  897. const processed = processData(json);
  898. renderDashboard(processed);
  899. } catch (err) {
  900. console.error(err);
  901. document.getElementById("status").textContent = "Error: " + err.message;
  902. }
  903. };
  904. reader.readAsText(file);
  905. });
  906. </script>
  907. </body>
  908. </html>
Add Comment
Please, Sign In to add comment