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 connects to a Microsoft SQL Server database through TypeORM. All entity definitions live in src/database/entities/, and all shared data-access logic — both ORM-based catalog lookups and stored-procedure wrappers — lives in src/database/repositories/. Module-level repositories (in src/modules/<name>/repositories/) use TypeORM’s QueryBuilder for complex queries but never define their own stored-procedure calls; those are always delegated to the shared SP repositories.

DataSource Configuration

The TypeORM DataSource is configured in src/config/data-source.ts. It targets MSSQL, uses glob-based entity auto-loading, and disables schema synchronization (the database schema is managed outside the application).
// src/config/data-source.ts
export const AppDataSource = new DataSource({
    type: 'mssql',
    host: envs.DB_HOST,
    port: envs.DB_PORT,
    username: envs.DB_USER,
    password: envs.DB_PASSWORD,
    database: envs.DB_NAME,
    entities: [path.join(__dirname, '../database/entities/**/*.entity{.ts,.js}')],
    synchronize: false,
    logging: false,
    extra: {
        trustServerCertificate: true,
    },
    options: {
        useUTC: false,
        encrypt: true,
    },
});
The connectDB() helper is called once during server startup (server.ts). If the connection fails, the process exits immediately (process.exit(1)) rather than serving partially-initialized requests. An getManager() export provides the EntityManager that is injected into shared repositories:
export const getManager = () => AppDataSource.manager;
synchronize: false is intentional. The database schema is managed by SQL Server migration scripts; TypeORM never alters tables automatically. This prevents accidental schema changes in production.

TypeORM Entities (21 total)

All entities are in src/database/entities/ and are auto-loaded via the glob pattern above. They are grouped into four categories by naming convention.

Core Entities

These entities model the primary transactional records of the court system.
Entity fileTypeScript classDescription
apelacion.entity.tsApelacionRoot appeal record — folio, dates, Sala assignment, case identifiers
apelacion-anexo.entity.tsApelacionAnexoDocuments and attachments associated with an appeal
apelacion-historico.entity.tsApelacionHistoricoHistorical snapshot entity for audit and search
apelacion-parte.entity.tsApelacionParteParties (defendants, plaintiffs) involved in an appeal

Catalog Entities

Catalog entities use the catalogo- prefix and back the drop-down data returned by every module’s getCatalogos() endpoint.
Entity fileTypeScript classCatalog meaning
catalogo-anexo.entity.tsCatAnexoTypes of allowed attachments
catalogo-apelacion.entity.tsCatApelacionAppeal categories
catalogo-delito.entity.tsCatDelitoCriminal offense definitions
catalogo-etnia.entity.tsCatEtniaEthnic groups (indigenous case support)
catalogo-juzgado.entity.tsCatJuzgadoOriginating courts of first instance
catalogo-localidad.entity.tsCatLocalidadLocalities, scoped by municipality
catalogo-magistrado.entity.tsCatMagistradoMagistrate roster
catalogo-materia.entity.tsCatMateriaLegal subject matters (e.g. criminal, civil)
catalogo-municipio.entity.tsCatMunicipioMunicipalities
catalogo-nomenclatura.entity.tsCatNomenclaturaFolio nomenclature codes used in toca assignment
catalogo-sala.entity.tsCatSalaCourt chambers (Salas)
catalogo-sexo.entity.tsCatSexoSex/gender options

Type Entities

Type entities use the tipo- prefix and represent classification sub-types that depend on a parent catalog entry.
Entity fileTypeScript classDescription
tipo-apelacion.entity.tsTipoApelacionAppeal sub-types, scoped to a parent CatApelacion via idApelacion
tipo-escrito.entity.tsTipoEscritoDocument/writ types
tipo-parte.entity.tsTipoParteParty role types (defendant, victim, etc.)

Relation Entities

These entities model many-to-many or join-table relationships that don’t fit neatly into the core or catalog groups.
Entity fileTypeScript classDescription
relacion.entity.tsRelacionGeneric association between appeal records
delito-relacion.entity.tsDelitoRelacionLinks criminal offenses to appeal records

