# FlowBankOS - EV Charging Management Platform

## Overview

FlowBankOS is a professional EV charging management platform designed for Singapore's 230V 50Hz electrical standard. The system provides real-time monitoring, smart charging modes, V2G (Vehicle-to-Grid) aggregator capabilities, fleet management, and multi-location charger management across Singapore.

The platform features:
- Real-time charging session monitoring with live power metrics
- Smart charging modes (Eco, Standard, Boost) with visual feedback
- **V2G (Vehicle-to-Grid) aggregator module** with comprehensive bidirectional energy management:
  - V2G pricing dashboard showing charging rates vs. discharge credits ($0.72/kWh)
  - Live vehicle SOC monitoring with minimum limit controls
  - V2G earnings tracker (daily/monthly) and grid event participation
  - Grid events card showing high demand periods with bonus rates and off-peak charging windows
  - Interactive hotspot overlay heat-map visualizing grid demand intensity across Singapore
  - V2G capability indicators on all chargers (6 out of 10 chargers support bidirectional charging)
  - Connector type display (CCS2/Type 2) for all charging stations
- Fleet charger management with bulk operations
- Multi-location charger mapping with Singapore-specific data
- Load management to prevent breaker overload
- Installer/commissioning mode for professional setup
- User access control and reservation system
- Comprehensive session history and analytics

## User Preferences

Preferred communication style: Simple, everyday language.

## Recent Changes

### Dashboard Enhancements (October 2025)
- **Session Metrics**: 5-card overview displaying:
  - Number of Sessions (05)
  - Power Made Available (1 MWh)
  - Average SOC (80%)
  - Active Sessions (01)
  - Currently Engaged status badge
- **Earnings Overview**: Total earnings tracker showing $500 from single user with prominent display
- **Grid Call Notification System**:
  - Header badges showing Grid Calls Made (24) and Accepted (18)
  - Preferred Location card (Marina Bay Sands) and Max No. Discharge limit (12)
  - Interactive notification cards with Accept/Decline buttons
  - Rich metadata display: incentive amount, location, fast charge status, duration
  - State management for notifications (pending/accepted/declined)
  - Sample notifications with real incentives ($12.50-$8.75) and 30-45 min durations

### Aggregator Tab Updates (October 2025)
- **Pricing Tiers**: Three pricing models for V2G discharge:
  - **Per Discharge**: $0.72/kWh base rate (Peak: $0.85/kWh, Off-Peak: $0.65/kWh)
  - **Flat Fee**: Monthly subscription plans ($50 Basic, $120 Premium, $200 Enterprise)
  - **Time-Based**: $1.20/hour base rate (Daytime: $1.50/hr, Evening: $1.20/hr, Night: $0.80/hr)
- **Singapore Pricing Benchmarks**: Location-based pricing across Singapore areas (average, min, max rates per kWh)
- **Active Incentives (Singapore-Wide)**: Island-wide incentive programs available to all EV owners
- **My Incentive Dashboard**: EV owner-specific incentive tracking with wallet balance, monthly earnings, and personal active incentives
- **V2G Status**: Real-time vehicle state of charge (SOC) monitoring with grid availability controls
- **V2G Earnings & Scheduling**: Daily/weekly/monthly earnings summaries and discharge scheduling with calendar view

### Technical Tab Consolidation (October 2025)
- **Unified Technical Hub**: Created single Technical tab with 4 sub-tabs:
  - **Charger Specs**: Charging rates (AC Level 2, DC Fast, Ultra-Fast), connection types (Type 2, CCS2, CHAdeMO), thermal management
  - **Warranties & Rules**: EV battery warranties (Tesla, BYD, Hyundai, Nissan), Grid Active Rules
  - **Load Management**: Load management panel, rules configuration, and history
  - **Installer Mode**: Installation panel, live diagnostics, diagnostic test suite
- Removed separate Load Management and Installer Mode navigation items
- **Session Limit Enforcement**: Platform-wide limits displayed (max 5 sessions shown, max 12 per car)

### Chargers Tab Enhancements (October 2025)
- **Available Chargers Section**: Moved from Aggregator with search, sort, and favorites functionality
- **Singapore Charger Network Map**: Interactive map with real Singapore charger locations and status
- **Quick Actions**: Route planner, charger reservation, session history, and payment methods (moved from Aggregator)
- **Upcoming Grid Events**: High demand periods, off-peak charging windows, and event notifications (moved from Aggregator)
- **All Chargers**: Complete charger list with search, filter, and management capabilities

### Previous Updates
- Implemented username/password authentication (test/test for development and production)
- Added Main Dashboard with EV owner perspective showing current charging session, notifications, charging history, and live charger status with ping visualization
- Integrated real Singapore charger data with V2G capability indicators (6 out of 10 chargers support bidirectional charging)

## System Architecture

### Frontend Architecture

**Technology Stack:**
- **Framework:** React 18 with TypeScript
- **Build Tool:** Vite with custom configuration for client-side rendering
- **Routing:** Wouter for client-side routing
- **State Management:** TanStack Query (React Query) for server state
- **UI Components:** Radix UI primitives with custom shadcn/ui implementation
- **Styling:** Tailwind CSS with custom design system based on Linear/Vercel/Stripe dashboard aesthetics

