Compare commits
9 Commits
dcfefc8371
...
backup5
| Author | SHA1 | Date | |
|---|---|---|---|
| 15655e3987 | |||
|
|
5263fa6834 | ||
|
|
923c86a3b3 | ||
| d8b3864411 | |||
|
|
4aaffe99c7 | ||
| 194cbd6ca8 | |||
|
|
a11da5a977 | ||
| d5445c2282 | |||
|
|
6bc7e13e78 |
@@ -19,7 +19,7 @@ GOOGLE_CLIENT_ID=
|
||||
# Server Configuration
|
||||
PORT=3001
|
||||
API_URL=http://localhost:3001
|
||||
FRONTEND_URL=http://localhost:3002
|
||||
FRONTEND_URL=http://localhost:3019
|
||||
|
||||
# Revalidation secret (shared with frontend for on-demand cache revalidation)
|
||||
# Must match the REVALIDATE_SECRET in frontend/.env
|
||||
|
||||
22
backend/src/lib/revalidate.ts
Normal file
22
backend/src/lib/revalidate.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
// Trigger frontend cache revalidation (fire-and-forget)
|
||||
// Revalidates both the sitemap and the next-event data (homepage, llms.txt)
|
||||
export function revalidateFrontendCache() {
|
||||
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3002';
|
||||
const secret = process.env.REVALIDATE_SECRET;
|
||||
if (!secret) {
|
||||
console.warn('REVALIDATE_SECRET not set, skipping frontend revalidation');
|
||||
return;
|
||||
}
|
||||
fetch(`${frontendUrl}/api/revalidate`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ secret, tag: ['events-sitemap', 'next-event'] }),
|
||||
})
|
||||
.then((res) => {
|
||||
if (!res.ok) console.error('Frontend revalidation failed:', res.status);
|
||||
else console.log('Frontend revalidation triggered (sitemap + next-event)');
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Frontend revalidation error:', err.message);
|
||||
});
|
||||
}
|
||||
@@ -222,11 +222,11 @@ adminRouter.get('/export/tickets', requireAuth(['admin']), async (c) => {
|
||||
return c.json({ tickets: enrichedTickets });
|
||||
});
|
||||
|
||||
// Export attendees for a specific event (admin) — CSV/XLSX download
|
||||
adminRouter.get('/events/:eventId/export', requireAuth(['admin']), async (c) => {
|
||||
// Export attendees for a specific event (admin) — CSV download
|
||||
adminRouter.get('/events/:eventId/attendees/export', requireAuth(['admin']), async (c) => {
|
||||
const eventId = c.req.param('eventId');
|
||||
const status = c.req.query('status') || 'all'; // confirmed | checked_in | confirmed_pending | all
|
||||
const format = c.req.query('format') || 'csv'; // csv | xlsx
|
||||
const q = c.req.query('q') || '';
|
||||
|
||||
// Verify event exists
|
||||
const event = await dbGet<any>(
|
||||
@@ -249,14 +249,28 @@ adminRouter.get('/events/:eventId/export', requireAuth(['admin']), async (c) =>
|
||||
// "all" — include everything
|
||||
}
|
||||
|
||||
const ticketList = await dbAll<any>(
|
||||
let ticketList = await dbAll<any>(
|
||||
(db as any)
|
||||
.select()
|
||||
.from(tickets)
|
||||
.where(conditions.length === 1 ? conditions[0] : and(...conditions))
|
||||
.orderBy((tickets as any).createdAt)
|
||||
.orderBy(desc((tickets as any).createdAt))
|
||||
);
|
||||
|
||||
// Apply text search filter in-memory
|
||||
if (q) {
|
||||
const query = q.toLowerCase();
|
||||
ticketList = ticketList.filter((t: any) => {
|
||||
const fullName = `${t.attendeeFirstName || ''} ${t.attendeeLastName || ''}`.toLowerCase();
|
||||
return (
|
||||
fullName.includes(query) ||
|
||||
(t.attendeeEmail || '').toLowerCase().includes(query) ||
|
||||
(t.attendeePhone || '').toLowerCase().includes(query) ||
|
||||
t.id.toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Enrich each ticket with payment data
|
||||
const rows = await Promise.all(
|
||||
ticketList.map(async (ticket: any) => {
|
||||
@@ -274,10 +288,12 @@ adminRouter.get('/events/:eventId/export', requireAuth(['admin']), async (c) =>
|
||||
'Ticket ID': ticket.id,
|
||||
'Full Name': fullName,
|
||||
'Email': ticket.attendeeEmail || '',
|
||||
'Phone': ticket.attendeePhone || '',
|
||||
'Status': ticket.status,
|
||||
'Checked In': isCheckedIn ? 'true' : 'false',
|
||||
'Check-in Time': ticket.checkinAt || '',
|
||||
'Payment Status': payment?.status || '',
|
||||
'Booked At': ticket.createdAt || '',
|
||||
'Notes': ticket.adminNote || '',
|
||||
};
|
||||
})
|
||||
@@ -294,9 +310,9 @@ adminRouter.get('/events/:eventId/export', requireAuth(['admin']), async (c) =>
|
||||
};
|
||||
|
||||
const columns = [
|
||||
'Ticket ID', 'Full Name', 'Email',
|
||||
'Ticket ID', 'Full Name', 'Email', 'Phone',
|
||||
'Status', 'Checked In', 'Check-in Time', 'Payment Status',
|
||||
'Notes',
|
||||
'Booked At', 'Notes',
|
||||
];
|
||||
|
||||
const headerLine = columns.map(csvEscape).join(',');
|
||||
@@ -319,6 +335,98 @@ adminRouter.get('/events/:eventId/export', requireAuth(['admin']), async (c) =>
|
||||
return c.body(csvContent);
|
||||
});
|
||||
|
||||
// Legacy alias — keep old path working
|
||||
adminRouter.get('/events/:eventId/export', requireAuth(['admin']), async (c) => {
|
||||
const newUrl = new URL(c.req.url);
|
||||
newUrl.pathname = newUrl.pathname.replace('/export', '/attendees/export');
|
||||
return c.redirect(newUrl.toString(), 301);
|
||||
});
|
||||
|
||||
// Export tickets for a specific event (admin) — CSV download (confirmed/checked_in only)
|
||||
adminRouter.get('/events/:eventId/tickets/export', requireAuth(['admin']), async (c) => {
|
||||
const eventId = c.req.param('eventId');
|
||||
const status = c.req.query('status') || 'all'; // confirmed | checked_in | all
|
||||
const q = c.req.query('q') || '';
|
||||
|
||||
// Verify event exists
|
||||
const event = await dbGet<any>(
|
||||
(db as any).select().from(events).where(eq((events as any).id, eventId))
|
||||
);
|
||||
if (!event) {
|
||||
return c.json({ error: 'Event not found' }, 404);
|
||||
}
|
||||
|
||||
// Only confirmed/checked_in for tickets export
|
||||
let conditions: any[] = [
|
||||
eq((tickets as any).eventId, eventId),
|
||||
inArray((tickets as any).status, ['confirmed', 'checked_in']),
|
||||
];
|
||||
|
||||
if (status === 'confirmed') {
|
||||
conditions = [eq((tickets as any).eventId, eventId), eq((tickets as any).status, 'confirmed')];
|
||||
} else if (status === 'checked_in') {
|
||||
conditions = [eq((tickets as any).eventId, eventId), eq((tickets as any).status, 'checked_in')];
|
||||
}
|
||||
|
||||
let ticketList = await dbAll<any>(
|
||||
(db as any)
|
||||
.select()
|
||||
.from(tickets)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc((tickets as any).createdAt))
|
||||
);
|
||||
|
||||
// Apply text search filter
|
||||
if (q) {
|
||||
const query = q.toLowerCase();
|
||||
ticketList = ticketList.filter((t: any) => {
|
||||
const fullName = `${t.attendeeFirstName || ''} ${t.attendeeLastName || ''}`.toLowerCase();
|
||||
return (
|
||||
fullName.includes(query) ||
|
||||
t.id.toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const csvEscape = (value: string) => {
|
||||
if (value == null) return '';
|
||||
const str = String(value);
|
||||
if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
|
||||
return '"' + str.replace(/"/g, '""') + '"';
|
||||
}
|
||||
return str;
|
||||
};
|
||||
|
||||
const columns = ['Ticket ID', 'Booking ID', 'Attendee Name', 'Status', 'Check-in Time', 'Booked At'];
|
||||
|
||||
const rows = ticketList.map((ticket: any) => ({
|
||||
'Ticket ID': ticket.id,
|
||||
'Booking ID': ticket.bookingId || '',
|
||||
'Attendee Name': [ticket.attendeeFirstName, ticket.attendeeLastName].filter(Boolean).join(' '),
|
||||
'Status': ticket.status,
|
||||
'Check-in Time': ticket.checkinAt || '',
|
||||
'Booked At': ticket.createdAt || '',
|
||||
}));
|
||||
|
||||
const headerLine = columns.map(csvEscape).join(',');
|
||||
const dataLines = rows.map((row: any) =>
|
||||
columns.map((col: string) => csvEscape(row[col])).join(',')
|
||||
);
|
||||
|
||||
const csvContent = '\uFEFF' + [headerLine, ...dataLines].join('\r\n');
|
||||
|
||||
const slug = (event.title || 'event')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/(^-|-$)/g, '');
|
||||
const dateStr = new Date().toISOString().split('T')[0];
|
||||
const filename = `${slug}-tickets-${dateStr}.csv`;
|
||||
|
||||
c.header('Content-Type', 'text/csv; charset=utf-8');
|
||||
c.header('Content-Disposition', `attachment; filename="${filename}"`);
|
||||
return c.body(csvContent);
|
||||
});
|
||||
|
||||
// Export financial data (admin)
|
||||
adminRouter.get('/export/financial', requireAuth(['admin']), async (c) => {
|
||||
const startDate = c.req.query('startDate');
|
||||
|
||||
@@ -5,6 +5,7 @@ import { db, dbGet, dbAll, events, tickets, payments, eventPaymentOverrides, ema
|
||||
import { eq, desc, and, gte, sql } from 'drizzle-orm';
|
||||
import { requireAuth, getAuthUser } from '../lib/auth.js';
|
||||
import { generateId, getNow, convertBooleansForDb, toDbDate, calculateAvailableSeats } from '../lib/utils.js';
|
||||
import { revalidateFrontendCache } from '../lib/revalidate.js';
|
||||
|
||||
interface UserContext {
|
||||
id: string;
|
||||
@@ -15,29 +16,6 @@ interface UserContext {
|
||||
|
||||
const eventsRouter = new Hono<{ Variables: { user: UserContext } }>();
|
||||
|
||||
// Trigger frontend cache revalidation (fire-and-forget)
|
||||
// Revalidates both the sitemap and the next-event data (homepage, llms.txt)
|
||||
function revalidateFrontendCache() {
|
||||
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3002';
|
||||
const secret = process.env.REVALIDATE_SECRET;
|
||||
if (!secret) {
|
||||
console.warn('REVALIDATE_SECRET not set, skipping frontend revalidation');
|
||||
return;
|
||||
}
|
||||
fetch(`${frontendUrl}/api/revalidate`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ secret, tag: ['events-sitemap', 'next-event'] }),
|
||||
})
|
||||
.then((res) => {
|
||||
if (!res.ok) console.error('Frontend revalidation failed:', res.status);
|
||||
else console.log('Frontend revalidation triggered (sitemap + next-event)');
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Frontend revalidation error:', err.message);
|
||||
});
|
||||
}
|
||||
|
||||
// Helper to normalize event data for API response
|
||||
// PostgreSQL decimal returns strings, booleans are stored as integers
|
||||
function normalizeEvent(event: any) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { db, dbGet, siteSettings, events } from '../db/index.js';
|
||||
import { eq, and, gte } from 'drizzle-orm';
|
||||
import { requireAuth } from '../lib/auth.js';
|
||||
import { generateId, getNow, toDbBool } from '../lib/utils.js';
|
||||
import { revalidateFrontendCache } from '../lib/revalidate.js';
|
||||
|
||||
interface UserContext {
|
||||
id: string;
|
||||
@@ -172,6 +173,11 @@ siteSettingsRouter.put('/', requireAuth(['admin']), zValidator('json', updateSit
|
||||
(db as any).select().from(siteSettings).where(eq((siteSettings as any).id, existing.id))
|
||||
);
|
||||
|
||||
// Revalidate frontend cache if featured event changed
|
||||
if (data.featuredEventId !== undefined) {
|
||||
revalidateFrontendCache();
|
||||
}
|
||||
|
||||
return c.json({ settings: updated, message: 'Settings updated successfully' });
|
||||
});
|
||||
|
||||
@@ -216,6 +222,9 @@ siteSettingsRouter.put('/featured-event', requireAuth(['admin']), zValidator('js
|
||||
|
||||
await (db as any).insert(siteSettings).values(newSettings);
|
||||
|
||||
// Revalidate frontend cache so homepage shows the updated featured event
|
||||
revalidateFrontendCache();
|
||||
|
||||
return c.json({ featuredEventId: eventId, message: eventId ? 'Event set as featured' : 'Featured event removed' });
|
||||
}
|
||||
|
||||
@@ -229,6 +238,9 @@ siteSettingsRouter.put('/featured-event', requireAuth(['admin']), zValidator('js
|
||||
})
|
||||
.where(eq((siteSettings as any).id, existing.id));
|
||||
|
||||
// Revalidate frontend cache so homepage shows the updated featured event
|
||||
revalidateFrontendCache();
|
||||
|
||||
return c.json({ featuredEventId: eventId, message: eventId ? 'Event set as featured' : 'Featured event removed' });
|
||||
});
|
||||
|
||||
|
||||
@@ -8,9 +8,9 @@ Type=simple
|
||||
User=spanglish
|
||||
Group=spanglish
|
||||
WorkingDirectory=/home/spanglish/Spanglish/backend
|
||||
EnvironmentFile=/home/spanglish/Spanglish/backend/.env
|
||||
Environment=NODE_ENV=production
|
||||
Environment=PORT=3018
|
||||
EnvironmentFile=/home/spanglish/Spanglish/backend/.env
|
||||
ExecStart=/usr/bin/node dist/index.js
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,7 @@ import {
|
||||
QrCodeIcon,
|
||||
CheckCircleIcon,
|
||||
XCircleIcon,
|
||||
XMarkIcon,
|
||||
MagnifyingGlassIcon,
|
||||
ArrowPathIcon,
|
||||
ClockIcon,
|
||||
@@ -76,86 +77,135 @@ function vibrate(pattern: number | number[]) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// ─── Stop all tracks on a media stream ───────────────────────
|
||||
function stopAllTracks() {
|
||||
try {
|
||||
// Find all video elements and stop their streams
|
||||
document.querySelectorAll('video').forEach((video) => {
|
||||
const stream = video.srcObject as MediaStream | null;
|
||||
if (stream) {
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
video.srcObject = null;
|
||||
}
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// ─── QR Scanner Component ────────────────────────────────────
|
||||
// This component fully mounts/unmounts — use a key prop externally
|
||||
// to force a fresh instance when the scan tab becomes active.
|
||||
function QRScanner({
|
||||
onScan,
|
||||
isActive,
|
||||
onActiveChange,
|
||||
onError,
|
||||
}: {
|
||||
onScan: (code: string) => void;
|
||||
isActive: boolean;
|
||||
onActiveChange: (active: boolean) => void;
|
||||
onError: () => void;
|
||||
}) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const scannerRef = useRef<any>(null);
|
||||
const scannerElementId = useRef(`qr-scanner-${Math.random().toString(36).substr(2, 9)}`);
|
||||
const mountedRef = useRef(true);
|
||||
const elementId = useRef(`qr-scanner-${Date.now()}`);
|
||||
const [facingMode, setFacingMode] = useState<'environment' | 'user'>('environment');
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (containerRef.current && !document.getElementById(scannerElementId.current)) {
|
||||
const scannerDiv = document.createElement('div');
|
||||
scannerDiv.id = scannerElementId.current;
|
||||
scannerDiv.style.width = '100%';
|
||||
containerRef.current.appendChild(scannerDiv);
|
||||
// Full cleanup helper
|
||||
const destroyScanner = useCallback(async () => {
|
||||
if (scannerRef.current) {
|
||||
try { await scannerRef.current.stop(); } catch {}
|
||||
try { scannerRef.current.clear(); } catch {}
|
||||
scannerRef.current = null;
|
||||
}
|
||||
return () => {
|
||||
if (scannerRef.current) {
|
||||
try { scannerRef.current.stop().catch(() => {}); } catch {}
|
||||
scannerRef.current = null;
|
||||
}
|
||||
};
|
||||
stopAllTracks();
|
||||
}, []);
|
||||
|
||||
// Start scanner on mount, destroy on unmount
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
let cancelled = false;
|
||||
|
||||
const startScanner = async () => {
|
||||
const elementId = scannerElementId.current;
|
||||
const element = document.getElementById(elementId);
|
||||
if (!element) return;
|
||||
const init = async () => {
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
// Create a fresh div for the scanner
|
||||
const id = elementId.current;
|
||||
container.innerHTML = '';
|
||||
const div = document.createElement('div');
|
||||
div.id = id;
|
||||
div.style.width = '100%';
|
||||
div.style.height = '100%';
|
||||
container.appendChild(div);
|
||||
|
||||
try {
|
||||
const { Html5Qrcode } = await import('html5-qrcode');
|
||||
if (cancelled) return;
|
||||
if (scannerRef.current) {
|
||||
try { await scannerRef.current.stop(); } catch {}
|
||||
scannerRef.current = null;
|
||||
}
|
||||
if (cancelled) return;
|
||||
|
||||
const scanner = new Html5Qrcode(elementId);
|
||||
const scanner = new Html5Qrcode(id);
|
||||
scannerRef.current = scanner;
|
||||
|
||||
await scanner.start(
|
||||
{ facingMode },
|
||||
{ fps: 10, qrbox: { width: 250, height: 250 }, aspectRatio: 1 },
|
||||
(decodedText: string) => onScan(decodedText),
|
||||
(decodedText: string) => {
|
||||
if (mountedRef.current) onScan(decodedText);
|
||||
},
|
||||
() => {}
|
||||
);
|
||||
|
||||
if (cancelled) {
|
||||
await destroyScanner();
|
||||
return;
|
||||
}
|
||||
|
||||
// Force layout recalculation after camera starts
|
||||
requestAnimationFrame(() => {
|
||||
if (container) {
|
||||
container.style.display = 'none';
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
||||
container.offsetHeight; // force reflow
|
||||
container.style.display = '';
|
||||
}
|
||||
if (mountedRef.current) setReady(true);
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('Scanner error:', error);
|
||||
if (!cancelled) {
|
||||
if (!cancelled && mountedRef.current) {
|
||||
toast.error('Failed to start camera. Check permissions.');
|
||||
onActiveChange(false);
|
||||
onError();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const stopScanner = async () => {
|
||||
if (scannerRef.current) {
|
||||
try { await scannerRef.current.stop(); } catch {}
|
||||
scannerRef.current = null;
|
||||
init();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
mountedRef.current = false;
|
||||
destroyScanner();
|
||||
};
|
||||
}, [facingMode]); // restart when camera flips
|
||||
|
||||
// Handle browser visibility change (suspend/resume)
|
||||
useEffect(() => {
|
||||
const handleVisibility = () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
destroyScanner();
|
||||
} else if (document.visibilityState === 'visible' && mountedRef.current) {
|
||||
// Re-trigger by flipping facingMode back-and-forth (forces useEffect re-run)
|
||||
setFacingMode((prev) => {
|
||||
// Toggle and toggle back to trigger the effect
|
||||
const temp = prev === 'environment' ? 'user' : 'environment';
|
||||
setTimeout(() => {
|
||||
if (mountedRef.current) setFacingMode(prev);
|
||||
}, 100);
|
||||
return temp;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (isActive) {
|
||||
startScanner();
|
||||
} else {
|
||||
stopScanner();
|
||||
}
|
||||
|
||||
return () => { cancelled = true; };
|
||||
}, [isActive, facingMode, onScan, onActiveChange]);
|
||||
document.addEventListener('visibilitychange', handleVisibility);
|
||||
return () => document.removeEventListener('visibilitychange', handleVisibility);
|
||||
}, [destroyScanner]);
|
||||
|
||||
const switchCamera = () => {
|
||||
setFacingMode((prev) => (prev === 'environment' ? 'user' : 'environment'));
|
||||
@@ -163,8 +213,11 @@ function QRScanner({
|
||||
|
||||
return (
|
||||
<div className="relative w-full bg-black flex-1 min-h-0 overflow-hidden">
|
||||
<div ref={containerRef} className="w-full h-full [&_video]:!object-cover [&_video]:!h-full" />
|
||||
{isActive && (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="w-full h-full [&_video]:!object-cover [&_video]:!h-full [&_video]:!w-full"
|
||||
/>
|
||||
{ready && (
|
||||
<button
|
||||
onClick={switchCamera}
|
||||
className="absolute top-3 right-3 z-10 bg-black/50 backdrop-blur-sm text-white p-2.5 rounded-full active:scale-95 transition-transform"
|
||||
@@ -173,7 +226,7 @@ function QRScanner({
|
||||
<VideoCameraIcon className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
{!isActive && (
|
||||
{!ready && (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
|
||||
<div className="text-center">
|
||||
<QrCodeIcon className="w-16 h-16 mx-auto mb-2 opacity-30" />
|
||||
@@ -189,15 +242,27 @@ function QRScanner({
|
||||
function ValidTicketScreen({
|
||||
validation,
|
||||
onConfirmCheckin,
|
||||
onClose,
|
||||
checkingIn,
|
||||
}: {
|
||||
validation: TicketValidationResult;
|
||||
onConfirmCheckin: () => void;
|
||||
onClose: () => void;
|
||||
checkingIn: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 bg-emerald-600 flex flex-col animate-in fade-in duration-200">
|
||||
<div className="flex-1 flex flex-col items-center justify-center px-6 text-white">
|
||||
{/* Close button (dismiss without check-in) */}
|
||||
<div className="flex justify-end p-4">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 rounded-full bg-white/20 text-white active:scale-95 transition-transform"
|
||||
aria-label="Close"
|
||||
>
|
||||
<XMarkIcon className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 flex flex-col items-center justify-center px-6 -mt-14 text-white">
|
||||
<div className="w-24 h-24 rounded-full bg-white/20 flex items-center justify-center mb-6">
|
||||
<CheckCircleIcon className="w-16 h-16 text-white" />
|
||||
</div>
|
||||
@@ -581,7 +646,7 @@ export default function AdminScannerPage() {
|
||||
const [activeTab, setActiveTab] = useState<ActiveTab>('scan');
|
||||
|
||||
// Scanner state
|
||||
const [cameraActive, setCameraActive] = useState(false);
|
||||
const [scannerKey, setScannerKey] = useState(0); // increment to force remount
|
||||
const [scanResult, setScanResult] = useState<ScanResultData>({ state: 'idle' });
|
||||
const [lastScannedCode, setLastScannedCode] = useState('');
|
||||
const [checkingIn, setCheckingIn] = useState(false);
|
||||
@@ -638,21 +703,8 @@ export default function AdminScannerPage() {
|
||||
loadStats();
|
||||
}, [selectedEventId]);
|
||||
|
||||
// Auto-start camera on page load (Scan tab)
|
||||
useEffect(() => {
|
||||
if (!loading && activeTab === 'scan') {
|
||||
setCameraActive(true);
|
||||
}
|
||||
}, [loading, activeTab]);
|
||||
|
||||
// Pause camera when switching away from scan tab
|
||||
useEffect(() => {
|
||||
if (activeTab !== 'scan') {
|
||||
setCameraActive(false);
|
||||
} else if (scanResult.state === 'idle') {
|
||||
setCameraActive(true);
|
||||
}
|
||||
}, [activeTab, scanResult.state]);
|
||||
// When scan tab becomes active again or scan result is dismissed, bump key to remount scanner
|
||||
const scannerActive = activeTab === 'scan' && scanResult.state === 'idle' && !loading;
|
||||
|
||||
// Validate ticket
|
||||
const validateTicket = useCallback(async (code: string) => {
|
||||
@@ -690,7 +742,6 @@ export default function AdminScannerPage() {
|
||||
if (decodedText === lastScannedCodeRef.current) return;
|
||||
lastScannedCodeRef.current = decodedText;
|
||||
setLastScannedCode(decodedText);
|
||||
setCameraActive(false);
|
||||
|
||||
let code = decodedText;
|
||||
const urlMatch = decodedText.match(/\/ticket\/([a-zA-Z0-9-_]+)/);
|
||||
@@ -768,12 +819,12 @@ export default function AdminScannerPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Reset scan state
|
||||
// Reset scan state — bump key so scanner fully remounts
|
||||
const resetScan = () => {
|
||||
setScanResult({ state: 'idle' });
|
||||
setLastScannedCode('');
|
||||
lastScannedCodeRef.current = '';
|
||||
if (activeTab === 'scan') setCameraActive(true);
|
||||
setScannerKey((k) => k + 1);
|
||||
};
|
||||
|
||||
// Get selected event name
|
||||
@@ -788,7 +839,7 @@ export default function AdminScannerPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 flex flex-col h-screen max-h-screen overflow-hidden">
|
||||
<div className="bg-gray-950 flex flex-col overflow-hidden" style={{ height: '100dvh' }}>
|
||||
{/* ── Sticky Header ── */}
|
||||
<header className="flex-shrink-0 bg-gray-900 border-b border-gray-800 px-4 py-3 safe-area-top">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
@@ -864,14 +915,17 @@ export default function AdminScannerPage() {
|
||||
|
||||
{/* ── Tab Content ── */}
|
||||
<div className="flex-1 min-h-0 flex flex-col overflow-hidden">
|
||||
{/* SCAN TAB */}
|
||||
{activeTab === 'scan' && (
|
||||
{/* SCAN TAB — scanner fully unmounts when not active */}
|
||||
{scannerActive && (
|
||||
<QRScanner
|
||||
isActive={cameraActive && scanResult.state === 'idle'}
|
||||
key={scannerKey}
|
||||
onScan={handleScan}
|
||||
onActiveChange={setCameraActive}
|
||||
onError={() => {}}
|
||||
/>
|
||||
)}
|
||||
{activeTab === 'scan' && !scannerActive && scanResult.state !== 'idle' && (
|
||||
<div className="flex-1 bg-black" />
|
||||
)}
|
||||
|
||||
{/* SEARCH TAB */}
|
||||
{activeTab === 'search' && (
|
||||
@@ -889,6 +943,7 @@ export default function AdminScannerPage() {
|
||||
<ValidTicketScreen
|
||||
validation={scanResult.validation}
|
||||
onConfirmCheckin={handleCheckin}
|
||||
onClose={resetScan}
|
||||
checkingIn={checkingIn}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -28,7 +28,7 @@ interface LlmsEvent {
|
||||
async function getNextUpcomingEvent(): Promise<LlmsEvent | null> {
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}/api/events/next/upcoming`, {
|
||||
next: { tags: ['next-event'] },
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const data = await response.json();
|
||||
@@ -41,7 +41,7 @@ async function getNextUpcomingEvent(): Promise<LlmsEvent | null> {
|
||||
async function getUpcomingEvents(): Promise<LlmsEvent[]> {
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}/api/events?status=published&upcoming=true`, {
|
||||
next: { tags: ['next-event'] },
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!response.ok) return [];
|
||||
const data = await response.json();
|
||||
@@ -115,7 +115,7 @@ function getEventStatus(event: LlmsEvent): string {
|
||||
async function getHomepageFaqs(): Promise<LlmsFaq[]> {
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}/api/faq?homepage=true`, {
|
||||
next: { revalidate: 3600 },
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!response.ok) return [];
|
||||
const data = await response.json();
|
||||
@@ -128,6 +128,8 @@ async function getHomepageFaqs(): Promise<LlmsFaq[]> {
|
||||
}
|
||||
}
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET() {
|
||||
const [nextEvent, upcomingEvents, faqs] = await Promise.all([
|
||||
getNextUpcomingEvent(),
|
||||
|
||||
@@ -373,16 +373,17 @@ export const adminApi = {
|
||||
return fetchApi<{ payments: ExportedPayment[]; summary: FinancialSummary }>(`/api/admin/export/financial?${query}`);
|
||||
},
|
||||
/** Download attendee export as a file (CSV). Returns a Blob. */
|
||||
exportAttendees: async (eventId: string, params?: { status?: string; format?: string }) => {
|
||||
exportAttendees: async (eventId: string, params?: { status?: string; format?: string; q?: string }) => {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.status) query.set('status', params.status);
|
||||
if (params?.format) query.set('format', params.format);
|
||||
if (params?.q) query.set('q', params.q);
|
||||
const token = typeof window !== 'undefined'
|
||||
? localStorage.getItem('spanglish-token')
|
||||
: null;
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
const res = await fetch(`${API_BASE}/api/admin/events/${eventId}/export?${query}`, { headers });
|
||||
const res = await fetch(`${API_BASE}/api/admin/events/${eventId}/attendees/export?${query}`, { headers });
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({ error: 'Export failed' }));
|
||||
throw new Error(errorData.error || 'Export failed');
|
||||
@@ -393,6 +394,27 @@ export const adminApi = {
|
||||
const blob = await res.blob();
|
||||
return { blob, filename };
|
||||
},
|
||||
/** Download tickets export as CSV. Returns a Blob. */
|
||||
exportTicketsCSV: async (eventId: string, params?: { status?: string; q?: string }) => {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.status) query.set('status', params.status);
|
||||
if (params?.q) query.set('q', params.q);
|
||||
const token = typeof window !== 'undefined'
|
||||
? localStorage.getItem('spanglish-token')
|
||||
: null;
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
const res = await fetch(`${API_BASE}/api/admin/events/${eventId}/tickets/export?${query}`, { headers });
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({ error: 'Export failed' }));
|
||||
throw new Error(errorData.error || 'Export failed');
|
||||
}
|
||||
const disposition = res.headers.get('Content-Disposition') || '';
|
||||
const filenameMatch = disposition.match(/filename="?([^"]+)"?/);
|
||||
const filename = filenameMatch ? filenameMatch[1] : `tickets-${new Date().toISOString().split('T')[0]}.csv`;
|
||||
const blob = await res.blob();
|
||||
return { blob, filename };
|
||||
},
|
||||
};
|
||||
|
||||
// Emails API
|
||||
|
||||
Reference in New Issue
Block a user