Shared Repositories

The four repositories in src/database/repositories/ are shared infrastructure — any module’s service can use them. They fall into two categories: ORM repositories (TypeORM manager.find / manager.findOne) and SP repositories (raw SQL EXEC calls via manager.query).

ORM Repository: catalogo.orm-repository.ts

CatalogoOrmRepository provides static methods for every catalog lookup needed across modules. Each method mirrors the behavior of a legacy stored procedure while using TypeORM’s type-safe manager.find API.
// Example: find all active Salas
CatalogoOrmRepository.findSalas(manager);
// → SELECT id, descripcion FROM CatSala WHERE activo = 1 ORDER BY descripcion ASC
Available static methods: findMaterias, findTiposEscrito, findDelitos, findSexos, findTiposParte, findJuzgados, findMagistrados, findApelaciones, findTiposApelacion, findMunicipios, findLocalidades, findEtnias, findAnexos, findSalas, findNomenclatura.

SP Repositories

The three stored-procedure repositories each wrap a specific EXEC call. They accept an EntityManager instance (enabling transaction participation) and the required parameters, and they throw AppError if the procedure returns no rows.

Stored Procedures Reference

Repository fileClassStored procedure(s)Purpose
folio.sp-repository.tsFolioSpRepositoryPA_SEL_FolioNomenclaturaTocaGenerate toca folio from Sala and nomenclature codes
folio.sp-repository.tsFolioSpRepositoryPA_INS_PCF_FolioTramiteInsert and retrieve a new procedure folio number
asignacion-toca-sala.sp-repository.tsAsignacionTocaSalaSpRepositoryPA_SEL_AsignacionTocaySalaDetermine Sala and Toca assignment for a new appeal
estadistica.sp-repository.tsEstadisticaSPRepositoryPA_SEL_PCF_EstadisticaApelacionesRetrieve statistical appeal data filtered by Sala, nomenclature, appeal type, and date range

FolioSpRepository

Called during appeal registration to obtain two system-generated identifiers:
// Generate folio from nomenclature + sala
const folio = await FolioSpRepository.getFolioNomenclaturaToca(manager, {
    idSala,
    idNomenclatura,
});

// Generate a new procedure (tramite) folio
const folioTramite = await FolioSpRepository.getFolioTramite(manager);

AsignacionTocaSalaSpRepository

Determines which Sala and Toca number should be assigned to a new appeal, based on the case origin and appeal type:
const asignacion = await AsignacionTocaSalaSpRepository.getAsignacionTocaSala(manager, {
    idGeneral,
    idAreaSistemaUsuario,
    idPantalla,
    expedienteCausa,
    idApelacion,
    idJuzgado,
    esReposicion,
    idMateria,
});

EstadisticaSPRepository

Fetches statistical records for the estadistica module, accepting optional filter parameters — all nullable so the SP can be called with any subset of filters:
const rows = await EstadisticaSPRepository.getEstadisticaApelaciones(manager, {
    idSala,           // optional
    idNomenclatura,   // optional
    idApelacion,      // optional
    fechaInicio,      // optional ISO date string
    fechaFin,         // optional ISO date string
});

Module Repositories vs. Shared Repositories

Understanding the distinction between the two repository layers avoids confusion when reading or extending the codebase:
CharacteristicModule repositories (modules/<name>/repositories/)Shared repositories (database/repositories/)
LocationInside the owning moduleOutside all modules
Query styleTypeORM QueryBuilder with dynamic filters and JOINsRaw EXEC (SP repos) or manager.find (ORM repo)
ReuseUsed only by their module’s serviceUsed by any module’s service
TransactionParticipate via injected manager or DataSourceAccept EntityManager argument for transaction participation
Examplesbusqueda-apelacion.repository.ts, apelacion.repository.tsfolio.sp-repository.ts, catalogo.orm-repository.ts
All SP repositories accept a raw EntityManager argument rather than creating their own connection. This means they can participate in the same database transaction as the module-level ORM operations — critical during appeal registration, where the folio SP call and the Apelacion entity insert must succeed or fail together.

Build docs developers (and LLMs) love