Initial Commit

This commit is contained in:
2025-11-16 16:00:51 +00:00
commit ba324b370e
52 changed files with 8014 additions and 0 deletions

View File

@@ -0,0 +1,809 @@
# Beach Litter Mapping Platform - Design Document
## Overview
The Beach Litter Mapping Platform is a full-stack web application that enables crowdsourced environmental monitoring of Irish coastal areas. The system combines modern web technologies with geospatial data processing to create an interactive platform for reporting, visualizing, and addressing beach litter and environmental concerns.
### Technology Stack
**Frontend:**
- React 18+ with TypeScript for type-safe component development
- Vite for build tooling
- Clerk React SDK (@clerk/clerk-react) for authentication
- Leaflet.js for interactive mapping (free, open-source alternative to Google Maps)
- OpenStreetMap tiles as the base map layer (free)
- Leaflet.heat plugin for heat map visualization
- Leaflet.markercluster for marker clustering
- React Query for server state management
- Tailwind CSS for responsive styling
**Backend:**
- Node.js with Express.js for REST API
- MySQL 8.0+ for database with spatial data support
- Prisma ORM for database access and migrations (or Sequelize as alternative)
- Clerk for authentication and user management
- Multer for file upload handling
- exifr library for EXIF metadata extraction
- Node-cron for scheduled tasks (hotspot calculations, notifications)
**Infrastructure:**
- Cloud storage (AWS S3 or Cloudinary) for photo storage
- Redis for caching external API responses
- Email service (SendGrid or similar) for notifications
**External APIs:**
- OpenWeatherMap API (free tier) for weather data
- WorldTides API or NOAA for tide information
- Irish EPA Open Data Portal for water quality
- OpenStreetMap Nominatim for reverse geocoding
## Architecture
### System Architecture Diagram
```
┌─────────────────────────────────────────────────────────────┐
│ Client Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Map View │ │ Report Form │ │ Analytics │ │
│ │ (Leaflet) │ │ │ │ Dashboard │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Event Mgmt │ │ User Profile │ │ Notifications│ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
│ HTTPS/REST API
▼
┌─────────────────────────────────────────────────────────────┐
│ API Gateway Layer │
│ (Express.js Router) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Auth │ │ Rate Limiting│ │ Validation │ │
│ │ Middleware │ │ │ │ │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Service Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Report │ │ Event │ │ Analytics │ │
│ │ Service │ │ Service │ │ Service │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ User │ │ Notification │ │ External API │ │
│ │ Service │ │ Service │ │ Service │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Data Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ PostgreSQL │ │ Redis Cache │ │ Cloud Storage│ │
│ │ + PostGIS │ │ │ │ (Photos) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ External Services │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Weather API │ │ Tide API │ │ EPA Data │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
### Design Patterns
1. **Repository Pattern**: Abstracts data access logic from business logic
2. **Service Layer Pattern**: Encapsulates business logic separate from API routes
3. **Dependency Injection**: Services receive dependencies through constructors
4. **Factory Pattern**: For creating complex objects like notifications
5. **Observer Pattern**: For event-driven notifications
## Components and Interfaces
### Frontend Components
#### 1. Map Interface Component
**Purpose**: Interactive map displaying litter reports and environmental data
**Key Features**:
- Leaflet map with OpenStreetMap tiles
- Custom marker icons for different litter types
- Marker clustering for dense areas
- Heat map overlay toggle
- Filter controls (date, type, quantity)
- Click handlers for marker details
- Geolocation button for user positioning
**Props Interface**:
```typescript
interface MapInterfaceProps {
reports: LitterReport[];
events: CleanupEvent[];
filters: FilterState;
onMarkerClick: (reportId: string) => void;
onMapClick: (lat: number, lng: number) => void;
showHeatmap: boolean;
showClusters: boolean;
}
```
#### 2. Report Form Component
**Purpose**: Multi-step form for submitting litter reports
**Key Features**:
- Photo upload with drag-and-drop
- EXIF metadata extraction on upload
- Location selection (auto from EXIF, device GPS, or map picker)
- Litter categorization dropdown
- Quantity estimation slider
- Optional description textarea
- Form validation
- Progress indicator
**Props Interface**:
```typescript
interface ReportFormProps {
onSubmit: (report: CreateReportDTO) => Promise<void>;
initialLocation?: Coordinates;
onCancel: () => void;
}
```
#### 3. Analytics Dashboard Component
**Purpose**: Data visualization and statistics display
**Key Features**:
- Chart.js or Recharts for data visualization
- Time series charts for report trends
- Pie charts for litter type distribution
- Summary statistics cards
- Date range selector
- Export to CSV button
- Comparison metrics (vs previous period)
#### 4. Event Management Component
**Purpose**: Create and manage cleanup events
**Key Features**:
- Event creation form
- Calendar date/time picker
- Location selector on map
- Participant list display
- Registration button
- Event completion form
- Photo gallery of cleanup results
#### 5. User Profile Component
**Purpose**: Display user contributions and impact
**Key Features**:
- User statistics (reports submitted, events attended)
- Impact score calculation and display
- Personal map of contributions
- Achievement badges
- Activity timeline
### Backend API Endpoints
#### Authentication Endpoints
Authentication is handled by Clerk. The backend uses Clerk's middleware to verify session tokens.
```
POST /api/webhooks/clerk # Clerk webhook for user sync
GET /api/auth/session # Verify current session (protected)
```
#### Report Endpoints
```
GET /api/reports # List reports with filters
GET /api/reports/:id # Get single report
POST /api/reports # Create new report
PATCH /api/reports/:id # Update report
DELETE /api/reports/:id # Delete report
POST /api/reports/:id/verify # Verify report
POST /api/reports/:id/dispute # Dispute report
```
#### Event Endpoints
```
GET /api/events # List events
GET /api/events/:id # Get single event
POST /api/events # Create event
PATCH /api/events/:id # Update event
DELETE /api/events/:id # Delete event
POST /api/events/:id/register # Register for event
POST /api/events/:id/complete # Mark event complete
```
#### Analytics Endpoints
```
GET /api/analytics/summary # Overall statistics
GET /api/analytics/trends # Time series data
GET /api/analytics/hotspots # Litter hotspot data
GET /api/analytics/export # Export data as CSV
```
#### User Endpoints
```
GET /api/users/:id # Get user profile
PATCH /api/users/:id # Update profile
GET /api/users/:id/reports # User's reports
GET /api/users/:id/events # User's events
PATCH /api/users/:id/preferences # Update notification preferences
```
#### External Data Endpoints
```
GET /api/external/weather/:lat/:lng # Weather data
GET /api/external/tides/:lat/:lng # Tide information
GET /api/external/water-quality/:lat/:lng # EPA water quality
```
## Data Models
### Database Configuration
**Connection Details:**
- Database: MySQL 8.0+
- Host: 192.168.4.20
- Port: 3306
- Database Name: beach_litter_mapping
- User: beach_litter_user
- Connection String: `mysql://beach_litter_user:BeachClean2024!@192.168.4.20:3306/beach_litter_mapping`
**Environment Variables:**
```env
DATABASE_URL=mysql://beach_litter_user:BeachClean2024!@192.168.4.20:3306/beach_litter_mapping
DB_HOST=192.168.4.20
DB_PORT=3306
DB_NAME=beach_litter_mapping
DB_USER=beach_litter_user
DB_PASSWORD=BeachClean2024!
```
### Authentication Configuration (Clerk)
**Frontend Setup:**
1. Install Clerk React SDK: `npm install @clerk/clerk-react@latest`
2. Set `VITE_CLERK_PUBLISHABLE_KEY` in `.env.local`
3. Wrap app in `<ClerkProvider>` in `main.tsx`
4. Use Clerk components: `<SignedIn>`, `<SignedOut>`, `<SignInButton>`, `<SignUpButton>`, `<UserButton>`
**Backend Setup:**
1. Install Clerk SDK: `npm install @clerk/clerk-sdk-node`
2. Set `CLERK_SECRET_KEY` for API authentication
3. Set `CLERK_WEBHOOK_SECRET` for webhook verification
4. Use Clerk middleware to protect routes
5. Set up webhook endpoint to sync user data
**Clerk Environment Variables:**
```env
# Frontend (.env.local)
VITE_CLERK_PUBLISHABLE_KEY=pk_test_...
# Backend (.env)
CLERK_SECRET_KEY=sk_test_...
CLERK_WEBHOOK_SECRET=whsec_...
```
### Database Schema
#### User Table (MySQL)
```sql
CREATE TABLE users (
id VARCHAR(36) PRIMARY KEY, -- Clerk user ID
clerk_id VARCHAR(255) UNIQUE NOT NULL, -- Clerk user ID for reference
email VARCHAR(255) UNIQUE NOT NULL,
username VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- Profile (synced from Clerk)
first_name VARCHAR(100),
last_name VARCHAR(100),
avatar_url VARCHAR(500),
-- App-specific data
impact_score INT DEFAULT 0,
-- Preferences
notification_email BOOLEAN DEFAULT TRUE,
notification_in_app BOOLEAN DEFAULT TRUE,
areas_of_interest JSON,
INDEX idx_clerk_id (clerk_id),
INDEX idx_email (email),
INDEX idx_username (username)
) ENGINE=InnoDB;
```
**TypeScript Interface:**
```typescript
interface User {
id: string; // Clerk user ID
clerkId: string;
email: string;
username: string;
createdAt: Date;
updatedAt: Date;
firstName?: string;
lastName?: string;
avatarUrl?: string;
impactScore: number;
notificationEmail: boolean;
notificationInApp: boolean;
areasOfInterest?: Array<{lat: number, lng: number, radius: number}>;
}
```
**Note:** User authentication is handled entirely by Clerk. The users table stores only app-specific data and syncs basic profile information from Clerk via webhooks.
#### Report Table (MySQL)
```sql
CREATE TABLE reports (
id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
user_id VARCHAR(36) NOT NULL,
-- Location (using POINT spatial type)
location POINT NOT NULL SRID 4326,
latitude DECIMAL(10, 8) NOT NULL,
longitude DECIMAL(11, 8) NOT NULL,
location_source ENUM('exif', 'gps', 'manual') NOT NULL,
-- Content
photo_urls JSON NOT NULL,
photo_timestamp TIMESTAMP NULL,
litter_type ENUM('plastic', 'metal', 'glass', 'organic', 'hazardous', 'other') NOT NULL,
quantity ENUM('minimal', 'moderate', 'significant', 'severe') NOT NULL,
description TEXT,
-- Metadata
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
-- Verification
verification_status ENUM('pending', 'verified', 'disputed') DEFAULT 'pending',
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
SPATIAL INDEX idx_location (location),
INDEX idx_created_at (created_at),
INDEX idx_litter_type (litter_type),
INDEX idx_lat_lng (latitude, longitude)
) ENGINE=InnoDB;
```
**TypeScript Interface:**
```typescript
interface Report {
id: string;
userId: string;
latitude: number;
longitude: number;
locationSource: 'exif' | 'gps' | 'manual';
photoUrls: string[];
photoTimestamp?: Date;
litterType: 'plastic' | 'metal' | 'glass' | 'organic' | 'hazardous' | 'other';
quantity: 'minimal' | 'moderate' | 'significant' | 'severe';
description?: string;
createdAt: Date;
updatedAt: Date;
submittedAt: Date;
verificationStatus: 'pending' | 'verified' | 'disputed';
}
```
#### Event Table (MySQL)
```sql
CREATE TABLE events (
id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
organizer_id VARCHAR(36) NOT NULL,
-- Details
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
location POINT NOT NULL SRID 4326,
latitude DECIMAL(10, 8) NOT NULL,
longitude DECIMAL(11, 8) NOT NULL,
location_name VARCHAR(255) NOT NULL,
-- Timing
scheduled_date TIMESTAMP NOT NULL,
duration INT NOT NULL COMMENT 'Duration in minutes',
-- Status
status ENUM('upcoming', 'completed', 'cancelled') DEFAULT 'upcoming',
participant_count INT DEFAULT 0,
litter_collected DECIMAL(10, 2) COMMENT 'Kilograms collected',
photos JSON,
-- Metadata
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (organizer_id) REFERENCES users(id) ON DELETE CASCADE,
SPATIAL INDEX idx_location (location),
INDEX idx_scheduled_date (scheduled_date),
INDEX idx_status (status)
) ENGINE=InnoDB;
```
#### EventRegistration Table (MySQL)
```sql
CREATE TABLE event_registrations (
id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
user_id VARCHAR(36) NOT NULL,
event_id VARCHAR(36) NOT NULL,
registered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
attended BOOLEAN DEFAULT FALSE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE,
UNIQUE KEY unique_user_event (user_id, event_id)
) ENGINE=InnoDB;
```
#### Verification Table (MySQL)
```sql
CREATE TABLE verifications (
id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
report_id VARCHAR(36) NOT NULL,
user_id VARCHAR(36) NOT NULL,
verification_type ENUM('verify', 'dispute') NOT NULL,
comment TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (report_id) REFERENCES reports(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE KEY unique_report_user (report_id, user_id)
) ENGINE=InnoDB;
```
#### EnvironmentalConcern Table (MySQL)
```sql
CREATE TABLE environmental_concerns (
id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
report_id VARCHAR(36) NOT NULL,
concern_type VARCHAR(100) NOT NULL COMMENT 'water_quality, erosion, wildlife_impact, algae_bloom, etc.',
severity ENUM('low', 'medium', 'high', 'critical') NOT NULL,
description TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (report_id) REFERENCES reports(id) ON DELETE CASCADE,
INDEX idx_concern_type (concern_type)
) ENGINE=InnoDB;
```
#### Hotspot Table (MySQL)
```sql
CREATE TABLE hotspots (
id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
location POINT NOT NULL SRID 4326,
latitude DECIMAL(10, 8) NOT NULL,
longitude DECIMAL(11, 8) NOT NULL,
radius DECIMAL(10, 2) NOT NULL COMMENT 'Radius in meters',
report_count INT NOT NULL,
severity_score DECIMAL(5, 2) NOT NULL,
last_report_date TIMESTAMP NOT NULL,
calculated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
SPATIAL INDEX idx_location (location),
INDEX idx_severity_score (severity_score)
) ENGINE=InnoDB;
```
### Data Transfer Objects (DTOs)
#### CreateReportDTO
```typescript
interface CreateReportDTO {
photos: File[];
latitude?: number;
longitude?: number;
locationSource: 'exif' | 'gps' | 'manual';
litterType: LitterType;
quantity: QuantityLevel;
description?: string;
environmentalConcerns?: {
type: string;
severity: string;
description: string;
}[];
}
```
#### ReportResponseDTO
```typescript
interface ReportResponseDTO {
id: string;
user: {
id: string;
username: string;
avatarUrl?: string;
};
location: {
latitude: number;
longitude: number;
};
photoUrls: string[];
photoTimestamp?: string;
litterType: LitterType;
quantity: QuantityLevel;
description?: string;
verificationStatus: VerificationStatus;
verificationCount: number;
disputeCount: number;
createdAt: string;
environmentalConcerns: EnvironmentalConcernDTO[];
}
```
## Error Handling
### Error Response Format
All API errors follow a consistent format:
```typescript
interface ErrorResponse {
error: {
code: string;
message: string;
details?: any;
timestamp: string;
}
}
```
### Error Codes
```typescript
enum ErrorCode {
// Authentication
UNAUTHORIZED = 'UNAUTHORIZED',
INVALID_CREDENTIALS = 'INVALID_CREDENTIALS',
TOKEN_EXPIRED = 'TOKEN_EXPIRED',
// Validation
VALIDATION_ERROR = 'VALIDATION_ERROR',
INVALID_COORDINATES = 'INVALID_COORDINATES',
INVALID_FILE_TYPE = 'INVALID_FILE_TYPE',
FILE_TOO_LARGE = 'FILE_TOO_LARGE',
// Resources
RESOURCE_NOT_FOUND = 'RESOURCE_NOT_FOUND',
DUPLICATE_RESOURCE = 'DUPLICATE_RESOURCE',
// Permissions
FORBIDDEN = 'FORBIDDEN',
INSUFFICIENT_PERMISSIONS = 'INSUFFICIENT_PERMISSIONS',
// External Services
EXTERNAL_API_ERROR = 'EXTERNAL_API_ERROR',
GEOCODING_FAILED = 'GEOCODING_FAILED',
// Server
INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',
DATABASE_ERROR = 'DATABASE_ERROR',
}
```
### Error Handling Strategy
1. **Input Validation**: Use Zod schemas for request validation at API boundary
2. **Try-Catch Blocks**: Wrap async operations with proper error handling
3. **Error Middleware**: Global Express error handler for consistent responses
4. **Logging**: Winston logger for error tracking and debugging
5. **User-Friendly Messages**: Transform technical errors into readable messages
6. **Retry Logic**: Implement exponential backoff for external API calls
7. **Circuit Breaker**: Prevent cascading failures from external services
### Frontend Error Handling
1. **Error Boundaries**: React error boundaries for component-level errors
2. **Toast Notifications**: User-friendly error messages via toast library
3. **Retry Mechanisms**: Automatic retry for failed API calls
4. **Offline Support**: Queue actions when offline, sync when online
5. **Validation Feedback**: Real-time form validation with clear messages
## Testing Strategy
### Unit Testing
**Backend**:
- Jest for test framework
- Test all service layer functions
- Mock database calls with Prisma mock
- Test utility functions (EXIF extraction, coordinate validation)
- Target: 80% code coverage
**Frontend**:
- Vitest for test framework
- React Testing Library for component tests
- Test user interactions and state changes
- Mock API calls with MSW (Mock Service Worker)
- Target: 70% code coverage
### Integration Testing
- Test API endpoints with Supertest
- Use test database with Docker
- Test authentication flows
- Test file upload pipeline
- Test external API integration with mocked responses
### End-to-End Testing
- Playwright or Cypress for E2E tests
- Test critical user journeys:
- User registration and login
- Submit report with photo
- View reports on map
- Create and register for event
- View analytics dashboard
- Run on CI/CD pipeline
### Performance Testing
- Load testing with Artillery or k6
- Test concurrent report submissions
- Test map rendering with 1000+ markers
- Test database query performance with PostGIS
- Monitor API response times
### Accessibility Testing
- Axe DevTools for automated a11y testing
- Manual keyboard navigation testing
- Screen reader compatibility (NVDA, JAWS)
- WCAG 2.1 AA compliance target
- Color contrast validation
## Security Considerations
### Authentication & Authorization
- Clerk handles all authentication (sign-up, sign-in, password management, MFA)
- Session tokens verified via Clerk middleware on backend
- User data synced to local database via Clerk webhooks
- Rate limiting on API endpoints
- Clerk provides built-in email verification and social auth options
### Data Protection
- HTTPS only in production
- Input sanitization to prevent XSS
- Parameterized queries to prevent SQL injection
- CORS configuration for allowed origins
- Content Security Policy headers
### File Upload Security
- File type validation (MIME type checking)
- File size limits (5MB per photo)
- Virus scanning for uploaded files
- Separate storage domain for user content
- Strip EXIF data except GPS/timestamp before public display
### API Security
- Rate limiting per IP and per user
- API key rotation for external services
- Secrets management (environment variables)
- Request validation with Zod schemas
- CSRF protection for state-changing operations
## Performance Optimization
### Frontend Optimization
- Code splitting by route
- Lazy loading for map components
- Image optimization and lazy loading
- Virtual scrolling for large lists
- Debouncing for search and filter inputs
- Service worker for offline capability
- CDN for static assets
### Backend Optimization
- Database indexing on frequently queried fields
- PostGIS spatial indexes for location queries
- Redis caching for:
- External API responses (6 hours)
- Hotspot calculations (15 minutes)
- Analytics aggregations (1 hour)
- Connection pooling for database
- Pagination for list endpoints
- Compression middleware (gzip)
### Database Optimization
- Materialized views for hotspot calculations
- Scheduled jobs to refresh materialized views
- Partitioning for large tables (by date)
- Query optimization with EXPLAIN ANALYZE
- Read replicas for analytics queries
## Deployment Architecture
### Development Environment
- Docker Compose for local development
- PostgreSQL + PostGIS container
- Redis container
- Hot reload for frontend and backend
- Mock external APIs for testing
### Production Environment
- Frontend: Vercel or Netlify
- Backend: Railway, Render, or AWS ECS
- Database: Managed PostgreSQL (AWS RDS, Supabase)
- Redis: Managed Redis (AWS ElastiCache, Upstash)
- Storage: AWS S3 or Cloudinary
- CDN: CloudFlare
- Monitoring: Sentry for error tracking
- Analytics: Plausible or Google Analytics
### CI/CD Pipeline
1. GitHub Actions workflow
2. Run linting and type checking
3. Run unit and integration tests
4. Build Docker images
5. Deploy to staging environment
6. Run E2E tests on staging
7. Deploy to production (manual approval)
## Scalability Considerations
### Horizontal Scaling
- Stateless API servers (can add more instances)
- Load balancer for API traffic
- Database read replicas for analytics
- CDN for static content and images
### Data Growth Strategy
- Archive old reports (>2 years) to cold storage
- Implement data retention policies
- Optimize photo storage with compression
- Use database partitioning for time-series data
### Future Enhancements
- Mobile native apps (React Native)
- Real-time updates with WebSockets
- Machine learning for litter type classification from photos
- Gamification with leaderboards and achievements
- Integration with local government systems
- Multi-language support for international expansion
- API for third-party integrations
- Blockchain for verified cleanup certificates

