Especificación de Modelos de Datos, Prisma Schema y Hono RPC: SGP (v2.2.2)

Diseñado por: Project-Planner
Consumido por: Backend-Architect, Frontend-UI y auditado por Systems-Auditor.


🗄️ Esquema de Prisma ORM (prisma/schema.prisma)

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
 
generator client {
  provider = "prisma-client-js"
}
 
model Role {
  id        Int      @id @default(autoincrement())
  name      String   @unique
  users     User[]
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")
 
  @@map("roles")
}
 
model User {
  id                 Int                  @id @default(autoincrement())
  name               String
  email              String               @unique
  password           String
  avatar             String?
  roleId             Int                  @map("role_id")
  role               Role                 @relation(fields: [roleId], references: [id])
  studentProfile     StudentProfile?
  companyProfile     CompanyProfile?
  professorProfile   ProfessorProfile?
  coordinatorProfile CoordinatorProfile?
  resetTokens        PasswordResetToken[]
  createdAt          DateTime             @default(now()) @map("created_at")
  updatedAt          DateTime             @updatedAt @map("updated_at")
 
  @@index([roleId])
  @@index([roleId, createdAt(sort: Desc)])
  @@map("users")
}
 
model StudentProfile {
  id           Int           @id @default(autoincrement())
  userId       Int           @unique @map("user_id")
  user         User          @relation(fields: [userId], references: [id], onDelete: Cascade)
  cedula       String?
  carrera      String?
  phone        String?
  cvPath       String?       @map("cv_path")
  period       String?
  applications Application[]
  internships  Internship[]
  createdAt    DateTime      @default(now()) @map("created_at")
  updatedAt    DateTime      @updatedAt @map("updated_at")
 
  @@map("student_profiles")
}
 
model CompanyProfile {
  id            Int      @id @default(autoincrement())
  userId        Int      @unique @map("user_id")
  user          User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  nombreE       String   @map("nombre_e")
  rif           String?
  direccion     String?
  areasP        String?  @map("areas_p")
  numeroT       String?  @map("numero_t")
  contactPerson String?  @map("contact_person")
  añoC          String?  @map("año_c")
  offers        Offer[]
  createdAt     DateTime @default(now()) @map("created_at")
  updatedAt     DateTime @updatedAt @map("updated_at")
 
  @@map("company_profiles")
}
 
model ProfessorProfile {
  id             Int              @id @default(autoincrement())
  userId         Int              @unique @map("user_id")
  user           User             @relation(fields: [userId], references: [id], onDelete: Cascade)
  cedula         String?
  department     String?
  academicTitle  String?          @map("academic_title")
  phone          String?
  tutoredInterns Internship[]     @relation("TutorProfessor")
  juryInterns    InternshipJury[]
  reviewedDocs   Document[]       @relation("DocumentReviewer")
  createdAt      DateTime         @default(now()) @map("created_at")
  updatedAt      DateTime         @updatedAt @map("updated_at")
 
  @@map("professor_profiles")
}
 
model PasswordResetToken {
  id        Int       @id @default(autoincrement())
  token     String    @unique
  userId    Int       @map("user_id")
  user      User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  expiresAt DateTime  @map("expires_at")
  usedAt    DateTime? @map("used_at")
  createdAt DateTime  @default(now()) @map("created_at")
 
  @@index([token])
  @@index([userId])
  @@map("password_reset_tokens")
}
 
model CoordinatorProfile {
  id         Int      @id @default(autoincrement())
  userId     Int      @unique @map("user_id")
  user       User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  department String?
  createdAt  DateTime @default(now()) @map("created_at")
  updatedAt  DateTime @updatedAt @map("updated_at")
 
  @@map("coordinator_profiles")
}
 
model Offer {
  id               Int            @id @default(autoincrement())
  companyProfileId Int            @map("company_profile_id")
  companyProfile   CompanyProfile @relation(fields: [companyProfileId], references: [id], onDelete: Cascade)
  title            String
  description      String
  vacancies        Int            @default(1)
  skills           String[]       @default([])
  location         String?
  status           String         @default("active") // active, closed
  applications     Application[]
  createdAt        DateTime       @default(now()) @map("created_at")
  updatedAt        DateTime       @updatedAt @map("updated_at")
 
  @@index([companyProfileId, createdAt(sort: Desc)])
  @@index([status, createdAt(sort: Desc)])
  @@map("offers")
}
 
model Application {
  id               Int            @id @default(autoincrement())
  studentProfileId Int            @map("student_profile_id")
  studentProfile   StudentProfile @relation(fields: [studentProfileId], references: [id], onDelete: Cascade)
  offerId          Int            @map("offer_id")
  offer            Offer          @relation(fields: [offerId], references: [id], onDelete: Cascade)
  status           String         @default("pending") // pending, accepted, rejected
  notes            String?
  isUsed           Boolean        @default(false) @map("is_used")
  createdAt        DateTime       @default(now()) @map("created_at")
  updatedAt        DateTime       @updatedAt @map("updated_at")
 
  @@index([studentProfileId, status])
  @@index([offerId, status])
  @@index([offerId, createdAt(sort: Desc)])
  @@map("applications")
}
 
