# carlosdb25/kare---back architecture

> Architecture diagram of the GitHub repository carlosdb25/kare---back, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-18). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/carlosdb25/kare---back
- Repository: https://github.com/carlosdb25/kare---back

## Overview

1. **System boundary**
   KARE is a backend-only API for labor incapacity management. There is no frontend in this repo; external clients consume the Express API over HTTP. The deployed instance runs on Render, and the local/dev instance uses Node.js 22 with SQLite persistence in a single file database.

2. **Core request pipeline**
   The architecture is layered and consistent across modules: **routes → middlewares → controllers → models/services → SQLite**. Routes define endpoint groups, middlewares enforce JWT/auth/roles and file upload handling, controllers orchestrate business flow, services handle OCR/validation logic, and models encapsulate database access.

3. **Main business subsystems**
   The domain is split into five functional areas:
   - **Auth**: registration, login, profile, JWT issuance.
   - **Incapacidades**: main CRUD plus status changes and document handling.
   - **Notificaciones**: read/unread lifecycle and counts.
   - **Conciliaciones**: financial calculation and payment state tracking.
   - **Reemplazos**: temporary assignment of substitutes with conflict checks.
   - **Usuarios**: administrative user management for GH/Contabilidad.

4. **Identity and access control**
   Authentication is stateless with JWT, and passwords are hashed with bcrypt. Authorization is role-based, enforced by middleware. The business roles are GH, Contabilidad, Líder, and Colaborador, and endpoint access differs materially by role; for example, GH/Contabilidad handle status/payment actions, while Líder manages replacements.

5. **Incapacidad workflow as the central domain flow**
   Incapacidades are the primary entity around which other modules revolve. A user reports an incapacity, it enters a state machine (`reportada → en_revision → validada → pagada`), and every transition is tracked. The model layer also stores a **historial de estados** to preserve traceability of changes.

6. **Document upload and OCR branch**
   File uploads are handled via Multer into `src/uploads/`. A dedicated OCR path accepts PDFs and images, extracts text using **pdf-parse** for PDFs and **Tesseract.js** for images, and uses the bundled `spa.traineddata` Spanish language model. The OCR output is then interpreted by a document analyzer that returns extracted fields, warnings, and a suggested action rather than a hard pass/fail on every mismatch.

7. **Validation boundary**
   Business validation is centralized in `validationService.js` and backed by additional checks in controllers/models. This layer enforces date coherence, allowed ranges by incapacity type, overlap detection, legal duration limits, state transition rules, role constraints, and document requirements. The design distinguishes blocking errors from non-blocking warnings, especially for OCR-derived data.

8. **Notifications as an event side effect**
   Notifications are a cross-cutting persistence flow triggered by incapacity creation, state changes, validation events, and replacement events. They are stored in the database, counted as unread, and can be marked read individually or in bulk. This subsystem acts as the user-facing event log for the workflow.

9. **Financial and operational adjacencies**
   **Conciliaciones** compute payment amounts from incapacity data, using day ranges and different percentages for EPS vs ARL. **Reemplazos** uses availability and overlap validation to prevent self-replacement and schedule conflicts. Both modules depend on the incapacity record as source-of-truth and are restricted by role.

10. **Persistence layer**
    SQLite is the only database technology in the repo, accessed through `src/db/database.js` and domain models under `src/models/`. The database file is created automatically at startup (`kare.db`) and is intentionally local/persistent rather than an external managed service. This makes the app self-contained but also ties persistence to the deployed instance’s storage.

11. **Startup and deployment**
    `src/server.js` is the entry point that boots Express, loads environment variables, registers routes, configures Swagger in development, and initializes the database/bootstrap data. `render.yaml` indicates deployment on Render, and the README describes automatic creation of tables and seed users when the server starts.

12. **Operational documentation and API surface**
    Swagger configuration is present in `src/config/swagger.js`, and the repository includes extensive docs for endpoint usage, test strategy, and integration. For architecture diagramming, the important point is that the public surface is a versioned `/api` REST API with clearly separated route groups and role-sensitive behavior.

