Skip to main content

Architecture Overview

System Architecture

┌─────────────────────────────────────────────────────────────────────┐
│ CLIENT (Next.js) │
├─────────────────────────────────────────────────────────────────────┤
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌────────────┐ │
│ │ Pages │ │ Components │ │ Hooks │ │ Lib │ │
│ │ (app/) │ │ │ │ │ │ Services │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └─────┬──────┘ │
│ │ │ │ │ │
│ └────────────────┴────────────────┴────────────────┘ │
│ │ │
└───────────────────────────────────┼──────────────────────────────────┘

┌───────────────────────────┼───────────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Firebase │ │ ML API │ │ Polygon │
│ (Auth + DB) │ │ (FastAPI) │ │ Blockchain │
└───────────────┘ └─────────────────┘ └─────────────────┘

Application Layers

1. Presentation Layer (/app, /components)

Responsibilities:

  • Page rendering and routing
  • User interface components
  • Form handling and validation
  • State management (local)

Key Patterns:

  • Next.js App Router with route groups
  • Client/Server component separation
  • Compound component patterns for UI

2. Business Logic Layer (/lib, /hooks)

Responsibilities:

  • API communication
  • Data transformation
  • Business rules implementation
  • Cross-cutting concerns

Key Patterns:

  • Custom hooks for state + side effects
  • Service classes for external APIs
  • Context providers for global state

3. Data Layer (/lib/firebase.ts, /lib/reports)

Responsibilities:

  • Database operations (Firestore)
  • Caching strategies
  • Data persistence

Key Patterns:

  • Repository pattern for Firestore
  • Type-safe document conversion
  • Optimistic updates

Data Flow

Prediction Flow

User Input → Form Validation → ML API Request → Response Processing
│ │
│ ┌──────────────────────────┘
│ ▼
│ ┌─────────────────────┐
│ │ Save to Firestore │
│ └──────────┬──────────┘
│ │
│ ┌──────────▼──────────┐
│ │ Store on Blockchain │
│ └──────────┬──────────┘
│ │
└─────────────────────────▼
Display Results + Status

Authentication Flow

┌──────────────┐     ┌─────────────────┐     ┌──────────────────┐
│ Auth Routes │────▶│ AuthProvider │────▶│ Firebase Auth │
│ /sign-in │ │ (Context) │ │ │
│ /sign-up │ └────────┬────────┘ └──────────────────┘
└──────────────┘ │

┌─────────────────┐
│ Protected │
│ Routes (core) │
└─────────────────┘

Design Patterns

1. Context Provider Pattern

Location: lib/auth-context.tsx

// Provides global auth state
const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }) {
// Auth state management
return <AuthContext.Provider value={...}>{children}</AuthContext.Provider>;
}

export function useAuth() {
return useContext(AuthContext);
}

2. Custom Hook Pattern

Location: hooks/, lib/*/hooks.ts

// Encapsulates state + API calls
export function useBlockchain() {
const [isStoring, setIsStoring] = useState(false);

const storeOnBlockchain = useCallback(async (params) => {
// Implementation
}, []);

return { storeOnBlockchain, isStoring, ... };
}

3. Service Singleton Pattern

Location: lib/blockchain/service.ts, lib/ml-api/client.ts

class BlockchainService {
private static instance: BlockchainService;

// Singleton instance
}

export const blockchainService = new BlockchainService();

4. Repository Pattern

Location: lib/reports/service.ts

// CRUD operations for reports
export async function saveReport(report) { ... }
export async function getReports(userId, filters) { ... }
export async function deleteReport(reportId) { ... }

5. Compound Component Pattern

Location: components/ui/sidebar.tsx

// Related components exported together
export { Sidebar, SidebarContent, SidebarHeader, SidebarFooter };

Route Groups

(auth) - Authentication Routes

  • /sign-in - User login
  • /sign-up - User registration

(core) - Protected Application Routes

  • /dashboard - Main dashboard
  • /prediction-model - Reusability prediction
  • /treatment-model - Treatment recommendations
  • /twin-engine - Combined analysis
  • /adaptive-optimizers - Real-time simulation
  • /cad-integration - 3D CAD visualization and plant design
  • /websocket-monitor - Real-time WebSocket data streaming
  • /history - Report history
  • /account - User settings
  • /reports - Report management

State Management

Local State

  • useState for component-level state
  • Form state via React Hook Form

Global State

  • AuthContext for user authentication
  • No external state library (Context is sufficient)

Server State

  • Custom hooks with loading/error states
  • Manual cache invalidation

Error Handling Strategy

API Errors

class MLAPIError extends Error {
constructor(
message: string,
public statusCode: number
) {
super(message);
}
}

UI Error Boundaries

  • Toast notifications for user feedback
  • Error cards for inline errors
  • Loading states during operations

Validation Errors

  • Zod schemas for type-safe validation
  • Form-level error display

Security Considerations

Authentication

  • Firebase Auth with email/password and Google OAuth
  • Protected routes redirect unauthenticated users
  • Session management via Firebase SDK

Blockchain

  • Server-side wallet (private key never exposed)
  • Report hashes stored on-chain (not raw data)
  • User IDs hashed before blockchain storage

API Security

  • Environment variables for sensitive config
  • CORS handled by ML API backend
  • No API keys exposed to client

Last Updated: December 2024