View File

@@ -0,0 +1,156 @@
# Requirements Document
## Introduction
The Beach Litter Mapping Platform is a web-based application designed to crowdsource environmental data about beach litter and other coastal concerns across Ireland. The system empowers communities to report, visualize, and address environmental issues through interactive mapping, data analytics, and coordinated clean-up events. By providing real-time visibility into coastal pollution patterns, the platform aims to raise awareness, drive community engagement, and support evidence-based environmental action.
## Glossary
- **Platform**: The Beach Litter Mapping web application system
- **User**: Any person accessing the Platform, including reporters, volunteers, and viewers
- **Litter Report**: A user-submitted record documenting observed beach litter or environmental concerns
- **Map Interface**: The interactive map component displaying geographical data and litter overlays
- **Clean-up Event**: An organized community activity to remove litter from a specific location
- **Litter Hotspot**: A geographical area with high concentration of reported litter incidents
- **Environmental Concern**: Any coastal pollution or ecological issue beyond physical litter (e.g., water quality, erosion)
- **Report Verification**: The process of confirming the accuracy and validity of submitted reports
- **Analytics Dashboard**: The interface displaying aggregated statistics and trends about litter data
## Requirements
### Requirement 1: Litter Reporting System
**User Story:** As a beach visitor, I want to report litter I observe with photos and location data, so that the community can be aware of pollution issues and take action.
#### Acceptance Criteria
1. WHEN a User submits a litter report, THE Platform SHALL capture the geographical coordinates of the report location with accuracy within 10 meters
2. WHEN a User uploads a photograph with EXIF metadata containing GPS coordinates, THE Platform SHALL extract and use those coordinates as the report location
3. WHEN a User uploads a photograph without GPS metadata, THE Platform SHALL prompt the User to provide location through device GPS or manual map selection
4. WHEN a User submits a litter report, THE Platform SHALL accept at least one photograph with minimum resolution of 800x600 pixels
5. WHEN a User uploads a photograph with EXIF metadata containing timestamp, THE Platform SHALL extract and display the original photo capture time
6. THE Platform SHALL allow Users to categorize litter by type (plastic, metal, glass, organic, hazardous, other)
7. THE Platform SHALL allow Users to estimate litter quantity using predefined ranges (minimal, moderate, significant, severe)
8. WHEN a User submits a report, THE Platform SHALL record the submission timestamp in ISO 8601 format
### Requirement 2: Interactive Map Visualization
**User Story:** As a community member, I want to view an interactive map showing all reported litter locations, so that I can understand pollution patterns in my area.
#### Acceptance Criteria
1. THE Platform SHALL display litter reports as visual markers on an interactive map using free mapping services
2. WHEN a User clicks on a map marker, THE Platform SHALL display the full report details including photos, category, quantity, and timestamp
3. THE Platform SHALL provide map zoom functionality from country-level view to street-level detail
4. THE Platform SHALL allow Users to filter visible reports by date range, litter type, and quantity level
5. WHEN multiple reports exist within 50 meters, THE Platform SHALL cluster markers and display the count of reports in that cluster
### Requirement 3: Litter Hotspot Analysis
**User Story:** As an environmental researcher, I want to identify areas with high concentrations of litter reports, so that I can prioritize clean-up efforts and study pollution patterns.
#### Acceptance Criteria
1. THE Platform SHALL generate heat map overlays showing litter density across geographical regions
2. WHEN the Platform calculates Litter Hotspots, THE Platform SHALL identify areas with at least 5 reports within a 500-meter radius over the past 30 days
3. THE Platform SHALL rank Litter Hotspots by severity score calculated from report quantity and frequency
4. THE Platform SHALL update Litter Hotspot calculations within 5 minutes of new report submissions
5. THE Platform SHALL display Litter Hotspot boundaries on the Map Interface with color-coded severity indicators
### Requirement 4: Clean-up Event Management
**User Story:** As a community organizer, I want to create and manage clean-up events at reported litter locations, so that volunteers can coordinate their efforts effectively.
#### Acceptance Criteria
1. THE Platform SHALL allow Users to create Clean-up Events with specified date, time, location, and description
2. WHEN a User creates a Clean-up Event, THE Platform SHALL display the event marker on the Map Interface
3. THE Platform SHALL allow Users to register their participation in Clean-up Events
4. THE Platform SHALL display the count of registered participants for each Clean-up Event
5. WHEN a Clean-up Event date passes, THE Platform SHALL allow the organizer to mark the event as completed and report the quantity of litter collected
### Requirement 5: Analytics and Reporting Dashboard
**User Story:** As an environmental advocate, I want to view statistics and trends about beach litter, so that I can use data to support awareness campaigns and policy recommendations.
#### Acceptance Criteria
1. THE Platform SHALL display total count of litter reports aggregated by time period (daily, weekly, monthly, yearly)
2. THE Platform SHALL generate charts showing litter distribution by category type
3. THE Platform SHALL calculate and display the total estimated quantity of litter reported across all locations
4. THE Platform SHALL show trends comparing current period data to previous periods with percentage change indicators
5. THE Platform SHALL allow Users to export analytics data in CSV format for external analysis
### Requirement 6: User Authentication and Profiles
**User Story:** As a platform user, I want to create an account and track my contributions, so that I can build a history of my environmental impact.
#### Acceptance Criteria
1. THE Platform SHALL allow Users to create accounts using email address and password with minimum 8 characters
2. THE Platform SHALL authenticate Users before allowing report submissions or event creation
3. THE Platform SHALL display a User profile showing their submitted reports count and Clean-up Events attended
4. THE Platform SHALL calculate and display an impact score for each User based on their contributions
5. WHEN a User views their profile, THE Platform SHALL show a map of all their submitted report locations
### Requirement 7: Report Verification and Quality Control
**User Story:** As a platform administrator, I want to verify submitted reports to maintain data quality, so that the platform provides reliable information to the community.
#### Acceptance Criteria
1. THE Platform SHALL flag reports for review when they lack photographs or location data
2. THE Platform SHALL allow designated Users to mark reports as verified or disputed
3. WHEN a report receives 3 or more dispute flags, THE Platform SHALL hide the report from public view pending review
4. THE Platform SHALL display verification status indicators on report details
5. THE Platform SHALL maintain an audit log of all verification actions with User identifier and timestamp
### Requirement 8: Mobile Responsiveness and Accessibility
**User Story:** As a mobile user at the beach, I want to easily report litter from my smartphone, so that I can contribute data while observing environmental issues in real-time.
#### Acceptance Criteria
1. THE Platform SHALL render all core functionality on mobile devices with screen widths from 320 pixels to 768 pixels
2. THE Platform SHALL access device GPS capabilities to auto-populate report location coordinates
3. THE Platform SHALL access device camera to capture photos directly within the reporting interface
4. THE Platform SHALL maintain touch-friendly interface elements with minimum tap target size of 44x44 pixels
5. THE Platform SHALL load the Map Interface within 3 seconds on mobile networks with 4G connectivity
### Requirement 9: Environmental Data Integration
**User Story:** As a scientist, I want to correlate litter data with other environmental factors, so that I can conduct comprehensive coastal health assessments.
#### Acceptance Criteria
1. THE Platform SHALL allow Users to report additional Environmental Concerns beyond physical litter (water quality, wildlife impact, coastal erosion)
2. THE Platform SHALL categorize Environmental Concerns using standardized taxonomy
3. THE Platform SHALL display Environmental Concern reports as distinct markers on the Map Interface
4. THE Platform SHALL link related reports when they reference the same geographical area within 100 meters
5. THE Platform SHALL provide API endpoints to export environmental data in JSON format for integration with research tools
### Requirement 10: Notification and Engagement System
**User Story:** As an active volunteer, I want to receive notifications about new reports and events in my area, so that I can respond quickly to environmental issues.
#### Acceptance Criteria
1. THE Platform SHALL allow Users to define geographical areas of interest with radius between 1 and 50 kilometers
2. WHEN a new Litter Report is submitted within a User's area of interest, THE Platform SHALL send a notification to that User within 10 minutes
3. WHEN a new Clean-up Event is created within a User's area of interest, THE Platform SHALL send a notification to that User within 10 minutes
4. THE Platform SHALL allow Users to configure notification preferences for report types and event categories
5. THE Platform SHALL deliver notifications through in-app alerts and email messages based on User preferences
### Requirement 11: External Environmental Data Integration
**User Story:** As a researcher, I want to view contextual environmental data alongside litter reports, so that I can understand the broader ecological conditions affecting coastal areas.
#### Acceptance Criteria
1. THE Platform SHALL integrate weather data from public APIs to display current conditions and forecasts for reported locations
2. THE Platform SHALL retrieve tide information from public APIs to show tide times and heights for coastal locations
3. THE Platform SHALL integrate water quality data from Irish Environmental Protection Agency (EPA) public datasets where available
4. WHEN a User views a report location, THE Platform SHALL display relevant environmental context data within 2 seconds
5. THE Platform SHALL cache external API data for up to 6 hours to minimize API calls and improve performance
6. THE Platform SHALL integrate beach quality ratings from EU Blue Flag or similar public databases for Irish beaches
7. THE Platform SHALL display marine biodiversity information from public databases when available for the report location

