Skip to content

Latest commit

Β 

History

247 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”‹ UrjaFlow - Energy as a Service Platform

CI/CD Pipeline License: MIT Node.js Version TypeScript Next.js

Enterprise-Grade Energy Management Platform with Real-Time Monitoring & Role-Based Access Control

πŸš€ Live Demo | πŸ“– Documentation | πŸ› οΈ Getting Started

πŸ“‹ Table of Contents


🎯 Problem Statement

Energy Management Challenges in Modern Organizations

Current Industry Problems:

  • Fragmented Systems: Multiple disconnected energy monitoring tools
  • Data Silos: Energy data scattered across different platforms
  • Limited Access Control: No role-based permissions for energy data
  • Poor Real-Time Insights: Delayed or incomplete energy analytics
  • High Operational Costs: Manual monitoring and inefficient resource allocation
  • Compliance Issues: Difficulty tracking energy consumption for regulatory compliance
  • Scalability Issues: Systems that don't grow with organizational needs

Business Impact

  • 30% higher energy costs due to poor monitoring
  • 45% of organizations lack real-time energy insights
  • 60% struggle with energy data accessibility
  • 25% compliance issues due to inadequate tracking

πŸ’‘ Solution

UrjaFlow: Comprehensive Energy as a Service Platform

UrjaFlow is a modern, scalable Energy Management Platform that provides:

  • Real-time Energy Monitoring: Live tracking of generation, consumption, and storage
  • Role-Based Access Control: Granular permissions for different user types
  • Advanced Analytics: AI-powered insights and predictive analytics
  • Multi-Organization Support: Manage multiple energy systems from one platform
  • Professional Logging: Custom colored terminal logging for better debugging
  • Enterprise-Grade Testing: Comprehensive CI/CD with real data validation

Key Differentiators

  • πŸ”₯ Real Data Integration: No mock data - actual energy readings and analytics
  • πŸ‘₯ Multi-Role Architecture: SUPER_ADMIN, ORG_ADMIN, MANAGER, VIEWER roles
  • 🎨 Professional UI/UX: Modern, responsive design with real-time updates
  • πŸ”’ Enterprise Security: JWT authentication, role-based permissions
  • πŸ“Š Advanced Analytics: Time-based analytics, performance metrics
  • πŸš€ Production Ready: Complete CI/CD pipeline with automated testing

πŸ—οΈ Architecture

System Architecture Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Frontend      β”‚    β”‚   Backend API   β”‚    β”‚   Database      β”‚
β”‚   (Next.js)     │◄──►│   (Next.js)     │◄──►│   (PostgreSQL)  β”‚
β”‚                 β”‚    β”‚                 β”‚    β”‚                 β”‚
β”‚ β€’ React 18      β”‚    β”‚ β€’ REST APIs     β”‚    β”‚ β€’ Energy Data   β”‚
β”‚ β€’ TypeScript    β”‚    β”‚ β€’ Auth (NextAuth)β”‚   β”‚ β€’ User Mgmt     β”‚
β”‚ β€’ Tailwind CSS  β”‚    β”‚ β€’ Prisma ORM    β”‚    β”‚ β€’ Device Mgmt   β”‚
β”‚ β€’ Real-time UI  β”‚    β”‚ β€’ Custom Logger β”‚    β”‚ β€’ Analytics     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                       β”‚                       β”‚
         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚   External      β”‚
                    β”‚   Services      β”‚
                    β”‚                 β”‚
                    β”‚ β€’ Stripe API    β”‚
                    β”‚ β€’ Email Service β”‚
                    β”‚ β€’ IoT Devices   β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Component Architecture

src/
β”œβ”€β”€ app/                    # Next.js App Router
β”‚   β”œβ”€β”€ (dashboard)/       # Dashboard routes
β”‚   β”œβ”€β”€ admin/            # Admin panel
β”‚   β”œβ”€β”€ analytics/        # Analytics pages
β”‚   β”œβ”€β”€ api/              # API routes
β”‚   └── auth/             # Authentication
β”œβ”€β”€ components/           # Reusable components
β”‚   β”œβ”€β”€ ui/              # UI components
β”‚   β”œβ”€β”€ forms/           # Form components
β”‚   └── charts/          # Chart components
β”œβ”€β”€ lib/                 # Utilities
β”‚   β”œβ”€β”€ auth.ts          # Authentication
β”‚   β”œβ”€β”€ prisma.ts        # Database client
β”‚   β”œβ”€β”€ logger.ts        # Custom logger
β”‚   └── utils.ts         # Helper functions
β”œβ”€β”€ hooks/               # Custom React hooks
β”œβ”€β”€ types/               # TypeScript definitions
└── tests/               # Test files

