created price-history.ts to get history data and added to modal via chart.js
This commit is contained in:
214
src/assets/js/priceChart.js
Normal file
214
src/assets/js/priceChart.js
Normal file
@@ -0,0 +1,214 @@
|
||||
import Chart from 'chart.js/auto';
|
||||
|
||||
const CONDITIONS = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
||||
|
||||
// Match the $tiers colors from your SCSS exactly
|
||||
const CONDITION_COLORS = {
|
||||
"Near Mint": { active: 'rgba(156, 204, 102, 1)', muted: 'rgba(156, 204, 102, 0.67)' },
|
||||
"Lightly Played": { active: 'rgba(211, 225, 86, 1)', muted: 'rgba(211, 225, 86, 0.67)' },
|
||||
"Moderately Played": { active: 'rgba(255, 238, 87, 1)', muted: 'rgba(255, 238, 87, 0.67)' },
|
||||
"Heavily Played": { active: 'rgba(255, 201, 41, 1)', muted: 'rgba(255, 201, 41, 0.67)' },
|
||||
"Damaged": { active: 'rgba(255, 167, 36, 1)', muted: 'rgba(255, 167, 36, 0.67)' },
|
||||
};
|
||||
|
||||
const RANGE_DAYS = { '1m': 30, '3m': 90 };
|
||||
|
||||
let chartInstance = null;
|
||||
let allHistory = [];
|
||||
let activeCondition = "Near Mint";
|
||||
let activeRange = '1m';
|
||||
|
||||
function formatDate(dateStr) {
|
||||
const [year, month, day] = dateStr.split('-');
|
||||
const d = new Date(Number(year), Number(month) - 1, Number(day));
|
||||
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
function buildChartData(history, rangeKey) {
|
||||
const cutoff = new Date(Date.now() - RANGE_DAYS[rangeKey] * 86_400_000);
|
||||
|
||||
const filtered = history.filter(r => new Date(r.calculatedAt) >= cutoff);
|
||||
|
||||
const allDates = [...new Set(filtered.map(r => r.calculatedAt))]
|
||||
.sort((a, b) => new Date(a) - new Date(b));
|
||||
|
||||
const labels = allDates.map(formatDate);
|
||||
|
||||
const lookup = {};
|
||||
for (const row of filtered) {
|
||||
if (!lookup[row.condition]) lookup[row.condition] = {};
|
||||
lookup[row.condition][row.calculatedAt] = Number(row.marketPrice);
|
||||
}
|
||||
|
||||
const datasets = CONDITIONS.map(condition => {
|
||||
const isActive = condition === activeCondition;
|
||||
const colors = CONDITION_COLORS[condition];
|
||||
const data = allDates.map(date => lookup[condition]?.[date] ?? null);
|
||||
|
||||
return {
|
||||
label: condition,
|
||||
data,
|
||||
borderColor: isActive ? colors.active : colors.muted,
|
||||
borderWidth: isActive ? 2.5 : 1,
|
||||
pointRadius: isActive ? 3 : 0,
|
||||
pointHoverRadius: isActive ? 5 : 3,
|
||||
pointBackgroundColor: isActive ? colors.active : colors.muted,
|
||||
tension: 0.3,
|
||||
fill: false,
|
||||
spanGaps: true,
|
||||
order: isActive ? 0 : 1,
|
||||
};
|
||||
});
|
||||
|
||||
return { labels, datasets };
|
||||
}
|
||||
|
||||
function updateChart() {
|
||||
if (!chartInstance) return;
|
||||
const { labels, datasets } = buildChartData(allHistory, activeRange);
|
||||
chartInstance.data.labels = labels;
|
||||
chartInstance.data.datasets = datasets;
|
||||
chartInstance.update('none');
|
||||
}
|
||||
|
||||
function initPriceChart(canvas) {
|
||||
if (chartInstance) {
|
||||
chartInstance.destroy();
|
||||
chartInstance = null;
|
||||
}
|
||||
|
||||
try {
|
||||
allHistory = JSON.parse(canvas.dataset.history ?? '[]');
|
||||
} catch (err) {
|
||||
console.error('Failed to parse price history:', err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!allHistory.length) {
|
||||
console.warn('No price history data for this card');
|
||||
return;
|
||||
}
|
||||
|
||||
const { labels, datasets } = buildChartData(allHistory, activeRange);
|
||||
|
||||
chartInstance = new Chart(canvas.getContext('2d'), {
|
||||
type: 'line',
|
||||
data: { labels, datasets },
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: {
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
},
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.85)',
|
||||
titleColor: 'rgba(255, 255, 255, 0.9)',
|
||||
bodyColor: 'rgba(255, 255, 255, 0.75)',
|
||||
borderColor: 'rgba(255, 255, 255, 0.1)',
|
||||
borderWidth: 1,
|
||||
padding: 10,
|
||||
callbacks: {
|
||||
labelColor: (ctx) => {
|
||||
const colors = CONDITION_COLORS[ctx.dataset.label];
|
||||
return {
|
||||
borderColor: colors.active,
|
||||
backgroundColor: colors.active,
|
||||
};
|
||||
},
|
||||
label: (ctx) => {
|
||||
const isActive = ctx.dataset.label === activeCondition;
|
||||
const price = ctx.parsed.y != null ? `$${ctx.parsed.y.toFixed(2)}` : '—';
|
||||
return isActive
|
||||
? ` ${ctx.dataset.label}: ${price} ◀`
|
||||
: ` ${ctx.dataset.label}: ${price}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
grid: { color: 'rgba(255, 255, 255, 0.05)' },
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.4)',
|
||||
maxTicksLimit: 6,
|
||||
maxRotation: 0,
|
||||
},
|
||||
border: { color: 'rgba(255, 255, 255, 0.1)' },
|
||||
},
|
||||
y: {
|
||||
grid: { color: 'rgba(255, 255, 255, 0.05)' },
|
||||
ticks: {
|
||||
color: 'rgba(255, 255, 255, 0.4)',
|
||||
callback: (val) => `$${Number(val).toFixed(2)}`,
|
||||
},
|
||||
border: { color: 'rgba(255, 255, 255, 0.1)' },
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setupObserver() {
|
||||
const modal = document.getElementById('cardModal');
|
||||
if (!modal) {
|
||||
console.error('cardModal element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
const canvas = document.getElementById('priceHistoryChart');
|
||||
if (!canvas) return;
|
||||
|
||||
// Disconnect immediately so tab switches don't retrigger initPriceChart
|
||||
observer.disconnect();
|
||||
|
||||
activeCondition = "Near Mint";
|
||||
activeRange = '1m';
|
||||
document.querySelectorAll('.price-range-btn').forEach(b => {
|
||||
b.classList.toggle('active', b.dataset.range === '1m');
|
||||
});
|
||||
|
||||
initPriceChart(canvas);
|
||||
});
|
||||
|
||||
observer.observe(modal, { childList: true, subtree: true });
|
||||
|
||||
modal.addEventListener('hidden.bs.modal', () => {
|
||||
if (chartInstance) {
|
||||
chartInstance.destroy();
|
||||
chartInstance = null;
|
||||
}
|
||||
allHistory = [];
|
||||
// Reconnect so the next card open is detected
|
||||
observer.observe(modal, { childList: true, subtree: true });
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('shown.bs.tab', (e) => {
|
||||
const target = e.target?.getAttribute('data-bs-target');
|
||||
const conditionMap = {
|
||||
'#nav-nm': 'Near Mint',
|
||||
'#nav-lp': 'Lightly Played',
|
||||
'#nav-mp': 'Moderately Played',
|
||||
'#nav-hp': 'Heavily Played',
|
||||
'#nav-dmg': 'Damaged',
|
||||
};
|
||||
if (target && conditionMap[target]) {
|
||||
activeCondition = conditionMap[target];
|
||||
updateChart();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
const btn = e.target?.closest('.price-range-btn');
|
||||
if (!btn) return;
|
||||
document.querySelectorAll('.price-range-btn').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
activeRange = btn.dataset.range ?? '1m';
|
||||
updateChart();
|
||||
});
|
||||
|
||||
setupObserver();
|
||||
@@ -112,3 +112,4 @@ export const priceHistory = pokeSchema.table('price_history', {
|
||||
export const processingSkus = pokeSchema.table('processing_skus', {
|
||||
skuId: integer().primaryKey(),
|
||||
});
|
||||
|
||||
@@ -38,7 +38,8 @@ const { title } = Astro.props;
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.9/dist/chart.umd.min.js"></script>
|
||||
<script src="../assets/js/main.js"></script>
|
||||
<script>import '../assets/js/priceChart.js';</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -4,7 +4,6 @@ import SetIcon from '../../components/SetIcon.astro';
|
||||
import EnergyIcon from '../../components/EnergyIcon.astro';
|
||||
import RarityIcon from '../../components/RarityIcon.astro';
|
||||
import { db } from '../../db/index';
|
||||
import { privateDecrypt } from "node:crypto";
|
||||
import FirstEditionIcon from "../../components/FirstEditionIcon.astro";
|
||||
|
||||
export const partial = true;
|
||||
@@ -13,30 +12,23 @@ export const prerender = false;
|
||||
const searchParams = Astro.url.searchParams;
|
||||
const cardId = Number(searchParams.get('cardId')) || 0;
|
||||
|
||||
// query the database for the card with the given productId and return the card data as json
|
||||
const card = await db.query.cards.findFirst({
|
||||
where: { cardId: Number(cardId) },
|
||||
with: {
|
||||
prices: true,
|
||||
prices: {
|
||||
with: {
|
||||
history: {
|
||||
orderBy: (ph, { asc }) => [asc(ph.calculatedAt)],
|
||||
}
|
||||
}
|
||||
},
|
||||
set: true,
|
||||
}
|
||||
});
|
||||
|
||||
// Get the current card's position in the grid and find previous/next cards
|
||||
// This assumes cards are displayed in a specific order in the DOM
|
||||
const cardElements = typeof document !== 'undefined' ? document.querySelectorAll('[data-card-id]') : [];
|
||||
let prevCardId = null;
|
||||
let nextCardId = null;
|
||||
|
||||
// Since this is server-side, we can't access the DOM directly
|
||||
// Instead, we'll pass the current cardId and let JavaScript handle navigation
|
||||
// The JS will look for the next/prev cards in the grid based on the visible cards
|
||||
|
||||
function timeAgo(date: Date | null) {
|
||||
if (!date) return "Not applicable";
|
||||
|
||||
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
|
||||
|
||||
const intervals: Record<string, number> = {
|
||||
year: 31536000,
|
||||
month: 2592000,
|
||||
@@ -44,31 +36,35 @@ function timeAgo(date: Date | null) {
|
||||
hour: 3600,
|
||||
minute: 60
|
||||
};
|
||||
|
||||
for (const [unit, value] of Object.entries(intervals)) {
|
||||
const count = Math.floor(seconds / value);
|
||||
if (count >= 1) return `${count} ${unit}${count > 1 ? "s" : ""} ago`;
|
||||
}
|
||||
|
||||
return "just now";
|
||||
}
|
||||
|
||||
// Get the most recent calculatedAt across all prices
|
||||
const calculatedAt = (() => {
|
||||
if (!card?.prices?.length) return null;
|
||||
|
||||
// Extract all valid calculatedAt timestamps
|
||||
const dates = card.prices
|
||||
.map(p => p.calculatedAt)
|
||||
.filter(d => d) // remove null/undefined
|
||||
.filter(d => d)
|
||||
.map(d => new Date(d));
|
||||
|
||||
if (!dates.length) return null;
|
||||
|
||||
// Return the most recent one
|
||||
return new Date(Math.max(...dates.map(d => d.getTime())));
|
||||
})();
|
||||
|
||||
// Flatten all price history across all skus into a single array for the chart,
|
||||
// normalising calculatedAt to a YYYY-MM-DD string to avoid timezone/dedup issues
|
||||
const priceHistoryForChart = (card?.prices ?? []).flatMap(sku =>
|
||||
(sku.history ?? []).map(ph => ({
|
||||
condition: sku.condition,
|
||||
calculatedAt: ph.calculatedAt
|
||||
? new Date(ph.calculatedAt).toISOString().split('T')[0]
|
||||
: null,
|
||||
marketPrice: ph.marketPrice,
|
||||
}))
|
||||
).filter(r => r.calculatedAt !== null);
|
||||
|
||||
const conditionOrder = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
||||
|
||||
const conditionAttributes = (price: any) => {
|
||||
@@ -76,13 +72,10 @@ const conditionAttributes = (price: any) => {
|
||||
const market = price?.marketPrice;
|
||||
const low = price?.lowestPrice;
|
||||
const high = price?.highestPrice;
|
||||
|
||||
if (market == null || low == null || high == null || Number(market) === 0) {
|
||||
return "Indeterminate";
|
||||
}
|
||||
|
||||
const spreadPct = (Number(high) - Number(low)) / Number(market) * 100;
|
||||
|
||||
if (spreadPct >= 81) return "High";
|
||||
if (spreadPct >= 59) return "Medium";
|
||||
return "Low";
|
||||
@@ -93,7 +86,7 @@ const conditionAttributes = (price: any) => {
|
||||
case "High": return "alert-danger";
|
||||
case "Medium": return "alert-warning";
|
||||
case "Low": return "alert-success";
|
||||
default: return "alert-dark"; // Indeterminate
|
||||
default: return "alert-dark";
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -133,41 +126,70 @@ const altSearchUrl = (card: any) => {
|
||||
<div class="container-fluid">
|
||||
<div class="card mb-2 border-0">
|
||||
<div class="row g-4">
|
||||
|
||||
<!-- Card image column -->
|
||||
<div class="col-sm-12 col-md-3">
|
||||
<div class="position-relative mt-1"><img src={`/cards/${card?.productId}.jpg`} class="card-image w-100 img-fluid rounded-4" alt={card?.productName} onerror="this.onerror=null;this.src='/cards/default.jpg'" onclick="copyImage(this); dataLayer.push({'event': 'copiedImage'});"><span class="position-absolute top-50 start-0 d-inline"><FirstEditionIcon edition={card?.variant} /></span><span class="position-absolute bottom-0 start-0 d-inline"><SetIcon set={card?.set?.setCode} /></span><span class="position-absolute top-0 end-0 d-inline"><EnergyIcon energy={card?.energyType} /></span><span class="rarity-icon-large position-absolute bottom-0 end-0 d-inline"><RarityIcon rarity={card?.rarityName} /></span></div>
|
||||
<div class="position-relative mt-1">
|
||||
<img
|
||||
src={`/cards/${card?.productId}.jpg`}
|
||||
class="card-image w-100 img-fluid rounded-4"
|
||||
alt={card?.productName}
|
||||
onerror="this.onerror=null;this.src='/cards/default.jpg'"
|
||||
onclick="copyImage(this); dataLayer.push({'event': 'copiedImage'});"
|
||||
/>
|
||||
<span class="position-absolute top-50 start-0 d-inline"><FirstEditionIcon edition={card?.variant} /></span>
|
||||
<span class="position-absolute bottom-0 start-0 d-inline"><SetIcon set={card?.set?.setCode} /></span>
|
||||
<span class="position-absolute top-0 end-0 d-inline"><EnergyIcon energy={card?.energyType} /></span>
|
||||
<span class="rarity-icon-large position-absolute bottom-0 end-0 d-inline"><RarityIcon rarity={card?.rarityName} /></span>
|
||||
</div>
|
||||
<div class="d-flex flex-column flex-lg-row justify-content-between mt-2">
|
||||
<div class="text-secondary">{card?.set?.setCode}</div>
|
||||
<div class="text-secondary">Illus<span class="d-none d-lg-inline">trator</span>: {card?.artist}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tabs + price data column -->
|
||||
<div class="col-sm-12 col-md-7">
|
||||
<ul class="nav nav-tabs nav-fill border-0 me-3 mb-2" id="myTab" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link nm active" id="nm-tab" data-bs-toggle="tab" data-bs-target="#nav-nm" type="button" role="tab" aria-controls="nav-nm" aria-selected="true"><span class="d-none d-lg-inline">Near Mint</span><span class="d-lg-none">NM</span></button>
|
||||
<button class="nav-link nm active" id="nm-tab" data-bs-toggle="tab" data-bs-target="#nav-nm" type="button" role="tab" aria-controls="nav-nm" aria-selected="true">
|
||||
<span class="d-none d-lg-inline">Near Mint</span><span class="d-lg-none">NM</span>
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link lp" id="lp-tab" data-bs-toggle="tab" data-bs-target="#nav-lp" type="button" role="tab" aria-controls="nav-lp" aria-selected="false"><span class="d-none d-lg-inline">Lightly Played</span><span class="d-lg-none">LP</span></button>
|
||||
<button class="nav-link lp" id="lp-tab" data-bs-toggle="tab" data-bs-target="#nav-lp" type="button" role="tab" aria-controls="nav-lp" aria-selected="false">
|
||||
<span class="d-none d-lg-inline">Lightly Played</span><span class="d-lg-none">LP</span>
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link mp" id="mp-tab" data-bs-toggle="tab" data-bs-target="#nav-mp" type="button" role="tab" aria-controls="nav-mp" aria-selected="false"><span class="d-none d-lg-inline">Moderately Played</span><span class="d-lg-none">MP</span></button>
|
||||
<button class="nav-link mp" id="mp-tab" data-bs-toggle="tab" data-bs-target="#nav-mp" type="button" role="tab" aria-controls="nav-mp" aria-selected="false">
|
||||
<span class="d-none d-lg-inline">Moderately Played</span><span class="d-lg-none">MP</span>
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link hp" id="hp-tab" data-bs-toggle="tab" data-bs-target="#nav-hp" type="button" role="tab" aria-controls="nav-hp" aria-selected="false"><span class="d-none d-lg-inline">Heavily Played</span><span class="d-lg-none">HP</span></button>
|
||||
<button class="nav-link hp" id="hp-tab" data-bs-toggle="tab" data-bs-target="#nav-hp" type="button" role="tab" aria-controls="nav-hp" aria-selected="false">
|
||||
<span class="d-none d-lg-inline">Heavily Played</span><span class="d-lg-none">HP</span>
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link dmg" id="dmg-tab" data-bs-toggle="tab" data-bs-target="#nav-dmg" type="button" role="tab" aria-controls="nav-dmg" aria-selected="false"><span class="d-none d-lg-inline">Damaged</span><span class="d-lg-none">DMG</span></button>
|
||||
<button class="nav-link dmg" id="dmg-tab" data-bs-toggle="tab" data-bs-target="#nav-dmg" type="button" role="tab" aria-controls="nav-dmg" aria-selected="false">
|
||||
<span class="d-none d-lg-inline">Damaged</span><span class="d-lg-none">DMG</span>
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link vendor d-none" id="vendor-tab" data-bs-toggle="tab" data-bs-target="#nav-vendor" type="button" role="tab" aria-controls="nav-vendor" aria-selected="false"><span class="d-none d-lg-inline">Inventory</span><span class="d-lg-none">+/-</span></button>
|
||||
<button class="nav-link vendor d-none" id="vendor-tab" data-bs-toggle="tab" data-bs-target="#nav-vendor" type="button" role="tab" aria-controls="nav-vendor" aria-selected="false">
|
||||
<span class="d-none d-lg-inline">Inventory</span><span class="d-lg-none">+/-</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content" id="myTabContent">
|
||||
{card?.prices.slice().sort((a, b) => conditionOrder.indexOf(a.condition) - conditionOrder.indexOf(b.condition)).map((price) => {
|
||||
const attributes = conditionAttributes(price);
|
||||
return (
|
||||
<div class={`tab-pane fade ${attributes?.label} ${attributes?.class}`} id={`${attributes?.label}`} role="tabpanel" tabindex="0">
|
||||
<div class="d-block gap-1 d-lg-flex">
|
||||
<div class="d-flex flex-row flex-lg-column gap-1 col-12 col-lg-2 mb-1">
|
||||
<div class={`tab-pane fade ${attributes?.label} ${attributes?.class ?? ''}`} id={`${attributes?.label}`} role="tabpanel" tabindex="0">
|
||||
<!-- Price stat cards only — chart lives outside tabs -->
|
||||
<div class="d-flex flex-row flex-wrap gap-1 mb-1">
|
||||
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-1">
|
||||
<h6 class="mb-auto">Market Price</h6>
|
||||
<p class="mb-0 mt-1">${price.marketPrice}</p>
|
||||
@@ -180,62 +202,45 @@ const altSearchUrl = (card: any) => {
|
||||
<h6 class="mb-auto">Highest Price</h6>
|
||||
<p class="mb-0 mt-1">${price.highestPrice}</p>
|
||||
</div>
|
||||
<div class={`alert alert-secondary rounded p-2 flex-fill d-flex flex-column mb-1 ${attributes?.volatilityClass}`}>
|
||||
<div class={`alert rounded p-2 flex-fill d-flex flex-column mb-1 ${attributes?.volatilityClass}`}>
|
||||
<h6 class="mb-auto">Volatility</h6>
|
||||
<p class="mb-0 mt-1">{attributes?.volatility}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex flex-column gap-1 col-12 col-lg-10 mb-0 me-2 clearfix">
|
||||
<div class="alert alert-dark rounded p-2 mb-1 table-responsive">
|
||||
<h6>Latest Verified Sales</h6>
|
||||
<table class="table table-sm mb-0">
|
||||
<caption class="small">Filtered to remove mismatched language variants</caption>
|
||||
<thead class="table-dark">
|
||||
<tr>
|
||||
<th scope="col">Date</th>
|
||||
<th scope="col">Title</th>
|
||||
<th scope="col">Price</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="alert alert-dark rounded p-2 mb-1">
|
||||
<h6>Market Price History</h6>
|
||||
<div class="position-relative" style="height: 200px;">
|
||||
<canvas id={`priceChart-${price.priceId}`} class="price-history-chart" data-card-id={card?.cardId} data-condition={price.condition}></canvas>
|
||||
</div>
|
||||
<div class="btn-group btn-group-sm d-flex flex-row gap-1 justify-content-end" role="group" aria-label="Time range">
|
||||
<button type="button" class="btn btn-dark price-range-btn active" data-range="1m">1M</button>
|
||||
<button type="button" class="btn btn-dark price-range-btn" data-range="3m">3M</button>
|
||||
<button type="button" class="btn btn-dark price-range-btn" data-range="6m">6M</button>
|
||||
<button type="button" class="btn btn-dark price-range-btn" data-range="1y">1Y</button>
|
||||
<button type="button" class="btn btn-dark price-range-btn" data-range="all">All</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div class="tab-pane fade" id="nav-vendor" role="tabpanel" aria-labelledby="nav-vendor" tabindex="0">
|
||||
<div class="row g-2 mt-2">
|
||||
|
||||
<div class="tab-pane fade" id="nav-vendor" role="tabpanel" aria-labelledby="nav-vendor" tabindex="0">
|
||||
<div class="row g-2 mt-2"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Chart lives outside tabs so it persists across condition switches -->
|
||||
<div class="alert alert-dark rounded p-2 mt-2">
|
||||
<h6>Market Price History</h6>
|
||||
<div class="position-relative" style="height: 200px;">
|
||||
<canvas
|
||||
id="priceHistoryChart"
|
||||
class="price-history-chart"
|
||||
data-card-id={card?.cardId}
|
||||
data-history={JSON.stringify(priceHistoryForChart)}>
|
||||
</canvas>
|
||||
</div>
|
||||
<div class="btn-group btn-group-sm d-flex flex-row gap-1 justify-content-end mt-2" role="group" aria-label="Time range">
|
||||
<button type="button" class="btn btn-dark price-range-btn active" data-range="1m">1M</button>
|
||||
<button type="button" class="btn btn-dark price-range-btn" data-range="3m">3M</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- External links column -->
|
||||
<div class="col-sm-12 col-md-2 mt-0 mt-md-5 d-flex flex-row flex-md-column">
|
||||
<a class="btn btn-dark mb-2 w-100 p-2" href={`https://www.tcgplayer.com/product/${card?.productId}`} target="_blank" onclick="dataLayer.push({'event': 'tcgplayerClick', 'tcgplayerUrl': this.getAttribute('href')});"><img src="/vendors/tcgplayer.webp"> <span class="d-none d-lg-inline">TCGPlayer</span></a>
|
||||
<a class="btn btn-dark mb-2 w-100 p-2" href={`${ebaySearchUrl(card)}`} target="_blank" onclick="dataLayer.push({'event': 'ebayClick', 'ebayUrl': this.getAttribute('href')});"><span set:html={ebay} /></a>
|
||||
<a class="btn btn-dark mb-2 w-100 p-2" href={`${altSearchUrl(card)}`} target="_blank" onclick="dataLayer.push({'event': 'altClick', 'altUrl': this.getAttribute('href')});"><svg width="48" height="20.16" viewBox="0 0 48 20" fill="none"><path d="M14.2761 19.9996H18.5308L11.6934 0.0712891H7.76953L14.2761 19.9996Z" fill="#ffffff"></path><path d="M6.17778 19.9986H6.14536L3.19643 11.2305L0 19.9988L6.17768 19.9989L6.17778 19.9986Z" fill="#ffffff"></path><path d="M24.7842 0H20.6759V19.9661H34.3427V16.5426H24.7842V0Z" fill="#ffffff"></path><path d="M41.6644 3.42355H47.4981V0H31.5033V3.42355H37.5561V19.9661H41.6644V3.42355Z" fill="#ffffff"></path></svg></a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="text-end my-0"><small class="text-body-tertiary">Prices last changed: {timeAgo(calculatedAt)}</small></div>
|
||||
</div>
|
||||
@@ -243,3 +248,181 @@ const altSearchUrl = (card: any) => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
import Chart from 'chart.js/auto';
|
||||
|
||||
const CONDITIONS = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
||||
|
||||
const CONDITION_COLORS = {
|
||||
"Near Mint": { active: '#22c55e', muted: 'rgba(34,197,94,0.2)' },
|
||||
"Lightly Played": { active: '#eab308', muted: 'rgba(234,179,8,0.2)' },
|
||||
"Moderately Played": { active: '#f97316', muted: 'rgba(249,115,22,0.2)' },
|
||||
"Heavily Played": { active: '#ef4444', muted: 'rgba(239,68,68,0.2)' },
|
||||
"Damaged": { active: '#a855f7', muted: 'rgba(168,85,247,0.2)' },
|
||||
};
|
||||
|
||||
const RANGE_DAYS = { '1m': 30, '3m': 90, '6m': 180, '1y': 365, 'all': Infinity };
|
||||
|
||||
let chartInstance = null;
|
||||
let allHistory = [];
|
||||
let activeCondition = "Near Mint";
|
||||
let activeRange = '1m';
|
||||
|
||||
function formatDate(dateStr) {
|
||||
const [year, month, day] = dateStr.split('-');
|
||||
const d = new Date(Number(year), Number(month) - 1, Number(day));
|
||||
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
function buildChartData(history, rangeKey) {
|
||||
const cutoff = rangeKey === 'all'
|
||||
? new Date(0)
|
||||
: new Date(Date.now() - RANGE_DAYS[rangeKey] * 86_400_000);
|
||||
|
||||
const filtered = history.filter(r => new Date(r.calculatedAt) >= cutoff);
|
||||
|
||||
const allDates = [...new Set(filtered.map(r => r.calculatedAt))]
|
||||
.sort((a, b) => new Date(a) - new Date(b));
|
||||
|
||||
const labels = allDates.map(formatDate);
|
||||
|
||||
const lookup = {};
|
||||
for (const row of filtered) {
|
||||
if (!lookup[row.condition]) lookup[row.condition] = {};
|
||||
lookup[row.condition][row.calculatedAt] = Number(row.marketPrice);
|
||||
}
|
||||
|
||||
const datasets = CONDITIONS.map(condition => {
|
||||
const isActive = condition === activeCondition;
|
||||
const colors = CONDITION_COLORS[condition];
|
||||
const data = allDates.map(date => lookup[condition]?.[date] ?? null);
|
||||
return {
|
||||
label: condition,
|
||||
data,
|
||||
borderColor: isActive ? colors.active : colors.muted,
|
||||
borderWidth: isActive ? 2 : 1,
|
||||
pointRadius: isActive ? 3 : 0,
|
||||
pointHoverRadius: isActive ? 5 : 2,
|
||||
tension: 0.3,
|
||||
fill: false,
|
||||
spanGaps: true,
|
||||
order: isActive ? 0 : 1,
|
||||
};
|
||||
});
|
||||
|
||||
return { labels, datasets };
|
||||
}
|
||||
|
||||
function updateChart() {
|
||||
if (!chartInstance) return;
|
||||
const { labels, datasets } = buildChartData(allHistory, activeRange);
|
||||
chartInstance.data.labels = labels;
|
||||
chartInstance.data.datasets = datasets;
|
||||
chartInstance.update('none');
|
||||
}
|
||||
|
||||
function initPriceChart(canvas) {
|
||||
if (chartInstance) {
|
||||
chartInstance.destroy();
|
||||
chartInstance = null;
|
||||
}
|
||||
|
||||
try {
|
||||
allHistory = JSON.parse(canvas.dataset.history ?? '[]');
|
||||
} catch (err) {
|
||||
console.error('Failed to parse price history:', err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!allHistory.length) return;
|
||||
|
||||
const { labels, datasets } = buildChartData(allHistory, activeRange);
|
||||
|
||||
chartInstance = new Chart(canvas.getContext('2d'), {
|
||||
type: 'line',
|
||||
data: { labels, datasets },
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(0,0,0,0.85)',
|
||||
titleColor: 'rgba(255,255,255,0.9)',
|
||||
bodyColor: 'rgba(255,255,255,0.65)',
|
||||
callbacks: {
|
||||
label: (ctx) => {
|
||||
const isActive = ctx.dataset.label === activeCondition;
|
||||
const price = ctx.parsed.y != null ? `$${ctx.parsed.y.toFixed(2)}` : '—';
|
||||
return isActive
|
||||
? ` ${ctx.dataset.label}: ${price} ◀`
|
||||
: ` ${ctx.dataset.label}: ${price}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
grid: { color: 'rgba(255,255,255,0.05)' },
|
||||
ticks: { color: 'rgba(255,255,255,0.4)', maxTicksLimit: 6, maxRotation: 0 },
|
||||
},
|
||||
y: {
|
||||
grid: { color: 'rgba(255,255,255,0.05)' },
|
||||
ticks: {
|
||||
color: 'rgba(255,255,255,0.4)',
|
||||
callback: (val) => `$${Number(val).toFixed(2)}`,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setupListeners() {
|
||||
const modal = document.getElementById('cardModal');
|
||||
if (!modal) return;
|
||||
|
||||
modal.addEventListener('shown.bs.modal', () => {
|
||||
activeCondition = "Near Mint";
|
||||
activeRange = '1m';
|
||||
document.querySelectorAll('.price-range-btn').forEach(b => {
|
||||
b.classList.toggle('active', b.dataset.range === '1m');
|
||||
});
|
||||
const canvas = document.getElementById('priceHistoryChart');
|
||||
if (canvas) initPriceChart(canvas);
|
||||
});
|
||||
|
||||
modal.addEventListener('hidden.bs.modal', () => {
|
||||
if (chartInstance) { chartInstance.destroy(); chartInstance = null; }
|
||||
allHistory = [];
|
||||
});
|
||||
|
||||
document.addEventListener('shown.bs.tab', (e) => {
|
||||
const target = e.target?.getAttribute('data-bs-target');
|
||||
const conditionMap = {
|
||||
'#nav-nm': 'Near Mint',
|
||||
'#nav-lp': 'Lightly Played',
|
||||
'#nav-mp': 'Moderately Played',
|
||||
'#nav-hp': 'Heavily Played',
|
||||
'#nav-dmg': 'Damaged',
|
||||
};
|
||||
if (target && conditionMap[target]) {
|
||||
activeCondition = conditionMap[target];
|
||||
updateChart();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
const btn = e.target?.closest('.price-range-btn');
|
||||
if (!btn) return;
|
||||
document.querySelectorAll('.price-range-btn').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
activeRange = btn.dataset.range ?? '1m';
|
||||
updateChart();
|
||||
});
|
||||
}
|
||||
|
||||
setupListeners();
|
||||
</script>
|
||||
39
src/pages/partials/price-history.ts
Normal file
39
src/pages/partials/price-history.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { APIRoute } from 'astro';
|
||||
import { db } from '../../db/index';
|
||||
import { priceHistory, skus } from '../../db/schema';
|
||||
import { eq, inArray } from 'drizzle-orm';
|
||||
|
||||
export const prerender = false;
|
||||
|
||||
export const GET: APIRoute = async ({ url }) => {
|
||||
const cardId = Number(url.searchParams.get('cardId')) || 0;
|
||||
|
||||
// Get all skus for this card
|
||||
const cardSkus = await db
|
||||
.select()
|
||||
.from(skus)
|
||||
.where(eq(skus.cardId, cardId));
|
||||
|
||||
if (!cardSkus.length) {
|
||||
return new Response(JSON.stringify([]), { headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
|
||||
const skuIds = cardSkus.map(s => s.skuId);
|
||||
|
||||
// Fetch price history for all skus
|
||||
const history = await db
|
||||
.select({
|
||||
skuId: priceHistory.skuId,
|
||||
calculatedAt: priceHistory.calculatedAt,
|
||||
marketPrice: priceHistory.marketPrice,
|
||||
condition: skus.condition,
|
||||
})
|
||||
.from(priceHistory)
|
||||
.innerJoin(skus, eq(priceHistory.skuId, skus.skuId))
|
||||
.where(inArray(priceHistory.skuId, skuIds))
|
||||
.orderBy(priceHistory.calculatedAt);
|
||||
|
||||
return new Response(JSON.stringify(history), {
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user