Resolves the launch-blocking 'TCG Vault vs Deck Hearth' inconsistency called out in AGENTS.md line 5 since project setup. Operator gate-0 decision: Deck Hearth wins. Two briefs applied serially. B1 (mechanical): 7-file display + comment sweep. B2 (infrastructure): Redis prefix rename in lib/rate-limit.js (5 prefixes, accept one-time counter reset), package.json + lockfile regen (STOP-on-churn confirmed only name lines changed), admin/alice/bob email rename in seed scripts + login pre-fill + NEW idempotent migration script scripts/migrations/2026-05-24-rename-admin-email.js. Risk 4 PRESERVE applied: test/lib/permission-middleware.test.js retains admin@tcgvault.com literal with 7-line architect-authored why comment (documents pre-fix-auth-bypass bug shape; preserves historical truth per project's gotcha-documentation convention). All 5 D-decisions ratified at gate-1 (Deck Hearth / deck-hearth / deckhearth / admin@deckhearth.com / full deckhearth Redis prefix). Local: lint 128 baseline (B1 + B2), vitest 21/21 (B1 + B2). CI all green: Playwright smoke 3/3 against rebranded preview in 1m4s, forbidden-cors-headers pass, forbidden-endpoints pass, Screenshot diff pass, Vercel deployment complete. Cross-validation lineage: 4th convoy where the same 3-test smoke spec defends auth surface through sweeping change (after PR #15 Layout default-user, PR #19 CORS, PR #20 rate-limit, now this PR #21 brand rename). OPERATOR POST-MERGE ACTION REQUIRED: run 'node scripts/migrations/2026-05-24-rename-admin-email.js' against prod Neon DB before next admin login (ordering: migration FIRST, then any subsequent setup-db invocation). Migration is ESM, idempotent, UNIQUE-collision-safe. PR #21 architect-commit50ce9ab, B1ac8c998, B21c18d21.
185 lines
No EOL
5.7 KiB
JavaScript
185 lines
No EOL
5.7 KiB
JavaScript
import { sql } from '@vercel/postgres';
|
|
import { getUserFromRequest } from '../../../lib/permission-middleware';
|
|
import { checkImportRateLimit } from '../../../lib/rate-limit.js';
|
|
|
|
// Helper function to delay execution
|
|
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
|
|
// Helper function to fetch with retry logic
|
|
async function fetchWithRetry(url, maxRetries = 3, delayMs = 2000) {
|
|
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
try {
|
|
const response = await fetch(url, {
|
|
headers: {
|
|
'User-Agent': 'Deck-Hearth/1.0',
|
|
'Accept': 'application/json'
|
|
},
|
|
timeout: 30000 // 30 second timeout
|
|
});
|
|
|
|
if (response.ok) {
|
|
return response;
|
|
}
|
|
|
|
// If it's a 404, don't retry
|
|
if (response.status === 404) {
|
|
throw new Error(`Set not found: ${response.status}`);
|
|
}
|
|
|
|
// If it's a 504 or 503, wait longer before retry
|
|
if (response.status === 504 || response.status === 503) {
|
|
console.log(`Attempt ${attempt}: Got ${response.status}, waiting ${delayMs * attempt}ms before retry...`);
|
|
await delay(delayMs * attempt);
|
|
continue;
|
|
}
|
|
|
|
throw new Error(`Lorcana API error: ${response.status}`);
|
|
} catch (error) {
|
|
if (attempt === maxRetries) {
|
|
throw error;
|
|
}
|
|
console.log(`Attempt ${attempt} failed:`, error.message);
|
|
await delay(delayMs * attempt);
|
|
}
|
|
}
|
|
}
|
|
|
|
export default async function handler(req, res) {
|
|
if (req.method !== 'POST') {
|
|
return res.status(405).json({ error: 'Method not allowed' });
|
|
}
|
|
|
|
const user = await getUserFromRequest(req);
|
|
if (!user) {
|
|
return res.status(401).json({ error: 'Authentication required' });
|
|
}
|
|
if (user.role !== 'admin') {
|
|
return res.status(403).json({ error: 'Admin access required' });
|
|
}
|
|
|
|
const { allowed, reset } = await checkImportRateLimit(req, user.userId);
|
|
if (!allowed) {
|
|
res.setHeader('Retry-After', Math.ceil((reset - Date.now()) / 1000));
|
|
return res.status(429).json({ error: 'Too many attempts. Try again later.' });
|
|
}
|
|
|
|
try {
|
|
const { setCode } = req.body;
|
|
|
|
if (!setCode) {
|
|
return res.status(400).json({ error: 'Set code is required' });
|
|
}
|
|
|
|
console.log(`Starting import for Lorcana set: ${setCode}`);
|
|
|
|
// Map set codes to Lorcast set codes
|
|
const setCodeMap = {
|
|
'tfc': '1', // The First Chapter
|
|
'rotf': '2', // Rise of the Floodborn
|
|
'ink': '3' // Into the Inklands
|
|
};
|
|
|
|
const lorcastSetCode = setCodeMap[setCode];
|
|
if (!lorcastSetCode) {
|
|
return res.status(400).json({ error: `Unknown set code: ${setCode}` });
|
|
}
|
|
|
|
// Fetch cards from Lorcast API
|
|
const response = await fetchWithRetry(`https://api.lorcast.com/v0/cards/search?q=set:${lorcastSetCode}&unique=prints`);
|
|
|
|
const data = await response.json();
|
|
const cards = data.results || [];
|
|
|
|
if (cards.length === 0) {
|
|
return res.status(200).json({
|
|
success: true,
|
|
message: `No cards found for set ${setCode}`,
|
|
imported: 0,
|
|
skipped: 0,
|
|
total: 0
|
|
});
|
|
}
|
|
|
|
console.log(`Found ${cards.length} cards for set ${setCode}`);
|
|
|
|
let importedCount = 0;
|
|
let skippedCount = 0;
|
|
|
|
for (const card of cards) {
|
|
try {
|
|
// Check if card already exists
|
|
const existingCard = await sql`
|
|
SELECT id FROM cards WHERE scryfall_id = ${card.id}
|
|
`;
|
|
|
|
if (existingCard.rows.length > 0) {
|
|
skippedCount++;
|
|
continue;
|
|
}
|
|
|
|
// Extract price data
|
|
let currentPrice = null;
|
|
if (card.prices?.usd) {
|
|
currentPrice = parseFloat(card.prices.usd);
|
|
} else if (card.prices?.usd_foil) {
|
|
currentPrice = parseFloat(card.prices.usd_foil);
|
|
}
|
|
|
|
// Determine rarity
|
|
let rarity = card.rarity || 'Common';
|
|
if (rarity === 'Super_rare') {
|
|
rarity = 'Super Rare';
|
|
}
|
|
|
|
// Extract card type and text
|
|
const cardType = card.type?.[0] || 'Character';
|
|
const cardText = card.text || null;
|
|
const flavorText = card.flavor_text || null;
|
|
|
|
// Extract stats
|
|
const strength = card.strength || null;
|
|
const willpower = card.willpower || null;
|
|
const lore = card.lore || null;
|
|
|
|
// Insert card into database
|
|
await sql`
|
|
INSERT INTO cards (
|
|
name, set_name, set_code, card_number, rarity, game,
|
|
mana_cost, cmc, card_type, colors, oracle_text,
|
|
power, toughness, image_url, stock_image_url,
|
|
current_price, market_price, scryfall_id, verified
|
|
) VALUES (
|
|
${card.name}, ${card.set.name}, ${card.set.code}, ${card.collector_number},
|
|
${rarity}, 'Lorcana', ${card.cost}, ${card.cost}, ${cardType},
|
|
${JSON.stringify(card.ink ? [card.ink] : [])}, ${cardText || flavorText},
|
|
${strength}, ${willpower || lore},
|
|
${card.image_uris?.digital?.large || card.image_uris?.digital?.small || null}, ${card.image_uris?.digital?.small || null},
|
|
${currentPrice}, null, ${card.id}, true
|
|
)
|
|
`;
|
|
|
|
importedCount++;
|
|
} catch (error) {
|
|
console.error(`Error importing card ${card.name}:`, error);
|
|
skippedCount++;
|
|
}
|
|
}
|
|
|
|
console.log(`Import completed for set ${setCode}: ${importedCount} imported, ${skippedCount} skipped`);
|
|
|
|
res.status(200).json({
|
|
success: true,
|
|
message: `Import completed for set ${setCode}`,
|
|
imported: importedCount,
|
|
skipped: skippedCount,
|
|
total: cards.length
|
|
});
|
|
|
|
} catch (error) {
|
|
console.error('Card import error:', error);
|
|
res.status(500).json({
|
|
error: 'Import failed',
|
|
details: error.message
|
|
});
|
|
}
|
|
}
|