How carlosdb25/kare---back works
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: server.js API server · incapacidadController.js Incapacity controller · database.js SQLite DB · incapacidadRoutes.js Incapacity routes
Components 29
Clients
External API consumers and deployment/runtime boundary.
- External clients · HTTP clients that consume the REST API.
HTTP API
Express entrypoint, route groups, and request gating.
- API server · Starts Express, loads env, mounts routes, initializes DB and dev docs.
src/server.js - Auth routes · Endpoints for registration, login, and profile.
src/routes/authRoutes.js - Incapacity routes · Primary workflow endpoints for incapacity lifecycle and documents.
src/routes/incapacidadRoutes.js - Notification routes · Read/unread and count endpoints for notifications.
src/routes/notificacionRoutes.js - Conciliation routes · Endpoints for payment calculation and payment state tracking.
src/routes/conciliacionRoutes.js - Replacement routes · Endpoints for substitute assignment and conflict checks.
src/routes/reemplazoRoutes.js - User routes · Administrative user management endpoints.
src/routes/usuarioRoutes.js - Auth middleware · JWT authentication and sessionless identity enforcement.
src/middlewares/authMiddleware.js - Role middleware · Role-based authorization for GH, Contabilidad, Líder, and Colaborador.
src/middlewares/roleMiddleware.js - Upload middleware · Multer-based file upload handling into the local upload area.
src/middlewares/uploadMiddleware.js
Domain
Controllers, services, and persistence-backed business modules.
- Auth controller · Handles registration, login, profile flow, and token issuance.
src/controller/authController.js - Incapacity controller · Coordinates incapacity creation, updates, state changes, and document handling.
src/controller/incapacidadController.js - Notification controller · Reads, marks, and counts notifications.
src/controller/notificacionController.js - Conciliation controller · Calculates financial values and updates payment state.
src/controller/conciliacionController.js - Replacement controller · Manages substitute assignments and availability checks.
src/controller/reemplazoController.js - User controller · Admin user management for operational roles.
src/controller/usuarioController.js - Validation service · Central business validation for dates, ranges, overlaps, transitions, and document requirements.
src/services/validationService.js - OCR service · Extracts text from PDFs and images for document analysis.
src/services/ocrService.js - Document analyzer · Turns OCR output into extracted fields, warnings, and suggested actions.
src/services/documentAnalyzer.js
Data & Ops
SQLite storage, uploads, and operational configuration.
- Incapacity model · Primary persistence model for incapacity records and workflow state.
src/models/Incapacidad.js - State history · Stores incapacity state transitions and traceability history.
src/models/HistorialEstado.js - Notification model · Persists notifications and unread/read status.
src/models/Notificacion.js - Conciliation model · Stores calculation outputs and payment tracking data.
src/models/Conciliacion.js - Replacement model · Persists substitute assignments and conflict-related data.
src/models/Reemplazo.js - User model · Persists application users and role data.
src/models/Usuario.js - SQLite DB · Database bootstrap and connection layer for local kare.db persistence.
src/db/database.js - Uploads · Local storage for uploaded documents and OCR inputs.
src/uploads - Swagger config · Development API documentation and route description configuration.
src/config/swagger.js
Connections 45
- 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.