πŸ‘₯ Role-Based System

User Roles & Permissions

πŸ”΄ SUPER_ADMIN

Full System Access

  • βœ… Manage all organizations
  • βœ… System-wide analytics
  • βœ… User management across orgs
  • βœ… Billing and subscription management
  • βœ… Platform configuration
  • βœ… Advanced reporting

🟑 ORG_ADMIN

Organization Management

  • βœ… Manage own organization
  • βœ… Organization analytics
  • βœ… Manage organization users
  • βœ… Device management
  • βœ… Billing for organization
  • βœ… Support ticket management

🟒 MANAGER

Operations Management

  • βœ… View analytics & reports
  • βœ… Device monitoring
  • βœ… Performance metrics
  • βœ… Support ticket creation
  • ❌ User management
  • ❌ Billing access

πŸ”΅ VIEWER

Read-Only Access

  • βœ… View dashboard
  • βœ… View analytics
  • βœ… View reports
  • ❌ Any management functions
  • ❌ Configuration access
  • ❌ Support tickets

Access Control Matrix

Feature SUPER_ADMIN ORG_ADMIN MANAGER VIEWER
Dashboard βœ… βœ… βœ… βœ…
Analytics βœ… βœ… βœ… βœ…
Reports βœ… βœ… βœ… βœ…
Organizations βœ… βœ… ❌ ❌
Billing βœ… βœ… ❌ ❌
Support βœ… βœ… βœ… ❌
Admin Panel βœ… ❌ ❌ ❌

✨ Features

🎯 Core Features

πŸ“Š Real-Time Energy Monitoring

  • Live Generation Tracking: Solar, wind, and other renewable sources
  • Consumption Analytics: Real-time energy usage patterns
  • Battery Management: Storage levels and efficiency metrics
  • Device Status: Connected IoT devices monitoring
  • Performance Metrics: Efficiency and output analysis

πŸ‘₯ Multi-Organization Support

  • Organization Management: Create and manage multiple organizations
  • User Assignment: Assign users to specific organizations
  • Data Isolation: Secure data separation between organizations
  • Custom Branding: Organization-specific configurations

πŸ” Advanced Security

  • JWT Authentication: Secure token-based authentication
  • Role-Based Access: Granular permission system
  • Session Management: Secure session handling
  • API Security: Protected API endpoints
  • Data Encryption: Sensitive data protection

πŸ“ˆ Analytics & Reporting

  • Time-Based Analytics: Hourly, daily, weekly, monthly views
  • Energy Trends: Consumption and generation patterns
  • Performance Reports: Efficiency and cost analysis
  • Custom Reports: Tailored reporting for different roles
  • Export Capabilities: Data export in multiple formats

πŸ’³ Billing & Subscriptions

  • Subscription Plans: Basic, Professional, Enterprise tiers
  • Usage-Based Billing: Pay-per-use energy tracking
  • Invoice Management: Automated billing and invoicing
  • Payment Processing: Stripe integration
  • Billing History: Complete transaction records

🎨 Professional UI/UX

  • Modern Design: Clean, intuitive interface
  • Responsive Layout: Works on all devices
  • Real-Time Updates: Live data refresh
  • Dark/Light Mode: Theme customization
  • Accessibility: WCAG compliant design

πŸš€ Advanced Features

πŸ”§ Professional Logging System

  • Color-Coded Logs: Different colors for log levels
  • Timestamp Tracking: Precise timing information
  • Performance Metrics: Request/response timing
  • Error Tracking: Detailed error reporting
  • Debug Information: Comprehensive debugging data

πŸ§ͺ Comprehensive Testing

  • Real Data Testing: Tests with actual database data
  • Role-Based Testing: All user roles tested
  • E2E Testing: Complete user journey testing
  • Performance Testing: Load and stress testing
  • Security Testing: Vulnerability scanning