View File

@@ -0,0 +1,323 @@
# Implementation Plan
## Frontend Foundation
- [x] 1. Set up project structure and dependencies
- Install required frontend dependencies: Leaflet, React Query, Tailwind CSS, React Router, date-fns, chart libraries
- Configure Tailwind CSS with Vite
- Set up folder structure: components, pages, services, hooks, utils, types
- Create TypeScript configuration for type safety
- _Requirements: 8.1, 8.4_
- [x] 2. Implement authentication UI and state management
- Create login and registration forms with validation
- Implement JWT token storage and refresh logic
- Create protected route wrapper component
- Build authentication context provider
- Create user profile display component
- _Requirements: 6.1, 6.2, 6.3_
- [x] 3. Build interactive map component with Leaflet
- Initialize Leaflet map with OpenStreetMap tiles
- Implement map zoom and pan controls
- Add geolocation button to center map on user location
- Create custom marker icons for different litter types
- Implement marker click handlers to show report details
- _Requirements: 2.1, 2.2, 2.3, 8.2_
- [x] 4. Implement marker clustering and filtering
- Integrate Leaflet.markercluster plugin
- Configure cluster radius and appearance
- Build filter controls for date range, litter type, and quantity
- Implement filter state management and map updates
- _Requirements: 2.4, 2.5_
- [ ] 5. Create heat map visualization
- Integrate Leaflet.heat plugin
- Implement heat map toggle control
- Configure heat map intensity based on report density
- Add heat map layer management
- _Requirements: 3.1, 3.5_
## Report Submission System
- [ ] 6. Build photo upload component with EXIF extraction
- Create drag-and-drop photo upload interface
- Implement file type and size validation
- Integrate exifr library to extract GPS coordinates and timestamps
- Display photo previews with metadata
- Handle multiple photo uploads
- _Requirements: 1.2, 1.3, 1.4, 1.5, 8.3_
- [ ] 7. Implement location selection interface
- Auto-populate location from EXIF data when available
- Add device GPS location capture button
- Create map-based location picker for manual selection
- Display selected location coordinates with accuracy indicator
- Validate coordinate ranges for Ireland
- _Requirements: 1.1, 1.2, 1.3, 8.2_
- [ ] 8. Create litter report form
- Build multi-step form with progress indicator
- Implement litter type categorization dropdown
- Create quantity estimation slider with visual indicators
- Add optional description textarea
- Implement form validation with error messages
- Create environmental concerns section
- _Requirements: 1.6, 1.7, 9.1, 9.2_
- [ ] 9. Implement report submission and display
- Connect form to API endpoint for report creation
- Handle submission success and error states
- Create report detail modal/popup component
- Display report information with photos and metadata
- Show verification status indicators
- _Requirements: 1.8, 7.4_
## Analytics and Visualization
- [ ] 10. Build analytics dashboard layout
- Create dashboard page with responsive grid layout
- Implement summary statistics cards (total reports, events, users)
- Add date range selector component
- Create export to CSV functionality
- _Requirements: 5.1, 5.5_
- [ ] 11. Implement data visualization charts
- Create time series chart for report trends
- Build pie chart for litter type distribution
- Implement comparison metrics with previous periods
- Add quantity estimation aggregation display
- Configure chart responsiveness for mobile
- _Requirements: 5.2, 5.3, 5.4_
- [ ] 12. Create hotspot visualization
- Fetch and display hotspot data on map
- Implement color-coded severity indicators
- Show hotspot boundaries and statistics
- Create hotspot detail popup with report count
- _Requirements: 3.2, 3.3, 3.5_
## Event Management
- [ ] 13. Build event creation and management interface
- Create event creation form with date/time picker
- Implement location selection on map
- Add participant registration functionality
- Build event list view with filters
- Create event detail page with participant count
- _Requirements: 4.1, 4.2, 4.3, 4.4_
- [ ] 14. Implement event completion workflow
- Create event completion form for organizers
- Add litter collected quantity input
- Implement photo upload for cleanup results
- Update event status and display completion data
- _Requirements: 4.5_
## User Profile and Engagement
- [ ] 15. Build user profile page
- Display user statistics (reports, events attended)
- Calculate and show impact score
- Create personal contribution map
- Implement activity timeline
- Add profile editing functionality
- _Requirements: 6.3, 6.4, 6.5_
- [ ] 16. Implement notification preferences
- Create notification settings interface
- Build area of interest selector with map
- Implement radius configuration (1-50km)
- Add notification type toggles (email, in-app)
- Save and load user preferences
- _Requirements: 10.1, 10.4_
## Report Verification System
- [ ] 17. Implement report verification interface
- Add verify/dispute buttons to report details
- Create verification comment form
- Display verification count and status
- Implement auto-hide logic for disputed reports (3+ disputes)
- Show verification audit log
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5_
## External Data Integration
- [ ] 18. Create external data display components
- Build weather information widget
- Implement tide times display
- Add water quality indicator
- Create beach quality rating display
- Show marine biodiversity information when available
- _Requirements: 11.1, 11.2, 11.3, 11.4, 11.6, 11.7_
## Mobile Optimization
- [ ] 19. Implement mobile-responsive design
- Apply Tailwind responsive classes throughout
- Optimize map controls for touch interfaces
- Ensure minimum tap target sizes (44x44px)
- Test and optimize for screen widths 320px-768px
- Implement mobile navigation menu
- _Requirements: 8.1, 8.4_
- [ ] 20. Optimize mobile performance
- Implement code splitting and lazy loading
- Add image optimization and lazy loading
- Configure service worker for offline capability
- Optimize bundle size and load times
- Test on 4G network conditions
- _Requirements: 8.5_
## Backend API Development
- [ ] 21. Set up backend project structure
- Initialize Node.js project with Express
- Configure TypeScript for backend
- Set up folder structure: routes, controllers, services, middleware, utils
- Install dependencies: Prisma, JWT, Multer, bcrypt, express-validator
- Create environment configuration
- _Requirements: All backend requirements_
- [ ] 22. Configure database with Prisma and PostGIS
- Set up PostgreSQL with PostGIS extension
- Create Prisma schema with all models (User, Report, Event, etc.)
- Configure PostGIS geography types for location fields
- Create database migrations
- Set up database indexes for performance
- _Requirements: 1.1, 2.1, 3.2, 4.1_
- [ ] 23. Implement authentication system
- Create user registration endpoint with password hashing
- Build login endpoint with JWT token generation
- Implement refresh token logic with httpOnly cookies
- Create authentication middleware for protected routes
- Add rate limiting to auth endpoints
- _Requirements: 6.1, 6.2_
- [ ] 24. Build report API endpoints
- Create POST /api/reports endpoint for report submission
- Implement GET /api/reports with filtering and pagination
- Build GET /api/reports/:id for single report retrieval
- Create PATCH /api/reports/:id for updates
- Implement DELETE /api/reports/:id with authorization
- Add spatial queries using PostGIS for location-based filtering
- _Requirements: 1.1-1.8, 2.1, 2.4_
- [ ] 25. Implement file upload and EXIF processing
- Configure Multer for photo uploads
- Set up cloud storage (S3 or Cloudinary) integration
- Implement EXIF metadata extraction with exifr
- Add file validation (type, size limits)
- Create photo URL generation and storage
- _Requirements: 1.2, 1.3, 1.4, 1.5_
- [ ] 26. Build event management endpoints
- Create POST /api/events for event creation
- Implement GET /api/events with filtering
- Build event registration endpoint
- Create event completion endpoint
- Add participant count tracking
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5_
- [ ] 27. Implement analytics endpoints
- Create GET /api/analytics/summary for overall statistics
- Build time series data endpoint for trends
- Implement CSV export functionality
- Add aggregation queries for litter types and quantities
- Create comparison calculations for period-over-period metrics
- _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5_
- [ ] 28. Build hotspot calculation system
- Create scheduled job with node-cron for hotspot calculations
- Implement PostGIS spatial queries to identify clusters
- Calculate severity scores based on report count and frequency
- Store hotspot data in database or materialized view
- Create GET /api/analytics/hotspots endpoint
- _Requirements: 3.2, 3.3, 3.4_
- [ ] 29. Implement verification system endpoints
- Create POST /api/reports/:id/verify endpoint
- Build POST /api/reports/:id/dispute endpoint
- Implement verification count tracking
- Add auto-hide logic for reports with 3+ disputes
- Create verification audit log
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5_
- [ ] 30. Build user profile endpoints
- Create GET /api/users/:id for profile retrieval
- Implement PATCH /api/users/:id for profile updates
- Build GET /api/users/:id/reports endpoint
- Create GET /api/users/:id/events endpoint
- Implement impact score calculation
- Add notification preferences endpoint
- _Requirements: 6.3, 6.4, 6.5, 10.4_
- [ ] 31. Integrate external APIs with caching
- Set up Redis for caching external API responses
- Implement weather API integration (OpenWeatherMap)
- Build tide API integration (WorldTides or NOAA)
- Create EPA water quality data integration
- Add beach quality rating integration
- Implement 6-hour cache expiration
- _Requirements: 11.1, 11.2, 11.3, 11.4, 11.5, 11.6_
- [ ] 32. Implement notification system
- Create notification service with area-of-interest matching
- Build email notification integration (SendGrid)
- Implement in-app notification storage and retrieval
- Create scheduled job to check for new reports/events
- Add notification delivery within 10-minute requirement
- _Requirements: 10.1, 10.2, 10.3, 10.4_
- [ ] 33. Add API security and validation
- Implement request validation with Zod schemas
- Add rate limiting middleware
- Configure CORS for allowed origins
- Implement input sanitization
- Add security headers (helmet)
- Create error handling middleware
- _Requirements: All security-related requirements_
- [ ] 34. Implement environmental concerns endpoints
- Create endpoints for submitting environmental concerns
- Build filtering and retrieval for concern types
- Implement linking of related reports within 100m
- Add JSON export endpoint for research integration
- _Requirements: 9.1, 9.2, 9.3, 9.4, 9.5_
## Integration and Polish
- [ ] 35. Connect frontend to backend APIs
- Configure API base URL and axios/fetch setup
- Implement React Query hooks for all endpoints
- Add error handling and retry logic
- Create loading states for all async operations
- Implement optimistic updates where appropriate
- _Requirements: All integration requirements_
- [ ] 36. Implement error handling and user feedback
- Create toast notification system for user feedback
- Add error boundaries for React components
- Implement form validation error displays
- Create user-friendly error messages
- Add loading spinners and skeleton screens
- _Requirements: All UX requirements_
- [ ]* 37. Write integration tests
- Create API endpoint tests with Supertest
- Test authentication flows
- Test file upload pipeline
- Test spatial queries with PostGIS
- Test external API integration with mocks
- _Requirements: All requirements_
- [ ] 38. Set up deployment configuration
- Create Docker configuration for development
- Set up environment variables for production
- Configure build scripts for frontend and backend
- Create database migration scripts
- Document deployment process
- _Requirements: Infrastructure requirements_

