17 Commits

Author SHA1 Message Date
47f18348bf [feat] boost card retrieval speed by removing typesense join 2026-05-27 17:32:46 -04:00
Zach Harding
6517044821 replace setname with setcode on mobile view card 2026-05-26 16:14:57 -04:00
Zach Harding
1b5e77d55d fixed incorrect set abbreviation 2026-05-26 15:38:50 -04:00
Zach Harding
d43ef99fea new set icon/mapping 2026-05-26 15:37:19 -04:00
Zach Harding
a566b82036 fixed tooltip init for card modal 2026-05-26 14:59:58 -04:00
Zach Harding
48b0098c6f equal height columns for card images 2026-05-26 11:31:19 -04:00
c582a40894 [bugfix] revert previous change because pricing wasn't showing 2026-05-26 11:10:49 -04:00
55af3a2e3c [feat] remove sku filter for speed 2026-05-26 11:02:32 -04:00
601cb7b770 Merge branch 'feat/inventory' 2026-05-26 05:32:26 -04:00
Zach Harding
85cfd1de64 added the ability to search by artist name 2026-04-07 08:07:47 -04:00
Zach Harding
c03a0b36a0 removed ads, fixed copy image for newer iOS 2026-04-05 13:11:46 -04:00
Zach Harding
5cdf9b1772 ads placement - tbd 2026-04-05 10:17:43 -04:00
Zach Harding
17465b13c1 adsense verification, remove latest sales table, add new search mechanic (weight, synonyms), fix low volatility (NaN%) 2026-04-01 17:43:47 -04:00
Zach Harding
c61cafecdc added /admin for admin panel - limited to users in the admin role (also updated local .env to match prod keys for clerk) 2026-03-28 16:52:53 -04:00
Zach Harding
2b3d5f322e Merge branch 'master' of papi.tkpups.com:tmiller/pokemon 2026-03-25 14:32:43 -04:00
Zach Harding
53cdddb183 correct sort by market price by adding a back a roll-up market price from skus to product ID during sync 2026-03-25 14:31:46 -04:00
35c8bf25f5 [bugfix] update static path on scripts 2026-03-25 13:42:19 -04:00
14 changed files with 258 additions and 97 deletions

View File

