Compare commits
8 Commits
7b1f470ee9
...
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`);
|
||||
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) {
|
||||
|
||||
@@ -54,6 +54,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 },
|
||||
@@ -94,7 +95,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(),
|
||||
@@ -105,12 +114,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())
|
||||
|
||||
@@ -242,7 +242,7 @@ async function syncProductLine(productLine: string, field: string, fieldValue: s
|
||||
}
|
||||
|
||||
// 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)) {
|
||||
const imageResponse = await fetch(`https://tcgplayer-cdn.tcgplayer.com/product/${item.productId}_in_1000x1000.jpg`);
|
||||
if (imageResponse.ok) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -112,6 +112,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");
|
||||
@@ -127,10 +130,17 @@ import BackToTop from "./BackToTop.astro"
|
||||
clean.src = img.src;
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
|
||||
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 })]);
|
||||
showCopyToast('📋 Image copied!', '#198754');
|
||||
} else {
|
||||
@@ -149,6 +159,7 @@ import BackToTop from "./BackToTop.astro"
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.name === 'AbortError') return;
|
||||
console.error('Failed:', err);
|
||||
showCopyToast('❌ Copy failed', '#dc3545');
|
||||
}
|
||||
@@ -388,5 +399,11 @@ import BackToTop from "./BackToTop.astro"
|
||||
currentCardId = null;
|
||||
updateNavButtons(null);
|
||||
});
|
||||
|
||||
// ── AdSense re-init on infinite scroll ───────────────────────────────────
|
||||
document.addEventListener('htmx:afterSwap', () => {
|
||||
(window.adsbygoogle = window.adsbygoogle || []).push({});
|
||||
});
|
||||
|
||||
})();
|
||||
</script>
|
||||
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 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>
|
||||
|
||||
@@ -1,17 +1,45 @@
|
||||
// src/middleware.ts
|
||||
import { clerkMiddleware, createRouteMatcher } from '@clerk/astro/server';
|
||||
import type { AstroMiddlewareRequest, AstroMiddlewareResponse } from 'astro';
|
||||
import { clerkMiddleware, createRouteMatcher, clerkClient } from '@clerk/astro/server';
|
||||
|
||||
const isProtectedRoute = createRouteMatcher([
|
||||
'/pokemon',
|
||||
]);
|
||||
const isProtectedRoute = createRouteMatcher(['/pokemon']);
|
||||
const isAdminRoute = createRouteMatcher(['/admin']);
|
||||
|
||||
export const onRequest = clerkMiddleware((auth, context) => {
|
||||
const { isAuthenticated, redirectToSignIn } = auth()
|
||||
const TARGET_ORG_ID = "org_3Baav9czkRLLlC7g89oJWqRRulK";
|
||||
|
||||
export const onRequest = clerkMiddleware(async (auth, context) => {
|
||||
const { isAuthenticated, userId, redirectToSignIn } = auth();
|
||||
|
||||
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>
|
||||
@@ -4,7 +4,7 @@ import Layout from '../layouts/Main.astro';
|
||||
import NavItems from '../components/NavItems.astro';
|
||||
import NavBar from '../components/NavBar.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">
|
||||
<NavBar slot="navbar">
|
||||
@@ -16,31 +16,41 @@ import { Show, SignInButton, SignUpButton, SignOutButton } from '@clerk/astro/co
|
||||
<p class="text-secondary">(working title)</p>
|
||||
</div>
|
||||
<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">
|
||||
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 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>
|
||||
<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>
|
||||
</div>
|
||||
<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">
|
||||
<SignInButton asChild mode="modal">
|
||||
<button class="btn btn-success">Sign In</button>
|
||||
</SignInButton>
|
||||
<div class="card border p-5 w-100">
|
||||
<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>
|
||||
<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 when="signed-in">
|
||||
<div class="w-100">
|
||||
<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>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -51,9 +51,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);
|
||||
@@ -72,41 +99,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
|
||||
@@ -115,29 +107,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) {
|
||||
@@ -150,7 +124,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" },
|
||||
@@ -190,9 +164,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}
|
||||
@@ -270,11 +241,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}`}>
|
||||
@@ -289,14 +260,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>
|
||||
`}
|
||||
@@ -310,7 +281,7 @@ const altSearchUrl = (card: any) => {
|
||||
|
||||
<!-- Table only — chart is outside the tab panes -->
|
||||
<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>
|
||||
<table class="table table-sm mb-0">
|
||||
<caption class="small">Filtered to remove mismatched language variants</caption>
|
||||
@@ -357,11 +328,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>
|
||||
|
||||
@@ -48,15 +48,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())) {
|
||||
for (const alias of ALIAS_FILTERS) {
|
||||
if (alias.re.test(query.trim())) {
|
||||
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())
|
||||
@@ -118,7 +156,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
|
||||
@@ -276,18 +317,21 @@ 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">
|
||||
{pokemon.map((card: any, i: number) => (
|
||||
|
||||
<div class="col equal-height-col">
|
||||
<div class="inventory-button position-relative float-end shadow-filter text-center d-none">
|
||||
<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="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-glare"></div>
|
||||
</div>
|
||||
@@ -302,13 +346,14 @@ const facets = searchResults.results.slice(1).map((result: any) => {
|
||||
</div>
|
||||
<div class="h5 my-0">{card.productName}</div>
|
||||
<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>
|
||||
<span class="ps-2 small-icon"><RarityIcon rarity={card.rarityName} /></span>
|
||||
</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>
|
||||
|
||||
</>
|
||||
))}
|
||||
{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)">
|
||||
|
||||
Reference in New Issue
Block a user