πŸš€ CI/CD Pipeline

  • Automated Testing: Multi-stage testing pipeline
  • Database Integration: Real database testing
  • Security Scanning: Automated vulnerability checks
  • Performance Monitoring: Lighthouse integration
  • Multi-Environment: Dev, staging, production deployments

πŸ› οΈ Technology Stack

Frontend Technologies

  • Next.js 14.2.35 - React framework with App Router
  • React 18 - UI library with hooks and concurrent features
  • TypeScript 4.9+ - Type-safe JavaScript
  • Tailwind CSS - Utility-first CSS framework
  • Lucide React - Modern icon library
  • Recharts - Chart library for analytics
  • React Hook Form - Form management
  • Zustand - State management

Backend Technologies

  • Next.js API Routes - Serverless API endpoints
  • NextAuth.js - Authentication solution
  • Prisma ORM - Database ORM and migrations
  • PostgreSQL - Primary database
  • JWT - Token-based authentication
  • bcrypt - Password hashing
  • Stripe API - Payment processing

Development & DevOps

  • Node.js 20+ - JavaScript runtime
  • ESLint - Code linting
  • Prettier - Code formatting
  • Jest - Unit testing framework
  • Playwright - E2E testing
  • Docker - Containerization
  • GitHub Actions - CI/CD pipeline
  • Vercel - Deployment platform

Monitoring & Analytics

  • Custom Logger - Professional logging system
  • Lighthouse CI - Performance monitoring
  • Sentry - Error tracking (optional)
  • Google Analytics - User analytics (optional)

πŸš€ Getting Started

Prerequisites

  • Node.js 20.0.0 or higher
  • PostgreSQL 13 or higher
  • npm or yarn package manager
  • Git for version control

Installation

  1. Clone the repository
git clone https://github.com/your-org/urjaflow.git
cd urjaflow
  1. Install dependencies
npm install
  1. Set up environment variables
cp .env.example .env
# Edit .env with your configuration
  1. Set up database
# Create PostgreSQL database
createdb urjaflow

# Run migrations
npm run prisma:migrate

# Generate Prisma client
npm run prisma:generate

# Seed database with real data
npm run prisma:seed
  1. Start development server
npm run dev
  1. Access the application

Environment Variables

# Database
DATABASE_URL="postgresql://username:password@localhost:5432/urjaflow"

# NextAuth
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="your-secret-key"

# Stripe (for payments)
STRIPE_SECRET_KEY="sk_test_..."
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_test_..."

# Email (optional)
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_USER="your-email@gmail.com"
SMTP_PASS="your-app-password"

# Features
ENABLE_REALTIME=true
ENABLE_STRIPE=true
ENABLE_EMAIL=true

Default Login Credentials

After running npm run prisma:seed, you can use these credentials:

Role Email Password Access
SUPER_ADMIN admin@urjaflow.com password123 Full system access
ORG_ADMIN org.admin@techsolutions.com password123 Organization management
MANAGER manager@techsolutions.com password123 Analytics & reports
VIEWER demo@urjaflow.com password123 Read-only access

πŸ“Š Database Schema

Core Tables

Organizations

organizations {
  id: UUID (Primary Key)
  name: String
  slug: String (Unique)
  description: Text
  address: JSON
  phone: String
  email: String
  website: String
  logo: String
  settings: JSON
  createdAt: DateTime
  updatedAt: DateTime
}

Users

users {
  id: UUID (Primary Key)
  email: String (Unique)
  name: String
  role: Enum (SUPER_ADMIN, ORG_ADMIN, MANAGER, VIEWER)
  password: String (Hashed)
  organizationId: UUID (Foreign Key)
  phone: String
  company: String
  address: JSON
  isActive: Boolean
  lastLoginAt: DateTime
  createdAt: DateTime
  updatedAt: DateTime
}

Devices

devices {
  id: UUID (Primary Key)
  name: String
  type: Enum (SOLAR_PANEL, BATTERY, INVERTER, METER)
  model: String
  serialNumber: String (Unique)
  organizationId: UUID (Foreign Key)
  location: JSON
  specifications: JSON
  status: Enum (ACTIVE, INACTIVE, MAINTENANCE)
  installedAt: DateTime
  createdAt: DateTime
  updatedAt: DateTime
}

Device Readings

