Skip to main content

Clean Architecture Implementation

Comprehensive documentation of the clean architecture implementation for the Toto ecosystem.

πŸ— Architecture Overview​

Complete Ecosystem Architecture with Next.js API Routes & App Hosting​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Toto Ecosystem β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ toto-app β”‚ β”‚ toto-bo β”‚ β”‚ toto-ai-hub β”‚ β”‚
β”‚ β”‚ (Main App) β”‚ β”‚ (Backoffice) β”‚ β”‚ (AI System) β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ πŸ” Core APIs │◄──── πŸ“Š Dashboard │◄──── πŸ€– AI Agents β”‚ β”‚
β”‚ β”‚ πŸ“‹ Cases β”‚ β”‚ πŸ‘₯ Management β”‚ β”‚ πŸ’¬ Conversationsβ”‚ β”‚
β”‚ β”‚ πŸ‘₯ Users β”‚ β”‚ πŸ”” Notificationsβ”‚ β”‚ πŸ“š Knowledge β”‚ β”‚
β”‚ β”‚ πŸ’° Donations β”‚ β”‚ πŸ“ˆ Analytics β”‚ β”‚ πŸ” Search β”‚ β”‚
β”‚ β”‚ 🏠 Guardians β”‚ β”‚ πŸ” Audit Logs β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ πŸ—„οΈ Firestore β”‚ β”‚ πŸ—„οΈ Firestore β”‚ β”‚ πŸ—„οΈ Firestore β”‚ β”‚
β”‚ β”‚ (Main DB) β”‚ β”‚ (Local DB) β”‚ β”‚ (Shared KB) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ toto-wallet β”‚ β”‚
β”‚ β”‚ (Payment System) β”‚ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ πŸ’³ Stellar Blockchain β”‚ β”‚
β”‚ β”‚ πŸ’° Donation Processing β”‚ β”‚
β”‚ β”‚ πŸ” Secure Transactions β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ πŸš€ Deployment: Next.js API Routes + App Hosting β”‚
β”‚ πŸ“± Frontend: Next.js with App Hosting β”‚
β”‚ πŸ”§ Backend: Next.js API Routes via App Hosting β”‚
β”‚ πŸ€– AI: Multi-agent system with Vertex AI β”‚
β”‚ πŸ’³ Payments: Stellar blockchain integration β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🌍 Environment Management​

The Toto ecosystem supports professional staging + production environments with complete data isolation. For detailed environment configuration, see Environment Management.

πŸš€ Deployment Architecture​

All projects use Firebase App Hosting for deployment:

  • Frontend: Next.js with App Hosting
  • Backend: Next.js API Routes via App Hosting
  • Database: Firestore with security rules
  • Authentication: Firebase Auth (main app) / NextAuth.js (backoffice)

For detailed deployment information, see the Deployment Guide.

🎯 Design Principles​

1. Separation of Concerns​

  • toto-f9d2f: Owns and manages core business data
  • toto-bo: Manages backoffice-specific data and consumes external APIs

2. Single Source of Truth​

  • Core business data (cases, users, donations) lives only in toto-f9d2f
  • Backoffice-specific data (collaborators, notifications) lives in toto-bo

3. API-First Design​

  • All data access goes through well-defined APIs
  • No direct database access across projects
  • Clear API contracts and error handling

4. Security by Design​

  • Role-based access control at both projects
  • JWT authentication for external APIs
  • Session-based authentication for local APIs

5. Unified Deployment Strategy​

  • Both projects use Next.js API Routes for APIs
  • Both projects use App Hosting for frontend
  • Consistent deployment patterns across ecosystem

πŸ”— API Integration​

The ecosystem uses a clean API architecture:

  • Main App APIs: External APIs for cases, users, donations (JWT-based auth)
  • Backoffice APIs: Local APIs for dashboard, analytics, notifications (Session-based auth)

For complete API documentation, see the API Reference.

πŸ›  Implementation Details​

All projects use Next.js API Routes deployed via Firebase App Hosting:

  • Main App: Next.js API Routes for cases, users, donations (JWT authentication)
  • Backoffice: Next.js API Routes for dashboard, analytics, notifications (Session authentication)
  • External API Integration: Backoffice consumes main app APIs via HTTP with JWT tokens

For detailed implementation and deployment configuration, see:

πŸ— Data Architecture​

πŸ“š For complete data model documentation, see:

Database Separation​

toto-f9d2f (Main Database):

// Core business entities
interface Case {
id: string;
title: string;
description: string;
status: 'active' | 'adopted' | 'closed';
guardianId: string;
createdAt: Timestamp;
updatedAt: Timestamp;
}

interface User {
id: string;
email: string;
name: string;
role: 'user' | 'guardian' | 'admin';
phone?: string;
createdAt: Timestamp;
}

interface Donation {
id: string;
caseId: string;
amount: number;
currency: string;
status: 'pending' | 'completed' | 'failed';
donorEmail: string;
createdAt: Timestamp;
}

