codigo0/.planning/codebase/ARCHITECTURE.md

240 lines
6.5 KiB
Markdown
Raw Normal View History

# Architecture
**Analysis Date:** 2026-03-13
## Pattern Overview
**Overall:** Modular Monorepo with Frontend-Backend Separation
**Key Characteristics:**
- **Separation of Concerns**: Frontend and backend are completely separate applications with no shared runtime
- **API-First Design**: Backend exposes RESTful API endpoints consumed by the frontend
- **Component-Based UI**: React application structured by feature domains (clinical, protocols, tools)
- **Lazy Loading**: Heavy pages are lazy-loaded for performance optimization
## Layers
### Backend Layer
**Purpose:** API server providing medical protocol data and authentication
**Location:** `backend/`
**Contains:**
- Express server setup (`src/index.ts`, `src/app.ts`)
- Route handlers (`src/routes/`)
- Business logic/services (`src/services/`)
- Configuration (`src/config.ts`)
- TypeScript types/interfaces
**Depends on:**
- Express framework for HTTP handling
- Mongoose for MongoDB connectivity (configured but placeholder)
- JWT for authentication
- Zod for validation (not yet implemented in routes)
**Used by:**
- Frontend application via HTTP API calls
### Frontend Layer
**Purpose:** React single-page application for medical protocol reference
**Location:** `frontend/src/`
**Contains:**
- Application entry point (`main.tsx`)
- Root component with routing (`App.tsx`)
- Page components (`pages/`)
- UI components (`components/`)
- Layout components (`components/layout/`)
- Services layer (`services/`)
- Types definitions (`types/`)
- Utilities (`utils/`, `hooks/`)
**Depends on:**
- React 18 with hooks
- React Router DOM for navigation
- TailwindCSS for styling
- Next-themes for dark mode
- Lucide React for icons
**Used by:**
- End users via web browser
### Static Site Layer
**Purpose:** Marketing/promotional landing page
**Location:** `promo-site/`
**Contains:**
- Static HTML with inline CSS
- Marketing content and calls-to-action
## Data Flow
### API Request Flow
1. **Frontend Component** triggers data fetch (e.g., `pages/Index.tsx`)
2. **Service Layer** (`frontend/src/services/`) makes HTTP request to backend
3. **Backend Route** (`backend/src/routes/`) receives request
4. **Service Layer** (`backend/src/services/`) processes business logic
5. **Response** returns JSON data to frontend
6. **Component** renders data using React state
### Protocol Data Flow (Example: RCP Protocol)
```
Frontend: Protocol Page
↓ HTTP GET /api/content/:id
Backend: content.ts route
↓ calls telephone-protocols.ts service
Backend: telephone-protocols.ts service
↓ returns TelephoneProtocol object
Backend: JSON response
Frontend: Service layer
↓ state update
Frontend: Component renders protocol steps
```
## State Management
**Frontend State:**
- **Local State**: Component-level state using `useState` for UI interactions (search modal, menu state)
- **URL State**: React Router for navigation and route parameters (`/protocolo/:id`)
- **Theme State**: `next-themes` for dark/light mode persistence
**Backend State:**
- **Configuration**: Environment variables loaded via `dotenv`
- **Session State**: JWT tokens (authentication flow placeholder)
- **Database State**: MongoDB connection (configured but not fully implemented)
## Key Abstractions
### Telephone Protocol Model
**Purpose:** Standardized structure for medical emergency protocols
**Location:** `backend/src/services/telephone-protocols.ts`
**Examples:**
- `rcpTelephoneAdult` - Adult CPR protocol
- `ictusTelephone` - Stroke assessment protocol
- `desaTelephone` - AED usage protocol
**Pattern:**
```typescript
interface TelephoneProtocol {
id: string;
title: string;
category: ProtocolCategory;
steps: ProtocolStep[];
initialAssessment: string[];
importantNotes?: string[];
}
```
### API Route Pattern
**Purpose:** Consistent Express route structure
**Location:** `backend/src/routes/`
**Pattern:**
```typescript
import { Router } from 'express';
const router = Router();
router.get('/', (req, res) => { /* ... */ });
router.get('/:id', (req, res) => { /* ... */ });
router.post('/', (req, res) => { /* ... */ });
export default router;
```
### React Page Pattern
**Purpose:** Consistent page component structure
**Location:** `frontend/src/pages/`
**Pattern:**
```typescript
import { useState } from 'react';
import { Link } from 'react-router-dom';
// ... imports
const PageName = () => {
// State and logic
return (
<div>
{/* JSX */}
</div>
);
};
export default PageName;
```
## Entry Points
### Backend Entry Point
**Location:** `backend/src/index.ts`
**Triggers:** Node.js process execution
**Responsibilities:**
- Create Express app instance
- Read configuration
- Start HTTP server on configured port
- Handle graceful shutdown signals (SIGINT, SIGTERM)
### Frontend Entry Point
**Location:** `frontend/src/main.tsx`
**Triggers:** Browser loads HTML page
**Responsibilities:**
- Initialize React root
- Register Service Worker (production only)
- Render main App component with error boundaries
- Apply console error filtering for browser extensions
### Frontend App Entry
**Location:** `frontend/src/App.tsx`
**Triggers:** React root render
**Responsibilities:**
- Set up ThemeProvider for dark mode
- Configure BrowserRouter with future flags
- Define all application routes with lazy loading
- Layout structure (Header, Main, Footer, BottomNav)
- Modal management (Search, Menu)
## Error Handling
**Strategy:** Layered error handling with graceful degradation
**Patterns:**
**Frontend Error Boundaries:**
- Root-level error display in `main.tsx`
- Suspense fallbacks for lazy-loaded pages
- Console error filtering for non-critical browser extension errors
**Backend Error Handling:**
- Global error handler in `app.ts` (line 51-57)
- 404 handler for undefined routes
- Development mode shows detailed error messages
- Production mode shows generic error messages
## Cross-Cutting Concerns
**Logging:**
- **Backend:** Console logging for server startup, errors, and graceful shutdown
- **Frontend:** Console logging for Service Worker registration, React rendering errors
**Validation:**
- **Backend:** Zod dependency available but not yet integrated into routes
- **Frontend:** No explicit validation layer detected
**Authentication:**
- **Backend:** JWT configuration in `config.ts` with placeholder secret
- **Frontend:** No authentication UI implemented (routes are placeholder)
**Security:**
- **Backend:** Helmet.js for security headers, CORS configuration
- **Frontend:** Service Worker for PWA capabilities (production only)
---
*Architecture analysis: 2026-03-13*