26
.kiro/steering/product.md Normal file
View File

@@ -0,0 +1,26 @@
# Product Overview
The Beach Litter Mapping Platform is a crowdsourced environmental monitoring web application for Irish coastal areas. It enables users to report beach litter with photos and GPS coordinates, visualize pollution patterns on interactive maps, organize cleanup events, and analyze environmental data.
## Core Features
- **Litter Reporting**: Submit reports with photos, GPS location, litter type categorization, and quantity estimates
- **Interactive Mapping**: View reports on Leaflet maps with clustering, heat maps, and filtering by date/type/quantity
- **Hotspot Analysis**: Identify high-concentration litter areas (5+ reports within 500m radius)
- **Event Management**: Create and coordinate community cleanup events with participant registration
- **Analytics Dashboard**: Visualize trends, statistics, and export data for research
- **User Profiles**: Track contributions, impact scores, and personal report history
- **Verification System**: Community-driven report verification and quality control
- **Environmental Context**: Integrate weather, tide, and water quality data from public APIs
## Target Users
- Beach visitors reporting litter
- Community organizers coordinating cleanups
- Environmental researchers analyzing pollution patterns
- Volunteers responding to local issues
- Policy advocates using data for campaigns
## Geographic Scope
Primary focus on Irish coastal areas with coordinate validation for Irish boundaries.

