Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/BladimirGS/judicial-backend/llms.txt

Use this file to discover all available pages before exploring further.

Judicial Backend partitions all business logic into four self-contained domain modules. Each module lives under src/modules/<name>/ and owns its routes, controllers, services, repositories, mappers, and types. No module imports directly from another; shared infrastructure is accessed through database/, shared/, and core/ only.

Module: apelacion

The apelacion module is the primary intake interface for the court’s second-instance proceedings. It handles the capture and registration of new appeals (apelaciones) submitted to the Oficialía, including their attachments (anexos), folio generation, and Sala/Toca assignment via stored procedures.

Routes

All routes are mounted at /api/apelaciones and require a valid JWT (enforced in routes/index.ts).
MethodPathHandlerDescription
GET/catalogosApelacionController.getCatalogosLoad drop-down catalogs for the appeal intake form
GET/:idMunicipio/localidadesApelacionController.getLocalidadesLocalidades filtered by municipality
GET/:idApelacion/tipos-apelacionApelacionController.getTiposApelacionAppeal sub-types filtered by appeal category
GET/detalleApelacionController.getByFolioRetrieve a full appeal record by folio number
POST/ApelacionController.createRegister a new appeal (validated against CreateApelacionDTO)
POST/anexosAnexoController.createAttach documents to an existing appeal
GET/anexos/catalogosAnexoController.getCatalogosLoad catalog of attachment types

Appeal Payload Types

The POST / endpoint accepts one of two union payload shapes depending on whether the appeal involves indigenous defendants:
// src/modules/apelacion/types/apelacion-payload.type.ts
type ApelacionPayload = ApelacionPenalPayload | ApelacionIndigenaPayload;
  • ApelacionPenalPayload — Standard criminal appeal; includes defendants, offenses, and sentencing data.
  • ApelacionIndigenaPayload — Extends the penal payload with ethnicity and language fields required for indigenous cases.

Service Factory Pattern

Services in this module use functional factory constructors, receiving all repository dependencies as arguments:
export const createApelacionService = (
    catalogoRepo,       // CatalogoOrmRepository — catalog lookups
    asignacionRepo,     // AsignacionTocaSalaSpRepository — Sala/Toca assignment SP
    folioRepo,          // FolioSpRepository — folio generation SPs
    apelacionRepo,      // ApelacionRepository — ORM CRUD on Apelacion entity
    getManagerFn = getManager, // optional; defaults to the live DataSource manager
) => ({
    getCatalogos: (materia: string) => { /* … */ },
    getLocalidades: (idMunicipio: number) => { /* … */ },
    getTiposApelacion: (idApelacion: number) => { /* … */ },
    getByFolio: (folioOficialia: string) => { /* … */ },
    create: (data: CreateApelacionDTO) => { /* … */ },
});
Because every dependency is injected at construction time, test suites can supply mock repositories to createApelacionService without any patching framework. Replacing folioRepo with a stub that returns a fixed folio string is sufficient to unit-test the full registration flow in isolation.
LayerFileResponsibility
Interfacecontrollers/apelacion.controller.tsValidates query params, calls service, returns response via responseUtil
Interfacecontrollers/anexo.controller.tsAttachment endpoints
Interfaceapelacion.routes.tsRegisters routes; applies validateDto middleware
Applicationservices/apelacion.service.tsOrchestrates ORM repos + SPs inside a single transaction
Applicationservices/anexo.service.tsBusiness logic for attachment management
Transformationmappers/apelacion.mapper.tsApelacion entity → ApelacionDetailDTO
Transformationmappers/anexo.mapper.tsApelacionAnexo entity → AnexoDTO
Infrastructurerepositories/apelacion.repository.tscreateApelacion(), findOneByFolio() via TypeORM
Infrastructurerepositories/anexo.repository.tsaddAnexos(), list annexes
Infrastructuredatabase/repositories/folio.sp-repository.tsStored procs: PA_SEL_FolioNomenclaturaToca, PA_INS_PCF_FolioTramite
Infrastructuredatabase/repositories/asignacion-toca-sala.sp-repository.tsStored proc: PA_SEL_AsignacionTocaySala
Domaintypes/apelacion-payload.type.tsApelacionPenalPayload | ApelacionIndigenaPayload
Domaintypes/anexo-payload.type.tsAnexoItemPayload, AddAnexosPayload

