7 Commits

Author SHA1 Message Date
15655e3987 Merge pull request 'dev' (#12) from dev into main
Reviewed-on: #12
2026-02-16 23:11:52 +00:00
Michilis
5263fa6834 Make llms.txt always fetch fresh data from the backend
- Switch from tag-based caching to cache: no-store for all backend fetches
- Add dynamic = force-dynamic to prevent Next.js static caching
- Ensures llms.txt always reflects the current featured event and FAQ data

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 23:10:33 +00:00
Michilis
923c86a3b3 Fix FRONTEND_URL pointing to wrong port, breaking cache revalidation
- Update FRONTEND_URL default from localhost:3002 to localhost:3019 (actual frontend port)
- Reorder systemd service so EnvironmentFile loads before Environment overrides

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 22:53:59 +00:00
d8b3864411 Merge pull request 'Fix stale featured event on homepage: revalidate cache when featured event changes' (#11) from dev into main
Reviewed-on: #11
2026-02-16 22:44:19 +00:00
Michilis
4aaffe99c7 Fix stale featured event on homepage: revalidate cache when featured event changes
- Extract revalidateFrontendCache() to backend/src/lib/revalidate.ts
- Call revalidation from site-settings when featuredEventId is set/cleared
- Ensures homepage shows updated featured event after admin changes

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 22:42:55 +00:00
194cbd6ca8 Merge pull request 'Scanner: close button on valid ticket, camera lifecycle fix' (#10) from dev into main
Reviewed-on: #10
2026-02-14 19:04:42 +00:00
Michilis
a11da5a977 Scanner: close button on valid ticket, camera lifecycle fix
- Add X close button on valid ticket screen to dismiss without check-in
- Rewrite QRScanner: full unmount when leaving Scan tab, stop MediaStream tracks
- Remount scanner via key when tab active; no hidden DOM
- Use 100dvh for mobile height; force layout reflow after camera start
- visibilitychange handler for tab suspend/resume

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-14 19:03:29 +00:00
7 changed files with 167 additions and 98 deletions

View File

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

View 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);
});
}

View File

@@ -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) {

View File

@@ -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' });
});

View File

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

View File

@@ -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}
/>
)}

View File

@@ -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(),