Skip to main content

Features Documentation

Table of Contents

  1. Authentication
  2. Dashboard
  3. Prediction Model
  4. Treatment Model
  5. Twin Engine
  6. Adaptive Optimizers
  7. CAD Integration
  8. WebSocket Monitor
  9. Report History
  10. Blockchain Verification
  11. 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

ActionRouteDescription
Prediction Model/prediction-modelAI water quality prediction
Treatment Model/treatment-modelTreatment recommendations
Twin Engine/twin-engineCombined analysis pipeline
Adaptive Optimizers/adaptive-optimizersReal-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

ParameterKeyUnitDefault
Influent BODinfluent_BODmg/L18
Influent CODinfluent_CODmg/L36
Influent TSSinfluent_TSSmg/L22
Influent pHinfluent_pH-6
Influent TDSinfluent_TDSmg/L65

Operational Parameters

ParameterKeyUnitDefault
Flow Rateflow_ratem³/hr150
Aeration Rateaeration_ratem³/hr35
Chemical Dosechemical_dosemg/L12
Sludge Recycle Ratesludge_recycle_rate%25
Retention Timeretention_timehours6
Temperaturetemperature°C25

Effluent Parameters (Optional - Auto-estimated)

ParameterKeyUnit
Effluent BODeffluent_BODmg/L
Effluent CODeffluent_CODmg/L
Effluent TSSeffluent_TSSmg/L
Effluent TDSeffluent_TDSmg/L
Effluent pHeffluent_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

ParameterKeyUnitDefault
pHpH-7.5
TSSTSSmg/L120
TurbidityTurbidityNTU45
BODBODmg/L180
CODCODmg/L350
Ammoniacal NitrogenNH4_Nmg/L25
Total NitrogenTotal_Nitrogenmg/L40
PhosphatePhosphatemg/L8
Fecal ColiformFecal_ColiformMPN/100mL5000
Oil & GreaseOil_Greasemg/L15
TDSTDSmg/L600
Heavy MetalsHeavy_Metalsmg/L0.5

Use Cases

  • Irrigation
  • Domestic Use
  • Industrial Use
  • Drinking Water
  • Aquaculture

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

ComponentDescription
Primary TankPrimary sedimentation tanks
Aeration BasinBiological treatment basins
ClarifierSecondary clarifiers
FilterFiltration units
DisinfectionUV/Chlorine disinfection chambers
Pump StationWater pumping facilities
Control RoomMonitoring and control stations

Usage

  1. Navigate to /cad-integration from dashboard
  2. Select component type from the library
  3. Place components on the 3D canvas
  4. Configure component properties
  5. Visualize flow connections
  6. 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

EndpointModelDescription
/ws/reusabilityReusabilityReal-time water reusability predictions
/ws/treatmentTreatmentReal-time treatment recommendations

Usage

  1. Connect: Click "Connect All" to establish WebSocket connections
  2. Stream: Click "Start Stream" to begin continuous data streaming
  3. Monitor: Watch real-time predictions in the log viewer
  4. 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

SettingDefaultDescription
Stream Interval2000msTime between automatic sends
Model SelectionBothWhich models to stream to
WebSocket URLenvFrom 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