**Design System:**
- Dark mode primary with optional light mode
- Custom color palette with electric green primary (#8EDE36) for charging states
- Typography: Inter for UI, JetBrains Mono for technical data
- Component library follows "New York" style variant from shadcn/ui
- Responsive design with mobile-first approach

**Key Frontend Patterns:**
- Component composition with reusable UI primitives
- Custom hooks for common functionality (use-mobile, use-toast)
- Theme provider for dark/light mode switching
- Sidebar layout with collapsible navigation
- Real-time data visualization with Recharts

### Backend Architecture

**Technology Stack:**
- **Runtime:** Node.js with TypeScript
- **Framework:** Express.js for REST API
- **Database ORM:** Drizzle ORM
- **Database:** PostgreSQL (Neon serverless with WebSocket support)
- **Build:** esbuild for production bundling, tsx for development

**Server Structure:**
- `/server/index.ts` - Main Express application with middleware setup
- `/server/routes.ts` - API route registration (currently minimal, ready for expansion)
- `/server/storage.ts` - Data access layer with interface abstraction (currently in-memory, ready for database migration)
- `/server/db.ts` - Database connection configuration using Neon serverless

**Current Implementation:**
- In-memory storage implementation (MemStorage) as placeholder
- IStorage interface defines CRUD contracts for future database integration
- User authentication schema defined but not yet implemented
- Session-based architecture ready for implementation

### Data Storage Solutions

**Database Configuration:**
- **Primary Database:** PostgreSQL via Neon Serverless
- **Connection:** WebSocket-based pooling for serverless compatibility
- **Schema Management:** Drizzle Kit for migrations
- **Schema Location:** `/shared/schema.ts` for type-safe sharing between client and server

**Current Schema:**
- Users table with username/password authentication (foundation for future OAuth2)
- UUID-based primary keys with PostgreSQL native generation
- Zod validation schemas using drizzle-zod for runtime type safety

**Data Architecture Decisions:**
- Shared schema between frontend and backend ensures type consistency
- Migration-based schema evolution using Drizzle Kit
- Prepared for multi-tenant architecture with location-based data isolation

### Authentication & Authorization

**Planned Implementation:**
- OAuth2 with Google/Apple SSO (referenced in user stories, not yet implemented)
- Session-based authentication with secure cookie storage
- Role-based access control (Owner, Member roles defined in UI)
- User invitation system for shared charger access

**Current State:**
- Basic user schema prepared
- Storage interface supports user CRUD operations
- Frontend components built for user access panels and role management

### External Dependencies

**Third-Party Services:**

1. **Neon Database (@neondatabase/serverless)**
   - Serverless PostgreSQL with WebSocket support
   - Used for primary data persistence
   - Connection pooling configured for optimal performance

2. **OCPP Integration (Referenced)**
   - Open Charge Point Protocol for charger communication
   - Mentioned in user stories for charger linking/verification
   - Backend validation system planned for charger registration

3. **Singapore Location Data (Custom)**
   - Hardcoded location database in `/shared/singapore-data.ts`
   - Includes pricing, GPS coordinates, and area information
   - Support for peak/off-peak pricing per location
   - V2G capability flags and connector type information for each charger
   - 6 out of 10 chargers across Singapore marked as V2G-capable

4. **Vehicle API Integration (Planned)**
   - Referenced in V2G aggregator module
   - EV model selection and battery state tracking
   - Not yet implemented

**UI/Component Libraries:**
- Radix UI - Unstyled accessible primitives (17+ components)
- Recharts - Data visualization for analytics
- Lucide React - Icon system
- date-fns - Date/time formatting
- class-variance-authority - Component variant management

**Development Tools:**
- Replit-specific plugins for development experience
- Vite runtime error overlay
- Cartographer for code mapping
- Development banner for environment indication

**Build & Deployment:**
- TypeScript with strict mode enabled
- ESM module system throughout
- Path aliases for clean imports (@/, @shared/, @assets/)
- Production build uses esbuild for bundling
- Static asset serving in production mode

### Key Architectural Decisions

**1. Monorepo Structure**
- Client and server code in single repository
- Shared type definitions in `/shared` directory
- **Rationale:** Simplifies type safety between frontend and backend, reduces duplication
- **Trade-off:** Larger repository size, but better developer experience

**2. Storage Abstraction Layer**
- IStorage interface separates business logic from data access
- Current in-memory implementation for rapid prototyping
- **Rationale:** Easy migration to database without changing business logic
- **Alternative Considered:** Direct database calls (rejected for lack of flexibility)

**3. Component-First UI Development**
- Extensive component library in `/client/src/components/examples`
- Each component documented with standalone examples
- **Rationale:** Facilitates rapid UI development and testing
- **Pro:** Reusable, well-tested components
- **Con:** Requires maintenance of example files

**4. Singapore-Specific Implementation**
- Hardcoded location data for Singapore market
- 230V 50Hz electrical standard assumptions
- **Rationale:** MVP focused on single market
- **Future Consideration:** Internationalization layer for multi-market support

**5. Real-Time Data Architecture**
- Frontend polling-based updates via React Query
- Stale time set to Infinity, refetch disabled by default
- **Rationale:** Simplicity for current scale
- **Alternative for Scale:** WebSocket implementation for true real-time updates
- **Trade-off:** Higher latency, but simpler implementation

**6. Theme System**
- Context-based theme provider with localStorage persistence
- CSS custom properties for dynamic theming
- **Rationale:** Flexible theming without CSS-in-JS overhead
- **Pro:** Performance, no runtime style calculation
- **Con:** Limited dynamic theme customization