@@ -12,7 +12,7 @@ async function findMissingImages() {
.where(sql`${schema.tcgcards.sealed} = false`);
const missingImages: string[] = [];
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 {
await fs.access(imagePath);
} catch (err) {

View File

@@ -56,6 +56,7 @@ export const createCardCollection = async () => {
{ name: 'productLineName', type: 'string', facet: true },
{ name: 'rarityName', type: 'string', facet: true },
{ name: 'setName', type: 'string', facet: true },
{ name: 'setCode', type: 'string' },
{ name: 'cardType', type: 'string', facet: true },
{ name: 'energyType', type: 'string', facet: true },
{ name: 'number', type: 'string', sort: true },
@@ -125,7 +126,15 @@ export const upsertCardCollection = async (db:DBInstance) => {
with: { set: true, tcgdata: true, prices: true },
});
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 {
id: card.cardId.toString(),
@@ -136,12 +145,13 @@ export const upsertCardCollection = async (db:DBInstance) => {
productLineName: card.productLineName,
rarityName: card.rarityName,
setName: card.set?.setName || "",
setCode: card.set?.setCode || "",
cardType: card.cardType || "",
energyType: card.energyType || "",
number: card.number,
Artist: card.artist || "",
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,
...(marketPrice !== null && { marketPrice }),
// sku_id: card.prices.map(price => price.skuId.toString())

View File

@@ -154,6 +154,7 @@ const updateLatestSales = async (updatedCards: Set<number>) => {
const start = Date.now();
const updatedCards = await syncPrices();
await helper.upsertSkuCollection(db);
await helper.upsertCardCollection(db);
//console.log(updatedCards);
//console.log(updatedCards.size);
//await updateLatestSales(updatedCards);

View File

@@ -185,6 +185,10 @@ $colors: mauve, lilac, "purple", "orchid", "snow";
}
}
.navbar-nav > .nav-item > .nav-link:hover {
color: rgba(255, 255, 255, 1);
}
.nav-tabs {
.nav-link.active,
.nav-item.show .nav-link {
@@ -1170,4 +1174,4 @@ input[type="search"]::-webkit-search-cancel-button {
background-size: 1rem;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAn0lEQVR42u3UMQrDMBBEUZ9WfQqDmm22EaTyjRMHAlM5K+Y7lb0wnUZPIKHlnutOa+25Z4D++MRBX98MD1V/trSppLKHqj9TTBWKcoUqffbUcbBBEhTjBOV4ja4l4OIAZThEOV6jHO8ARXD+gPPvKMABinGOrnu6gTNUawrcQKNCAQ7QeTxORzle3+sDfjJpPCqhJh7GixZq4rHcc9l5A9qZ+WeBhgEuAAAAAElFTkSuQmCC);
}
-------------------------------------------------- */
-------------------------------------------------- */

View File

@@ -49,6 +49,13 @@ import BackToTop from "./BackToTop.astro"
<script is:inline>
(function () {
// ── Tooltip initializer ───────────────────────────────────────────────────
function initTooltips(root = document) {
root.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
bootstrap.Tooltip.getOrCreateInstance(el, { container: 'body' });
});
}
// ── Price mode helpers ────────────────────────────────────────────────────
// marketPriceByCondition is injected into the modal HTML via a data attribute
// on #inventoryEntryList: data-market-prices='{"Near Mint":6.00,...}'
@@ -246,6 +253,9 @@ import BackToTop from "./BackToTop.astro"
// ── Global helpers ────────────────────────────────────────────────────────
window.copyImage = async function(img) {
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
try {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
@@ -260,10 +270,17 @@ import BackToTop from "./BackToTop.astro"
clean.src = img.src;
});
const blob = await new Promise((resolve, reject) => {
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) {
const blob = await new Promise((resolve, reject) => {
canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/png');
});
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
showCopyToast('📋 Image copied!', '#198754');
} else {
@@ -282,6 +299,7 @@ import BackToTop from "./BackToTop.astro"
}
}
} catch (err) {
if (err.name === 'AbortError') return;
console.error('Failed:', err);
showCopyToast('❌ Copy failed', '#dc3545');
}
@@ -414,6 +432,7 @@ import BackToTop from "./BackToTop.astro"
if (typeof htmx !== 'undefined') htmx.process(modal);
initInventoryForms(modal);
initTooltips(modal);
updateNavButtons(modal);
initChartAfterSwap(modal);
switchToRequestedTab();
@@ -509,6 +528,7 @@ import BackToTop from "./BackToTop.astro"
if (typeof htmx !== 'undefined') htmx.process(target);
initInventoryForms(target);
initTooltips(target);
const destImg = target.querySelector('img.card-image');
if (destImg) {
@@ -638,6 +658,7 @@ import BackToTop from "./BackToTop.astro"
updateNavButtons(cardModal);
initChartAfterSwap(cardModal);
initInventoryForms(cardModal);
initTooltips(cardModal);
switchToRequestedTab();
});
@@ -648,6 +669,7 @@ import BackToTop from "./BackToTop.astro"
document.addEventListener('DOMContentLoaded', () => {
initInventoryForms();
initTooltips();
const pending = sessionStorage.getItem('pendingSearch');
if (pending) {
@@ -656,7 +678,7 @@ import BackToTop from "./BackToTop.astro"
if (input) input.value = pending;
// The form's hx-trigger="load" will fire automatically on page load,
// picking up the pre-populated input value — no manual trigger needed.
}
}
});
})();

View 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>

View File

@@ -125,6 +125,7 @@ import destined_rivals from "/src/svg/set/destined_rivals.svg?raw";
import surging_sparks from "/src/svg/set/surging_sparks.svg?raw";
import team_rocket from "/src/svg/set/team_rocket.svg?raw";
import perfect_order from "/src/svg/set/perfect_order.svg?raw";
import chaos_rising from "/src/svg/set/chaos_rising.svg?raw";
const { set } = Astro.props;
@@ -254,6 +255,7 @@ const setMap = {
"DRI": destined_rivals,
"SSP": surging_sparks,
"ME03": perfect_order,
"CRI": chaos_rising,
};
const svg = setMap[set as keyof typeof setMap] ?? "";

View File

@@ -19,6 +19,7 @@ const { title } = Astro.props;
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<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" href="/favicon.ico" />
<title>{title}</title>
@@ -45,4 +46,4 @@ const { title } = Astro.props;
<script src="../assets/js/main.js"></script>
<script>import '../assets/js/priceChart.js';</script>
</body>
</html>
</html>

View File