13. **Key external dependencies that shape architecture**
    The meaningful technology choices are Express for routing, SQLite for embedded persistence, JWT/bcrypt for auth, Multer for multipart file ingestion, Tesseract.js + pdf-parse for OCR, and date-fns/express-validator-style validation utilities for domain rules. These libraries are not incidental; they define how the system handles identity, files, dates, and document intelligence.

14. **Suggested diagram shape**
    A good diagram would show: external clients on top; Express API as the core; middleware as a gate in front of controllers; services branching out for OCR/validation; models talking to SQLite; and side flows for uploads and notifications. The incapacity module should be drawn as the hub, with arrows to OCR, state history, conciliations, replacements, and notifications.

Main entry points: [`src/server.js`](https://github.com/carlosdb25/kare---back/blob/main/src/server.js) (API server), [`src/controller/incapacidadController.js`](https://github.com/carlosdb25/kare---back/blob/main/src/controller/incapacidadController.js) (Incapacity controller), [`src/db/database.js`](https://github.com/carlosdb25/kare---back/blob/main/src/db/database.js) (SQLite DB), [`src/routes/incapacidadRoutes.js`](https://github.com/carlosdb25/kare---back/blob/main/src/routes/incapacidadRoutes.js) (Incapacity routes)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_g_clients["Clients"]
  node_n_clients(("External clients<br/>consumer"))
end

subgraph group_g_api["HTTP API"]
  node_n_server["API server<br/>express bootstrap<br/>[server.js]"]
  node_n_auth_routes["Auth routes<br/>route group<br/>[authRoutes.js]"]
  node_n_incap_routes["Incapacity routes<br/>route group"]
  node_n_notif_routes["Notification routes<br/>route group"]
  node_n_conc_routes["Conciliation routes<br/>route group"]
  node_n_reemp_routes["Replacement routes<br/>route group<br/>[reemplazoRoutes.js]"]
  node_n_user_routes["User routes<br/>route group<br/>[usuarioRoutes.js]"]
  node_n_auth_mid["Auth middleware<br/>jwt gate<br/>[authMiddleware.js]"]
  node_n_role_mid["Role middleware<br/>access control<br/>[roleMiddleware.js]"]
  node_n_upload_mid["Upload middleware<br/>multipart gate"]
end

subgraph group_g_domain["Domain"]
  node_n_auth_ctrl["Auth controller<br/>[authController.js]"]
  node_n_incap_ctrl["Incapacity controller"]
  node_n_notif_ctrl["Notification controller"]
  node_n_conc_ctrl["Conciliation controller"]
  node_n_reemp_ctrl["Replacement controller"]
  node_n_user_ctrl["User controller"]
  node_n_validation["Validation service<br/>domain rules"]
  node_n_ocr["OCR service<br/>document parsing<br/>[ocrService.js]"]
  node_n_doc_analyzer["Document analyzer<br/>interpretation"]
end

subgraph group_g_data["Data & Ops"]
  node_n_incap_model[("Incapacity model<br/>sqlite model<br/>[Incapacidad.js]")]
  node_n_hist_model[("State history<br/>sqlite model<br/>[HistorialEstado.js]")]
  node_n_notif_model[("Notification model<br/>sqlite model<br/>[Notificacion.js]")]
  node_n_conc_model[("Conciliation model<br/>sqlite model<br/>[Conciliacion.js]")]
  node_n_reemp_model[("Replacement model<br/>sqlite model<br/>[Reemplazo.js]")]
  node_n_user_model[("User model<br/>sqlite model<br/>[Usuario.js]")]
  node_n_db[("SQLite DB<br/>embedded storage<br/>[database.js]")]
  node_n_uploads["Uploads<br/>file storage"]
  node_n_swagger["Swagger config<br/>api docs<br/>[swagger.js]"]
end

node_n_clients -->|"HTTP requests"| node_n_server
node_n_server -->|"mounts"| node_n_auth_routes
node_n_server -->|"mounts"| node_n_incap_routes
node_n_server -->|"mounts"| node_n_notif_routes
node_n_server -->|"mounts"| node_n_conc_routes
node_n_server -->|"mounts"| node_n_reemp_routes
node_n_server -->|"mounts"| node_n_user_routes
node_n_server -.->|"dev docs"| node_n_swagger
node_n_auth_routes -->|"protects"| node_n_auth_mid
node_n_incap_routes -->|"protects"| node_n_auth_mid
node_n_incap_routes -->|"guards"| node_n_role_mid
node_n_incap_routes -->|"uploads"| node_n_upload_mid
node_n_notif_routes -->|"protects"| node_n_auth_mid
node_n_conc_routes -->|"guards"| node_n_role_mid
node_n_reemp_routes -->|"guards"| node_n_role_mid
node_n_user_routes -->|"guards"| node_n_role_mid
node_n_auth_routes -->|"calls"| node_n_auth_ctrl
node_n_incap_routes -->|"calls"| node_n_incap_ctrl
node_n_notif_routes -->|"calls"| node_n_notif_ctrl
node_n_conc_routes -->|"calls"| node_n_conc_ctrl
node_n_reemp_routes -->|"calls"| node_n_reemp_ctrl
node_n_user_routes -->|"calls"| node_n_user_ctrl
node_n_auth_ctrl -->|"uses"| node_n_user_model
node_n_incap_ctrl -->|"uses"| node_n_incap_model
node_n_incap_ctrl -->|"tracks"| node_n_hist_model
node_n_incap_ctrl -->|"validates"| node_n_validation
node_n_incap_ctrl -->|"analyzes"| node_n_ocr
node_n_incap_ctrl -->|"interprets"| node_n_doc_analyzer
node_n_incap_ctrl -->|"emits"| node_n_notif_model
node_n_notif_ctrl -->|"uses"| node_n_notif_model
node_n_conc_ctrl -->|"uses"| node_n_conc_model
node_n_conc_ctrl -->|"reads"| node_n_incap_model
node_n_reemp_ctrl -->|"uses"| node_n_reemp_model
node_n_reemp_ctrl -->|"reads"| node_n_incap_model
node_n_reemp_ctrl -->|"validates"| node_n_validation
node_n_user_ctrl -->|"uses"| node_n_user_model
node_n_validation -.->|"checks"| node_n_incap_model
node_n_ocr -->|"reads files"| node_n_uploads
node_n_db -->|"backs"| node_n_incap_model
node_n_db -->|"backs"| node_n_hist_model
node_n_db -->|"backs"| node_n_notif_model
node_n_db -->|"backs"| node_n_conc_model
node_n_db -->|"backs"| node_n_reemp_model
node_n_db -->|"backs"| node_n_user_model
node_n_server -->|"initializes"| node_n_db

click node_n_server "https://github.com/carlosdb25/kare---back/blob/main/src/server.js"
click node_n_auth_routes "https://github.com/carlosdb25/kare---back/blob/main/src/routes/authRoutes.js"
click node_n_incap_routes "https://github.com/carlosdb25/kare---back/blob/main/src/routes/incapacidadRoutes.js"
click node_n_notif_routes "https://github.com/carlosdb25/kare---back/blob/main/src/routes/notificacionRoutes.js"
click node_n_conc_routes "https://github.com/carlosdb25/kare---back/blob/main/src/routes/conciliacionRoutes.js"
click node_n_reemp_routes "https://github.com/carlosdb25/kare---back/blob/main/src/routes/reemplazoRoutes.js"
click node_n_user_routes "https://github.com/carlosdb25/kare---back/blob/main/src/routes/usuarioRoutes.js"
click node_n_auth_mid "https://github.com/carlosdb25/kare---back/blob/main/src/middlewares/authMiddleware.js"
click node_n_role_mid "https://github.com/carlosdb25/kare---back/blob/main/src/middlewares/roleMiddleware.js"
click node_n_upload_mid "https://github.com/carlosdb25/kare---back/blob/main/src/middlewares/uploadMiddleware.js"
click node_n_auth_ctrl "https://github.com/carlosdb25/kare---back/blob/main/src/controller/authController.js"
click node_n_incap_ctrl "https://github.com/carlosdb25/kare---back/blob/main/src/controller/incapacidadController.js"
click node_n_notif_ctrl "https://github.com/carlosdb25/kare---back/blob/main/src/controller/notificacionController.js"
click node_n_conc_ctrl "https://github.com/carlosdb25/kare---back/blob/main/src/controller/conciliacionController.js"
click node_n_reemp_ctrl "https://github.com/carlosdb25/kare---back/blob/main/src/controller/reemplazoController.js"
click node_n_user_ctrl "https://github.com/carlosdb25/kare---back/blob/main/src/controller/usuarioController.js"
click node_n_validation "https://github.com/carlosdb25/kare---back/blob/main/src/services/validationService.js"
click node_n_ocr "https://github.com/carlosdb25/kare---back/blob/main/src/services/ocrService.js"
click node_n_doc_analyzer "https://github.com/carlosdb25/kare---back/blob/main/src/services/documentAnalyzer.js"
click node_n_incap_model "https://github.com/carlosdb25/kare---back/blob/main/src/models/Incapacidad.js"
click node_n_hist_model "https://github.com/carlosdb25/kare---back/blob/main/src/models/HistorialEstado.js"
click node_n_notif_model "https://github.com/carlosdb25/kare---back/blob/main/src/models/Notificacion.js"
click node_n_conc_model "https://github.com/carlosdb25/kare---back/blob/main/src/models/Conciliacion.js"
click node_n_reemp_model "https://github.com/carlosdb25/kare---back/blob/main/src/models/Reemplazo.js"
click node_n_user_model "https://github.com/carlosdb25/kare---back/blob/main/src/models/Usuario.js"
click node_n_db "https://github.com/carlosdb25/kare---back/blob/main/src/db/database.js"
click node_n_uploads "https://github.com/carlosdb25/kare---back/tree/main/src/uploads"
click node_n_swagger "https://github.com/carlosdb25/kare---back/blob/main/src/config/swagger.js"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_n_clients toneBlue
class node_n_server,node_n_auth_routes,node_n_incap_routes,node_n_notif_routes,node_n_conc_routes,node_n_reemp_routes,node_n_user_routes,node_n_auth_mid,node_n_role_mid,node_n_upload_mid toneAmber
class node_n_auth_ctrl,node_n_incap_ctrl,node_n_notif_ctrl,node_n_conc_ctrl,node_n_reemp_ctrl,node_n_user_ctrl,node_n_validation,node_n_ocr,node_n_doc_analyzer toneMint
class node_n_incap_model,node_n_hist_model,node_n_notif_model,node_n_conc_model,node_n_reemp_model,node_n_user_model,node_n_db,node_n_uploads,node_n_swagger toneRose
```

## Components

### Clients

External API consumers and deployment/runtime boundary.

- **External clients**: consumer · HTTP clients that consume the REST API.

### HTTP API

Express entrypoint, route groups, and request gating.

- [API server](https://github.com/carlosdb25/kare---back/blob/main/src/server.js): express bootstrap · Starts Express, loads env, mounts routes, initializes DB and dev docs. · `src/server.js`
- [Auth routes](https://github.com/carlosdb25/kare---back/blob/main/src/routes/authRoutes.js): route group · Endpoints for registration, login, and profile. · `src/routes/authRoutes.js`
- [Incapacity routes](https://github.com/carlosdb25/kare---back/blob/main/src/routes/incapacidadRoutes.js): route group · Primary workflow endpoints for incapacity lifecycle and documents. · `src/routes/incapacidadRoutes.js`
- [Notification routes](https://github.com/carlosdb25/kare---back/blob/main/src/routes/notificacionRoutes.js): route group · Read/unread and count endpoints for notifications. · `src/routes/notificacionRoutes.js`
- [Conciliation routes](https://github.com/carlosdb25/kare---back/blob/main/src/routes/conciliacionRoutes.js): route group · Endpoints for payment calculation and payment state tracking. · `src/routes/conciliacionRoutes.js`
- [Replacement routes](https://github.com/carlosdb25/kare---back/blob/main/src/routes/reemplazoRoutes.js): route group · Endpoints for substitute assignment and conflict checks. · `src/routes/reemplazoRoutes.js`
- [User routes](https://github.com/carlosdb25/kare---back/blob/main/src/routes/usuarioRoutes.js): route group · Administrative user management endpoints. · `src/routes/usuarioRoutes.js`
- [Auth middleware](https://github.com/carlosdb25/kare---back/blob/main/src/middlewares/authMiddleware.js): jwt gate · JWT authentication and sessionless identity enforcement. · `src/middlewares/authMiddleware.js`
- [Role middleware](https://github.com/carlosdb25/kare---back/blob/main/src/middlewares/roleMiddleware.js): access control · Role-based authorization for GH, Contabilidad, Líder, and Colaborador. · `src/middlewares/roleMiddleware.js`
- [Upload middleware](https://github.com/carlosdb25/kare---back/blob/main/src/middlewares/uploadMiddleware.js): multipart gate · Multer-based file upload handling into the local upload area. · `src/middlewares/uploadMiddleware.js`

### Domain

Controllers, services, and persistence-backed business modules.

- [Auth controller](https://github.com/carlosdb25/kare---back/blob/main/src/controller/authController.js): controller · Handles registration, login, profile flow, and token issuance. · `src/controller/authController.js`
- [Incapacity controller](https://github.com/carlosdb25/kare---back/blob/main/src/controller/incapacidadController.js): controller · Coordinates incapacity creation, updates, state changes, and document handling. · `src/controller/incapacidadController.js`
- [Notification controller](https://github.com/carlosdb25/kare---back/blob/main/src/controller/notificacionController.js): controller · Reads, marks, and counts notifications. · `src/controller/notificacionController.js`
- [Conciliation controller](https://github.com/carlosdb25/kare---back/blob/main/src/controller/conciliacionController.js): controller · Calculates financial values and updates payment state. · `src/controller/conciliacionController.js`
- [Replacement controller](https://github.com/carlosdb25/kare---back/blob/main/src/controller/reemplazoController.js): controller · Manages substitute assignments and availability checks. · `src/controller/reemplazoController.js`
- [User controller](https://github.com/carlosdb25/kare---back/blob/main/src/controller/usuarioController.js): controller · Admin user management for operational roles. · `src/controller/usuarioController.js`
- [Validation service](https://github.com/carlosdb25/kare---back/blob/main/src/services/validationService.js): domain rules · Central business validation for dates, ranges, overlaps, transitions, and document requirements. · `src/services/validationService.js`
- [OCR service](https://github.com/carlosdb25/kare---back/blob/main/src/services/ocrService.js): document parsing · Extracts text from PDFs and images for document analysis. · `src/services/ocrService.js`
- [Document analyzer](https://github.com/carlosdb25/kare---back/blob/main/src/services/documentAnalyzer.js): interpretation · Turns OCR output into extracted fields, warnings, and suggested actions. · `src/services/documentAnalyzer.js`

### Data & Ops

SQLite storage, uploads, and operational configuration.

- [Incapacity model](https://github.com/carlosdb25/kare---back/blob/main/src/models/Incapacidad.js): sqlite model · Primary persistence model for incapacity records and workflow state. · `src/models/Incapacidad.js`
- [State history](https://github.com/carlosdb25/kare---back/blob/main/src/models/HistorialEstado.js): sqlite model · Stores incapacity state transitions and traceability history. · `src/models/HistorialEstado.js`
- [Notification model](https://github.com/carlosdb25/kare---back/blob/main/src/models/Notificacion.js): sqlite model · Persists notifications and unread/read status. · `src/models/Notificacion.js`
- [Conciliation model](https://github.com/carlosdb25/kare---back/blob/main/src/models/Conciliacion.js): sqlite model · Stores calculation outputs and payment tracking data. · `src/models/Conciliacion.js`
- [Replacement model](https://github.com/carlosdb25/kare---back/blob/main/src/models/Reemplazo.js): sqlite model · Persists substitute assignments and conflict-related data. · `src/models/Reemplazo.js`
- [User model](https://github.com/carlosdb25/kare---back/blob/main/src/models/Usuario.js): sqlite model · Persists application users and role data. · `src/models/Usuario.js`
- [SQLite DB](https://github.com/carlosdb25/kare---back/blob/main/src/db/database.js): embedded storage · Database bootstrap and connection layer for local kare.db persistence. · `src/db/database.js`
- [Uploads](https://github.com/carlosdb25/kare---back/tree/main/src/uploads): file storage · Local storage for uploaded documents and OCR inputs. · `src/uploads`
- [Swagger config](https://github.com/carlosdb25/kare---back/blob/main/src/config/swagger.js): api docs · Development API documentation and route description configuration. · `src/config/swagger.js`

## Connections

- External clients → API server: HTTP requests · External clients call the versioned REST API.
- API server → Auth routes: mounts · Registers auth route group.
- API server → Incapacity routes: mounts · Registers incapacity route group.
- API server → Notification routes: mounts · Registers notification route group.
- API server → Conciliation routes: mounts · Registers conciliation route group.
- API server → Replacement routes: mounts · Registers replacement route group.
- API server → User routes: mounts · Registers user route group.
- API server → Swagger config: dev docs · Loads Swagger configuration in development.
- Auth routes → Auth middleware: protects · Applies authentication where required.
- Incapacity routes → Auth middleware: protects · Requires authenticated identity for workflow actions.
- Incapacity routes → Role middleware: guards · Enforces role-specific incapacity actions.
- Incapacity routes → Upload middleware: uploads · Handles document ingestion for incapacity evidence.
- Notification routes → Auth middleware: protects · Restricts notification access to authenticated users.
- Conciliation routes → Role middleware: guards · Restricts financial actions to authorized roles.
- Replacement routes → Role middleware: guards · Restricts replacement actions to authorized roles.
- User routes → Role middleware: guards · Restricts user administration to privileged roles.
- Auth routes → Auth controller: calls · Routes delegate auth flow to controller.
- Incapacity routes → Incapacity controller: calls · Routes delegate incapacity workflow to controller.
- Notification routes → Notification controller: calls · Routes delegate notification operations to controller.
- Conciliation routes → Conciliation controller: calls · Routes delegate conciliation operations to controller.
- Replacement routes → Replacement controller: calls · Routes delegate replacement operations to controller.
- User routes → User controller: calls · Routes delegate admin user operations to controller.
- Auth controller → User model: uses · Authenticates and persists user identity data.
- Incapacity controller → Incapacity model: uses · Reads and writes incapacity records.
- Incapacity controller → State history: tracks · Appends state transitions to history.
- Incapacity controller → Validation service: validates · Applies business rules before state changes.
- Incapacity controller → OCR service: analyzes · Processes uploaded documents through OCR.
- Incapacity controller → Document analyzer: interprets · Converts OCR output into extracted fields and warnings.
- Incapacity controller → Notification model: emits · Creates notifications as workflow side effects.
- Notification controller → Notification model: uses · Reads and updates notification records.
- Conciliation controller → Conciliation model: uses · Stores conciliation calculations and payment state.
- Conciliation controller → Incapacity model: reads · Uses incapacity data as source of truth.
- Replacement controller → Replacement model: uses · Persists substitute assignments.
- Replacement controller → Incapacity model: reads · Checks incapacity context for replacement eligibility.
- Replacement controller → Validation service: validates · Checks overlaps, self-replacement, and availability.
- User controller → User model: uses · Creates and manages administrative users.
- Validation service → Incapacity model: checks · Evaluates coherence, duration, overlap, and transition rules.
- OCR service → Uploads: reads files · Consumes PDFs and images from local uploads.
- SQLite DB → Incapacity model: backs · SQLite persistence layer for domain models.
- SQLite DB → State history: backs · SQLite persistence layer for state history.
- SQLite DB → Notification model: backs · SQLite persistence layer for notifications.
- SQLite DB → Conciliation model: backs · SQLite persistence layer for conciliation data.
- SQLite DB → Replacement model: backs · SQLite persistence layer for replacements.
- SQLite DB → User model: backs · SQLite persistence layer for users.
- API server → SQLite DB: initializes · Bootstraps database and seed data at startup.