device_readings {
  id: UUID (Primary Key)
  deviceId: UUID (Foreign Key)
  timestamp: DateTime
  generationKW: Float
  consumptionKW: Float
  batteryPercent: Float
  voltage: Float
  current: Float
  temperature: Float
  efficiency: Float
  metadata: JSON
}

Relationships

Organizations (1) ←→ (N) Users
Organizations (1) ←→ (N) Devices
Devices (1) ←→ (N) Device Readings
Users (1) ←→ (N) Support Tickets
Organizations (1) ←→ (N) Subscriptions

πŸ§ͺ Testing

Test Structure

tests/
β”œβ”€β”€ e2e/                    # End-to-end tests
β”‚   β”œβ”€β”€ auth-helper.ts     # Authentication helpers
β”‚   β”œβ”€β”€ dashboard.spec.ts  # Dashboard tests
β”‚   β”œβ”€β”€ analytics.spec.ts  # Analytics tests
β”‚   └── auth.spec.ts       # Authentication tests
β”œβ”€β”€ unit/                   # Unit tests
└── integration/            # Integration tests

Running Tests

Local Testing

# Run all tests
npm run test:real-data

# Run role-based tests
npm run test:roles

# Run specific feature tests
npm run test:dashboard
npm run test:analytics

# Run E2E tests
npm run test:e2e

# Run unit tests
npm test

CI/CD Testing

# Run complete CI pipeline locally
npm run ci:local

# Run Docker-based CI
npm run ci:docker

Test Coverage

  • Authentication: All 4 user roles tested
  • Authorization: Route protection and permissions
  • Real Data: Tests with actual database data
  • UI Components: Component-level testing
  • API Endpoints: All API routes tested
  • Database Operations: CRUD operations verified
  • Performance: Load and stress testing
  • Security: Vulnerability scanning

πŸš€ Deployment

Production Deployment

Vercel (Recommended)

# Install Vercel CLI
npm i -g vercel

# Deploy to production
vercel --prod

# Set environment variables
vercel env add DATABASE_URL
vercel env add NEXTAUTH_SECRET
vercel env add STRIPE_SECRET_KEY

Docker Deployment

# Build production image
docker build -t urjaflow:latest .

# Run with Docker Compose
docker-compose -f docker-compose.prod.yml up -d

Self-Hosted

# Build application
npm run build

# Start production server
npm start

# Use PM2 for process management
pm2 start ecosystem.config.js

Environment Configuration

Production Environment Variables

NODE_ENV=production
DATABASE_URL=postgresql://user:pass@host:5432/urjaflow_prod
NEXTAUTH_URL=https://your-domain.com
NEXTAUTH_SECRET=production-secret-key
STRIPE_SECRET_KEY=sk_live_...

Database Setup

# Create production database
createdb urjaflow_prod

# Run migrations
npm run prisma:migrate

# Seed production data (optional)
npm run prisma:seed

Monitoring & Maintenance

Health Checks

  • API Health: /api/health endpoint
  • Database Health: Connection monitoring
  • Performance Metrics: Response time tracking
  • Error Tracking: Comprehensive error logging

Backup Strategy

  • Database Backups: Daily automated backups
  • Code Backups: Git version control
  • Configuration Backups: Environment variables
  • Asset Backups: User uploads and media

πŸ“ˆ Performance

Optimization Features

Frontend Performance

  • Code Splitting: Automatic route-based splitting
  • Image Optimization: Next.js Image component
  • Static Generation: Pre-built pages where possible
  • Caching: Browser and CDN caching
  • Bundle Optimization: Tree shaking and minification

Backend Performance

  • Database Indexing: Optimized queries
  • Connection Pooling: Efficient database connections
  • API Caching: Response caching for static data
  • Lazy Loading: On-demand data loading
  • Compression: Gzip compression

Performance Metrics

  • Lighthouse Score: 95+ across all categories
  • First Contentful Paint: < 1.5 seconds
  • Time to Interactive: < 3 seconds
  • Database Query Time: < 100ms average
  • API Response Time: < 200ms average

Monitoring Tools

Built-in Monitoring

  • Custom Logger: Professional logging system
  • Performance Metrics: Request timing
  • Error Tracking: Comprehensive error reporting
  • Health Checks: Application health monitoring

External Monitoring (Optional)

  • Sentry: Error tracking and performance
  • Google Analytics: User behavior analytics
  • New Relic: Application performance monitoring
  • Datadog: Infrastructure monitoring