@@ -37,7 +37,7 @@ export const onRequest = clerkMiddleware(async (auth, context, next) => {
// Expose the flag to your Astro pages via locals
context.locals.canAddInventory = Boolean(canAddInventory);
// ── Admin route guard (unchanged) ───────────────────────────────────────────
// ── Admin route guard ───────────────────────────────────────────
if (isAdminRoute(context.request)) {
if (!isAuthenticated || !userId) {
return redirectToSignIn();
@@ -75,4 +75,4 @@ async function getUserOrgIds(context: any, userId: string): Promise<string[]> {
console.error("Failed to fetch user org memberships:", e);
return [];
}
}
}

18
src/pages/admin.astro Normal file
View 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>

View File

@@ -55,9 +55,36 @@ const calculatedAt = (() => {
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
? 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);
@@ -76,41 +103,6 @@ const historyRows = skuIds.length
.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 => ({
condition: row.condition,
calculatedAt: row.calculatedAt
@@ -119,29 +111,11 @@ const priceHistoryForChart = historyRows.map(row => ({
marketPrice: row.marketPrice,
})).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 conditionAttributes = (price: any) => {
const condition: string = price?.condition || "Near Mint";
const vol = volatilityByCondition[condition] ?? { label: '—', monthlyVol: 0 };
const vol = volatilityByCondition[condition] ?? { label: '—', spread: 0 };
const volatilityClass = (() => {
switch (vol.label) {
@@ -154,7 +128,7 @@ const conditionAttributes = (price: any) => {
const volatilityDisplay = vol.label === '—'
? '—'
: `${vol.label} (${(vol.monthlyVol * 100).toFixed(0)}%)`;
: `${vol.label} (${(vol.spread * 100).toFixed(0)}%)`;
return {
"Near Mint": { label: "nav-nm", volatility: volatilityDisplay, volatilityClass, class: "show active" },
@@ -205,9 +179,6 @@ const altSearchUrl = (card: any) => {
<!-- Card image column -->
<div class="col-sm-12 col-md-3">
<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
class="card-image-wrap rounded-4"
data-energy={card?.energyType}
@@ -287,11 +258,11 @@ const altSearchUrl = (card: any) => {
<p class="mb-0 mt-1">${price.marketPrice}</p>
</div>
<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>
</div>
<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>
</div>
<div class={`alert rounded p-2 flex-fill d-flex flex-column mb-0 ${attributes?.volatilityClass}`}>
@@ -306,14 +277,14 @@ const altSearchUrl = (card: any) => {
data-bs-trigger="hover focus click"
data-bs-html="true"
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'>
<p class="mb-1">
<strong>What this measures:</strong> how much the market price tends to move day-to-day,
scaled up to a monthly expectation.
<strong>What this measures:</strong> how wide the gap between the 30-day low and high is,
relative to the market price.
</p>
<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>
</div>
`}
@@ -566,11 +537,11 @@ const altSearchUrl = (card: any) => {
</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">
{showRanges['1m'] && <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>}
{showRanges['6m'] && <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>}
{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 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>

View File

@@ -51,15 +51,53 @@ const languageFilter = language === 'en' ? " && productLineName:=`Pokemon`"
// 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
// 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 queryFilter = '';
if (EREADER_RE.test(query.trim())) {
resolvedQuery = '';
queryFilter = `setName:=[${EREADER_SETS.map(s => '`' + s + '`').join(',')}]`;
for (const alias of ALIAS_FILTERS) {
if (alias.re.test(query.trim())) {
resolvedQuery = '';
queryFilter = `${alias.field}:=[${alias.values.map(s => '`' + s + '`').join(',')}]`;
break;
}
}
const filters = Array.from(formData.entries())
@@ -91,15 +129,15 @@ const facetFilter = (facet:string) => {
// primary search values (for cards)
let searchArray = [{
// Note: no `$skus(...)` join here — see the sku fetch below for why.
let searchArray: any[] = [{
collection: 'cards',
filter_by: `$skus(id:*) && sealed:false${languageFilter}${queryFilter ? ` && ${queryFilter}` : ''}${filterBy ? ` && ${filterBy}` : ''}`,
filter_by: `sealed:false${languageFilter}${queryFilter ? ` && ${queryFilter}` : ''}${filterBy ? ` && ${filterBy}` : ''}`,
per_page: 20,
facet_by: '',
max_facet_values: 0,
page: Math.floor(start / 20) + 1,
sort_by: resolvedSort,
include_fields: '$skus(*)',
}];
// on first load (start === 0) we want to get the facets for the filters
@@ -121,7 +159,10 @@ if (start === 0) {
const searchRequests = { searches: searchArray };
const commonSearchParams = {
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
@@ -131,6 +172,28 @@ const cardResults = searchResults.results[0] as any;
const pokemon = cardResults.hits?.map((hit: any) => hit.document) ?? [];
const totalHits = cardResults?.found;
// Skus aren't used for searching or sorting — they only supply the per-condition
// prices displayed on each card. Joining them into the primary search via
// `$skus(id:*)` forces Typesense to materialize the reverse join across the whole
// filtered result set before pagination (~20x slower). Instead, fetch skus for
// just the visible cards in one direct, indexed filter and attach them by id.
if (pokemon.length > 0) {
const cardIds = pokemon.map((c: any) => c.id);
const skuSearch = await client.collections('skus').documents().search({
q: '*',
query_by: 'condition',
filter_by: `card_id:=[${cardIds.map((id: string) => '`' + id + '`').join(',')}]`,
per_page: 250,
include_fields: 'condition,marketPrice,card_id',
});
const skusByCard: Record<string, any[]> = {};
for (const hit of (skuSearch.hits ?? []) as any[]) {
const sku = hit.document;
(skusByCard[sku.card_id] ??= []).push(sku);
}
for (const card of pokemon) card.skus = skusByCard[card.id] ?? [];
}
// format price to 2 decimal places (or 0 if price >=100) and adds a $ sign, if the price is null it returns ""
const formatPrice = (condition:string, skus: any) => {
@@ -280,20 +343,20 @@ const facets = searchResults.results.slice(1).map((result: any) => {
}
{pokemon.length === 0 && (
<div id="notfound" hx-swap-oob="true">
Pokemon not found
<div id="notfound" class="mt-4 h6" hx-swap-oob="true">
No cards found! Please modify your search and try again.
</div>
)}
{pokemon.map((card:any) => (
<div class="col">
<div class="col equal-height-col">
{canAddInventory && (
<button type="button" class="btn btn-sm inventory-button position-relative float-end shadow-filter text-center p-2 fw-bold" 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');">
+/
</button>
)}
<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" 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 h-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-glare"></div>
</div>
@@ -309,15 +372,15 @@ const facets = searchResults.results.slice(1).map((result: any) => {
<div class="fs-5 fw-semibold my-0">{card.productName}</div>
<div class="d-flex flex-row lh-1 mt-1 justify-content-between">
<div class="text-body-tertiary flex-grow-1 d-none d-lg-flex fst-normal">{card.setName}</div>
<div class="text-body-tertiary flex-grow-1 d-flex d-lg-none fst-normal">{card.setCode}</div>
<div class="text-body-tertiary fst-normal">{card.number}</div>
<span class="ps-2 small-icon"><RarityIcon rarity={card.rarityName} /></span>
</div>
<div class="text-secondary fst-italic">{card.variant}</div><span class="d-none">{card.productId}</span>
</div>
))}
{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)">
Loading...
</div>
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.5 KiB

61
src/volatility.ts Normal file
View File

@@ -0,0 +1,61 @@
export interface VolatilityResult {
label: 'High' | 'Medium' | 'Low' | '—';
monthlyVol: number;
}
/**
* Computes 30-day rolling volatility from an array of prices using
* log-return standard deviation scaled to a monthly expectation.
*
* @param prices - Ordered array of market prices (oldest → newest)
* @returns label ('High' | 'Medium' | 'Low' | '—') and monthlyVol (01 range)
*/
export function computeVolatility(prices: number[]): VolatilityResult {
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: VolatilityResult['label'] =
monthlyVol >= 0.30 ? 'High'
: monthlyVol >= 0.15 ? 'Medium'
: 'Low';
return { label, monthlyVol: Math.round(monthlyVol * 100) / 100 };
}
/**
* Groups a list of price-history rows by condition and computes volatility
* for each, filtered to a rolling window.
*
* @param rows - Array of { condition, calculatedAt, marketPrice }
* @param windowMs - Rolling window in milliseconds (default: 30 days)
*/
export function volatilityByCondition(
rows: Array<{ condition: string; calculatedAt: string | Date | null; marketPrice: number | string | null }>,
windowMs = 30 * 86_400_000,
): Record<string, VolatilityResult> {
const cutoff = new Date(Date.now() - windowMs);
const grouped: Record<string, number[]> = {};
for (const row of rows) {
if (row.marketPrice == null || !row.calculatedAt) continue;
if (new Date(row.calculatedAt) < cutoff) continue;
const price = Number(row.marketPrice);
if (price <= 0) continue;
if (!grouped[row.condition]) grouped[row.condition] = [];
grouped[row.condition].push(price);
}
const result: Record<string, VolatilityResult> = {};
for (const [condition, prices] of Object.entries(grouped)) {
result[condition] = computeVolatility(prices);
}
return result;
}