Compare commits
8 Commits
b65e2a2859
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85cfd1de64 | ||
|
|
c03a0b36a0 | ||
|
|
5cdf9b1772 | ||
|
|
17465b13c1 | ||
|
|
c61cafecdc | ||
|
|
2b3d5f322e | ||
|
|
53cdddb183 | ||
| 35c8bf25f5 |
@@ -12,7 +12,7 @@ async function findMissingImages() {
|
|||||||
.where(sql`${schema.tcgcards.sealed} = false`);
|
.where(sql`${schema.tcgcards.sealed} = false`);
|
||||||
const missingImages: string[] = [];
|
const missingImages: string[] = [];
|
||||||
for (const card of cards) {
|
for (const card of cards) {
|
||||||
const imagePath = path.join(process.cwd(), 'public', 'cards', `${card.productId}.jpg`);
|
const imagePath = path.join(process.cwd(), 'static', 'cards', `${card.productId}.jpg`);
|
||||||
try {
|
try {
|
||||||
await fs.access(imagePath);
|
await fs.access(imagePath);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ export const createCardCollection = async () => {
|
|||||||
{ name: 'productLineName', type: 'string', facet: true },
|
{ name: 'productLineName', type: 'string', facet: true },
|
||||||
{ name: 'rarityName', type: 'string', facet: true },
|
{ name: 'rarityName', type: 'string', facet: true },
|
||||||
{ name: 'setName', type: 'string', facet: true },
|
{ name: 'setName', type: 'string', facet: true },
|
||||||
|
{ name: 'setCode', type: 'string' },
|
||||||
{ name: 'cardType', type: 'string', facet: true },
|
{ name: 'cardType', type: 'string', facet: true },
|
||||||
{ name: 'energyType', type: 'string', facet: true },
|
{ name: 'energyType', type: 'string', facet: true },
|
||||||
{ name: 'number', type: 'string', sort: true },
|
{ name: 'number', type: 'string', sort: true },
|
||||||
@@ -94,7 +95,15 @@ export const upsertCardCollection = async (db:DBInstance) => {
|
|||||||
with: { set: true, tcgdata: true, prices: true },
|
with: { set: true, tcgdata: true, prices: true },
|
||||||
});
|
});
|
||||||
await client.collections('cards').documents().import(pokemon.map(card => {
|
await client.collections('cards').documents().import(pokemon.map(card => {
|
||||||
const marketPrice = card.tcgdata?.marketPrice ? DollarToInt(card.tcgdata.marketPrice) : null;
|
// Use the NM SKU price matching the card's variant (kept fresh by syncPrices)
|
||||||
|
// Fall back to any NM sku, then to tcgdata price
|
||||||
|
const nmSku = card.prices.find(p => p.condition === 'Near Mint' && p.variant === card.variant)
|
||||||
|
?? card.prices.find(p => p.condition === 'Near Mint');
|
||||||
|
const marketPrice = nmSku?.marketPrice
|
||||||
|
? DollarToInt(nmSku.marketPrice)
|
||||||
|
: card.tcgdata?.marketPrice
|
||||||
|
? DollarToInt(card.tcgdata.marketPrice)
|
||||||
|
: null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: card.cardId.toString(),
|
id: card.cardId.toString(),
|
||||||
@@ -105,12 +114,13 @@ export const upsertCardCollection = async (db:DBInstance) => {
|
|||||||
productLineName: card.productLineName,
|
productLineName: card.productLineName,
|
||||||
rarityName: card.rarityName,
|
rarityName: card.rarityName,
|
||||||
setName: card.set?.setName || "",
|
setName: card.set?.setName || "",
|
||||||
|
setCode: card.set?.setCode || "",
|
||||||
cardType: card.cardType || "",
|
cardType: card.cardType || "",
|
||||||
energyType: card.energyType || "",
|
energyType: card.energyType || "",
|
||||||
number: card.number,
|
number: card.number,
|
||||||
Artist: card.artist || "",
|
Artist: card.artist || "",
|
||||||
sealed: card.sealed,
|
sealed: card.sealed,
|
||||||
content: [card.productName, card.productLineName, card.set?.setName || "", card.number, card.rarityName, card.artist || ""].join(' '),
|
content: [card.productName, card.productLineName, card.set?.setName || "", card.set?.setCode || "", card.number, card.rarityName, card.artist || ""].join(' '),
|
||||||
releaseDate: card.tcgdata?.releaseDate ? Math.floor(new Date(card.tcgdata.releaseDate).getTime() / 1000) : 0,
|
releaseDate: card.tcgdata?.releaseDate ? Math.floor(new Date(card.tcgdata.releaseDate).getTime() / 1000) : 0,
|
||||||
...(marketPrice !== null && { marketPrice }),
|
...(marketPrice !== null && { marketPrice }),
|
||||||
sku_id: card.prices.map(price => price.skuId.toString())
|
sku_id: card.prices.map(price => price.skuId.toString())
|
||||||
|
|||||||
@@ -242,7 +242,7 @@ async function syncProductLine(productLine: string, field: string, fieldValue: s
|
|||||||
}
|
}
|
||||||
|
|
||||||
// get image if it doesn't already exist
|
// get image if it doesn't already exist
|
||||||
const imagePath = path.join(process.cwd(), 'public', 'cards', `${item.productId}.jpg`);
|
const imagePath = path.join(process.cwd(), 'static', 'cards', `${item.productId}.jpg`);
|
||||||
if (!await helper.FileExists(imagePath)) {
|
if (!await helper.FileExists(imagePath)) {
|
||||||
const imageResponse = await fetch(`https://tcgplayer-cdn.tcgplayer.com/product/${item.productId}_in_1000x1000.jpg`);
|
const imageResponse = await fetch(`https://tcgplayer-cdn.tcgplayer.com/product/${item.productId}_in_1000x1000.jpg`);
|
||||||
if (imageResponse.ok) {
|
if (imageResponse.ok) {
|
||||||
|
|||||||
@@ -154,6 +154,7 @@ const updateLatestSales = async (updatedCards: Set<number>) => {
|
|||||||
const start = Date.now();
|
const start = Date.now();
|
||||||
const updatedCards = await syncPrices();
|
const updatedCards = await syncPrices();
|
||||||
await helper.upsertSkuCollection(db);
|
await helper.upsertSkuCollection(db);
|
||||||
|
await helper.upsertCardCollection(db);
|
||||||
//console.log(updatedCards);
|
//console.log(updatedCards);
|
||||||
//console.log(updatedCards.size);
|
//console.log(updatedCards.size);
|
||||||
//await updateLatestSales(updatedCards);
|
//await updateLatestSales(updatedCards);
|
||||||
|
|||||||
@@ -278,40 +278,6 @@ $tiers: (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Inventory form condition buttons ──────────────────────────────────────
|
|
||||||
// Reuses $tiers map so colors stay in sync with nav tabs and price-row
|
|
||||||
|
|
||||||
$cond-text: (
|
|
||||||
nm: rgba(156, 204, 102, 1),
|
|
||||||
lp: rgba(211, 225, 86, 1),
|
|
||||||
mp: rgba(255, 238, 87, 1),
|
|
||||||
hp: rgba(255, 201, 41, 1),
|
|
||||||
dmg: rgba(255, 167, 36, 1),
|
|
||||||
);
|
|
||||||
|
|
||||||
@each $name, $color in $tiers {
|
|
||||||
@if map-has-key($cond-text, $name) {
|
|
||||||
.btn-check:checked + .btn-cond-#{$name} {
|
|
||||||
background-color: $color;
|
|
||||||
border-color: $color;
|
|
||||||
color: rgba(0, 0, 0, 0.94);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-cond-#{$name} {
|
|
||||||
border-color: rgba($color, 0.4);
|
|
||||||
color: var(--bs-body-color);
|
|
||||||
background: transparent;
|
|
||||||
font-weight: 600;
|
|
||||||
transition: background-color 0.1s, border-color 0.1s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-check:not(:checked) + .btn-cond-#{$name}:hover {
|
|
||||||
background-color: rgba($color, 0.67);
|
|
||||||
border-color: transparent;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --------------------------------------------------
|
/* --------------------------------------------------
|
||||||
Misc UI
|
Misc UI
|
||||||
-------------------------------------------------- */
|
-------------------------------------------------- */
|
||||||
@@ -412,30 +378,6 @@ $cond-text: (
|
|||||||
stroke: var(--bs-info-border-subtle);
|
stroke: var(--bs-info-border-subtle);
|
||||||
}
|
}
|
||||||
|
|
||||||
.delete-svg {
|
|
||||||
width: 1.25rem;
|
|
||||||
height: 1.25rem;
|
|
||||||
fill: var(--bs-danger);
|
|
||||||
stroke: var(--bs-danger);
|
|
||||||
}
|
|
||||||
|
|
||||||
.edit-svg {
|
|
||||||
width: 1.25rem;
|
|
||||||
height: 1.25rem;
|
|
||||||
fill: var(--bs-warning);
|
|
||||||
stroke: var(--bs-warning);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn:hover .delete-svg {
|
|
||||||
fill: var(--bs-danger-border-subtle);
|
|
||||||
stroke: var(--bs-danger-border-subtle);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn:hover .edit-svg {
|
|
||||||
fill: var(--bs-warning-border-subtle);
|
|
||||||
stroke: var(--bs-warning-border-subtle);
|
|
||||||
}
|
|
||||||
|
|
||||||
.shadow-filter {
|
.shadow-filter {
|
||||||
filter:
|
filter:
|
||||||
drop-shadow(0 5px 5px rgba(0, 0, 0, 0.3))
|
drop-shadow(0 5px 5px rgba(0, 0, 0, 0.3))
|
||||||
@@ -475,20 +417,21 @@ $cond-text: (
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
.inventory-button, .btn-vendor {
|
.inventory-button {
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
margin-bottom: -2rem;
|
||||||
|
margin-right: -0.25rem;
|
||||||
|
border-radius: 0.33rem;
|
||||||
background-color: hsl(262, 47%, 55%);
|
background-color: hsl(262, 47%, 55%);
|
||||||
color: #fff;
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
.inventory-button {
|
.inventory-label {
|
||||||
margin-bottom: -2.25rem;
|
width: 100%;
|
||||||
margin-right: -0.5rem;
|
height: 100%;
|
||||||
z-index: 2;
|
font-size: 1rem;
|
||||||
}
|
font-weight: 700;
|
||||||
|
|
||||||
.inventory-button:hover, .btn-vendor:hover {
|
|
||||||
background-color: hsl(262, 39%, 40%);
|
|
||||||
color: #fff;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.fs-7 {
|
.fs-7 {
|
||||||
|
|||||||
@@ -2,97 +2,51 @@ import * as bootstrap from 'bootstrap';
|
|||||||
window.bootstrap = bootstrap;
|
window.bootstrap = bootstrap;
|
||||||
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
|
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
// trap browser back and close the modal if open
|
||||||
|
const cardModal = document.getElementById('cardModal');
|
||||||
// Initialize all Bootstrap modals
|
const loadingMsg = cardModal.innerHTML;
|
||||||
document.querySelectorAll('.modal').forEach(modalEl => {
|
// Push a new history state when the modal is shown
|
||||||
bootstrap.Modal.getOrCreateInstance(modalEl);
|
cardModal.addEventListener('shown.bs.modal', () => {
|
||||||
|
history.pushState({ modalOpen: true }, null, '#cardModal');
|
||||||
|
});
|
||||||
|
// Listen for the browser's back button (popstate event)
|
||||||
|
window.addEventListener('popstate', (e) => {
|
||||||
|
if (cardModal.classList.contains('show')) {
|
||||||
|
const modalInstance = bootstrap.Modal.getInstance(cardModal);
|
||||||
|
if (modalInstance) {
|
||||||
|
modalInstance.hide();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Trigger a back navigation when the modal is closed via its native controls (X, backdrop click)
|
||||||
|
cardModal.addEventListener('hide.bs.modal', () => {
|
||||||
|
cardModal.innerHTML = loadingMsg;
|
||||||
|
if (history.state && history.state.modalOpen) {
|
||||||
|
history.back();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Initialize tooltips
|
|
||||||
|
import { Tooltip } from "bootstrap";
|
||||||
|
|
||||||
|
// Initialize all tooltips globally
|
||||||
|
const initTooltips = () => {
|
||||||
document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
|
document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
|
||||||
if (!el._tooltipInstance) {
|
if (!el._tooltipInstance) {
|
||||||
el._tooltipInstance = new bootstrap.Tooltip(el, { container: 'body' });
|
el._tooltipInstance = new Tooltip(el, {
|
||||||
|
container: 'body', // ensures tooltip is appended to body, important for modals
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// ---------------- DASHBOARD LOGIC ----------------
|
// Run on page load
|
||||||
const toggleBtn = document.getElementById("toggleViewBtn");
|
if (document.readyState === 'loading') {
|
||||||
const gridView = document.getElementById("gridView");
|
document.addEventListener('DOMContentLoaded', initTooltips);
|
||||||
const tableView = document.getElementById("tableView");
|
|
||||||
const searchInput = document.getElementById("inventorySearch");
|
|
||||||
const tbody = document.getElementById("inventoryRows");
|
|
||||||
|
|
||||||
if(toggleBtn && gridView && tableView && tbody) {
|
|
||||||
// TOGGLE GRID/TABLE
|
|
||||||
toggleBtn.addEventListener("click", () => {
|
|
||||||
if(gridView.style.display !== "none") {
|
|
||||||
gridView.style.display = "none";
|
|
||||||
tableView.style.display = "block";
|
|
||||||
toggleBtn.textContent = "Switch to Grid View";
|
|
||||||
} else {
|
} else {
|
||||||
gridView.style.display = "block";
|
initTooltips();
|
||||||
tableView.style.display = "none";
|
|
||||||
toggleBtn.textContent = "Switch to Table View";
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// SEARCH FILTER
|
|
||||||
if(searchInput) {
|
|
||||||
searchInput.addEventListener("input", e => {
|
|
||||||
const term = e.target.value.toLowerCase();
|
|
||||||
[...tbody.querySelectorAll("tr")].forEach(row => {
|
|
||||||
row.style.display = row.textContent.toLowerCase().includes(term) ? "" : "none";
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SORTING
|
// Optional: observe DOM changes for dynamically added tooltips (e.g., modals loaded later)
|
||||||
document.querySelectorAll("th[data-key]").forEach(th => {
|
const observer = new MutationObserver(() => initTooltips());
|
||||||
let sortAsc = true;
|
observer.observe(document.body, { childList: true, subtree: true });
|
||||||
th.addEventListener("click", () => {
|
|
||||||
const key = th.dataset.key;
|
|
||||||
const indexMap = {name:0,set:1,condition:2,qty:3,price:4,market:5,gain:6};
|
|
||||||
const idx = indexMap[key];
|
|
||||||
const rows = [...tbody.querySelectorAll("tr")];
|
|
||||||
|
|
||||||
rows.sort((a,b) => {
|
|
||||||
let aText = a.children[idx].textContent.replace(/\$|,/g,'').toLowerCase();
|
|
||||||
let bText = b.children[idx].textContent.replace(/\$|,/g,'').toLowerCase();
|
|
||||||
if(!isNaN(aText) && !isNaN(bText)) return sortAsc ? aText-bText : bText-aText;
|
|
||||||
return sortAsc ? aText.localeCompare(bText) : bText.localeCompare(aText);
|
|
||||||
});
|
|
||||||
|
|
||||||
sortAsc = !sortAsc;
|
|
||||||
tbody.innerHTML="";
|
|
||||||
rows.forEach(r => tbody.appendChild(r));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// INLINE EDITING + GAIN/LOSS UPDATE
|
|
||||||
tbody.addEventListener("input", e => {
|
|
||||||
const row = e.target.closest("tr");
|
|
||||||
if(!row) return;
|
|
||||||
|
|
||||||
const priceCell = row.querySelector(".editable-price");
|
|
||||||
const qtyCell = row.querySelector(".editable-qty");
|
|
||||||
const marketCell = row.children[5];
|
|
||||||
const gainCell = row.querySelector(".gain");
|
|
||||||
|
|
||||||
if(e.target.classList.contains("editable-price")) {
|
|
||||||
e.target.textContent = e.target.textContent.replace(/[^\d.]/g,"");
|
|
||||||
}
|
|
||||||
if(e.target.classList.contains("editable-qty")) {
|
|
||||||
e.target.textContent = e.target.textContent.replace(/\D/g,"");
|
|
||||||
}
|
|
||||||
|
|
||||||
const price = parseFloat(priceCell.textContent) || 0;
|
|
||||||
const qty = parseInt(qtyCell.textContent) || 0;
|
|
||||||
const market = parseFloat(marketCell.textContent) || 0;
|
|
||||||
const gain = market - price;
|
|
||||||
|
|
||||||
gainCell.textContent = (gain>=0 ? "+" : "-") + Math.abs(gain);
|
|
||||||
gainCell.className = gain>=0 ? "gain text-success" : "gain text-danger";
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -32,12 +32,6 @@ function setEmptyState(isEmpty) {
|
|||||||
canvasWrapper.classList.toggle('d-none', isEmpty);
|
canvasWrapper.classList.toggle('d-none', isEmpty);
|
||||||
}
|
}
|
||||||
|
|
||||||
function setChartVisible(visible) {
|
|
||||||
const modal = document.getElementById('cardModal');
|
|
||||||
const chartWrapper = modal?.querySelector('#priceHistoryChart')?.closest('.alert');
|
|
||||||
if (chartWrapper) chartWrapper.classList.toggle('d-none', !visible);
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildChartData(history, rangeKey) {
|
function buildChartData(history, rangeKey) {
|
||||||
const cutoff = RANGE_DAYS[rangeKey] === Infinity
|
const cutoff = RANGE_DAYS[rangeKey] === Infinity
|
||||||
? new Date(0)
|
? new Date(0)
|
||||||
@@ -45,14 +39,20 @@ function buildChartData(history, rangeKey) {
|
|||||||
|
|
||||||
const filtered = history.filter(r => new Date(r.calculatedAt) >= cutoff);
|
const filtered = history.filter(r => new Date(r.calculatedAt) >= cutoff);
|
||||||
|
|
||||||
|
// Always build the full date axis for the selected window, even if sparse.
|
||||||
|
// Generate one label per day in the range so the x-axis reflects the
|
||||||
|
// chosen period rather than collapsing to only the days that have data.
|
||||||
const dataDateSet = new Set(filtered.map(r => r.calculatedAt));
|
const dataDateSet = new Set(filtered.map(r => r.calculatedAt));
|
||||||
const allDates = [...dataDateSet].sort((a, b) => new Date(a) - new Date(b));
|
const allDates = [...dataDateSet].sort((a, b) => new Date(a) - new Date(b));
|
||||||
|
|
||||||
|
// If we have real data, expand the axis to span from cutoff → today so
|
||||||
|
// empty stretches at the start/end of a range are visible.
|
||||||
let axisLabels = allDates;
|
let axisLabels = allDates;
|
||||||
if (allDates.length > 0 && RANGE_DAYS[rangeKey] !== Infinity) {
|
if (allDates.length > 0 && RANGE_DAYS[rangeKey] !== Infinity) {
|
||||||
const start = new Date(cutoff);
|
const start = new Date(cutoff);
|
||||||
const end = new Date();
|
const end = new Date();
|
||||||
const expanded = [];
|
const expanded = [];
|
||||||
|
// Step through every day in the window
|
||||||
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
|
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
|
||||||
expanded.push(d.toISOString().split('T')[0]);
|
expanded.push(d.toISOString().split('T')[0]);
|
||||||
}
|
}
|
||||||
@@ -101,9 +101,17 @@ function buildChartData(history, rangeKey) {
|
|||||||
function updateChart() {
|
function updateChart() {
|
||||||
if (!chartInstance) return;
|
if (!chartInstance) return;
|
||||||
const { labels, datasets, hasData, activeConditionHasData } = buildChartData(allHistory, activeRange);
|
const { labels, datasets, hasData, activeConditionHasData } = buildChartData(allHistory, activeRange);
|
||||||
|
|
||||||
|
// Always push the new labels/datasets to the chart so the x-axis
|
||||||
|
// reflects the selected time window — even when there's no data for
|
||||||
|
// the active condition. Then toggle the empty state overlay on top.
|
||||||
chartInstance.data.labels = labels;
|
chartInstance.data.labels = labels;
|
||||||
chartInstance.data.datasets = datasets;
|
chartInstance.data.datasets = datasets;
|
||||||
chartInstance.update('none');
|
chartInstance.update('none');
|
||||||
|
|
||||||
|
// Show the empty state overlay if the active condition has no points
|
||||||
|
// in this window, but leave the (empty) chart visible underneath so
|
||||||
|
// the axis communicates the selected period.
|
||||||
setEmptyState(!hasData || !activeConditionHasData);
|
setEmptyState(!hasData || !activeConditionHasData);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,6 +135,7 @@ function initPriceChart(canvas) {
|
|||||||
|
|
||||||
const { labels, datasets, hasData, activeConditionHasData } = buildChartData(allHistory, activeRange);
|
const { labels, datasets, hasData, activeConditionHasData } = buildChartData(allHistory, activeRange);
|
||||||
|
|
||||||
|
// Render the chart regardless — show empty state overlay if needed
|
||||||
setEmptyState(!hasData || !activeConditionHasData);
|
setEmptyState(!hasData || !activeConditionHasData);
|
||||||
|
|
||||||
chartInstance = new Chart(canvas.getContext('2d'), {
|
chartInstance = new Chart(canvas.getContext('2d'), {
|
||||||
@@ -193,16 +202,9 @@ function initFromCanvas(canvas) {
|
|||||||
activeCondition = "Near Mint";
|
activeCondition = "Near Mint";
|
||||||
activeRange = '1m';
|
activeRange = '1m';
|
||||||
const modal = document.getElementById('cardModal');
|
const modal = document.getElementById('cardModal');
|
||||||
|
|
||||||
modal?.querySelectorAll('.price-range-btn').forEach(b => {
|
modal?.querySelectorAll('.price-range-btn').forEach(b => {
|
||||||
b.classList.toggle('active', b.dataset.range === '1m');
|
b.classList.toggle('active', b.dataset.range === '1m');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Hide chart if the vendor tab is already active when the modal opens
|
|
||||||
// (e.g. opened via the inventory button)
|
|
||||||
const activeTab = modal?.querySelector('.nav-link.active')?.getAttribute('data-bs-target');
|
|
||||||
setChartVisible(activeTab !== '#nav-vendor');
|
|
||||||
|
|
||||||
initPriceChart(canvas);
|
initPriceChart(canvas);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,10 +225,6 @@ function setup() {
|
|||||||
document.addEventListener('shown.bs.tab', (e) => {
|
document.addEventListener('shown.bs.tab', (e) => {
|
||||||
if (!modal.contains(e.target)) return;
|
if (!modal.contains(e.target)) return;
|
||||||
const target = e.target?.getAttribute('data-bs-target');
|
const target = e.target?.getAttribute('data-bs-target');
|
||||||
|
|
||||||
// Hide the chart when the vendor tab is active, show it for all others
|
|
||||||
setChartVisible(target !== '#nav-vendor');
|
|
||||||
|
|
||||||
const conditionMap = {
|
const conditionMap = {
|
||||||
'#nav-nm': 'Near Mint',
|
'#nav-nm': 'Near Mint',
|
||||||
'#nav-lp': 'Lightly Played',
|
'#nav-lp': 'Lightly Played',
|
||||||
|
|||||||
@@ -44,54 +44,15 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
|
|
||||||
<BackToTop />
|
<BackToTop />
|
||||||
|
|
||||||
|
<!-- <script src="src/assets/js/holofoil-init.js" is:inline></script> -->
|
||||||
|
|
||||||
<script is:inline>
|
<script is:inline>
|
||||||
(function () {
|
(function () {
|
||||||
|
|
||||||
function initInventoryForms(root = document) {
|
|
||||||
const forms = root.querySelectorAll('[data-inventory-form]');
|
|
||||||
|
|
||||||
forms.forEach((form) => {
|
|
||||||
if (form.dataset.inventoryBound === 'true') return;
|
|
||||||
form.dataset.inventoryBound = 'true';
|
|
||||||
|
|
||||||
const priceInput = form.querySelector('#purchasePrice');
|
|
||||||
const pricePrefix = form.querySelector('#pricePrefix');
|
|
||||||
const priceSuffix = form.querySelector('#priceSuffix');
|
|
||||||
const priceHint = form.querySelector('#priceHint');
|
|
||||||
const modeInputs = form.querySelectorAll('input[name="priceMode"]');
|
|
||||||
|
|
||||||
if (!priceInput || !pricePrefix || !priceSuffix || !priceHint || !modeInputs.length) return;
|
|
||||||
|
|
||||||
function updatePriceMode(mode) {
|
|
||||||
const isPct = mode === 'percent';
|
|
||||||
|
|
||||||
pricePrefix.classList.toggle('d-none', isPct);
|
|
||||||
priceSuffix.classList.toggle('d-none', !isPct);
|
|
||||||
|
|
||||||
priceInput.step = isPct ? '1' : '0.01';
|
|
||||||
priceInput.max = isPct ? '100' : '';
|
|
||||||
priceInput.placeholder = isPct ? '100' : '0.00';
|
|
||||||
priceInput.value = '';
|
|
||||||
priceHint.textContent = isPct
|
|
||||||
? 'Enter the percentage of market price you paid.'
|
|
||||||
: 'Enter the purchase price.';
|
|
||||||
|
|
||||||
// swap rounded edge classes based on visible prepend/append
|
|
||||||
priceInput.classList.toggle('rounded-end', !isPct);
|
|
||||||
priceInput.classList.toggle('rounded-start', isPct);
|
|
||||||
}
|
|
||||||
|
|
||||||
modeInputs.forEach((input) => {
|
|
||||||
input.addEventListener('change', () => updatePriceMode(input.value));
|
|
||||||
});
|
|
||||||
|
|
||||||
const checked = form.querySelector('input[name="priceMode"]:checked');
|
|
||||||
updatePriceMode(checked ? checked.value : 'dollar');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Sort dropdown ─────────────────────────────────────────────────────────
|
// ── Sort dropdown ─────────────────────────────────────────────────────────
|
||||||
document.addEventListener('click', (e) => {
|
document.addEventListener('click', (e) => {
|
||||||
|
const sortBy = document.getElementById('sortBy');
|
||||||
|
|
||||||
const btn = e.target.closest('#sortBy [data-bs-toggle="dropdown"]');
|
const btn = e.target.closest('#sortBy [data-bs-toggle="dropdown"]');
|
||||||
if (btn) {
|
if (btn) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -151,12 +112,16 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
|
|
||||||
// ── Global helpers ────────────────────────────────────────────────────────
|
// ── Global helpers ────────────────────────────────────────────────────────
|
||||||
window.copyImage = async function(img) {
|
window.copyImage = async function(img) {
|
||||||
|
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) ||
|
||||||
|
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const canvas = document.createElement("canvas");
|
const canvas = document.createElement("canvas");
|
||||||
const ctx = canvas.getContext("2d");
|
const ctx = canvas.getContext("2d");
|
||||||
canvas.width = img.naturalWidth;
|
canvas.width = img.naturalWidth;
|
||||||
canvas.height = img.naturalHeight;
|
canvas.height = img.naturalHeight;
|
||||||
|
|
||||||
|
// Load with crossOrigin so toBlob() stays untainted
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
const clean = new Image();
|
const clean = new Image();
|
||||||
clean.crossOrigin = 'anonymous';
|
clean.crossOrigin = 'anonymous';
|
||||||
@@ -165,10 +130,17 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
clean.src = img.src;
|
clean.src = img.src;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (navigator.clipboard && navigator.clipboard.write) {
|
|
||||||
const blob = await new Promise((resolve, reject) => {
|
const blob = await new Promise((resolve, reject) => {
|
||||||
canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/png');
|
canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/png');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (isIOS) {
|
||||||
|
const file = new File([blob], 'card.png', { type: 'image/png' });
|
||||||
|
await navigator.share({ files: [file] });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (navigator.clipboard && navigator.clipboard.write) {
|
||||||
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
|
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
|
||||||
showCopyToast('📋 Image copied!', '#198754');
|
showCopyToast('📋 Image copied!', '#198754');
|
||||||
} else {
|
} else {
|
||||||
@@ -187,6 +159,7 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (err.name === 'AbortError') return;
|
||||||
console.error('Failed:', err);
|
console.error('Failed:', err);
|
||||||
showCopyToast('❌ Copy failed', '#dc3545');
|
showCopyToast('❌ Copy failed', '#dc3545');
|
||||||
}
|
}
|
||||||
@@ -210,20 +183,6 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
}, 2000);
|
}, 2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Tab switching helper ──────────────────────────────────────────────────
|
|
||||||
function switchToRequestedTab() {
|
|
||||||
const tab = sessionStorage.getItem('openModalTab');
|
|
||||||
if (!tab) return;
|
|
||||||
sessionStorage.removeItem('openModalTab');
|
|
||||||
requestAnimationFrame(() => {
|
|
||||||
try {
|
|
||||||
const tabEl = document.querySelector(`#cardModal [data-bs-target="#${tab}"]`);
|
|
||||||
if (tabEl) bootstrap.Tab.getOrCreateInstance(tabEl).show();
|
|
||||||
} catch (e) {
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── State ─────────────────────────────────────────────────────────────────
|
// ── State ─────────────────────────────────────────────────────────────────
|
||||||
const cardIndex = [];
|
const cardIndex = [];
|
||||||
let currentCardId = null;
|
let currentCardId = null;
|
||||||
@@ -311,17 +270,10 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
|
|
||||||
if (modal._reconnectChartObserver) modal._reconnectChartObserver();
|
if (modal._reconnectChartObserver) modal._reconnectChartObserver();
|
||||||
|
|
||||||
modal.querySelectorAll('[data-bs-toggle="tab"]').forEach(el => {
|
|
||||||
bootstrap.Tab.getInstance(el)?.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
modal.innerHTML = html;
|
modal.innerHTML = html;
|
||||||
|
|
||||||
if (typeof htmx !== 'undefined') htmx.process(modal);
|
if (typeof htmx !== 'undefined') htmx.process(modal);
|
||||||
initInventoryForms(modal);
|
|
||||||
updateNavButtons(modal);
|
updateNavButtons(modal);
|
||||||
initChartAfterSwap(modal);
|
initChartAfterSwap(modal);
|
||||||
switchToRequestedTab();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (document.startViewTransition && direction) {
|
if (document.startViewTransition && direction) {
|
||||||
@@ -406,14 +358,8 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
|
|
||||||
if (target._reconnectChartObserver) target._reconnectChartObserver();
|
if (target._reconnectChartObserver) target._reconnectChartObserver();
|
||||||
|
|
||||||
target.querySelectorAll('[data-bs-toggle="tab"]').forEach(el => {
|
|
||||||
bootstrap.Tab.getInstance(el)?.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
target.innerHTML = html;
|
target.innerHTML = html;
|
||||||
|
|
||||||
if (typeof htmx !== 'undefined') htmx.process(target);
|
if (typeof htmx !== 'undefined') htmx.process(target);
|
||||||
initInventoryForms(target);
|
|
||||||
|
|
||||||
const destImg = target.querySelector('img.card-image');
|
const destImg = target.querySelector('img.card-image');
|
||||||
if (destImg) {
|
if (destImg) {
|
||||||
@@ -430,7 +376,6 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
await transition.finished;
|
await transition.finished;
|
||||||
updateNavButtons(target);
|
updateNavButtons(target);
|
||||||
initChartAfterSwap(target);
|
initChartAfterSwap(target);
|
||||||
switchToRequestedTab();
|
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[card-modal] transition failed:', err);
|
console.error('[card-modal] transition failed:', err);
|
||||||
@@ -449,17 +394,15 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
cardModal.addEventListener('shown.bs.modal', () => {
|
cardModal.addEventListener('shown.bs.modal', () => {
|
||||||
updateNavButtons(cardModal);
|
updateNavButtons(cardModal);
|
||||||
initChartAfterSwap(cardModal);
|
initChartAfterSwap(cardModal);
|
||||||
initInventoryForms(cardModal);
|
|
||||||
switchToRequestedTab();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
cardModal.addEventListener('hidden.bs.modal', () => {
|
cardModal.addEventListener('hidden.bs.modal', () => {
|
||||||
currentCardId = null;
|
currentCardId = null;
|
||||||
updateNavButtons(null);
|
updateNavButtons(null);
|
||||||
});
|
});
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
// ── AdSense re-init on infinite scroll ───────────────────────────────────
|
||||||
initInventoryForms();
|
document.addEventListener('htmx:afterSwap', () => {
|
||||||
|
(window.adsbygoogle = window.adsbygoogle || []).push({});
|
||||||
});
|
});
|
||||||
|
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
---
|
|
||||||
const mockInventory = [
|
|
||||||
{ name: "Charizard", set: "Base Set", condition: "NM", qty: 2, price: 350, market: 400, gain: 50 },
|
|
||||||
{ name: "Pikachu", set: "Shining Legends", condition: "LP", qty: 5, price: 15, market: 20, gain: 5 },
|
|
||||||
];
|
|
||||||
---
|
|
||||||
|
|
||||||
<div class="table-responsive">
|
|
||||||
<table class="table table-dark table-striped table-hover align-middle">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Card</th>
|
|
||||||
<th>Set</th>
|
|
||||||
<th>Condition</th>
|
|
||||||
<th>Qty</th>
|
|
||||||
<th>Price</th>
|
|
||||||
<th>Market</th>
|
|
||||||
<th>Gain/Loss</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{mockInventory.map(card => (
|
|
||||||
<tr>
|
|
||||||
<td>{card.name}</td>
|
|
||||||
<td>{card.set}</td>
|
|
||||||
<td>{card.condition}</td>
|
|
||||||
<td>{card.qty}</td>
|
|
||||||
<td>${card.price}</td>
|
|
||||||
<td>${card.market}</td>
|
|
||||||
<td class={card.gain >= 0 ? "text-success" : "text-danger"}>
|
|
||||||
{card.gain >= 0 ? "+" : "-"}${Math.abs(card.gain)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
7
src/components/LeftSidebarDesktop.astro
Normal file
7
src/components/LeftSidebarDesktop.astro
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<div class="d-none d-xl-block sticky-top mt-5" style="top: 70px;">
|
||||||
|
<ins class="adsbygoogle"
|
||||||
|
style="display:block"
|
||||||
|
data-ad-format="autorelaxed"
|
||||||
|
data-ad-client="ca-pub-1140571217687341"
|
||||||
|
data-ad-slot="8889263515"></ins>
|
||||||
|
</div>
|
||||||
@@ -16,6 +16,7 @@ const { title } = Astro.props;
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="htmx-config" content='{"historyCacheSize": 50}'/>
|
<meta name="htmx-config" content='{"historyCacheSize": 50}'/>
|
||||||
|
<meta name="google-adsense-account" content="ca-pub-1140571217687341">
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<link rel="icon" href="/favicon.ico" />
|
<link rel="icon" href="/favicon.ico" />
|
||||||
<title>{title}</title>
|
<title>{title}</title>
|
||||||
|
|||||||
@@ -1,17 +1,45 @@
|
|||||||
// src/middleware.ts
|
import { clerkMiddleware, createRouteMatcher, clerkClient } from '@clerk/astro/server';
|
||||||
import { clerkMiddleware, createRouteMatcher } from '@clerk/astro/server';
|
|
||||||
import type { AstroMiddlewareRequest, AstroMiddlewareResponse } from 'astro';
|
|
||||||
|
|
||||||
const isProtectedRoute = createRouteMatcher([
|
const isProtectedRoute = createRouteMatcher(['/pokemon']);
|
||||||
'/pokemon',
|
const isAdminRoute = createRouteMatcher(['/admin']);
|
||||||
]);
|
|
||||||
|
|
||||||
export const onRequest = clerkMiddleware((auth, context) => {
|
const TARGET_ORG_ID = "org_3Baav9czkRLLlC7g89oJWqRRulK";
|
||||||
const { isAuthenticated, redirectToSignIn } = auth()
|
|
||||||
|
export const onRequest = clerkMiddleware(async (auth, context) => {
|
||||||
|
const { isAuthenticated, userId, redirectToSignIn } = auth();
|
||||||
|
|
||||||
if (!isAuthenticated && isProtectedRoute(context.request)) {
|
if (!isAuthenticated && isProtectedRoute(context.request)) {
|
||||||
// Add custom logic to run before redirecting
|
return redirectToSignIn();
|
||||||
|
}
|
||||||
|
|
||||||
return redirectToSignIn()
|
if (isAdminRoute(context.request)) {
|
||||||
|
if (!isAuthenticated || !userId) {
|
||||||
|
return redirectToSignIn();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = await clerkClient(context); // pass context here
|
||||||
|
const memberships = await client.organizations.getOrganizationMembershipList({
|
||||||
|
organizationId: TARGET_ORG_ID,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("Total memberships found:", memberships.data.length);
|
||||||
|
console.log("Current userId:", userId);
|
||||||
|
console.log("Memberships:", JSON.stringify(memberships.data.map(m => ({
|
||||||
|
userId: m.publicUserData?.userId,
|
||||||
|
role: m.role,
|
||||||
|
})), null, 2));
|
||||||
|
|
||||||
|
const userMembership = memberships.data.find(
|
||||||
|
(m) => m.publicUserData?.userId === userId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!userMembership || userMembership.role !== "org:admin") {
|
||||||
|
return context.redirect("/");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Clerk membership check failed:", e);
|
||||||
|
return context.redirect("/");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
18
src/pages/admin.astro
Normal file
18
src/pages/admin.astro
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
export const prerender = false;
|
||||||
|
import Layout from '../layouts/Main.astro';
|
||||||
|
import NavItems from '../components/NavItems.astro';
|
||||||
|
import NavBar from '../components/NavBar.astro';
|
||||||
|
import Footer from '../components/Footer.astro';
|
||||||
|
---
|
||||||
|
<Layout title="Admin Panel">
|
||||||
|
<NavBar slot="navbar">
|
||||||
|
<NavItems slot="navItems" />
|
||||||
|
</NavBar>
|
||||||
|
<div class="row mb-4" slot="page">
|
||||||
|
<div class="col-12">
|
||||||
|
<h1>Admin Panel</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Footer slot="footer" />
|
||||||
|
</Layout>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ import Layout from '../layouts/Main.astro';
|
|||||||
import NavItems from '../components/NavItems.astro';
|
import NavItems from '../components/NavItems.astro';
|
||||||
import NavBar from '../components/NavBar.astro';
|
import NavBar from '../components/NavBar.astro';
|
||||||
import Footer from '../components/Footer.astro';
|
import Footer from '../components/Footer.astro';
|
||||||
import { Show, SignInButton, SignUpButton, SignOutButton } from '@clerk/astro/components'
|
import { Show, SignInButton, SignUpButton, SignOutButton, GoogleOneTap, UserAvatar, UserButton, UserProfile } from '@clerk/astro/components'
|
||||||
---
|
---
|
||||||
<Layout title="Rigid's App Thing">
|
<Layout title="Rigid's App Thing">
|
||||||
<NavBar slot="navbar">
|
<NavBar slot="navbar">
|
||||||
@@ -16,31 +16,41 @@ import { Show, SignInButton, SignUpButton, SignOutButton } from '@clerk/astro/co
|
|||||||
<p class="text-secondary">(working title)</p>
|
<p class="text-secondary">(working title)</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-12 col-md-6 mb-2">
|
<div class="col-12 col-md-6 mb-2">
|
||||||
<h2 class="mt-3">Welcome!</h2>
|
<h2 class="mt-3">The Pokémon card tracker you actually want.</h2>
|
||||||
<p class="mt-2">
|
<p class="mt-2">
|
||||||
You've been selected to participate in the closed beta! This single page web application is meant to elevate condition/variant data for the Pokemon TCG. In future iterations, we will add vendor inventory/collection management features, as well.
|
Browse real market prices and condition data across 70,000+ cards! No more
|
||||||
|
juggling multiple tabs or guessing what your cards are worth.
|
||||||
</p>
|
</p>
|
||||||
<p class="my-2">
|
<p class="my-2">
|
||||||
After the closed beta is complete, the app will move into a more open beta. Feel free to play "Who's that Pokémon?" with the random Pokémon generator <a href="/404">here</a>. Refresh the page to see a new Pokémon!
|
We're now open to everyone. Create a free account to get started —
|
||||||
|
collection and inventory management tools are coming soon as part of a
|
||||||
|
premium plan.
|
||||||
</p>
|
</p>
|
||||||
<Show when="signed-in">
|
<Show when="signed-in">
|
||||||
<a href="/pokemon" class="btn btn-warning mt-2">Take me to the cards</a>
|
<a href="/pokemon" class="btn btn-warning mt-2">Take me to the cards!</a>
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-12 col-md-6 d-flex justify-content-end align-items-start mt-3">
|
<div class="col-12 col-md-6 d-flex justify-content-end align-items-start mt-3">
|
||||||
<div class="d-flex gap-3">
|
<div class="d-flex gap-3 mx-auto">
|
||||||
<Show when="signed-out">
|
<Show when="signed-out">
|
||||||
<SignInButton asChild mode="modal">
|
<div class="card border p-5 w-100">
|
||||||
<button class="btn btn-success">Sign In</button>
|
|
||||||
</SignInButton>
|
|
||||||
<SignUpButton asChild mode="modal">
|
<SignUpButton asChild mode="modal">
|
||||||
<button class="btn btn-dark">Request Access</button>
|
<button class="btn btn-success w-100 mb-2">Create free account</button>
|
||||||
</SignUpButton>
|
</SignUpButton>
|
||||||
|
<SignInButton asChild mode="modal">
|
||||||
|
<p class="text-center text-secondary my-2">Already have an account?</p>
|
||||||
|
<button class="btn btn-outline-light w-100">Sign in</button>
|
||||||
|
</SignInButton>
|
||||||
|
<p class="text-center h6 text-light mt-2 mb-0">Free to join!</p>
|
||||||
|
</div>
|
||||||
|
<GoogleOneTap />
|
||||||
</Show>
|
</Show>
|
||||||
<Show when="signed-in">
|
<Show when="signed-in">
|
||||||
|
<div class="w-100">
|
||||||
<SignOutButton asChild>
|
<SignOutButton asChild>
|
||||||
<button class="btn btn-danger">Sign Out</button>
|
<button class="btn btn-danger mt-2 ms-auto float-end">Sign Out</button>
|
||||||
</SignOutButton>
|
</SignOutButton>
|
||||||
|
</div>
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -51,9 +51,36 @@ const calculatedAt = (() => {
|
|||||||
return new Date(Math.max(...dates.map(d => d.getTime())));
|
return new Date(Math.max(...dates.map(d => d.getTime())));
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// ── Fetch price history + compute volatility ──────────────────────────────
|
// ── Spread-based volatility (high - low) / low ────────────────────────────
|
||||||
|
// Log-return volatility was unreliable because marketPrice is a smoothed daily
|
||||||
|
// value, not transaction-driven. The 30-day high/low spread is a more honest
|
||||||
|
// proxy for price movement over the period.
|
||||||
|
|
||||||
|
const volatilityByCondition: Record<string, { label: string; spread: number }> = {};
|
||||||
|
|
||||||
|
for (const price of card?.prices ?? []) {
|
||||||
|
const condition = price.condition;
|
||||||
|
const low = Number(price.lowestPrice);
|
||||||
|
const high = Number(price.highestPrice);
|
||||||
|
const market = Number(price.marketPrice);
|
||||||
|
|
||||||
|
if (!low || !high || !market || market <= 0) {
|
||||||
|
volatilityByCondition[condition] = { label: '—', spread: 0 };
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const spread = (high - low) / market;
|
||||||
|
|
||||||
|
const label = spread >= 0.50 ? 'High'
|
||||||
|
: spread >= 0.25 ? 'Medium'
|
||||||
|
: 'Low';
|
||||||
|
|
||||||
|
volatilityByCondition[condition] = { label, spread: Math.round(spread * 100) / 100 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Price history for chart ───────────────────────────────────────────────
|
||||||
const cardSkus = card?.prices?.length
|
const cardSkus = card?.prices?.length
|
||||||
? await db.select().from(skus).where(eq(skus.cardId, cardId))
|
? await db.select().from(skus).where(eq(skus.productId, card.productId))
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
const skuIds = cardSkus.map(s => s.skuId);
|
const skuIds = cardSkus.map(s => s.skuId);
|
||||||
@@ -72,41 +99,6 @@ const historyRows = skuIds.length
|
|||||||
.orderBy(priceHistory.calculatedAt)
|
.orderBy(priceHistory.calculatedAt)
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
// Rolling 30-day cutoff for volatility calculation
|
|
||||||
const thirtyDaysAgo = new Date(Date.now() - 30 * 86_400_000);
|
|
||||||
|
|
||||||
const byCondition: Record<string, number[]> = {};
|
|
||||||
for (const row of historyRows) {
|
|
||||||
if (row.marketPrice == null) continue;
|
|
||||||
if (!row.calculatedAt) continue;
|
|
||||||
if (new Date(row.calculatedAt) < thirtyDaysAgo) continue;
|
|
||||||
const price = Number(row.marketPrice);
|
|
||||||
if (price <= 0) continue;
|
|
||||||
if (!byCondition[row.condition]) byCondition[row.condition] = [];
|
|
||||||
byCondition[row.condition].push(price);
|
|
||||||
}
|
|
||||||
|
|
||||||
function computeVolatility(prices: number[]): { label: string; monthlyVol: number } {
|
|
||||||
if (prices.length < 2) return { label: '—', monthlyVol: 0 };
|
|
||||||
const returns: number[] = [];
|
|
||||||
for (let i = 1; i < prices.length; i++) {
|
|
||||||
returns.push(Math.log(prices[i] / prices[i - 1]));
|
|
||||||
}
|
|
||||||
const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
|
|
||||||
const variance = returns.reduce((sum, r) => sum + (r - mean) ** 2, 0) / (returns.length - 1);
|
|
||||||
const monthlyVol = Math.sqrt(variance) * Math.sqrt(30);
|
|
||||||
const label = monthlyVol >= 0.30 ? 'High'
|
|
||||||
: monthlyVol >= 0.15 ? 'Medium'
|
|
||||||
: 'Low';
|
|
||||||
return { label, monthlyVol: Math.round(monthlyVol * 100) / 100 };
|
|
||||||
}
|
|
||||||
|
|
||||||
const volatilityByCondition: Record<string, { label: string; monthlyVol: number }> = {};
|
|
||||||
for (const [condition, prices] of Object.entries(byCondition)) {
|
|
||||||
volatilityByCondition[condition] = computeVolatility(prices);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Price history for chart (full history, not windowed) ──────────────────
|
|
||||||
const priceHistoryForChart = historyRows.map(row => ({
|
const priceHistoryForChart = historyRows.map(row => ({
|
||||||
condition: row.condition,
|
condition: row.condition,
|
||||||
calculatedAt: row.calculatedAt
|
calculatedAt: row.calculatedAt
|
||||||
@@ -115,29 +107,11 @@ const priceHistoryForChart = historyRows.map(row => ({
|
|||||||
marketPrice: row.marketPrice,
|
marketPrice: row.marketPrice,
|
||||||
})).filter(r => r.calculatedAt !== null);
|
})).filter(r => r.calculatedAt !== null);
|
||||||
|
|
||||||
// ── Determine which range buttons to show ────────────────────────────────
|
|
||||||
const now = Date.now();
|
|
||||||
const oldestDate = historyRows.length
|
|
||||||
? Math.min(...historyRows
|
|
||||||
.filter(r => r.calculatedAt)
|
|
||||||
.map(r => new Date(r.calculatedAt!).getTime()))
|
|
||||||
: now;
|
|
||||||
|
|
||||||
const dataSpanDays = (now - oldestDate) / 86_400_000;
|
|
||||||
|
|
||||||
const showRanges = {
|
|
||||||
'1m': dataSpanDays >= 1,
|
|
||||||
'3m': dataSpanDays >= 60,
|
|
||||||
'6m': dataSpanDays >= 180,
|
|
||||||
'1y': dataSpanDays >= 365,
|
|
||||||
'all': dataSpanDays >= 400,
|
|
||||||
};
|
|
||||||
|
|
||||||
const conditionOrder = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
const conditionOrder = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
||||||
|
|
||||||
const conditionAttributes = (price: any) => {
|
const conditionAttributes = (price: any) => {
|
||||||
const condition: string = price?.condition || "Near Mint";
|
const condition: string = price?.condition || "Near Mint";
|
||||||
const vol = volatilityByCondition[condition] ?? { label: '—', monthlyVol: 0 };
|
const vol = volatilityByCondition[condition] ?? { label: '—', spread: 0 };
|
||||||
|
|
||||||
const volatilityClass = (() => {
|
const volatilityClass = (() => {
|
||||||
switch (vol.label) {
|
switch (vol.label) {
|
||||||
@@ -150,7 +124,7 @@ const conditionAttributes = (price: any) => {
|
|||||||
|
|
||||||
const volatilityDisplay = vol.label === '—'
|
const volatilityDisplay = vol.label === '—'
|
||||||
? '—'
|
? '—'
|
||||||
: `${vol.label} (${(vol.monthlyVol * 100).toFixed(0)}%)`;
|
: `${vol.label} (${(vol.spread * 100).toFixed(0)}%)`;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"Near Mint": { label: "nav-nm", volatility: volatilityDisplay, volatilityClass, class: "show active" },
|
"Near Mint": { label: "nav-nm", volatility: volatilityDisplay, volatilityClass, class: "show active" },
|
||||||
@@ -190,9 +164,6 @@ const altSearchUrl = (card: any) => {
|
|||||||
<!-- Card image column -->
|
<!-- Card image column -->
|
||||||
<div class="col-sm-12 col-md-3">
|
<div class="col-sm-12 col-md-3">
|
||||||
<div class="position-relative mt-1">
|
<div class="position-relative mt-1">
|
||||||
|
|
||||||
<!-- card-image-wrap gives the modal image shimmer effects
|
|
||||||
without the hover lift/scale that image-grow has in main.scss -->
|
|
||||||
<div
|
<div
|
||||||
class="card-image-wrap rounded-4"
|
class="card-image-wrap rounded-4"
|
||||||
data-energy={card?.energyType}
|
data-energy={card?.energyType}
|
||||||
@@ -226,31 +197,31 @@ const altSearchUrl = (card: any) => {
|
|||||||
<ul class="nav nav-tabs nav-fill border-0 me-3 mb-2" id="myTab" role="tablist">
|
<ul class="nav nav-tabs nav-fill border-0 me-3 mb-2" id="myTab" role="tablist">
|
||||||
<li class="nav-item" role="presentation">
|
<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">
|
<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">Near Mint</span><span class="d-inline">NM</span>
|
<span class="d-none d-xxl-inline">Near Mint</span><span class="d-xxl-none">NM</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<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">
|
<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">Lightly Played</span><span class="d-inline">LP</span>
|
<span class="d-none d-xxl-inline">Lightly Played</span><span class="d-xxl-none">LP</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<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">
|
<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">Moderately Played</span><span class="d-inline">MP</span>
|
<span class="d-none d-xxl-inline">Moderately Played</span><span class="d-xxl-none">MP</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<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">
|
<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">Heavily Played</span><span class="d-inline">HP</span>
|
<span class="d-none d-xxl-inline">Heavily Played</span><span class="d-xxl-none">HP</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<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">
|
<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">Damaged</span><span class="d-inline">DMG</span>
|
<span class="d-none d-xxl-inline">Damaged</span><span class="d-xxl-none">DMG</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link vendor" id="vendor-tab" data-bs-toggle="tab" data-bs-target="#nav-vendor" type="button" role="tab" aria-controls="nav-vendor" aria-selected="false">
|
<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-xxl-inline">Inventory</span><span class="d-xxl-none">+/-</span>
|
<span class="d-none d-xxl-inline">Inventory</span><span class="d-xxl-none">+/-</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
@@ -270,11 +241,11 @@ const altSearchUrl = (card: any) => {
|
|||||||
<p class="mb-0 mt-1">${price.marketPrice}</p>
|
<p class="mb-0 mt-1">${price.marketPrice}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
|
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
|
||||||
<h6 class="mb-auto">Lowest Price</h6>
|
<h6 class="mb-auto">Low Price <span class="small p text-secondary">(30 day)</span></h6>
|
||||||
<p class="mb-0 mt-1">${price.lowestPrice}</p>
|
<p class="mb-0 mt-1">${price.lowestPrice}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
|
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
|
||||||
<h6 class="mb-auto">Highest Price</h6>
|
<h6 class="mb-auto">High Price <span class="small p text-secondary">(30 day)</span></h6>
|
||||||
<p class="mb-0 mt-1">${price.highestPrice}</p>
|
<p class="mb-0 mt-1">${price.highestPrice}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class={`alert rounded p-2 flex-fill d-flex flex-column mb-0 ${attributes?.volatilityClass}`}>
|
<div class={`alert rounded p-2 flex-fill d-flex flex-column mb-0 ${attributes?.volatilityClass}`}>
|
||||||
@@ -289,14 +260,14 @@ const altSearchUrl = (card: any) => {
|
|||||||
data-bs-trigger="hover focus click"
|
data-bs-trigger="hover focus click"
|
||||||
data-bs-html="true"
|
data-bs-html="true"
|
||||||
data-bs-title={`
|
data-bs-title={`
|
||||||
<div class='tooltip-heading fw-bold mb-1'>Monthly Volatility</div>
|
<div class='tooltip-heading fw-bold mb-1'>30-Day Price Spread</div>
|
||||||
<div class='small'>
|
<div class='small'>
|
||||||
<p class="mb-1">
|
<p class="mb-1">
|
||||||
<strong>What this measures:</strong> how much the market price tends to move day-to-day,
|
<strong>What this measures:</strong> how wide the gap between the 30-day low and high is,
|
||||||
scaled up to a monthly expectation.
|
relative to the market price.
|
||||||
</p>
|
</p>
|
||||||
<p class="mb-0">
|
<p class="mb-0">
|
||||||
A card with <strong>30% volatility</strong> typically swings ±30% over a month.
|
A card with <strong>50%+ spread</strong> has seen significant price swings over the past month.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
`}
|
`}
|
||||||
@@ -310,7 +281,7 @@ const altSearchUrl = (card: any) => {
|
|||||||
|
|
||||||
<!-- Table only — chart is outside the tab panes -->
|
<!-- Table only — chart is outside the tab panes -->
|
||||||
<div class="w-100">
|
<div class="w-100">
|
||||||
<div class="alert alert-dark rounded p-2 mb-0 table-responsive">
|
<div class="alert alert-dark rounded p-2 mb-0 table-responsive d-none">
|
||||||
<h6>Latest Verified Sales</h6>
|
<h6>Latest Verified Sales</h6>
|
||||||
<table class="table table-sm mb-0">
|
<table class="table table-sm mb-0">
|
||||||
<caption class="small">Filtered to remove mismatched language variants</caption>
|
<caption class="small">Filtered to remove mismatched language variants</caption>
|
||||||
@@ -337,267 +308,7 @@ const altSearchUrl = (card: any) => {
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
<div class="tab-pane fade" id="nav-vendor" role="tabpanel" aria-labelledby="nav-vendor" tabindex="0">
|
<div class="tab-pane fade" id="nav-vendor" role="tabpanel" aria-labelledby="nav-vendor" tabindex="0"></div>
|
||||||
<div class="row g-3">
|
|
||||||
<div class="col-12 col-md-6">
|
|
||||||
<h5 class="my-3">Add {card?.productName} to inventory</h5>
|
|
||||||
|
|
||||||
<form id="inventoryForm" data-inventory-form novalidate>
|
|
||||||
<div class="row g-3">
|
|
||||||
<div class="col-4">
|
|
||||||
<label for="quantity" class="form-label fw-medium">Quantity</label>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
class="form-control mt-1"
|
|
||||||
id="quantity"
|
|
||||||
name="quantity"
|
|
||||||
min="1"
|
|
||||||
step="1"
|
|
||||||
value="1"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<div class="invalid-feedback">Required.</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="col-8">
|
|
||||||
<div class="d-flex justify-content-between align-items-start gap-2 flex-wrap">
|
|
||||||
<label for="purchasePrice" class="form-label fw-medium mb-0 mt-1">
|
|
||||||
Purchase price
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<div class="btn-group btn-group-sm price-toggle" role="group" aria-label="Price mode">
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
class="btn-check"
|
|
||||||
name="priceMode"
|
|
||||||
id="mode-dollar"
|
|
||||||
value="dollar"
|
|
||||||
autocomplete="off"
|
|
||||||
checked
|
|
||||||
/>
|
|
||||||
<label class="btn btn-outline-secondary" for="mode-dollar">$</label>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
class="btn-check"
|
|
||||||
name="priceMode"
|
|
||||||
id="mode-percent"
|
|
||||||
value="percent"
|
|
||||||
autocomplete="off"
|
|
||||||
/>
|
|
||||||
<label class="btn btn-outline-secondary" for="mode-percent">%</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="input-group">
|
|
||||||
<span class="input-group-text mt-1" id="pricePrefix">$</span>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
class="form-control mt-1 rounded-end"
|
|
||||||
id="purchasePrice"
|
|
||||||
name="purchasePrice"
|
|
||||||
min="0"
|
|
||||||
step="0.01"
|
|
||||||
placeholder="0.00"
|
|
||||||
aria-describedby="pricePrefix priceSuffix priceHint"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<span class="input-group-text d-none mt-1" id="priceSuffix">%</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-text" id="priceHint">Enter the purchase price.</div>
|
|
||||||
<div class="invalid-feedback">Enter a purchase price.</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="col-12">
|
|
||||||
<label class="form-label fw-medium">Condition</label>
|
|
||||||
<div class="btn-group condition-input w-100" role="group" aria-label="Condition">
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
class="btn-check"
|
|
||||||
name="condition"
|
|
||||||
id="cond-nm"
|
|
||||||
value="Near Mint"
|
|
||||||
autocomplete="off"
|
|
||||||
checked
|
|
||||||
/>
|
|
||||||
<label class="btn btn-cond-nm" for="cond-nm">NM</label>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
class="btn-check"
|
|
||||||
name="condition"
|
|
||||||
id="cond-lp"
|
|
||||||
value="Lightly Played"
|
|
||||||
autocomplete="off"
|
|
||||||
/>
|
|
||||||
<label class="btn btn-cond-lp" for="cond-lp">LP</label>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
class="btn-check"
|
|
||||||
name="condition"
|
|
||||||
id="cond-mp"
|
|
||||||
value="Moderately Played"
|
|
||||||
autocomplete="off"
|
|
||||||
/>
|
|
||||||
<label class="btn btn-cond-mp" for="cond-mp">MP</label>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
class="btn-check"
|
|
||||||
name="condition"
|
|
||||||
id="cond-hp"
|
|
||||||
value="Heavily Played"
|
|
||||||
autocomplete="off"
|
|
||||||
/>
|
|
||||||
<label class="btn btn-cond-hp" for="cond-hp">HP</label>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
class="btn-check"
|
|
||||||
name="condition"
|
|
||||||
id="cond-dmg"
|
|
||||||
value="Damaged"
|
|
||||||
autocomplete="off"
|
|
||||||
/>
|
|
||||||
<label class="btn btn-cond-dmg" for="cond-dmg">DMG</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="col-12">
|
|
||||||
<label for="note" class="form-label fw-medium">
|
|
||||||
Note
|
|
||||||
<span class="text-body-tertiary fw-normal ms-1 small">optional</span>
|
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
class="form-control"
|
|
||||||
id="note"
|
|
||||||
name="note"
|
|
||||||
rows="2"
|
|
||||||
maxlength="255"
|
|
||||||
placeholder="e.g. bought at local shop, gift, graded copy…"
|
|
||||||
></textarea>
|
|
||||||
<div class="form-text text-end" id="noteCount">0 / 255</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="col-12 d-flex gap-3 pt-2">
|
|
||||||
<button type="reset" class="btn btn-outline-danger flex-fill">Reset</button>
|
|
||||||
<button type="submit" class="btn btn-success flex-fill">Save to inventory</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="col-12 col-md-6">
|
|
||||||
<h5 class="my-3">Inventory entries for {card?.productName}</h5>
|
|
||||||
|
|
||||||
<!-- Empty state -->
|
|
||||||
<div class="alert alert-dark border-0 rounded-4 d-none" id="inventoryEmptyState">
|
|
||||||
<div class="fw-medium mb-1">No inventory entries yet</div>
|
|
||||||
<div class="text-secondary small">
|
|
||||||
Once you add copies of this card, they’ll show up here.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Inventory list -->
|
|
||||||
<div class="d-flex flex-column gap-3" id="inventoryEntryList">
|
|
||||||
|
|
||||||
<!-- Inventory card -->
|
|
||||||
<article class="border rounded-4 p-2 bg-body-tertiary inventory-entry-card">
|
|
||||||
<div class="d-flex flex-column gap-2">
|
|
||||||
|
|
||||||
<!-- Top row -->
|
|
||||||
<div class="d-flex justify-content-between align-items-start gap-3">
|
|
||||||
<div class="min-w-0 flex-grow-1">
|
|
||||||
<div class="fw-semibold fs-5 text-body mb-1">Near Mint</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Middle row -->
|
|
||||||
<div class="row g-2">
|
|
||||||
<div class="col-4">
|
|
||||||
<div class="small text-secondary">Purchase price</div>
|
|
||||||
<div class="fs-5 fw-semibold">$8.50</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-4">
|
|
||||||
<div class="small text-secondary">Market price</div>
|
|
||||||
<div class="fs-5 text-success">$10.25</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-4">
|
|
||||||
<div class="small text-secondary">Gain / loss</div>
|
|
||||||
<div class="fs-5 fw-semibold text-success">+$1.75</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Bottom row -->
|
|
||||||
<div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
|
|
||||||
<div class="d-flex align-items-center gap-2">
|
|
||||||
<span class="small text-secondary">Qty</span>
|
|
||||||
|
|
||||||
<div class="btn-group" role="group" aria-label="Quantity controls">
|
|
||||||
<button type="button" class="btn btn-outline-secondary btn-sm">−</button>
|
|
||||||
<button type="button" class="btn btn-outline-secondary btn-sm" tabindex="-1">2</button>
|
|
||||||
<button type="button" class="btn btn-outline-secondary btn-sm">+</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="d-flex align-items-center gap-2 flex-wrap">
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-danger">Remove</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<!-- Inventory card -->
|
|
||||||
<article class="border rounded-4 p-2 bg-body-tertiary inventory-entry-card">
|
|
||||||
<div class="d-flex flex-column gap-2">
|
|
||||||
|
|
||||||
<!-- Top row -->
|
|
||||||
<div class="d-flex justify-content-between align-items-start gap-3">
|
|
||||||
<div class="min-w-0 flex-grow-1">
|
|
||||||
<div class="fw-semibold fs-5 text-body mb-1">Lightly Played</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="row g-2">
|
|
||||||
<div class="col-4">
|
|
||||||
<div class="small text-secondary">Purchase price</div>
|
|
||||||
<div class="fs-5 fw-semibold">$6.00</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-4">
|
|
||||||
<div class="small text-secondary">Market price</div>
|
|
||||||
<div class="fs-5 text-success">$8.00</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-4">
|
|
||||||
<div class="small text-secondary">Gain / loss</div>
|
|
||||||
<div class="fs-5 fw-semibold text-success">+$4.00</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
|
|
||||||
<div class="d-flex align-items-center gap-2">
|
|
||||||
<span class="small text-secondary">Qty</span>
|
|
||||||
<div class="btn-group" role="group" aria-label="Quantity controls">
|
|
||||||
<button type="button" class="btn btn-outline-secondary btn-sm">−</button>
|
|
||||||
<button type="button" class="btn btn-outline-secondary btn-sm" tabindex="-1">2</button>
|
|
||||||
<button type="button" class="btn btn-outline-secondary btn-sm">+</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="d-flex align-items-center gap-2 flex-wrap">
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-danger">Remove</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Chart lives permanently outside tab-content so Bootstrap never hides it. -->
|
<!-- Chart lives permanently outside tab-content so Bootstrap never hides it. -->
|
||||||
@@ -617,11 +328,11 @@ const altSearchUrl = (card: any) => {
|
|||||||
</canvas>
|
</canvas>
|
||||||
</div>
|
</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">
|
<div class="btn-group btn-group-sm d-flex flex-row gap-1 justify-content-end mt-2" role="group" aria-label="Time range">
|
||||||
{showRanges['1m'] && <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 active" data-range="1m">1M</button>
|
||||||
{showRanges['3m'] && <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="3m">3M</button>
|
||||||
{showRanges['6m'] && <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="6m">6M</button>
|
||||||
{showRanges['1y'] && <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="1y">1Y</button>
|
||||||
{showRanges['all'] && <button type="button" class="btn btn-dark price-range-btn" data-range="all">All</button>}
|
<button type="button" class="btn btn-dark price-range-btn" data-range="all">All</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -48,15 +48,53 @@ const languageFilter = language === 'en' ? " && productLineName:=`Pokemon`"
|
|||||||
// synonyms alone (e.g. terms that need to match across multiple set names)
|
// synonyms alone (e.g. terms that need to match across multiple set names)
|
||||||
// and rewrites them into a direct filter, clearing the query so it doesn't
|
// and rewrites them into a direct filter, clearing the query so it doesn't
|
||||||
// also try to text-match against card names.
|
// also try to text-match against card names.
|
||||||
const EREADER_SETS = ['Expedition Base Set', 'Aquapolis', 'Skyridge', 'Battle-e'];
|
|
||||||
const EREADER_RE = /^(e-?reader|e reader)$/i;
|
const ALIAS_FILTERS = [
|
||||||
|
// ── Era / set groupings ───────────────────────────────────────────────
|
||||||
|
{ re: /^(e-?reader|e reader)$/i, field: 'setName',
|
||||||
|
values: ['Expedition Base Set', 'Aquapolis', 'Skyridge', 'Battle-e'] },
|
||||||
|
|
||||||
|
{ re: /^neo$/i, field: 'setName',
|
||||||
|
values: ['Neo Genesis', 'Neo Discovery', 'Neo Revelation', 'Neo Destiny'] },
|
||||||
|
|
||||||
|
{ re: /^(wotc|wizards)$/i, field: 'setName',
|
||||||
|
values: ['Base Set', 'Jungle', 'Fossil', 'Base Set 2', 'Team Rocket',
|
||||||
|
'Gym Heroes', 'Gym Challenge', 'Neo Genesis', 'Neo Discovery',
|
||||||
|
'Neo Revelation', 'Neo Destiny', 'Expedition Base Set',
|
||||||
|
'Aquapolis', 'Skyridge', 'Battle-e'] },
|
||||||
|
|
||||||
|
{ re: /^(sun\s*(&|and)\s*moon|s(&|and)m|sm)$/i, field: 'setName',
|
||||||
|
values: ['Sun & Moon', 'Guardians Rising', 'Burning Shadows', 'Crimson Invasion',
|
||||||
|
'Ultra Prism', 'Forbidden Light', 'Celestial Storm', 'Dragon Majesty',
|
||||||
|
'Lost Thunder', 'Team Up', 'Unbroken Bonds', 'Unified Minds',
|
||||||
|
'Hidden Fates', 'Cosmic Eclipse', 'Detective Pikachu'] },
|
||||||
|
|
||||||
|
{ re: /^(sword\s*(&|and)\s*shield|s(&|and)s|swsh)$/i, field: 'setName',
|
||||||
|
values: ['Sword & Shield', 'Rebel Clash', 'Darkness Ablaze', 'Vivid Voltage',
|
||||||
|
'Battle Styles', 'Chilling Reign', 'Evolving Skies', 'Fusion Strike',
|
||||||
|
'Brilliant Stars', 'Astral Radiance', 'Pokemon GO', 'Lost Origin',
|
||||||
|
'Silver Tempest', 'Crown Zenith'] },
|
||||||
|
|
||||||
|
// ── Card type shorthands ──────────────────────────────────────────────
|
||||||
|
{ re: /^trainers?$/i, field: 'cardType', values: ['Trainer'] },
|
||||||
|
{ re: /^supporters?$/i, field: 'cardType', values: ['Supporter'] },
|
||||||
|
{ re: /^stadiums?$/i, field: 'cardType', values: ['Stadium'] },
|
||||||
|
{ re: /^items?$/i, field: 'cardType', values: ['Item'] },
|
||||||
|
{ re: /^(energys?|energies)$/i, field: 'cardType', values: ['Energy'] },
|
||||||
|
|
||||||
|
// ── Rarity shorthands ─────────────────────────────────────────────────
|
||||||
|
{ re: /^promos?$/i, field: 'rarityName', values: ['Promo'] },
|
||||||
|
];
|
||||||
|
|
||||||
let resolvedQuery = query;
|
let resolvedQuery = query;
|
||||||
let queryFilter = '';
|
let queryFilter = '';
|
||||||
|
|
||||||
if (EREADER_RE.test(query.trim())) {
|
for (const alias of ALIAS_FILTERS) {
|
||||||
|
if (alias.re.test(query.trim())) {
|
||||||
resolvedQuery = '';
|
resolvedQuery = '';
|
||||||
queryFilter = `setName:=[${EREADER_SETS.map(s => '`' + s + '`').join(',')}]`;
|
queryFilter = `${alias.field}:=[${alias.values.map(s => '`' + s + '`').join(',')}]`;
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const filters = Array.from(formData.entries())
|
const filters = Array.from(formData.entries())
|
||||||
@@ -118,7 +156,10 @@ if (start === 0) {
|
|||||||
const searchRequests = { searches: searchArray };
|
const searchRequests = { searches: searchArray };
|
||||||
const commonSearchParams = {
|
const commonSearchParams = {
|
||||||
q: resolvedQuery,
|
q: resolvedQuery,
|
||||||
query_by: 'content,setName,productLineName,rarityName,energyType,cardType'
|
query_by: 'content,setName,setCode,productName,Artist',
|
||||||
|
query_by_weights: '10,6,8,9,8',
|
||||||
|
num_typos: '2,1,0,1,2',
|
||||||
|
prefix: 'true,true,false,false,false',
|
||||||
};
|
};
|
||||||
|
|
||||||
// use typesense to search for cards matching the query and return the productIds of the results
|
// use typesense to search for cards matching the query and return the productIds of the results
|
||||||
@@ -276,18 +317,21 @@ const facets = searchResults.results.slice(1).map((result: any) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
{pokemon.length === 0 && (
|
{pokemon.length === 0 && (
|
||||||
<div id="notfound" hx-swap-oob="true">
|
<div id="notfound" class="mt-4 h6" hx-swap-oob="true">
|
||||||
Pokemon not found
|
No cards found! Please modify your search and try again.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{pokemon.map((card:any) => (
|
{pokemon.map((card: any, i: number) => (
|
||||||
<div class="col">
|
|
||||||
<button type="button" class="btn btn-sm inventory-button position-relative float-end shadow-filter text-center p-2" data-card-id={card.cardId} hx-get={`/partials/card-modal?cardId=${card.cardId}`} hx-target="#cardModal" hx-trigger="click" data-bs-toggle="modal" data-bs-target="#cardModal" onclick="event.stopPropagation(); sessionStorage.setItem('openModalTab', 'nav-vendor');">
|
<div class="col equal-height-col">
|
||||||
<b>+/–</b>
|
<div class="inventory-button position-relative float-end shadow-filter text-center d-none">
|
||||||
</button>
|
<div class="inventory-label pt-2">+/-</div>
|
||||||
|
</div>
|
||||||
<div class="card-trigger position-relative" data-card-id={card.cardId} hx-get={`/partials/card-modal?cardId=${card.cardId}`} hx-target="#cardModal" hx-trigger="click" data-bs-toggle="modal" data-bs-target="#cardModal" onclick="const cardTitle = this.querySelector('#cardImage').getAttribute('alt'); dataLayer.push({'event': 'virtualPageview', 'pageUrl': this.getAttribute('hx-get'), 'pageTitle': cardTitle, 'previousUrl': '/pokemon'});">
|
<div class="card-trigger position-relative" data-card-id={card.cardId} hx-get={`/partials/card-modal?cardId=${card.cardId}`} hx-target="#cardModal" hx-trigger="click" data-bs-toggle="modal" data-bs-target="#cardModal" onclick="const cardTitle = this.querySelector('#cardImage').getAttribute('alt'); dataLayer.push({'event': 'virtualPageview', 'pageUrl': this.getAttribute('hx-get'), 'pageTitle': cardTitle, 'previousUrl': '/pokemon'});">
|
||||||
<div class="image-grow rounded-4 card-image" data-energy={card.energyType} data-rarity={card.rarityName} data-variant={card.variant} data-name={card.productName}><img src={`/static/cards/${card.productId}.jpg`} alt={card.productName} id="cardImage" loading="lazy" decoding="async" class="img-fluid rounded-4 mb-2 w-100" onerror="this.onerror=null; this.src='/static/cards/default.jpg'; this.closest('.image-grow')?.setAttribute('data-default','true')"/><span class="position-absolute top-50 start-0 d-inline medium-icon"><FirstEditionIcon edition={card?.variant} /></span>
|
<div class="image-grow rounded-4 card-image h-100" data-energy={card.energyType} data-rarity={card.rarityName} data-variant={card.variant} data-name={card.productName}>
|
||||||
|
<img src={`/static/cards/${card.productId}.jpg`} alt={card.productName} id="cardImage" loading="lazy" decoding="async" class="img-fluid rounded-4 mb-2 w-100" onerror="this.onerror=null; this.src='/static/cards/default.jpg'; this.closest('.image-grow')?.setAttribute('data-default','true')"/>
|
||||||
|
<span class="position-absolute top-50 start-0 d-inline medium-icon"><FirstEditionIcon edition={card?.variant} /></span>
|
||||||
<div class="holo-shine"></div>
|
<div class="holo-shine"></div>
|
||||||
<div class="holo-glare"></div>
|
<div class="holo-glare"></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -302,13 +346,14 @@ const facets = searchResults.results.slice(1).map((result: any) => {
|
|||||||
</div>
|
</div>
|
||||||
<div class="h5 my-0">{card.productName}</div>
|
<div class="h5 my-0">{card.productName}</div>
|
||||||
<div class="d-flex flex-row lh-1 mt-1 justify-content-between">
|
<div class="d-flex flex-row lh-1 mt-1 justify-content-between">
|
||||||
<div class="text-secondary flex-grow-1 d-none d-lg-flex">{card.setName}</div>
|
<div class="text-secondary flex-grow-1"><span class="d-none d-lg-flex">{card.setName}</span><span class="d-flex d-lg-none">{card.setCode}</span></div>
|
||||||
<div class="text-body-tertiary">{card.number}</div>
|
<div class="text-body-tertiary">{card.number}</div>
|
||||||
<span class="ps-2 small-icon"><RarityIcon rarity={card.rarityName} /></span>
|
<span class="ps-2 small-icon"><RarityIcon rarity={card.rarityName} /></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-body-tertiary">{card.variant}</div><span class="d-none">{card.productId}</span>
|
<div class="text-body-tertiary">{card.variant}</div>
|
||||||
|
<span class="d-none">{card.productId}</span>
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
))}
|
))}
|
||||||
{start + 20 < totalHits &&
|
{start + 20 < totalHits &&
|
||||||
<div hx-post="/partials/cards" hx-trigger="revealed" hx-include="#searchform" hx-target="#cardGrid" hx-swap="beforeend" hx-on--after-request="afterUpdate(event)">
|
<div hx-post="/partials/cards" hx-trigger="revealed" hx-include="#searchform" hx-target="#cardGrid" hx-swap="beforeend" hx-on--after-request="afterUpdate(event)">
|
||||||
|
|||||||
Reference in New Issue
Block a user