119
.kiro/steering/structure.md Normal file
View File

@@ -0,0 +1,119 @@
# Project Structure
## Directory Organization
```
src/
├── components/ # React components organized by feature
│ ├── auth/ # Authentication components (SignIn, SignUp, ProtectedRoute)
│ ├── layout/ # Layout components (Header, Footer, Navigation)
│ └── map/ # Map components (MapView, MapFilters)
├── pages/ # Page-level components for routing
├── services/ # API clients and external service integrations
├── hooks/ # Custom React hooks
├── utils/ # Utility functions and helpers
├── types/ # TypeScript type definitions
├── App.tsx # Main application component with routing
├── main.tsx # Application entry point
└── index.css # Global styles with Tailwind directives
```
## Component Organization
Components are organized by **feature/domain** rather than by type:
- `components/auth/` - All authentication-related components
- `components/map/` - All mapping-related components
- `components/layout/` - Shared layout components
- Each feature folder includes an `index.ts` for clean exports
## File Naming Conventions
- **Components**: PascalCase (e.g., `MapView.tsx`, `ReportForm.tsx`)
- **Hooks**: camelCase with `use` prefix (e.g., `useAuth.ts`, `useGeolocation.ts`)
- **Services**: camelCase (e.g., `api.ts`, `reportService.ts`)
- **Utils**: camelCase (e.g., `validation.ts`, `coordinates.ts`)
- **Types**: PascalCase for interfaces/types in `types/index.ts`
## Import/Export Patterns
Each feature directory includes an `index.ts` barrel file for clean exports:
```typescript
// components/map/index.ts
export { MapView } from './MapView';
export { MapFilters } from './MapFilters';
// Usage elsewhere
import { MapView, MapFilters } from '@/components/map';
```
## Page Structure
Pages in `src/pages/` correspond to routes:
- `HomePage.tsx` - Landing page
- `MapPage.tsx` - Interactive map view
- `ReportFormPage.tsx` - Report submission form
- `EventsPage.tsx` - Event listing and management
- `AnalyticsPage.tsx` - Analytics dashboard
All pages are exported through `pages/index.ts` for centralized route configuration.
## Type Definitions
Centralized in `src/types/index.ts`:
- Domain models (Report, Event, User)
- DTOs (Data Transfer Objects)
- Enums (LitterType, QuantityLevel, VerificationStatus)
- API response types
## Service Layer
Services in `src/services/` handle external communication:
- `api.ts` - Base API client with HTTP methods
- `reportService.ts` - Report-related API calls
- `eventService.ts` - Event-related API calls
- `analyticsService.ts` - Analytics API calls
- `exifService.ts` - EXIF metadata extraction
## Hooks
Custom hooks in `src/hooks/`:
- `useAuth.ts` - Authentication state and methods (Clerk wrapper)
- `useGeolocation.ts` - Device geolocation access
- Additional hooks as needed for shared logic
## Utilities
Helper functions in `src/utils/`:
- Coordinate validation
- Distance calculations
- File validation
- Date formatting
- Other pure utility functions
## Styling Approach
- **Tailwind CSS** for component styling
- Utility classes directly in JSX
- Global styles in `index.css` (minimal)
- No CSS modules or styled-components
## Authentication Pattern
- Clerk handles all authentication
- Use `<SignedIn>` and `<SignedOut>` components for conditional rendering
- Use `<ProtectedRoute>` wrapper for authenticated pages
- Access user with `useUser()` hook from Clerk
## State Management
- **Local state**: React useState for component-specific state
- **Server state**: React Query for API data fetching/caching
- **Auth state**: Clerk provider
- No Redux or other global state libraries