Module: busqueda

The busqueda module provides a parameterized search interface over existing appeals, with results exportable as Excel (.xlsx) or PDF. It offers three independent search sub-modes, each with its own controller, service, repository, mapper, and report builders.

Routes

All routes are mounted at /api/busquedas and require a valid JWT.
MethodPathDescription
GET/filtrosCatalogs for the full-appeal search form
GET/Search full appeals (with Partes and Anexos)
GET/exportar-excelExport full-appeal results as .xlsx
GET/exportar-pdfExport full-appeal results as PDF
GET/planoSearch flat appeals (no Partes/Anexos)
GET/plano/exportar-excelExport flat results as .xlsx
GET/plano/exportar-pdfExport flat results as PDF
GET/historico/filtrosCatalogs for the historical search form
GET/historicoSearch historical appeal entities
GET/historico/exportar-excelExport historical results as .xlsx
GET/historico/exportar-pdfExport historical results as PDF

Three Search Sub-Modes

Sub-modeEntity queriedIncludesUse case
CompletaApelacionAll relations — Partes, Anexos, CatálogosFull case review
PlanaApelacionBasic scalar fields and catalog IDs onlyTabular exports, reporting
HistóricaApelacionHistoricoSimple catalog relationsHistorical audit trails

Standard Service Contract