toto-bo (Local Database):

// Backoffice-specific entities
interface Collaborator {
id: string;
email: string;
name: string;
role: 'admin' | 'staff' | 'partner';
permissions: string[];
createdAt: Timestamp;
}

interface Notification {
id: string;
type: 'system' | 'case' | 'donation';
title: string;
message: string;
recipientId: string;
read: boolean;
createdAt: Timestamp;
}

interface AuditLog {
id: string;
action: string;
userId: string;
resource: string;
resourceId: string;
changes: Record<string, any>;
timestamp: Timestamp;
}

πŸ“Š Data Flow​

Read Operations​

1. User Request β†’ toto-bo App Hosting
2. toto-bo Next.js API Routes β†’ External API (toto-f9d2f Next.js API Routes)
3. External API β†’ Firestore (toto-f9d2f)
4. Firestore β†’ External API β†’ toto-bo Next.js API Routes
5. toto-bo Next.js API Routes β†’ User Response

Write Operations​

1. User Request β†’ toto-bo App Hosting
2. toto-bo Next.js API Routes β†’ Firestore (toto-bo) [for local data]
3. Firestore β†’ toto-bo Next.js API Routes β†’ User Response

OR

1. User Request β†’ External API (toto-f9d2f Next.js API Routes)
2. External API β†’ Firestore (toto-f9d2f)
3. Firestore β†’ External API β†’ User Response

πŸ” Security Architecture​

Security Overview​

The Toto ecosystem implements a multi-layered security approach with role-based access control, secure authentication, and data isolation.

Authentication Strategy​

Main App (JWT-based):

// Firebase Auth with JWT tokens
const auth = getAuth();
const user = auth.currentUser;

// JWT token for API calls
const token = await user?.getIdToken();

Backoffice (Session-based):

// NextAuth.js with session management
export const authOptions: NextAuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
session: { strategy: 'jwt' },
callbacks: {
async session({ session, token }) {
return session;
},
},
};

Authorization Strategy​

Role-based Access Control:

// Permission checking
const canViewCases = (user: User) => {
return ['admin', 'staff', 'guardian'].includes(user.role);
};

const canManageUsers = (user: User) => {
return ['admin', 'staff'].includes(user.role);
};

const canViewAnalytics = (user: User) => {
return ['admin', 'staff'].includes(user.role);
};

Role-based Access Control (Detailed)​

// Permission system
export type Permission =
| 'canManageCases'
| 'canManageUsers'
| 'canManageGuardians'
| 'canManageDonations'
| 'canManageNotifications'
| 'canViewAnalytics'
| 'canManagePartners'
| 'canManageSupport'
| 'canViewAuditLogs'
| 'canManageCollaborators';

export type Role = 'admin' | 'staff' | 'partner' | 'guardian' | 'user';

const rolePermissions: Record<Role, Permission[]> = {
admin: [/* all permissions */],
staff: [/* staff permissions */],
partner: [/* partner permissions */],
guardian: [/* guardian permissions */],
user: []
};

export function hasPermission(role: Role, permission: Permission): boolean {
const permissions = rolePermissions[role] || [];
return permissions.includes(permission);
}

API Security​

// External API authentication
const token = await getToken({ req: request });
if (!token) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

// Local API authentication
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

// Permission checking
if (!hasPermission(userRole, 'canManageCases')) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}

🧩 React Components​

Component Architecture​

The Toto ecosystem uses a modern React component architecture with TypeScript, ensuring type safety and maintainable code.

Component Categories​

  • UI Components: Reusable interface elements (buttons, forms, cards)
  • Page Components: Full page layouts and routing
  • Feature Components: Business logic components (case cards, donation forms)
  • Layout Components: Navigation, headers, and structural elements

Component Standards​

  • TypeScript: All components use TypeScript for type safety
  • Props Interface: Clear prop definitions for each component
  • Error Boundaries: Graceful error handling and fallbacks
  • Accessibility: ARIA labels and keyboard navigation support

πŸ“Š Performance Architecture​

Caching Strategy​

API Response Caching:

// Cache frequently accessed data
const cache = new Map();

const getCachedData = async (key: string, fetcher: () => Promise<any>) => {
if (cache.has(key)) {
return cache.get(key);
}

const data = await fetcher();
cache.set(key, data);
return data;
};

Database Query Optimization:

// Optimized Firestore queries
const getCases = async (limit: number = 10) => {
return await db
.collection('cases')
.where('status', '==', 'active')
.orderBy('createdAt', 'desc')
.limit(limit)
.get();
};

Monitoring & Analytics​

Performance Monitoring:

// Custom performance tracking
const trackPerformance = (operation: string, duration: number) => {
// Send to analytics service
analytics.track('performance', { operation, duration });
};

Error Tracking:

// Error monitoring
const handleError = (error: Error, context: string) => {
// Log error with context
console.error(`Error in ${context}:`, error);

// Send to error tracking service
errorTracking.captureException(error, { context });
};