πŸ”’ Security

Security Features

Authentication & Authorization

  • JWT Tokens: Secure token-based authentication
  • Role-Based Access: Granular permission system
  • Session Management: Secure session handling
  • Password Security: bcrypt hashing with salt
  • Multi-Factor Auth: Optional 2FA support

Data Protection

  • Encryption: Data encryption at rest and in transit
  • Input Validation: Comprehensive input sanitization
  • SQL Injection Prevention: Parameterized queries
  • XSS Protection: Content Security Policy
  • CSRF Protection: Token-based CSRF protection

API Security

  • Rate Limiting: API request throttling
  • CORS Configuration: Proper cross-origin settings
  • API Key Management: Secure API key handling
  • Endpoint Protection: Role-based API access
  • Audit Logging: Complete access logging

Security Best Practices

Development Security

  • Code Reviews: Security-focused code reviews
  • Dependency Scanning: Automated vulnerability scanning
  • Secret Management: Environment variable protection
  • Secure Coding: OWASP guidelines compliance
  • Regular Updates: Dependency security updates

Operational Security

  • Access Control: Principle of least privilege
  • Network Security: Firewall and network segmentation
  • Backup Security: Encrypted backup storage
  • Incident Response: Security incident procedures
  • Compliance: GDPR and data protection compliance

🀝 Contributing

Development Workflow

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/amazing-feature
  3. Make changes with proper testing
  4. Run tests: npm run ci:local
  5. Commit changes: git commit -m 'Add amazing feature'
  6. Push to branch: git push origin feature/amazing-feature
  7. Open Pull Request

Code Standards

TypeScript Guidelines

  • Use strict TypeScript configuration
  • Provide proper type definitions
  • Use interfaces for object shapes
  • Avoid any type when possible
  • Use proper error handling

Code Style

  • Follow ESLint configuration
  • Use Prettier for formatting
  • Write descriptive variable names
  • Add comments for complex logic
  • Use consistent naming conventions

Testing Requirements

  • Write tests for new features
  • Maintain test coverage above 80%
  • Test all user roles and permissions
  • Include real data testing
  • Add performance tests for critical paths

Pull Request Process

PR Requirements

  • Description: Clear description of changes
  • Testing: All tests must pass
  • Documentation: Update relevant documentation
  • Performance: No performance regression
  • Security: No security vulnerabilities

Review Process

  • Code Review: At least one review required
  • Automated Checks: CI/CD pipeline must pass
  • Security Review: Security team approval for sensitive changes
  • Performance Review: Performance team approval for impactful changes
  • Documentation Review: Documentation team approval for user-facing changes

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

License Summary

  • βœ… Commercial use allowed
  • βœ… Modification allowed
  • βœ… Distribution allowed
  • βœ… Private use allowed
  • ❌ Liability and warranty disclaimed

Attribution

If you use this project, please include attribution:

Powered by UrjaFlow - Energy as a Service Platform
https://github.com/your-org/urjaflow

πŸ™ Acknowledgments

Core Contributors

  • Development Team: Full-stack development and architecture
  • Design Team: UI/UX design and user experience
  • Testing Team: Quality assurance and testing
  • DevOps Team: Infrastructure and deployment

Open Source Libraries

  • Next.js: React framework and serverless functions
  • Prisma: Database ORM and migrations
  • Tailwind CSS: Utility-first CSS framework
  • NextAuth.js: Authentication solution
  • Playwright: End-to-end testing framework

Community Support

  • GitHub Community: Issue reporting and feature requests
  • Discord Community: Real-time discussions and support
  • Stack Overflow: Technical questions and answers
  • Blog Contributors: Tutorials and best practices

πŸ“ž Support & Contact

Getting Help

Business Inquiries

Social Media


πŸ”‹ UrjaFlow - Empowering Sustainable Energy Management

⭐ Star this repo β€’ πŸ› Report issues β€’ πŸš€ Deploy your own

Made with ❀️ by the UrjaFlow Team

About

A digital platform for the Energy-as-a-Service (EaaS) model. This system allows consumers to subscribe to energy services (like solar & storage) without owning the hardware. It features plan management, real-time usage monitoring, and integrated billing to make clean energy accessible and affordable.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages