tpt-power-utility
TypeScriptOpen-source electricity utility management platform — grid monitoring, real-time consumption analytics, smart meter integration, outage management, billing engine & customer self-service portal. TypeScript. MIT.
Languages
Power Utility Management System
A comprehensive and flexible platform for power utilities to manage their infrastructure. Built with modern technologies for easy deployment across multiple platforms.
Features
- Asset Management: Track and manage power infrastructure components (substations, transformers, lines, etc.) with pagination support
- Real-time Monitoring: Monitor system performance, voltage, current, temperature, and other metrics
- Alert System: Automated alerts for system anomalies and maintenance requirements with toast notifications
- Reporting & Analytics: Generate comprehensive reports and performance analytics
- User Management: Role-based access control for different utility personnel
- Responsive UI: Works on desktop and mobile devices with loading skeletons for better UX
- API-First Design: RESTful APIs for easy integration with existing systems
- Security First: SQL injection protection, safe formula evaluation, and environment validation
- Type Safety: Comprehensive TypeScript types for better development experience
- API Documentation: Interactive Swagger documentation for all endpoints
Technology Stack
- Backend: Node.js, Express, TypeScript, PostgreSQL
- Frontend: React, TypeScript, Material-UI
- Database: PostgreSQL
- Containerization: Docker & Docker Compose
- Authentication: JWT with bcrypt password hashing
Quick Start
Prerequisites
- Node.js 18+
- PostgreSQL 15+
- Docker & Docker Compose (for containerized deployment)
Local Development with Docker
- Clone the repository
- Run the application:
docker-compose up --build - Access the application:
- Frontend: http://localhost:3000
- Backend API: http://localhost:5000
- Database: localhost:5432
Local Development without Docker
Backend Setup
-
Navigate to backend directory:
cd backend -
Install dependencies:
npm install -
Set up PostgreSQL database and update
.envfile with your database credentials -
Run database migrations:
# Connect to PostgreSQL and run the schema.sql file psql -U postgres -d power_utility -f database/schema.sql -
Start the development server:
npm run dev
Frontend Setup
-
Navigate to frontend directory:
cd frontend -
Install dependencies:
npm install -
Start the development server:
npm start
Deployment Options
Docker Deployment
DigitalOcean App Platform
- Create a new app on DigitalOcean App Platform
- Connect your GitHub repository
- Configure the app:
- Service: Web Service
- Source: GitHub
- Runtime: Docker
- Dockerfile Path:
./Dockerfile - Environment Variables:
NODE_ENV=production DB_HOST=your_database_host DB_PORT=5432 DB_NAME=power_utility DB_USER=your_db_user DB_PASSWORD=your_db_password JWT_SECRET=your_secure_jwt_secret
DigitalOcean Droplet
-
Create a Ubuntu droplet
-
SSH into the droplet
-
Install Docker and Docker Compose:
sudo apt update sudo apt install docker.io docker-compose sudo systemctl start docker sudo systemctl enable docker -
Clone your repository and navigate to the project directory
-
Update environment variables in
docker-compose.yml -
Run the application:
docker-compose up -d --build
Non-Docker Deployment
Backend Deployment
-
PM2 Process Manager (Recommended):
npm install -g pm2 cd backend npm run build pm2 start dist/index.js --name "power-utility-backend" pm2 startup pm2 save -
Systemd Service:
sudo nano /etc/systemd/system/power-utility.serviceAdd the following content:
[Unit] Description=Power Utility Backend After=network.target [Service] Type=simple User=ubuntu WorkingDirectory=/path/to/your/app/backend ExecStart=/usr/bin/node dist/index.js Restart=on-failure [Install] WantedBy=multi-user.targetEnable and start the service:
sudo systemctl enable power-utility sudo systemctl start power-utility
Frontend Deployment
-
Build the production bundle:
cd frontend npm run build -
Nginx (Recommended):
sudo apt install nginx sudo nano /etc/nginx/sites-available/power-utilityAdd the following configuration:
server { listen 80; server_name your-domain.com; location / { root /path/to/your/app/frontend/build; index index.html index.htm; try_files $uri $uri/ /index.html; } location /api { proxy_pass http://localhost:5000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }Enable the site:
sudo ln -s /etc/nginx/sites-available/power-utility /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx
Database Setup
-
DigitalOcean Managed Database:
- Create a PostgreSQL database cluster
- Note the connection details
- Update your environment variables
-
Self-hosted PostgreSQL:
sudo apt install postgresql postgresql-contrib sudo -u postgres createdb power_utility sudo -u postgres psql -c "CREATE USER power_user WITH PASSWORD 'secure_password';" sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE power_utility TO power_user;"
Environment Variables
Backend (.env) - Required Variables
All of the following environment variables are required for the application to start:
# Database Configuration (Required)
DB_HOST=localhost
DB_PORT=5432
DB_NAME=power_utility
DB_USER=postgres
DB_PASSWORD=your_secure_password
# JWT Configuration (Required - DO NOT use default values)
JWT_SECRET=your_super_secret_jwt_key_here_change_in_production
# Server Configuration (Required)
PORT=5000
NODE_ENV=development
# CORS Configuration (Required)
CORS_ORIGIN=http://localhost:3000
Important Notes:
- All variables listed above are mandatory
- The application will fail to start if any required variable is missing
JWT_SECRETcannot be set to'secret'or'your-secret-key'(common default values)- For production, use strong, unique values for all secrets
- Multiple CORS origins can be specified as comma-separated values:
CORS_ORIGIN=http://localhost:3000,https://yourdomain.com
Frontend (.env)
REACT_APP_API_URL=http://localhost:5000/api
API Documentation
The API is fully documented using Swagger/OpenAPI. Access the interactive documentation at:
- Development: http://localhost:5000/api-docs
- Production: https://your-domain.com/api-docs
Authentication Endpoints
POST /api/auth/register- Register a new userPOST /api/auth/login- Login user
Asset Management
GET /api/assets- Get all assets (with pagination:?page=1&limit=50)GET /api/assets/:id- Get specific assetPOST /api/assets- Create new assetPUT /api/assets/:id- Update assetDELETE /api/assets/:id- Delete asset
Monitoring
GET /api/monitoring- Get monitoring data (with pagination)GET /api/monitoring/status/summary- Get system status summaryGET /api/monitoring/alerts- Get active alertsPOST /api/monitoring- Add monitoring dataPUT /api/monitoring/alerts/:id- Update alert status
Reports
GET /api/reports/utilization- Asset utilization reportGET /api/reports/alerts/summary- Alert summary reportGET /api/reports/performance- System performance report
Security Features
SQL Injection Protection
- All database queries use parameterized statements
- No direct string interpolation in SQL queries
- Comprehensive test coverage for injection prevention
Safe Formula Evaluation
Data transformation formulas use the expr-eval library for safe mathematical expression evaluation instead of the dangerous eval() function. All formulas are validated to prevent code injection attacks.
Supported Formula Syntax
Formulas use x as the variable representing the input value. The following syntax elements are supported:
Basic Arithmetic:
- Addition:
x + 5 - Subtraction:
x - 10 - Multiplication:
x * 2 - Division:
x / 100 - Exponentiation:
x ^ 2orx ** 2 - Modulo:
x % 10
Mathematical Functions:
- Trigonometric:
sin(x),cos(x),tan(x),asin(x),acos(x),atan(x) - Logarithmic:
log(x)(base 10),ln(x)(natural log) - Power/Square root:
sqrt(x),x ^ 0.5 - Rounding:
round(x),ceil(x),floor(x) - Absolute value:
abs(x)
Constants:
- Pi:
PI(≈ 3.14159) - Euler's number:
E(≈ 2.71828)
Grouping:
- Parentheses for precedence:
(x + 5) * 2
Formula Examples
Temperature Conversion:
- Celsius to Fahrenheit:
(x * 9/5) + 32 - Fahrenheit to Celsius:
(x - 32) * 5/9
Voltage/Current Calculations:
- Power calculation:
x * 220(current × voltage) - Efficiency percentage:
x * 100 - Scale to engineering units:
x / 1000
Sensor Calibration:
- Linear offset:
x + 2.5 - Linear scaling:
x * 1.15 - Non-linear correction:
x + (x * 0.05)
Common Engineering Formulas:
- RMS value:
x * 0.707(for sinusoidal waveforms) - Percentage error:
abs(x - 100) / 100 * 100 - Moving average approximation:
(x + prev) / 2(where prev is previous value)
Security Validation
Formulas are validated using multiple security checks:
- Pattern Filtering: Blocks dangerous JavaScript constructs (
eval,require,process, etc.) - Character Whitelisting: Only allows mathematical characters and the variable
x - Syntax Validation: Ensures balanced parentheses and valid expression structure
- Function Whitelisting: Only predefined mathematical functions are allowed
Invalid formulas are rejected with clear error messages, and the original value is preserved if formula evaluation fails.
Environment Validation
- Application fails fast if required environment variables are missing
- Prevents deployment with insecure default values
- Clear error messages for configuration issues
Testing
The backend includes comprehensive security and functionality tests:
cd backend
npm test # Run all tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage report
Test Coverage
- Security Tests: SQL injection protection, formula evaluation safety, environment validation
- API Tests: Endpoint functionality, error handling, authentication
- Integration Tests: Database operations, real-time features
Development
Code Quality
- TypeScript: Full type safety with centralized type definitions
- ESLint: Code linting and formatting
- Prettier: Consistent code formatting
User Experience
- Toast Notifications: Real-time feedback for user actions
- Loading Skeletons: Improved perceived performance
- Pagination: Efficient handling of large datasets
- Responsive Design: Works on all device sizes
Security Considerations
- Change default JWT secret in production
- Use strong passwords for database users
- Enable SSL/TLS for production deployments
- Regularly update dependencies
- Implement rate limiting for API endpoints
- Use environment-specific configuration
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
License
This project is licensed under the MIT License.
Support
For support and questions, please open an issue on GitHub or contact the development team.