ZoneBud Application - Complete Function Analysis
■■ Application Architecture Overview
Frontend Stack: React + TypeScript + Tailwind CSS + Vite
Backend: Supabase (PostgreSQL + Edge Functions)
Mobile: Capacitor for native features (GPS, geolocation)
State Management: React Context + TanStack Query
■ 1. AUTHENTICATION & AUTHORIZATION SYSTEM
Frontend Components:
EnhancedAuthContext.tsx - Main authentication state management
ZoneRoleContext.tsx - Zone-based role assignment
ProtectedRoute.tsx - Route-level access control
LoginPage.tsx / SignUpPage.tsx - Authentication UI
Backend Functions:
secure-auth/index.ts - PIN hashing/verification, secure login
track-login-attempt/index.ts - Login attempt tracking
Database Tables:
user_profiles - User information with role-based access
authentication_data - Secure PIN storage with salt/hash
login_attempts - Failed login tracking for security
security_logs - Audit trail for security events
How It Works:
Login Flow: User enters credentials → Frontend validates → Edge function securely verifies →
JWT token issued
Role Management: Global roles (super_admin, admin, client_admin) + Zone-specific roles
(zone_manager_rw, zone_manager_ro, app_user)
Security: PIN hashing with salt, failed attempt tracking, session management
Access Control: RLS policies enforce role-based data access automatically
■ 2. REAL-TIME WORKFORCE TRACKING SYSTEM
Frontend Services:
enhancedLocationService.ts - High-accuracy GPS tracking (5-15m precision)
enhancedPresenceService.ts - Presence management and reporting
LocationTracker.tsx - Real-time location component
Backend Functions:
geofencing/index.ts - Server-side zone detection
trigger-location-tracking/index.ts - Location update processing
Database Tables:
presence_tracking - Current user zone status
presence_history - Historical entry/exit events
location_requests - Manager-initiated location requests
How It Works:
GPS Tracking: Capacitor Geolocation API → 15-second intervals → High accuracy optimization
Zone Detection: Client-side initial check → Server-side verification using point_in_zone() function
Entry/Exit Events: Automatic detection → Database functions handle presence updates →
Real-time notifications
Manager Tracking: Zone managers can request immediate location updates from workers
■■ 3. GEOFENCED ZONES MANAGEMENT
Frontend Components:
enhancedZoneService.ts - Zone CRUD operations
EnhancedInteractiveZoneCreator.tsx - Multi-coordinate zone creation
MultiCoordinateZoneCreator.tsx - Polygon zone drawing
Database Tables:
zones - Zone definitions with rectangular bounds
zone_coordinates - Polygon coordinates for irregular shapes
zone_assignments - User-to-zone mappings with roles
Database Functions:
point_in_zone() - Server-side geofence validation using ray-casting algorithm
update_user_presence() - Presence tracking with zone detection
How It Works:
Zone Creation: Draw polygon on map → Calculate bounding box → Store coordinates → Validate
geometry
Zone Types: Rectangular (simple) or Polygon (irregular shapes with 4+ coordinates)
Zone States: Pending → Approved → Active → Suspended → Closed → Archived
Access Control: Role-based zone management with assignment tracking
■■ 4. HAZARD MANAGEMENT SYSTEM
Frontend Components:
hazardService.ts - Hazard CRUD operations
AlertCreator.tsx - Hazard reporting with media
HazardsPage.tsx - Hazard dashboard
Database Tables:
hazards - Hazard reports with GPS coordinates
user_alerts - Real-time notifications
Database Functions:
create_hazard_alerts() - Trigger function for zone manager notifications
How It Works:
Report Creation: User captures location → Adds photos/videos → Submits hazard report
Severity Levels: Low, Medium, High, Critical with color coding
Workflow: Open → In Progress → Resolved → Closed
Notifications: Auto-alert zone managers in affected zones
■ 5. BROADCAST MESSAGING SYSTEM
Frontend Services:
cleanBroadcastService.ts - Broadcast management
BroadcastsPage.tsx - Message center UI
Database Tables:
broadcasts - Message content and metadata
broadcast_group_links - Group targeting
user_alerts - Delivery tracking
How It Works:
Message Creation: Zone managers compose messages → Select target groups → Set priority
Delivery: Broadcast created → Group links established → User alerts generated
Media Support: Text, images, videos with file size limits
Targeting: All users in zone OR specific user groups
■ 6. USER GROUPS & COMMUNICATION
Frontend Services:
enhancedGroupService.ts - Group management with messaging
GroupsPage.tsx - Group administration
GroupChat.tsx - Real-time messaging
Database Tables:
groups - Group definitions
group_members - Membership management
group_messages - Chat messages
group_files - File sharing within groups
How It Works:
Group Creation: Zone managers create groups → Assign members → Set permissions
Messaging: Real-time chat → File sharing → Message history
File Management: Upload limits (10MB) → Group-based access control
Notifications: Message alerts → Activity tracking
■ 7. DOCUMENT & FOLDER MANAGEMENT
Frontend Services:
enhancedDocumentService.ts - File operations
folderGroupService.ts - Folder-group linking
FilesAndFoldersPage.tsx - File browser UI
Database Tables:
documents - File metadata and URLs
folders - Folder structure
folder_group_links - Group access permissions
How It Works:
File Upload: Zone managers upload files → Store in Supabase Storage → Link to folders/groups
Organization: Hierarchical folder structure → Group-based access control
Permissions: Public files OR group-restricted access
File Types: Documents, images, videos with metadata tracking
■ 8. USER MANAGEMENT SYSTEM
Frontend Services:
cleanUserService.ts - User CRUD operations
superAdminUserService.ts - Admin-level user management
CleanUsersPage.tsx - User administration
Database Functions:
delete_user_permanently() - Comprehensive user deletion
generate_user_code() - Unique user code generation
create_user_pin() - Secure PIN creation
How It Works:
User Creation: Admin creates profile → Generates unique code → Sets initial role
Code System: Format "ZB-XXXX-XXXX-XXXX" for easy identification
Role Assignment: Global + zone-specific roles with inheritance
PIN Management: Secure storage with salt/hash for mobile access
■ 9. PRESENCE & REPORTING SYSTEM
Frontend Services:
reportsService.ts - Report generation
pdfService.ts - PDF export functionality
Database Functions:
record_location_check() - Location validation and logging
Various reporting functions for data aggregation
How It Works:
Data Collection: Continuous presence tracking → Event logging → Accuracy validation
Report Types: Daily, Fortnightly, Instant reports with various formats
Export Options: PDF, CSV, Excel with customizable date ranges
Metrics: Entry/exit times, duration, occupancy statistics
■ 10. SECURITY & AUDIT SYSTEM
Database Tables:
security_logs - Comprehensive audit trail
audit_logs - Database change tracking
data_breach_notifications - Security incident management
Database Functions:
log_security_incident() - Security event logging
track_login_attempt() - Authentication monitoring
How It Works:
Event Tracking: All security events logged → IP tracking → User agent capture
Breach Detection: Failed login monitoring → Suspicious activity alerts
Audit Trail: Complete data change history → User action tracking
Compliance: GDPR-ready with data deletion capabilities
■ 11. MOBILE-SPECIFIC FEATURES
Capacitor Integration:
GPS/Geolocation services with high accuracy
Background location tracking
Native permission management
Platform-specific optimizations
How It Works:
GPS Optimization: Warm-up sequences → High accuracy mode → Battery optimization
Permissions: Runtime permission requests → Graceful degradation
Background Tracking: Continuous monitoring while app is backgrounded
Platform Detection: Different strategies for iOS/Android/Web
■ 12. ROLE-BASED ACCESS CONTROL
Role Hierarchy:
Internal: super_admin, admin (full access)
Client: client_admin (organization management)
Zone: zone_manager_rw, zone_manager_ro (zone-specific)
User: app_user (basic worker access)
Permission Matrix:
Each role has specific permissions enforced through:
RLS policies (database level)
Context providers (application level)
Component-level access control
■ 13. REAL-TIME FEATURES
Supabase Realtime:
Live presence updates
Real-time messaging
Location change notifications
Alert broadcasting
How It Works:
WebSocket Connections: Supabase Realtime channels
Event Subscriptions: Table-specific change monitoring
Live Updates: Automatic UI updates without refresh
Offline Handling: Graceful degradation and sync on reconnect