deckhearth/lib/scanner-session.js
varutasu 83d73eecaf
refactor(scanner): extract session and route API libs (page Brief 1) (#74)
Move scanner session persistence, queue merge helpers, and destination
routing fetch calls into lib/scanner-session.js and lib/scanner-route-api.js.
Load collections/decks on mount (were defined but never invoked).
Remove unused mana-symbol imports and dead select-all helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 16:15:27 -05:00

87 lines
2.5 KiB
JavaScript

import { VOCAB } from './collection-vocabulary.js';
export const SCANNER_SESSION_STORAGE_KEY = 'deckhearth:scanner-session';
export const DEFAULT_SCANNER_DESTINATION = {
type: 'owned',
id: null,
label: VOCAB.MY_COLLECTION,
};
export const DEFAULT_SCAN_DEFAULTS = { condition: 'NM', isFoil: false };
export function loadSavedScannerSession() {
if (typeof window === 'undefined') {
return {
destination: DEFAULT_SCANNER_DESTINATION,
gameFilter: 'All',
scanDefaults: DEFAULT_SCAN_DEFAULTS,
};
}
try {
const saved = JSON.parse(localStorage.getItem(SCANNER_SESSION_STORAGE_KEY));
return {
destination: saved?.destination || DEFAULT_SCANNER_DESTINATION,
gameFilter: saved?.gameFilter || 'All',
scanDefaults: saved?.scanDefaults || DEFAULT_SCAN_DEFAULTS,
};
} catch {
return {
destination: DEFAULT_SCANNER_DESTINATION,
gameFilter: 'All',
scanDefaults: DEFAULT_SCAN_DEFAULTS,
};
}
}
export function saveScannerSession({ destination, gameFilter, scanDefaults }) {
if (typeof window === 'undefined') return;
localStorage.setItem(
SCANNER_SESSION_STORAGE_KEY,
JSON.stringify({ destination, gameFilter, scanDefaults })
);
}
export function createScanCardId() {
return Date.now() + Math.random();
}
export function destinationActionKey(destination) {
if (!destination) return 'pending';
return destination.type === 'owned' ? 'owned' : destination.type;
}
export function mergeScannedCardEntry(existingCards, cardData, scanDefaults) {
const existingCardIndex = existingCards.findIndex(
(existing) =>
existing.name === cardData.name && existing.set === cardData.set && !existing.processed
);
if (existingCardIndex !== -1) {
const existing = existingCards[existingCardIndex];
const cardEntry = {
...existing,
quantity: (existing.quantity || 1) + 1,
scanImageUrl: cardData.scanImageUrl || existing.scanImageUrl,
timestamp: new Date().toISOString(),
};
const updated = [...existingCards];
updated[existingCardIndex] = cardEntry;
return { cardEntry, scannedCards: updated, merged: true };
}
const cardEntry = {
...cardData,
id: createScanCardId(),
name: cardData.name,
set: cardData.set,
quantity: 1,
condition: scanDefaults.condition,
isFoil: scanDefaults.isFoil,
timestamp: new Date().toISOString(),
processed: false,
};
return { cardEntry, scannedCards: [cardEntry, ...existingCards], merged: false };
}