feat: add QR code event check-in system

Backend:
- Add event_checkin_tokens table with unique tokens per event
- Implement GET /api/events/:slug/details endpoint (on-demand token generation)
- Implement POST /api/events/checkin/:token endpoint (date validation only in production)
- Implement DELETE /api/events/:slug/leave endpoint
- Add comprehensive test suite for check-in endpoints

Frontend:
- Add EventDetailsPage with QR code display, participant list, and stats
- Add EventCheckinPage with success/error screens
- Add "Leave Event" button with confirmation modal to EventChatPage
- Install qrcode.react library for QR code generation
- Update routing and API client with new endpoints

Features:
- QR codes valid from (startDate-1d) to (endDate+1d)
- Development mode bypasses date validation for testing
- Automatic participant count tracking
- Duplicate check-in prevention
- Token reuse for same event (generated once, cached)
This commit is contained in:
Radosław Gierwiało
2025-11-14 14:11:24 +01:00
parent 5bea2ad133
commit 71cba01db3
11 changed files with 1095 additions and 1 deletions

View File

@@ -2,7 +2,7 @@ import { useState, useRef, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import Layout from '../components/layout/Layout';
import { useAuth } from '../contexts/AuthContext';
import { Send, UserPlus, Loader2 } from 'lucide-react';
import { Send, UserPlus, Loader2, LogOut, AlertTriangle } from 'lucide-react';
import { connectSocket, disconnectSocket, getSocket } from '../services/socket';
import { eventsAPI } from '../services/api';
@@ -18,6 +18,8 @@ const EventChatPage = () => {
const [isConnected, setIsConnected] = useState(false);
const [loadingOlder, setLoadingOlder] = useState(false);
const [hasMore, setHasMore] = useState(true);
const [showLeaveModal, setShowLeaveModal] = useState(false);
const [isLeaving, setIsLeaving] = useState(false);
const messagesEndRef = useRef(null);
const messagesContainerRef = useRef(null);
@@ -173,6 +175,28 @@ const EventChatPage = () => {
}, 1000);
};
const handleLeaveEvent = async () => {
try {
setIsLeaving(true);
await eventsAPI.leave(slug);
// Disconnect socket
const socket = getSocket();
if (socket) {
socket.emit('leave_event_room');
}
// Redirect to events page
navigate('/events');
} catch (error) {
console.error('Failed to leave event:', error);
alert('Failed to leave event. Please try again.');
} finally {
setIsLeaving(false);
setShowLeaveModal(false);
}
};
// Infinite scroll - detect scroll to top
useEffect(() => {
const container = messagesContainerRef.current;
@@ -344,7 +368,67 @@ const EventChatPage = () => {
</div>
</div>
</div>
{/* Leave Event Button */}
<div className="mt-4 flex justify-center">
<button
onClick={() => setShowLeaveModal(true)}
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors font-medium"
>
<LogOut size={16} />
Leave Event
</button>
</div>
</div>
{/* Leave Confirmation Modal */}
{showLeaveModal && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
<div className="flex items-center gap-3 mb-4">
<div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center">
<AlertTriangle className="text-red-600" size={24} />
</div>
<div>
<h3 className="text-lg font-semibold text-gray-900">Leave Event?</h3>
<p className="text-sm text-gray-600">This action cannot be undone</p>
</div>
</div>
<p className="text-gray-700 mb-6">
Are you sure you want to leave <strong>{event.name}</strong>?
You will need to scan the QR code again to rejoin.
</p>
<div className="flex gap-3">
<button
onClick={() => setShowLeaveModal(false)}
disabled={isLeaving}
className="flex-1 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors font-medium disabled:opacity-50"
>
Cancel
</button>
<button
onClick={handleLeaveEvent}
disabled={isLeaving}
className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors font-medium disabled:opacity-50 flex items-center justify-center gap-2"
>
{isLeaving ? (
<>
<Loader2 className="animate-spin" size={16} />
Leaving...
</>
) : (
<>
<LogOut size={16} />
Leave Event
</>
)}
</button>
</div>
</div>
</div>
)}
</div>
</Layout>
);

View File

@@ -0,0 +1,154 @@
import { useState, useEffect } from 'react';
import { useParams, useNavigate, useLocation, Link } from 'react-router-dom';
import { CheckCircle, XCircle, Calendar, MapPin, Loader } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { eventsAPI } from '../services/api';
export default function EventCheckinPage() {
const { token } = useParams();
const navigate = useNavigate();
const location = useLocation();
const { user } = useAuth();
const [loading, setLoading] = useState(true);
const [success, setSuccess] = useState(false);
const [alreadyCheckedIn, setAlreadyCheckedIn] = useState(false);
const [eventData, setEventData] = useState(null);
const [error, setError] = useState('');
useEffect(() => {
// Redirect to login if not authenticated
if (!user) {
navigate('/login', {
state: { from: location.pathname },
replace: true,
});
return;
}
// Perform check-in
performCheckin();
}, [user]);
const performCheckin = async () => {
try {
setLoading(true);
const response = await eventsAPI.checkin(token);
if (response.success) {
setSuccess(true);
setAlreadyCheckedIn(response.alreadyCheckedIn);
setEventData(response.data.event);
}
} catch (err) {
console.error('Check-in error:', err);
setError(err.message || 'Failed to check in to event');
} finally {
setLoading(false);
}
};
const formatDate = (dateString) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
};
if (loading) {
return (
<div className="min-h-screen bg-gradient-to-br from-primary-50 to-primary-100 flex items-center justify-center p-6">
<div className="bg-white rounded-lg shadow-xl p-8 max-w-md w-full text-center">
<Loader className="animate-spin mx-auto mb-4 text-primary-600" size={48} />
<h2 className="text-2xl font-bold text-gray-900 mb-2">
Checking you in...
</h2>
<p className="text-gray-600">Please wait while we process your check-in</p>
</div>
</div>
);
}
if (error) {
return (
<div className="min-h-screen bg-gradient-to-br from-red-50 to-red-100 flex items-center justify-center p-6">
<div className="bg-white rounded-lg shadow-xl p-8 max-w-md w-full">
<div className="text-center mb-6">
<XCircle className="mx-auto mb-4 text-red-600" size={64} />
<h2 className="text-2xl font-bold text-gray-900 mb-2">
Check-in Failed
</h2>
<p className="text-gray-600">{error}</p>
</div>
<div className="space-y-3">
<Link
to="/events"
className="block w-full bg-primary-600 text-white px-6 py-3 rounded-lg hover:bg-primary-700 transition-colors text-center font-medium"
>
Back to Events
</Link>
</div>
</div>
</div>
);
}
if (success && eventData) {
return (
<div className="min-h-screen bg-gradient-to-br from-green-50 to-green-100 flex items-center justify-center p-6">
<div className="bg-white rounded-lg shadow-xl p-8 max-w-md w-full">
<div className="text-center mb-6">
<CheckCircle className="mx-auto mb-4 text-green-600" size={64} />
<h2 className="text-2xl font-bold text-gray-900 mb-2">
{alreadyCheckedIn ? 'Already Checked In!' : 'Check-in Successful!'}
</h2>
<p className="text-gray-600">
{alreadyCheckedIn
? 'You are already a participant of this event'
: 'You have successfully joined this event'}
</p>
</div>
{/* Event Info */}
<div className="bg-gray-50 rounded-lg p-4 mb-6">
<h3 className="font-semibold text-lg text-gray-900 mb-3">
{eventData.name}
</h3>
<div className="space-y-2 text-sm text-gray-600">
<div className="flex items-center gap-2">
<MapPin size={16} className="text-gray-400" />
<span>{eventData.location}</span>
</div>
<div className="flex items-center gap-2">
<Calendar size={16} className="text-gray-400" />
<span>
{formatDate(eventData.startDate)} - {formatDate(eventData.endDate)}
</span>
</div>
</div>
</div>
{/* Actions */}
<div className="space-y-3">
<Link
to={`/events/${eventData.slug}/chat`}
className="block w-full bg-primary-600 text-white px-6 py-3 rounded-lg hover:bg-primary-700 transition-colors text-center font-medium"
>
Go to Event Chat
</Link>
<Link
to="/events"
className="block w-full border border-gray-300 px-6 py-3 rounded-lg hover:bg-gray-50 transition-colors text-center font-medium text-gray-700"
>
Browse Other Events
</Link>
</div>
</div>
</div>
);
}
return null;
}