93
.kiro/steering/tech.md Normal file
View File

@@ -0,0 +1,93 @@
# Technology Stack
## Frontend
- **React 19** with **TypeScript** for type-safe development
- **Vite** for build tooling and dev server
- **React Router** for client-side routing
- **Tailwind CSS v4** for styling (utility-first)
- **Clerk** (@clerk/clerk-react) for authentication
- **React Query** (@tanstack/react-query) for server state management
### Mapping & Visualization
- **Leaflet** for interactive maps (free, open-source)
- **OpenStreetMap** tiles as base layer
- **Leaflet.heat** for heat map overlays
- **Leaflet.markercluster** for marker clustering
- **Recharts** for charts and data visualization
### Utilities
- **date-fns** for date manipulation
## Backend (Planned)
- **Node.js** with **Express.js** REST API
- **MySQL 8.0+** database with spatial data support
- **Prisma** ORM for database access
- **Clerk** for authentication (backend SDK)
- **Multer** for file uploads
- **exifr** for EXIF metadata extraction
- **Redis** for caching external API responses
## Path Aliases
Use TypeScript path aliases for cleaner imports:
```typescript
import { Report } from '@/types';
import { apiClient } from '@/services/api';
import { useGeolocation } from '@/hooks';
```
Available aliases:
- `@/*` → `src/*`
- `@/components/*` → `src/components/*`
- `@/pages/*` → `src/pages/*`
- `@/services/*` → `src/services/*`
- `@/hooks/*` → `src/hooks/*`
- `@/utils/*` → `src/utils/*`
- `@/types/*` → `src/types/*`
## Environment Variables
Required in `.env.local`:
```env
# Clerk Authentication
VITE_CLERK_PUBLISHABLE_KEY=your_publishable_key
# API Configuration
VITE_API_BASE_URL=http://localhost:3000/api
```
## Common Commands
```bash
# Development
npm run dev # Start dev server (http://localhost:5173)
# Build
npm run build # Production build to dist/
# Preview
npm run preview # Preview production build locally
# Linting
npm run lint # Run ESLint
```
## TypeScript Configuration
- **Strict mode** enabled
- **noUnusedLocals** and **noUnusedParameters** enforced
- **noUncheckedIndexedAccess** for safer array/object access
- **JSX**: react-jsx (React 17+ transform)
- **Module resolution**: bundler mode
## Code Quality
- ESLint with React hooks and React refresh plugins
- Strict TypeScript checking
- No unused variables/parameters allowed