Every service in this module exposes the same four methods:
MethodSignatureDescription
obtenerCatalogos()(): Promise<CatalogosDTO>Returns drop-down data for the filter form
buscar(filtros)(filtros: FiltrosDTO): Promise<ResultadoDTO[]>Paginated and filtered query
exportarExcel(filtros)(filtros: FiltrosDTO): Promise<Buffer>Builds an .xlsx workbook buffer from search results
exportarPdf(filtros)(filtros: FiltrosDTO): Promise<Buffer>Builds a PDF buffer from search results
Export endpoints stream the buffer directly to the HTTP response using responseUtil.file(), which sets Content-Disposition: attachment and the appropriate MIME type (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for Excel, application/pdf for PDF).
LayerFileResponsibility
Interfacecontrollers/busqueda-apelacion.controller.tsgetCatalogos, getApelaciones, exportarExcel, exportarPdf
Interfacecontrollers/busqueda-plano.controller.tsSame surface for the flat projection
Interfacecontrollers/busqueda-historico.controller.tsSame surface for the historical projection
Applicationservices/busqueda-apelacion.service.tsCalls repository, applies mapper, dispatches to report builder
Applicationservices/busqueda-plano.service.tsFlat query variant
Applicationservices/busqueda-historico.service.tsHistorical query variant
Transformationmappers/apelacion.mapper.tsApelacionApelacionDTO (full)
Transformationmappers/apelacion-plano.mapper.tsApelacionApelacionPlanoDTO
Transformationmappers/apelacion-historica.mapper.tsApelacionHistoricoApelacionHistoricoDTO
Infrastructurerepositories/busqueda-apelacion.repository.tsDeep QueryBuilder with Partes + Anexos JOINs
Infrastructurerepositories/busqueda-plano.repository.tsShallow QueryBuilder — no Partes/Anexos
Infrastructurerepositories/busqueda-historico.repository.tsQueryBuilder over ApelacionHistorico
Reportsreports/excel/*.report.tsBuild Excel buffers via shared/excel
Reportsreports/pdf/*.report.tsBuild PDF buffers via shared/pdf

Module: estadistica

The estadistica module generates statistical reports on court appeals. All data is retrieved through a single stored procedure (PA_SEL_PCF_EstadisticaApelaciones) and then shaped by mappers into one of two presentation modes before being returned as JSON or exported to Excel.

Routes

All routes are mounted at /api/estadisticas and require a valid JWT.
MethodPathHandlerDescription
GET/planoEstadisticaController.getReportePlanoFlat list of statistical records
GET/agrupadoEstadisticaController.getReporteAgrupadoRecords grouped by Sala and appeal type
POST/exportarEstadisticaController.exportarExcelExport statistics to Excel (three format options)

Two Report Modes

ModeMapperResult shape
Planoestadistica.mapper.tsOne row per appeal — raw SP result mapped to a flat DTO
Agrupadoestadistica-agrupado.mapper.tsSP results grouped by Sala/Apelación; suitable for pivot tables and charts

Excel Export Formats

The POST /exportar endpoint supports three Excel output formats within the same workbook, generated by dedicated report builders in reports/excel/:
Report fileSheet content
estadistica-plano-excel.report.tsFlat tabular list
estadistica-agrupado-excel.report.tsGrouped summary with subtotals
estadistica-grafico-excel.report.tsChart-ready data layout
LayerFileResponsibility
Interfacecontrollers/estadistica.controller.tsEndpoints /plano, /agrupado, /exportar
Interfaceestadistica.routes.tsRoute registration
Applicationservices/estadistica.service.tsCalls SP repository, selects mapper, builds Excel report
Transformationmappers/estadistica.mapper.tsSP result row → flat DTO
Transformationmappers/estadistica-agrupado.mapper.tsGroups SP rows by Sala/Apelación
Infrastructuredatabase/repositories/estadistica.sp-repository.tsExecutes PA_SEL_PCF_EstadisticaApelaciones
Reportsreports/excel/estadistica-plano-excel.report.tsFlat Excel sheet
Reportsreports/excel/estadistica-agrupado-excel.report.tsGrouped Excel sheet
Reportsreports/excel/estadistica-grafico-excel.report.tsChart-data Excel sheet

Module: auth

The auth module implements authentication using a Backend-for-Frontend (BFF) proxy pattern. The backend does not manage users or issue tokens itself; instead, it proxies credential exchanges to an external authentication API and validates the resulting JWTs locally using RS256 public keys fetched via JWKS.

Routes

Auth routes are mounted at /api/auth and are public — no protect middleware is applied at this level.
MethodPathHandlerDescription
POST/loginAuthController.loginAuthenticate with { usuario, contrasenia }; sets httpOnly refresh-token cookie
POST/refreshAuthController.refreshExchange refresh token (from cookie) for a new access token
POST/logoutAuthController.logoutRevoke the session on the external auth API and clear the cookie

JWT Protection for Business Modules

The protect middleware (modules/auth/middlewares/protect.middleware.ts) guards every non-auth route. It runs the following sequence on every incoming request:
Client → GET /api/apelaciones  (Authorization: Bearer <token>)


  protect middleware
    1. Extract Bearer token from Authorization header
    2. Decode JWT header → read key ID (kid)
    3. Fetch JWKS from external provider: GET .../GetJwks
    4. Verify RS256 signature, issuer, and audience
    5. Attach decoded payload to req.user
    6. Call next()


  ApelacionController / BusquedaController / EstadisticaController

BFF Proxy Flow

Client → POST /api/auth/login { usuario, contrasenia }


  AuthController.login()


  AuthExternalAdapter.login()  ──HTTP──► External Auth API
          │                                    │
          │◄───────────────────────────────────┤ { access_token, refreshToken }

  Sets httpOnly cookie: refreshToken
  Responds: { access_token }

Required Environment Variables

VariableDescription
EXTERNAL_AUTH_URLBase URL of the external authentication API
JWT_ISSUERExpected iss claim in incoming JWTs
JWT_AUDIENCEExpected aud claim in incoming JWTs
ID_SISTEMASystem identifier sent with login requests (idSistema)
All four variables are validated at startup. If any are missing, the application calls process.exit(1) before binding to the network port.
LayerFileResponsibility
Interfaceauth.routes.tsRegisters /login, /refresh, /logout; applies validateDto(LoginDto) on login
Interfacecontrollers/auth.controller.tsExtracts credentials, calls adapter, sets httpOnly cookie, returns access_token
Applicationmiddlewares/protect.middleware.tsVerifies RS256 Bearer JWT via JWKS; sets req.user; rejects with 401 on failure
Infrastructureadapters/auth-external.adapter.tsHTTP proxy client: login(), refreshToken(), revoke()
Domaintypes/auth.types.tsJwtPayload interface + global Express Request.user augmentation
Domaindtos/login.dto.ts{ usuario: string, contrasenia: string } with class-validator decorators

Build docs developers (and LLMs) love