model Internship {
  id                      Int               @id @default(autoincrement())
  studentProfileId        Int               @map("student_profile_id")
  studentProfile          StudentProfile    @relation(fields: [studentProfileId], references: [id], onDelete: Cascade)
  companyName             String            @map("company_name")
  companyTutorName        String?           @map("company_tutor_name")
  companyTutorPhone       String?           @map("company_tutor_phone")
  academicPeriod          String?           @map("academic_period")
  startDate               DateTime?         @map("start_date")
  endDate                 DateTime?         @map("end_date")
  status                  String            @default("solicitud_tutor") 
  // status: solicitud_tutor, tutor_pendiente, tutor_rechazado, en_progreso, borrador_aprobado, defensa_programada, defendida, culminada
  tutorProfessorProfileId Int?              @map("tutor_professor_profile_id")
  tutorProfessor          ProfessorProfile? @relation("TutorProfessor", fields: [tutorProfessorProfileId], references: [id])
  juries                  InternshipJury[]
  documents               Document[]
  defense                 Defense?
  defenseDate             DateTime?         @map("defense_date")
  createdAt               DateTime          @default(now()) @map("created_at")
  updatedAt               DateTime          @updatedAt @map("updated_at")
 
  @@index([studentProfileId, status])
  @@index([tutorProfessorProfileId, status])
  @@map("internships")
}
 
model InternshipJury {
  id                 Int              @id @default(autoincrement())
  internshipId       Int              @map("internship_id")
  internship         Internship       @relation(fields: [internshipId], references: [id], onDelete: Cascade)
  professorProfileId Int              @map("professor_profile_id")
  professorProfile   ProfessorProfile @relation(fields: [professorProfileId], references: [id], onDelete: Cascade)
  createdAt          DateTime         @default(now()) @map("created_at")
 
  @@unique([internshipId, professorProfileId])
  @@map("internship_jury")
}
 
model Document {
  id               Int               @id @default(autoincrement())
  internshipId     Int               @map("internship_id")
  internship       Internship        @relation(fields: [internshipId], references: [id], onDelete: Cascade)
  documentType     String            @map("document_type") 
  // documentType: carta_postulacion, carta_aceptacion, borrador_tutor, borrador_jurado, presentacion, constancia_culminacion
  filePath         String            @map("file_path")
  feedbackFilePath String?           @map("feedback_file_path")
  status           String            @default("pending") // pending, approved, rejected
  feedback         String?
  reviewerId       Int?              @map("reviewer_id")
  reviewer         ProfessorProfile? @relation("DocumentReviewer", fields: [reviewerId], references: [id])
  createdAt        DateTime          @default(now()) @map("created_at")
  updatedAt        DateTime          @updatedAt @map("updated_at")
 
  @@index([internshipId, documentType, status])
  @@map("documents")
}
 
model Defense {
  id           Int        @id @default(autoincrement())
  internshipId Int        @unique @map("internship_id")
  internship   Internship @relation(fields: [internshipId], references: [id], onDelete: Cascade)
  defenseDate  DateTime?  @map("defense_date")
  classroom    String?
  grade        Float?
  notaTrabajo  Float?     @map("nota_trabajo")
  status       String     @default("scheduled") // scheduled, approved, reproved
  notes        String?
  createdAt    DateTime   @default(now()) @map("created_at")
  updatedAt    DateTime   @updatedAt @map("updated_at")
 
  @@map("defenses")
}

