Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 127 additions & 0 deletions backend/prisma/ERD.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Diagrama ERD - Base de Datos de Candidatos

## Análisis del Esquema

Este esquema de Prisma define un sistema de gestión de candidatos con las siguientes características:

### Entidades Principales

1. **Candidate** - Entidad principal que representa a un candidato
2. **Education** - Historial educativo de los candidatos
3. **WorkExperience** - Experiencia laboral de los candidatos
4. **Resume** - Archivos de currículum asociados a los candidatos

### Relaciones

- **Candidate → Education**: Relación uno-a-muchos (un candidato puede tener múltiples registros educativos)
- **Candidate → WorkExperience**: Relación uno-a-muchos (un candidato puede tener múltiples experiencias laborales)
- **Candidate → Resume**: Relación uno-a-muchos (un candidato puede tener múltiples currículums)

## Diagrama ERD

```mermaid
erDiagram
Candidate {
int id PK "AUTO_INCREMENT"
varchar firstName "100"
varchar lastName "100"
varchar email UK "255, UNIQUE"
varchar phone "15, NULLABLE"
varchar address "100, NULLABLE"
}

Education {
int id PK "AUTO_INCREMENT"
varchar institution "100"
varchar title "250"
datetime startDate
datetime endDate "NULLABLE"
int candidateId FK
}

WorkExperience {
int id PK "AUTO_INCREMENT"
varchar company "100"
varchar position "100"
varchar description "200, NULLABLE"
datetime startDate
datetime endDate "NULLABLE"
int candidateId FK
}

Resume {
int id PK "AUTO_INCREMENT"
varchar filePath "500"
varchar fileType "50"
datetime uploadDate
int candidateId FK
}

Candidate ||--o{ Education : "has many"
Candidate ||--o{ WorkExperience : "has many"
Candidate ||--o{ Resume : "has many"
```

## Descripción Detallada de las Entidades

### Candidate (Candidato)
- **Propósito**: Almacena la información personal básica de los candidatos
- **Campos Clave**:
- `id`: Identificador único autoincremental
- `email`: Email único del candidato (constraint UNIQUE)
- `firstName`, `lastName`: Nombre y apellido del candidato
- `phone`, `address`: Campos opcionales para contacto y ubicación

### Education (Educación)
- **Propósito**: Registra el historial educativo de los candidatos
- **Campos Clave**:
- `id`: Identificador único autoincremental
- `candidateId`: Clave foránea que referencia a Candidate
- `institution`: Nombre de la institución educativa
- `title`: Título o grado obtenido
- `startDate`: Fecha de inicio (obligatoria)
- `endDate`: Fecha de finalización (opcional, permite educación en curso)

### WorkExperience (Experiencia Laboral)
- **Propósito**: Almacena la experiencia laboral de los candidatos
- **Campos Clave**:
- `id`: Identificador único autoincremental
- `candidateId`: Clave foránea que referencia a Candidate
- `company`: Nombre de la empresa
- `position`: Cargo o posición ocupada
- `description`: Descripción opcional de las responsabilidades
- `startDate`: Fecha de inicio (obligatoria)
- `endDate`: Fecha de finalización (opcional, permite trabajos actuales)

### Resume (Currículum)
- **Propósito**: Gestiona los archivos de currículum subidos por los candidatos
- **Campos Clave**:
- `id`: Identificador único autoincremental
- `candidateId`: Clave foránea que referencia a Candidate
- `filePath`: Ruta del archivo en el sistema de almacenamiento
- `fileType`: Tipo de archivo (PDF, DOC, etc.)
- `uploadDate`: Fecha y hora de carga del archivo

## Características del Esquema

### Constraints y Validaciones
- **Email único**: El campo `email` en Candidate tiene constraint UNIQUE, garantizando que no haya duplicados
- **Claves foráneas**: Todas las relaciones están definidas con foreign keys que aseguran integridad referencial
- **Campos opcionales**: Varios campos permiten valores NULL para flexibilidad (phone, address, endDate, description)

### Tipos de Datos
- **PostgreSQL**: El esquema utiliza PostgreSQL como base de datos
- **VarChar con límites**: Todos los campos de texto tienen límites específicos para optimizar el almacenamiento
- **DateTime**: Fechas almacenadas como DateTime para precisión temporal

### Relaciones
- **Cascada implícita**: Las relaciones están configuradas para mantener la integridad referencial
- **Cardinalidad**: Todas las relaciones son uno-a-muchos (1:N), permitiendo múltiples registros relacionados por candidato

## Consideraciones de Diseño

1. **Normalización**: El esquema está bien normalizado, separando información personal, educativa, laboral y archivos
2. **Escalabilidad**: Permite múltiples registros por candidato en cada entidad relacionada
3. **Flexibilidad**: Campos opcionales permiten datos incompletos sin comprometer la integridad
4. **Trazabilidad**: El campo `uploadDate` en Resume permite rastrear cuándo se subieron los archivos

