File: //srv/rmgun_admin/admin-next/claude_tasks.md
# RMGun Range Admin - RFID Scanner Integration
This document outlines the implementation requirements for the RFID scanner integration with the RMGun Range Admin system.
## 📋 PROJECT CONTEXT
The application has been successfully refactored with:
- Complete modular architecture (6 feature modules)
- Configuration-driven navigation and routing
- Full Polish translation support
- Enhanced service layer with error handling
- Reusable component library
## 🎯 NEW REQUIREMENTS: RFID SCANNER INTEGRATION
### Overview
Integrate RFID card scanning functionality with a Raspberry Pi 5 to automate user check-in/check-out at the shooting range.
### Business Logic
#### 1. Card Scanning Flow
When an RFID card is scanned:
1. **Card with Associated User ID**:
   - If NO registration exists in the last 2-3 hours:
     - Create a NEW registration entry with check-in time
   - If a registration EXISTS within the last 2-3 hours:
     - Update the existing registration with check-out time
   - If scanning after check-out is already set:
     - Create a NEW registration entry (new session)
2. **Card with Unknown ID**:
   - If the ID is not default (need to determine what's default: 0, null, empty?)
   - Add to "unassigned cards" list
   - Allow admin to associate the card with a user later
3. **Invalid/Default Card**:
   - Log the attempt but don't create any records
### Technical Requirements
#### API Endpoint(s)
Single endpoint recommended: `POST /api/rfid/scan`
**Request Body**:
```json
{
  "cardId": "string (required)",
  "deviceId": "string (optional - to identify which scanner)"
}
```
**Response**:
```json
{
  "success": boolean,
  "action": "check_in" | "check_out" | "unassigned" | "invalid",
  "registration": { /* registration data if applicable */ },
  "user": { /* user data if found */ },
  "message": "string (Polish translation key)"
}
```
#### Database Schema
**New Collection: `rfid_cards`**
```typescript
interface RfidCard {
  id: string;
  cardId: string; // The RFID tag ID
  userId: string | null; // Associated user ID
  assignedAt: Timestamp | null;
  assignedBy: string | null; // Admin who assigned it
  createdAt: Timestamp;
  lastScanned: Timestamp;
  scanCount: number;
  isActive: boolean;
}
```
**Updated `registrations` Collection**
Add fields:
- `checkInMethod: 'manual' | 'rfid'`
- `rfidCardId?: string`
#### Module Structure
```
src/features/rfid/
├── components/
│   ├── card-assignment-dialog.tsx    // Assign unassigned cards to users
│   ├── unassigned-cards-list.tsx     // List of cards awaiting assignment
│   ├── user-cards-table.tsx          // Manage user's RFID cards
│   └── scan-history.tsx              // Recent RFID scan attempts
├── services/
│   ├── rfid-service.ts               // RFID business logic
│   └── scan-processor.ts             // Process scan requests
├── types/
│   └── rfid.types.ts                 // TypeScript interfaces
└── index.ts                          // Module exports
```
#### Business Rules Configuration
Add to `app-config.ts`:
```typescript
rfid: {
  checkInWindowHours: 3,        // Hours to look back for existing registration
  defaultCardIds: ['0', ''],    // IDs to ignore as default/invalid
  scanCooldownMs: 1000,         // Prevent rapid duplicate scans
  maxCardsPerUser: 5,           // Limit cards per user
}
```
### UI Components Needed
1. **RFID Cards Management Page** (`/rfid-cards`)
   - Tab 1: Unassigned Cards List
     - Show all unassigned card IDs
     - Quick assign button
     - Last scanned timestamp
   - Tab 2: All Cards
     - Search by card ID or user
     - Bulk operations
     - Export to CSV
2. **User Profile Enhancement**
   - Add "RFID Cards" section to user details
   - Allow adding/removing cards
   - Show card scan history
3. **Dashboard Widget**
   - Recent RFID scans (last 10)
   - Quick stats (total cards, unassigned count)
### Implementation Tasks
## 📋 TASKS TO COMPLETE
### Priority 1: Core RFID Functionality
1. **Database Setup**
   - Create `rfid_cards` collection schema
   - Update `registrations` collection schema
   - Add indexes for performance
2. **API Development**
   - Create `/api/rfid/scan` endpoint
   - Implement scan processing logic
   - Add rate limiting for security
3. **Service Layer**
   - Create `RfidService` extending `BaseService`
   - Implement card assignment logic
   - Add scan history tracking
### Priority 2: Admin UI
1. **RFID Module Creation**
   - Create feature module structure
   - Build unassigned cards list
   - Implement card assignment dialog
2. **Integration Updates**
   - Add RFID section to user management
   - Update registration list to show check-in method
   - Add RFID stats to dashboard
### Priority 3: Polish & Documentation
1. **Translations**
   - Add Polish translations for all RFID features
   - Update existing translations for new fields
2. **Testing & Documentation**
   - Document API for Raspberry Pi integration
   - Create setup guide for hardware
   - Add configuration examples
## 🔧 TECHNICAL DECISIONS
### Single vs Multiple Endpoints
**Recommendation**: Single endpoint `/api/rfid/scan`
- Simpler for Raspberry Pi client
- All logic centralized in one place
- Easier to maintain and debug
### Registration Window Logic
- Use 3-hour window (configurable)
- Check for most recent registration first
- If found and no checkout: add checkout time
- Otherwise: create new registration
### Security Considerations
- Rate limit scanning endpoint
- Validate card IDs (format, length)
- Log all scan attempts for audit
- Require admin role for card management
## 📊 IMPLEMENTATION PLAN
### Phase 1: Backend (4-6 hours) ✅ COMPLETED
- [x] Create RFID types and schemas
- [x] Implement scan endpoint
- [x] Build RfidService with business logic
- [x] Add scan processing with registration logic
### Phase 2: Frontend (6-8 hours) ✅ COMPLETED
- [x] Create RFID feature module
- [x] Build unassigned cards list
- [x] Implement card assignment UI
- [x] Integrate with user management
- [x] Add dashboard widgets
### Phase 3: Polish & Testing (2-3 hours) ✅ COMPLETED
- [x] Add all Polish translations
- [x] Create API documentation (in code)
- [x] Implement error handling
- [x] Add rate limiting
## 🎯 SUCCESS CRITERIA
1. Raspberry Pi can successfully send scan data
2. Check-in/check-out logic works correctly
3. Unassigned cards are tracked and manageable
4. UI provides clear visibility of RFID activity
5. System handles edge cases gracefully
## ✅ IMPLEMENTATION COMPLETED
### What Was Built:
1. **Backend Implementation**:
   - Created `rfid_cards` collection schema with full TypeScript types
   - Implemented `/api/rfid/scan` endpoint with rate limiting
   - Built `RfidService` with card management functionality
   - Created `ScanProcessor` with check-in/check-out logic
   - Added RFID configuration to app-config.ts
2. **Frontend Components**:
   - **RFID Cards Management Page** (`/rfid-cards`) with tabs for:
     - Unassigned cards list with assignment functionality
     - All cards table with user associations
   - **Dashboard Integration**:
     - RFID stats cards (total cards, unassigned count)
     - Recent scan history widget
   - **Card Assignment Dialog** for associating cards with users
3. **Business Logic**:
   - 3-hour check-in window for automatic check-out
   - Unassigned card tracking and management
   - Rate limiting to prevent scan spam
   - Support for invalid/default card IDs
4. **Polish & Integration**:
   - Complete Polish translations for all RFID features
   - Navigation menu item added
   - Error handling and user feedback
   - TypeScript types throughout
### API Documentation for Raspberry Pi:
**Endpoint**: `POST /api/rfid/scan`
**Request**:
```json
{
  "cardId": "string (required)",
  "deviceId": "string (optional)"
}
```
**Response**:
```json
{
  "success": boolean,
  "action": "check_in" | "check_out" | "unassigned" | "invalid",
  "registration": { /* if applicable */ },
  "user": { /* if applicable */ },
  "message": "translation key"
}
```
**Rate Limiting**: 1 scan per card per second
---
**Created**: 2025-08-03
**Completed**: 2025-08-03
**Status**: ✅ COMPLETED
**Actual Time**: ~3 hours