πŸ“ˆ Monitoring & Observability​

External API Monitoring​

// Health checks
const healthCheck = async () => {
try {
const response = await totoApiService.getCases({ limit: 1 });
return response.error ? 'unhealthy' : 'healthy';
} catch (error) {
return 'unhealthy';
}
};

Performance Metrics​

  • Response Time: Track external API response times
  • Error Rate: Monitor API failure rates
  • Availability: Track uptime of both systems
  • Throughput: Monitor request volumes

Logging Strategy​

// Structured logging
console.log('External API call', {
endpoint: '/cases',
params: { limit: 10 },
responseTime: Date.now() - startTime,
success: !response.error
});

πŸ”„ Migration Strategy​

From Express to Next.js API Routes​

Phase 1: Parallel Development:

  • Keep existing Express APIs running
  • Develop new Next.js API routes alongside
  • Gradual migration of endpoints

Phase 2: Feature Parity:

  • Ensure all Express endpoints have Next.js equivalents
  • Comprehensive testing of new APIs
  • Performance comparison and optimization

Phase 3: Cutover:

  • Switch frontend to use new APIs
  • Monitor for issues
  • Decommission Express APIs

Database Migration​

Schema Evolution:

// Versioned schema updates
interface SchemaVersion {
version: number;
changes: SchemaChange[];
migrationScript: string;
}

const migrations: SchemaVersion[] = [
{
version: 1,
changes: ['Add user roles', 'Add case status'],
migrationScript: 'migration-v1.js'
}
];

πŸš€ Deployment Strategy​

Unified Deployment Pattern​

Both Projects Use:

  • Next.js API Routes: For API endpoints and server-side logic
  • App Hosting: For frontend deployment and static assets
  • Firestore: For data storage with security rules
  • Firebase Auth: For authentication and user management

Deployment Commands​

toto-f9d2f:

# Deploy Next.js API Routes (automatic on push)
git push origin main

# App Hosting deployment is automatic

toto-bo:

# Deploy Next.js API Routes (automatic on push)
git push origin main

# App Hosting deployment is automatic

Environment Management​

toto-f9d2f Environment:

# Next.js API Routes Configuration
JWT_SECRET=your_jwt_secret
FIREBASE_PROJECT_ID=toto-f9d2f

# App Hosting environment
NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key
NEXT_PUBLIC_FIREBASE_PROJECT_ID=toto-f9d2f

toto-bo Environment (Production):

# Next.js API Routes Configuration
TOTO_API_BASE_URL=https://app.betoto.pet/api
NEXTAUTH_SECRET=your_nextauth_secret
NEXTAUTH_URL=https://bo.betoto.pet

# App Hosting environment
NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key
NEXT_PUBLIC_FIREBASE_PROJECT_ID=toto-bo

toto-bo Environment (Staging):

# Next.js API Routes Configuration
TOTO_API_BASE_URL=https://stg.app.betoto.pet/api
NEXTAUTH_SECRET=your_nextauth_secret_staging
NEXTAUTH_URL=https://stg.bo.betoto.pet

# App Hosting environment
NEXT_PUBLIC_FIREBASE_API_KEY=your_staging_api_key
NEXT_PUBLIC_FIREBASE_PROJECT_ID=toto-bo-stg

Configuration Management​

toto-f9d2f Environment:

# Next.js API Routes Configuration
JWT_SECRET=your_jwt_secret
FIREBASE_PROJECT_ID=toto-f9d2f

# App Hosting Configuration
NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key
NEXT_PUBLIC_FIREBASE_PROJECT_ID=toto-f9d2f

toto-bo Environment:

# Next.js API Routes Configuration
TOTO_API_BASE_URL=https://app.betoto.pet/api
NEXTAUTH_SECRET=your_nextauth_secret

# App Hosting Configuration
NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key
NEXT_PUBLIC_FIREBASE_PROJECT_ID=toto-bo
NEXTAUTH_URL=https://bo.betoto.pet

App Hosting Configuration:

# apphosting.production.yaml (toto-bo)
runConfig:
minInstances: 1
maxInstances: 10
concurrency: 80
cpu: 1
memoryMiB: 1024

env:
- variable: TOTO_API_BASE_URL
value: https://app.betoto.pet/api
availability:
- BUILD
- RUNTIME

πŸ”„ Benefits of Clean Architecture​

1. Scalability​

  • Independent scaling of main app and backoffice
  • Separate resource allocation based on usage patterns
  • Isolated performance optimization

2. Security​

  • Clear separation of data access
  • Role-based permissions at both levels
  • Audit trails for all operations

3. Maintainability​

  • Clear API contracts
  • Independent development cycles
  • Isolated testing and deployment

4. Reliability​

  • Graceful degradation when external APIs are unavailable
  • Independent error handling and recovery
  • Separate monitoring and alerting

5. Unified Technology Stack​

  • Consistent deployment patterns
  • Shared development practices
  • Common security and monitoring approaches