88 changes: 88 additions & 0 deletions backend/prisma/ERD_update.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
```mermaid
erDiagram
COMPANY {
int id PK
string name
}
EMPLOYEE {
int id PK
int company_id FK
string name
string email
string role
boolean is_active
}
POSITION {
int id PK
int company_id FK
int interview_flow_id FK
string title
text description
string status
boolean is_visible
string location
text job_description
text requirements
text responsibilities
numeric salary_min
numeric salary_max
string employment_type
text benefits
text company_description
date application_deadline
string contact_info
}
INTERVIEW_FLOW {
int id PK
string description
}
INTERVIEW_STEP {
int id PK
int interview_flow_id FK
int interview_type_id FK
string name
int order_index
}
INTERVIEW_TYPE {
int id PK
string name
text description
}
CANDIDATE {
int id PK
string firstName
string lastName
string email
string phone
string address
}
APPLICATION {
int id PK
int position_id FK
int candidate_id FK
date application_date
string status
text notes
}
INTERVIEW {
int id PK
int application_id FK
int interview_step_id FK
int employee_id FK
date interview_date
string result
int score
text notes
}

COMPANY ||--o{ EMPLOYEE : employs
COMPANY ||--o{ POSITION : offers
POSITION ||--|| INTERVIEW_FLOW : assigns
INTERVIEW_FLOW ||--o{ INTERVIEW_STEP : contains
INTERVIEW_STEP ||--|| INTERVIEW_TYPE : uses
POSITION ||--o{ APPLICATION : receives
CANDIDATE ||--o{ APPLICATION : submits
APPLICATION ||--o{ INTERVIEW : has
INTERVIEW ||--|| INTERVIEW_STEP : consists_of
EMPLOYEE ||--o{ INTERVIEW : conducts
```
Comment on lines +1 to +88
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify ERD diagram consistency with migration script and existing schema.

The Mermaid diagram is well-structured and defines all recruitment entities and relationships. However, the CANDIDATE entity appears in the diagram but is not created in migration_erd_update.sql—it's expected to be an existing table per the migration comments. Verify that:

  1. The CANDIDATE entity and its attributes match the existing schema (typically defined in the candidate-related tables noted in ERD.md)
  2. All foreign key relationships in lines 78–87 are correctly implemented in the migration script
  3. Cardinality matches the migration's ON DELETE and ON UPDATE rules

🏁 Script executed:

#!/bin/bash
# Verify ERD diagram entities match migration script table definitions

echo "=== Entities in ERD diagram ==="
grep -oP '^\s+\K\w+(?=\s*\{)' backend/prisma/ERD_update.md | sort | uniq

echo ""
echo "=== Tables created in migration script ==="
grep -oP 'CREATE TABLE IF NOT EXISTS "\K[^"]+' backend/prisma/migration_erd_update.sql | sort | uniq

echo ""
echo "=== CANDIDATE references in migration ==="
rg -C2 'REFERENCES.*Candidate'

Length of output: 863



---

🏁 Script executed:

```shell
#!/bin/bash
# Search for Candidate table definition across migration files

echo "=== Searching for CREATE TABLE.*Candidate ==="
rg -i 'create table.*candidate' backend/prisma/ || echo "No matches found"

echo ""
echo "=== Listing all migration files ==="
ls -la backend/prisma/migrations/ 2>/dev/null || ls -la backend/prisma/*.sql | head -20

echo ""
echo "=== Checking if Candidate is defined in migration_erd_update.sql ==="
grep -i 'create table.*candidate' backend/prisma/migration_erd_update.sql || echo "Candidate CREATE TABLE not found in migration_erd_update.sql"

Length of output: 407


Migration script is missing Candidate table definition—foreign key constraint references non-existent table.

The ERD diagram correctly includes the CANDIDATE entity, but migration_erd_update.sql does not create the corresponding table. However, the Application table's foreign key constraint references "Candidate"(id), which will cause the migration to fail with a "referenced table does not exist" error.

The migration script must include a CREATE TABLE statement for the Candidate table with columns matching the ERD diagram (id, firstName, lastName, email, phone, address) before the Application table is created.

🤖 Prompt for AI Agents
In backend/prisma/migration_erd_update.sql (around the Application CREATE TABLE
and its preceding statements), the migration omits creating the Candidate table
while Application declares a foreign key to "Candidate"(id); add a CREATE TABLE
"Candidate" statement before creating Application with columns id (primary key,
integer/serial), firstName (varchar), lastName (varchar), email (varchar), phone
(varchar), address (text) to match the ERD, ensure the table name/casing matches
the FK reference, and update the down/rollback section (if present) to drop
Candidate in the correct order.

Loading