📡 Endpoints Hono RPC (/api/...)

  1. Auth & Session (/api/auth):

    • POST /login -> { email, password } => session cookie + user data
    • POST /register -> { name, email, password, role ('Estudiante' | 'Empresa'), ...profileFields } => autoservicio público, crea cuenta y sesión
    • POST /forgot-password -> { email } => genera token de recuperación de clave
    • POST /reset-password -> { token, password } => valida token y actualiza contraseña hasheada
    • PATCH /profile -> actualiza datos del perfil (5 roles); exige obligatoriamente currentPassword para cambios de clave
    • POST /logout -> clears session cookie
    • GET /me -> returns authenticated user profile & role
    • GET /login-as/:id -> switches session for quick development/demo
  2. Dashboard (/api/dashboard):

    • GET /metrics -> KPI metrics by role (estudiantes activos, ofertas, jurados asignados, defensas pendientes)
    • GET /chart-metrics -> analítica agregada para Recharts (internshipsByStatus, internshipsByPeriod, schoolMetrics)
  3. Offers (/api/offers):

    • GET / -> list published offers (filter by query/skills)
    • POST / -> create new offer (Company/Admin)
    • GET /:id -> detail of an offer
    • POST /:id/apply -> student application with optional notes
  4. Applications (/api/applications):

    • GET /mine -> list of logged-in student’s applications
    • GET /by-offer/:offerId -> applications received for an offer (Company)
    • PATCH /:id/status -> change status to ‘accepted’ or ‘rejected’
  5. Internships (/api/internships):

    • GET / -> list internships filtered by user role (Estudiante, Empresa, Profesor, Coordinador, Administrador)
    • POST / -> create new internship from accepted application
    • GET /tutor-requests -> pending tutor requests for professor
    • POST /:id/request-tutor -> student selects professor tutor
    • POST /:id/accept-tutor -> professor accepts
    • POST /:id/reject-tutor -> professor rejects
    • POST /:id/assign-juries -> assign 2 professors as evaluators
    • POST /:id/schedule-defense -> set defense date, time and classroom
    • GET /history -> completed/defended internships
    • POST /:id/reset -> reset internship flow if required
  6. Documents (/api/documents):

    • GET /by-internship/:internshipId -> list documents
    • POST /upload -> subida a directorio privado storage/documents/ con validación de extensión y magic bytes (%PDF-, etc.)
    • GET /:id/download -> descarga autenticada con control de acceso RBAC estricto
    • PATCH /:id/review -> review verdict (approved / rejected) + feedback text + feedback file
    • DELETE /:id -> delete pending document (unlinks from storage)
  7. Defenses (/api/defenses):

    • POST /:internshipId/grade -> registro de calificación de defensa y/o evaluación laboral empresarial (notaTrabajo, escala 0-20)
  8. Admin (/api/admin):

    • GET /roles -> list 5 official roles
    • GET /users -> list users with roles and profiles
    • POST /users -> create user and profile
    • PATCH /users/:id -> Edición Integral de Usuario y Perfil por Administrador:
      • RBAC: Requiere authMiddleware y roleGuard('Administrador').
      • Parámetro URL: :id (entero positivo, identificador del usuario a modificar).
      • Contrato de Entrada (JSON Body):
        {
          name?: string,          // min 2 caracteres
          email?: string,         // formato email válido
          password?: string,      // min 6 caracteres o string vacío '' para no alterar
          roleId?: number,        // entero positivo del rol destino
          // Campos de perfiles institucionales (opcionales / nullables)
          cedula?: string | null,
          phone?: string | null,
          carrera?: string | null,
          department?: string | null,
          academicTitle?: string | null,
          nombreE?: string | null,
          rif?: string | null,
          direccion?: string | null,
          numeroT?: string | null,
          areasP?: string | null
        }
      • Reglas de Negocio:
        • 404 Not Found: Si el usuario objetivo no existe en el sistema (Usuario no encontrado).
        • 400 Bad Request: Si el correo proporcionado ya se encuentra registrado por otro usuario (El correo ya se encuentra registrado por otro usuario).
        • 400 Bad Request: Si el Administrador intenta degradar su propia cuenta a un rol diferente de Administrador (No puedes degradar tu propia cuenta de Administrador).
        • 400 Bad Request: Si el roleId indicado no existe en la base de datos.
        • Si se suministra password no vacío, se hashea criptográficamente mediante hashPassword(password).
        • Actualiza los datos de cuenta en el modelo User (name, email, roleId, password).
        • Ejecuta upsert en la tabla de perfil asociada al rol final del usuario:
          • Estudiante: actualiza/crea en StudentProfile (cedula, carrera, phone).
          • Profesor: actualiza/crea en ProfessorProfile (cedula, department, phone, academicTitle).
          • Coordinador: actualiza/crea en CoordinatorProfile (department).
          • Empresa: actualiza/crea en CompanyProfile (nombreE, rif, direccion, numeroT, areasP).
      • Respuestas:
        • 200 OK:
          {
            "success": true,
            "message": "Usuario y perfil actualizados exitosamente",
            "user": {
              "id": 1,
              "name": "Profesor Actualizado",
              "email": "profesor@sgp.test",
              "roleId": 3,
              "role": { "id": 3, "name": "Profesor" },
              "studentProfile": null,
              "professorProfile": { "id": 1, "cedula": "12345678", "department": "Sistemas", "academicTitle": "MSc." },
              "coordinatorProfile": null,
              "companyProfile": null,
              "createdAt": "2026-09-11T12:00:00.000Z",
              "updatedAt": "2026-09-12T19:00:00.000Z"
            }
          }
        • 400 Bad Request: Error de validación Zod, colisión de correo institucional o violación de auto-degradación.
        • 401 Unauthorized: Token de sesión ausente o inválido.
        • 403 Forbidden: Usuario sin privilegios de Administrador.
        • 404 Not Found: Usuario objetivo no encontrado.
    • PATCH /users/:id/role -> change role (prevents self-demotion)
    • DELETE /users/:id -> delete user (prevents self-deletion)