Features Documentation
Table of Contents
- Authentication
- Dashboard
- Prediction Model
- Treatment Model
- Twin Engine
- Adaptive Optimizers
- CAD Integration
- WebSocket Monitor
- Report History
- Blockchain Verification
- Account Management
1. Authentication
Overview
Firebase-based authentication supporting email/password and Google OAuth.
Features
- Sign In: Email/password login
- Sign Up: New user registration with optional display name
- Google OAuth: One-click Google sign-in
- Auto-redirect: Logged-in users redirected from auth pages to dashboard
- Protected Routes: Unauthenticated users redirected to sign-in
Files
src/
├── lib/auth-context.tsx # AuthProvider, useAuth hook
├── lib/firebase.ts # Firebase initialization
├── app/(auth)/
│ ├── sign-in/page.tsx # Login page
│ └── sign-up/page.tsx # Registration page
└── components/auth/
├── sign-in-form.tsx # Login form component
└── sign-up-form.tsx # Registration form component
Auth Context API
interface AuthContextType {
user: User | null; // Firebase user object
loading: boolean; // Auth state loading
signIn: (email, password) => Promise<void>;
signUp: (email, password, displayName?) => Promise<void>;
signInWithGoogle: () => Promise<void>;
logout: () => Promise<void>;
}
// Usage
const { user, loading, signIn, logout } = useAuth();
Route Protection
// In (core)/layout.tsx
useEffect(() => {
if (!loading && !user) {
router.push("/sign-in");
}
}, [user, loading, router]);
2. Dashboard
Overview
Main application hub showing quick actions, system status, and blockchain status.
Features
- Personalized greeting based on time of day
- Quick action cards for all main features
- System stats (analysis tools, blockchain status)
- Blockchain status widget showing chain connection
Files
src/app/(core)/dashboard/page.tsx
Quick Actions
| Action | Route | Description |
|---|---|---|
| Prediction Model | /prediction-model | AI water quality prediction |
| Treatment Model | /treatment-model | Treatment recommendations |
| Twin Engine | /twin-engine | Combined analysis pipeline |
| Adaptive Optimizers | /adaptive-optimizers | Real-time simulation |
3. Prediction Model
Overview
AI-powered water reusability prediction with CPCB compliance checking.
Features
- 17 input parameters for comprehensive analysis
- Auto-estimation of missing effluent values
- CPCB compliance check with pass/fail status
- Smart verdict with actionable recommendations
- Treatment upgrade suggestions
- Alternative classifications with probabilities
- PDF export of results
- Auto-save to Firebase
- Blockchain storage of report hash
Files
src/
├── app/(core)/prediction-model/page.tsx # Main page
├── lib/ml-api/
│ ├── client.ts # API client
│ ├── hooks.ts # useReusabilityPrediction
│ └── types.ts # WastewaterInput, ReusabilityResult
├── lib/pdf/generators/prediction-pdf.ts # PDF generation
└── config/parameters.ts # INFLUENT_PARAMETERS, EFFLUENT_PARAMETERS
Input Parameters
Influent Parameters
| Parameter | Key | Unit | Default |
|---|---|---|---|
| Influent BOD | influent_BOD | mg/L | 18 |
| Influent COD | influent_COD | mg/L | 36 |
| Influent TSS | influent_TSS | mg/L | 22 |
| Influent pH | influent_pH | - | 6 |
| Influent TDS | influent_TDS | mg/L | 65 |
Operational Parameters
| Parameter | Key | Unit | Default |
|---|---|---|---|
| Flow Rate | flow_rate | m³/hr | 150 |
| Aeration Rate | aeration_rate | m³/hr | 35 |
| Chemical Dose | chemical_dose | mg/L | 12 |
| Sludge Recycle Rate | sludge_recycle_rate | % | 25 |
| Retention Time | retention_time | hours | 6 |
| Temperature | temperature | °C | 25 |
Effluent Parameters (Optional - Auto-estimated)
| Parameter | Key | Unit |
|---|---|---|
| Effluent BOD | effluent_BOD | mg/L |
| Effluent COD | effluent_COD | mg/L |
| Effluent TSS | effluent_TSS | mg/L |
| Effluent TDS | effluent_TDS | mg/L |
| Effluent pH | effluent_pH | - |
Result Structure
interface ReusabilityResult {
prediction: string; // Raw class name
prediction_display: string; // Human-readable name
confidence_percent: number; // 0-100
cpcb_compliance: {
status: "PASS" | "FAIL" | "UNKNOWN";
is_compliant: boolean | null;
reason: string;
records: CPCBRecord[]; // Parameter-by-parameter check
};
treatment_upgrade: {
upgrade_label: string;
upgrade_reason: string;
};
smart_verdict: {
status: "safe" | "unsafe" | "unknown";
headline: string;
bullets: string[];
};
alternatives: AlternativeClass[];
estimated_values?: Record<string, number>;
}
4. Treatment Model
Overview
Treatment stage recommendation based on water quality parameters.
Features
- 12 input parameters for water quality
- Use case selection (Irrigation, Domestic, Industrial, etc.)
- Multi-step treatment recommendations
- Quality score (0-100)
- Severity assessment (low/moderate/high/critical)
- Chemical dosing suggestions
- Risk assessment with reasons
- Parameter status breakdown
Files
src/
├── app/(core)/treatment-model/page.tsx # Main page
├── lib/ml-api/
│ ├── client.ts # API client
│ ├─ ─ hooks.ts # useTreatmentRecommendation
│ └── types.ts # TreatmentInput, TreatmentResult
└── config/parameters.ts # TREATMENT_PARAMETERS
Input Parameters
| Parameter | Key | Unit | Default |
|---|---|---|---|
| pH | pH | - | 7.5 |
| TSS | TSS | mg/L | 120 |
| Turbidity | Turbidity | NTU | 45 |
| BOD | BOD | mg/L | 180 |
| COD | COD | mg/L | 350 |
| Ammoniacal Nitrogen | NH4_N | mg/L | 25 |
| Total Nitrogen | Total_Nitrogen | mg/L | 40 |
| Phosphate | Phosphate | mg/L | 8 |
| Fecal Coliform | Fecal_Coliform | MPN/100mL | 5000 |
| Oil & Grease | Oil_Grease | mg/L | 15 |
| TDS | TDS | mg/L | 600 |
| Heavy Metals | Heavy_Metals | mg/L | 0.5 |
Use Cases
IrrigationDomestic UseIndustrial UseDrinking WaterAquaculture
Result Structure
interface TreatmentResult {
predicted_stage: string;
recommended_stage: string;
steps: string[];
step_descriptions: Record<string, string>;
severity_level: "low" | "moderate" | "high" | "critical";
quality_score: number;
parameter_status: Record<string, "Good" | "Moderate" | "Poor">;
chemical_suggestions: {
chlorine_dose_mg_l: number;
alum_dose_mg_l: number;
recommend_ro: boolean;
notes: string;
};
risk_assessment: {
level: "Low" | "Medium" | "High";
reasons: string[];
};
}
5. Twin Engine
Overview
Combined analysis running both Prediction and Treatment models in a unified workflow.
Features
- Shared parameters synced between models
- Sequential execution (Prediction → Treatment)
- Combined results view
- Unified PDF export
- Single blockchain transaction for both results
Files
src/app/(core)/twin-engine/page.tsx
Data Flow
┌──────────────────────────────────────────┐
│ Combined Input Form │
├────────────────┬─────────────────────────┤
│ Shared Params │ Model-specific Params │
│ (pH, TSS, etc) │ (aeration, turbidity) │
└───────┬────────┴───────────┬─────────────┘
│ │
▼ ▼
┌───────────────┐ ┌───────────────┐
│ Reusability │ │ Treatment │
│ Prediction │ │ Recommendation│
└───────┬───────┘ └───────┬───────┘
│ │
└────────┬───────────┘
▼
┌─────────────────┐
│ Combined Report │
│ + Blockchain │
└─────────────────┘
6. Adaptive Optimizers
Overview
Real-time simulation engine for water treatment scenario modeling.
Features
- Scenario selection (Normal, Stressed, Recovery, etc.)
- Real-time charts with live parameter updates
- Tick-based simulation with configurable speed
- Anomaly detection highlighting
- Control panel for simulation management
- Results export and report saving
Files
src/app/(core)/adaptive-optimizers/
├── page.tsx # Main page
├── components/
│ ├── chart-display.tsx # Chart visualization
│ ├── control-panel.tsx # Start/stop/reset controls
│ ├── parameter-sliders.tsx # Parameter adjustment
│ ├── results-panel.tsx # Summary and stats
│ ├── scenario-selector.tsx # Scenario dropdown
│ ├── simulation-chart.tsx # Real-time chart
│ └── status-indicator.tsx # Running/stopped status
└── utils/
├── scenarios.ts # Scenario definitions
├── simulation.ts # Simulation logic
└── types.ts # Type definitions
Simulation Result
interface AdaptiveOptimizerReport {
input: {
model: string;
scenario: string;
duration: number;
speed: number;
};
output: {
results: Array<{
tick: number;
timestamp: string;
parameters: { BOD; COD; pH; TSS; TDS };
qualityLabel?: string;
isAnomaly: boolean;
}>;
summary: {
totalTicks: number;
successCount: number;
errorCount: number;
anomalyCount: number;
};
};
}
7. CAD Integration
Overview
3D plant visualization and design tools for wastewater treatment facility planning and monitoring.
Features
- 3D Plant Visualization: Interactive 3D models of treatment facilities
- Component Library: Pre-built treatment component models
- Flow Simulation: Visual representation of water flow through the plant
- Equipment Placement: Drag-and-drop equipment positioning
- Export Capabilities: Export designs for engineering review
- Integration with Treatment Data: Real-time data overlay on 3D models
Files
src/
├── app/(core)/cad-integration/
│ ├── page.tsx # Main CAD integration page
│ └── components/ # 3D visualization components
└── lib/cad-integration/
├── index.ts # Barrel export
├── types.ts # CAD type definitions
└── utils.ts # CAD utility functions
Component Types
| Component | Description |
|---|---|
| Primary Tank | Primary sedimentation tanks |
| Aeration Basin | Biological treatment basins |
| Clarifier | Secondary clarifiers |
| Filter | Filtration units |
| Disinfection | UV/Chlorine disinfection chambers |
| Pump Station | Water pumping facilities |
| Control Room | Monitoring and control stations |
Usage
- Navigate to
/cad-integrationfrom dashboard - Select component type from the library
- Place components on the 3D canvas
- Configure component properties
- Visualize flow connections
- Export or save design
8. WebSocket Monitor
Overview
Real-time WebSocket monitoring interface for SCADA system integration and continuous ML model streaming.
Features
- Dual WebSocket Connections: Connect to both reusability and treatment endpoints simultaneously
- Connection Status: Visual indicators for each connection (disconnected, connecting, connected, error)
- Stream Controls: Start/stop continuous data streaming with configurable intervals
- Single Send: Send individual prediction requests manually
- Live Log Viewer: Real-time message log with expandable JSON details
- Model Selection: Stream to both models, reusability only, or treatment only
- SCADA Simulation: Auto-generates realistic sensor data for testing
- Dark Mode Support: Full dark mode compatibility
Files
src/
├── app/(core)/websocket-monitor/
│ └── page.tsx # WebSocket monitor page
└── ml/
└── ws_scada_simulator.py # Python SCADA simulator
WebSocket Endpoints
| Endpoint | Model | Description |
|---|---|---|
/ws/reusability | Reusability | Real-time water reusability predictions |
/ws/treatment | Treatment | Real-time treatment recommendations |
Usage
- Connect: Click "Connect All" to establish WebSocket connections
- Stream: Click "Start Stream" to begin continuous data streaming
- Monitor: Watch real-time predictions in the log viewer
- Adjust: Use settings to change interval or select specific models
Message Format
// Client → Server
{
type: "predict",
request_id: "web-reuse-001",
payload: { /* sensor data */ }
}
// Server → Client
{
ok: true,
request_id: "web-reuse-001",
data: { /* prediction result */ }
}
Configuration
| Setting | Default | Description |
|---|---|---|
| Stream Interval | 2000ms | Time between automatic sends |
| Model Selection | Both | Which models to stream to |
| WebSocket URL | env | From NEXT_PUBLIC_ML_API_URL |
9. Report History
Overview
Complete history of all analyses with filtering, viewing, and management.
Features
- Filter by type (Prediction, Treatment, Twin Engine, Adaptive)
- Date range filtering
- Search functionality
- Blockchain status indicator per report
- Detail view with full results
- Delete capability
- PDF re-export
Files
src/
├── app/(core)/history/
│ ├── page.tsx # History list
│ └── [id]/page.tsx # Report detail
├── lib/reports/
│ ├ ── service.ts # CRUD operations
│ ├── hooks.ts # useReports, useSaveReport
│ ├── types.ts # Report type definitions
│ └── components/
│ ├── report-card.tsx # Summary card
│ ├── report-list.tsx # List container
│ ├── report-detail.tsx # Full detail view
│ └── report-filters.tsx # Filter controls
Report Types
type ReportType =
| "prediction" // Reusability prediction
| "treatment" // Treatment recommendation
| "twin-engine" // Combined analysis
| "adaptive-optimizer"; // Simulation results
// Collection mapping
const REPORT_COLLECTIONS = {
prediction: "prediction_reports",
treatment: "treatment_reports",
"twin-engine": "twin_engine_reports",
"adaptive-optimizer": "adaptive_optimizer_reports",
};
10. Blockchain Verification
Overview
Immutable report hash storage on Polygon blockchain for tamper-proof verification.
Features
- Automatic storage after report creation
- SHA-256 hash of report data
- Transaction explorer link
- Verification check against stored hash
- Status display on dashboard and reports
Files
src/
├── lib/blockchain/
│ ├── config.ts # Chain configuration
│ ├── hash.ts # Hash generation
│ ├── service.ts # BlockchainService
│ └── types.ts # Interfaces
├── hooks/use-blockchain.ts # Client hook
├── app/api/blockchain/
│ ├── status/route.ts # GET status
│ ├── store/route.ts # POST store hash
│ └── verify/route.ts # POST verify
└── components/blockchain/
├── blockchain-status.tsx # Status card
├── blockchain-badge.tsx # Verification badge
└── verify-dialog.tsx # Verification modal
Blockchain Record
interface BlockchainRecord {
transactionHash: string;
blockNumber: number;
reportHash: string; // SHA-256 of report
chainId: number; // 80002 for Polygon Amoy
chainName: string;
explorerUrl: string;
storedAt: Date;
}
Hash Generation
// Hash includes: reportType, userId, input, output, createdAt
function generateReportHash(report): string {
const normalized = JSON.stringify({
reportType: report.reportType,
userId: hashUserId(report.userId), // Privacy
input: report.input,
output: report.output,
createdAt: report.createdAt,
});
return sha256(normalized);
}
11. Account Management
Overview
User profile settings and account management.
Features
- Profile overview with avatar
- Display name editing
- Avatar URL editing with preview
- Password change with re-authentication
- Account info display (email, UID, creation date)
Files
src/app/(core)/account/page.tsx
Profile Update
// Uses Firebase updateProfile
await updateProfile(user, {
displayName: newName,
photoURL: newPhotoURL,
});
Password Change
// Requires re-authentication
const credential = EmailAuthProvider.credential(email, currentPassword);
await reauthenticateWithCredential(user, credential);
await updatePassword(user, newPassword);
Last Updated: December 2024