View File

@@ -0,0 +1,248 @@
import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { QRCodeSVG } from 'qrcode.react';
import { Copy, Check, Users, Calendar, MapPin, QrCode } from 'lucide-react';
import Layout from '../components/layout/Layout';
import { eventsAPI } from '../services/api';
export default function EventDetailsPage() {
const { slug } = useParams();
const [eventDetails, setEventDetails] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [copied, setCopied] = useState(false);
useEffect(() => {
fetchEventDetails();
}, [slug]);
const fetchEventDetails = async () => {
try {
setLoading(true);
const response = await eventsAPI.getDetails(slug);
setEventDetails(response.data);
} catch (err) {
console.error('Error loading event details:', err);
setError(err.message || 'Failed to load event details');
} finally {
setLoading(false);
}
};
const copyToClipboard = async () => {
try {
await navigator.clipboard.writeText(eventDetails.checkin.url);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
};
const formatDate = (dateString) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
};
if (loading) {
return (
<Layout>
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
<p className="mt-4 text-gray-600">Loading event details...</p>
</div>
</div>
</Layout>
);
}
if (error) {
return (
<Layout>
<div className="max-w-4xl mx-auto p-6">
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
<p className="text-red-800">{error}</p>
<Link to="/events" className="text-red-600 hover:underline mt-2 inline-block">
Back to Events
</Link>
</div>
</div>
</Layout>
);
}
if (!eventDetails) {
return null;
}
const { event, checkin, participants, stats } = eventDetails;
return (
<Layout>
<div className="max-w-6xl mx-auto p-6">
{/* Header */}
<div className="mb-6">
<Link to="/events" className="text-primary-600 hover:underline mb-2 inline-block">
&larr; Back to Events
</Link>
<h1 className="text-3xl font-bold text-gray-900">{event.name}</h1>
<div className="flex items-center gap-4 mt-2 text-gray-600">
<div className="flex items-center gap-1">
<MapPin size={16} />
<span>{event.location}</span>
</div>
<div className="flex items-center gap-1">
<Calendar size={16} />
<span>{formatDate(event.startDate)} - {formatDate(event.endDate)}</span>
</div>
</div>
</div>
<div className="grid md:grid-cols-2 gap-6">
{/* QR Code Section */}
<div className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
<QrCode className="text-primary-600" />
Event Check-in QR Code
</h2>
{/* QR Code Display */}
<div className="bg-white p-6 rounded-lg border-2 border-gray-200 mb-4 flex justify-center">
<QRCodeSVG
value={checkin.url}
size={256}
level="H"
includeMargin={true}
/>
</div>
{/* Check-in URL */}
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700 mb-2">
Check-in Link
</label>
<div className="flex gap-2">
<input
type="text"
value={checkin.url}
readOnly
className="flex-1 px-3 py-2 border border-gray-300 rounded-md bg-gray-50 text-sm"
/>
<button
onClick={copyToClipboard}
className="px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 transition-colors flex items-center gap-2"
>
{copied ? <Check size={16} /> : <Copy size={16} />}
{copied ? 'Copied!' : 'Copy'}
</button>
</div>
</div>
{/* Valid Dates */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm">
<p className="font-medium text-blue-900 mb-1">Valid Period</p>
<p className="text-blue-700">
{formatDate(checkin.validFrom)} - {formatDate(checkin.validUntil)}
</p>
{process.env.NODE_ENV === 'development' && (
<p className="text-blue-600 mt-2 text-xs">
Development mode: Date validation disabled
</p>
)}
</div>
</div>
{/* Participants Section */}
<div className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
<Users className="text-primary-600" />
Participants ({stats.totalParticipants})
</h2>
{participants.length === 0 ? (
<div className="text-center py-8 text-gray-500">
<Users size={48} className="mx-auto mb-2 text-gray-300" />
<p>No participants yet</p>
<p className="text-sm">Share the QR code to get started!</p>
</div>
) : (
<div className="space-y-3 max-h-[500px] overflow-y-auto">
{participants.map((participant) => (
<div
key={participant.userId}
className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
>
{/* Avatar */}
<div className="w-10 h-10 rounded-full bg-primary-600 flex items-center justify-center text-white font-semibold">
{participant.avatar ? (
<img
src={participant.avatar}
alt={participant.username}
className="w-10 h-10 rounded-full object-cover"
/>
) : (
<span>{participant.username.charAt(0).toUpperCase()}</span>
)}
</div>
{/* User Info */}
<div className="flex-1">
<p className="font-medium text-gray-900">
{participant.firstName && participant.lastName
? `${participant.firstName} ${participant.lastName}`
: participant.username}
</p>
<p className="text-sm text-gray-600">@{participant.username}</p>
</div>
{/* Joined Date */}
<div className="text-xs text-gray-500">
{new Date(participant.joinedAt).toLocaleDateString()}
</div>
</div>
))}
</div>
)}
</div>
</div>
{/* Action Buttons */}
<div className="mt-6 flex gap-4">
<Link
to={`/events/${slug}/chat`}
className="flex-1 bg-primary-600 text-white px-6 py-3 rounded-lg hover:bg-primary-700 transition-colors text-center font-medium"
>
Go to Event Chat
</Link>
<button
onClick={() => window.print()}
className="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors font-medium"
>
Print QR Code
</button>
</div>
{/* Print Styles */}
<style>{`
@media print {
body * {
visibility: hidden;
}
.print-area, .print-area * {
visibility: visible;
}
.print-area {
position: absolute;
left: 0;
top: 0;
}
}
`}</style>
</div>
</Layout>
);
}