Compare commits

...

No commits in common. '93775bd1caf789d1e2a92c63ad64fe6fbb798772' and '42a4be98e9073d141f5f348250421da6dfb4c0b4' have entirely different histories.

@ -1,61 +0,0 @@
# ===========================================
# Produccion - Direccion de Admision 2026
# ===========================================
# Copiar este archivo como .env.prod y completar los valores
# --- App ---
APP_NAME="Direccion de Admision"
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://tu-dominio.com
# Puerto interno donde Docker escucha (el nginx del host hace proxy a este puerto)
APP_PORT=8080
# --- Base de datos ---
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=admision_2026
DB_USERNAME=root
DB_PASSWORD=CAMBIAR_PASSWORD_SEGURA
# --- Sessions ---
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=true
SESSION_DOMAIN=tu-dominio.com
# --- Cache & Queue ---
CACHE_STORE=database
QUEUE_CONNECTION=database
# --- Sanctum ---
SANCTUM_STATEFUL_DOMAINS=tu-dominio.com
# --- Frontend ---
VITE_API_URL=/api
# --- Mail (configurar segun proveedor) ---
MAIL_MAILER=smtp
MAIL_HOST=smtp.ejemplo.com
MAIL_PORT=587
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="admision@tu-dominio.com"
MAIL_FROM_NAME="${APP_NAME}"
# --- Logging ---
LOG_CHANNEL=stack
LOG_STACK=single
LOG_LEVEL=error
# --- Docker / Registry ---
GITHUB_REPO=tu-usuario/tu-repo
IMAGE_TAG=latest
# --- Misc ---
BCRYPT_ROUNDS=12
FILESYSTEM_DISK=local

2
.gitattributes vendored

@ -1,2 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto

@ -1,150 +0,0 @@
name: Build & Deploy
on:
push:
branches: [main]
workflow_dispatch:
inputs:
deploy:
description: 'Desplegar en el VPS despues de construir'
required: true
default: true
type: boolean
# Un solo deploy a la vez — si llega uno nuevo, cancela el anterior
concurrency:
group: deploy-production
cancel-in-progress: true
env:
REGISTRY: ghcr.io
BACKEND_IMAGE: ghcr.io/${{ github.repository }}/backend
FRONTEND_IMAGE: ghcr.io/${{ github.repository }}/frontend
BACKEND_CACHE: ghcr.io/${{ github.repository }}/cache-backend
FRONTEND_CACHE: ghcr.io/${{ github.repository }}/cache-frontend
jobs:
build-backend:
name: Build Backend
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build & push backend
uses: docker/build-push-action@v5
with:
context: ./back
push: true
cache-from: type=registry,ref=${{ env.BACKEND_CACHE }}
cache-to: type=registry,ref=${{ env.BACKEND_CACHE }},mode=max
tags: |
${{ env.BACKEND_IMAGE }}:latest
${{ env.BACKEND_IMAGE }}:${{ github.sha }}
build-frontend:
name: Build Frontend
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build & push frontend
uses: docker/build-push-action@v5
with:
context: ./front
push: true
cache-from: type=registry,ref=${{ env.FRONTEND_CACHE }}
cache-to: type=registry,ref=${{ env.FRONTEND_CACHE }},mode=max
build-args: |
VITE_API_URL=/api
tags: |
${{ env.FRONTEND_IMAGE }}:latest
${{ env.FRONTEND_IMAGE }}:${{ github.sha }}
deploy:
name: Deploy to VPS
needs: [build-backend, build-frontend]
if: ${{ github.event_name == 'push' || inputs.deploy }}
runs-on: ubuntu-latest
steps:
- name: Deploy via SSH
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.VPS_HOST }}
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_SSH_KEY }}
port: ${{ secrets.VPS_PORT || 22 }}
command_timeout: 30m
script: |
cd ${{ secrets.VPS_PROJECT_PATH }}
# Sincronizar archivos del host con el repo (sin conflictos)
git fetch origin main && git reset --hard origin/main
# Login al registry
echo ${{ secrets.CR_PAT }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin
# Descargar imagenes nuevas
docker pull ${{ env.BACKEND_IMAGE }}:latest
docker pull ${{ env.FRONTEND_IMAGE }}:latest
# Reiniciar servicios
docker compose --env-file .env.prod -f docker-compose.prod.yml up -d --force-recreate backend frontend nginx
# Esperar que el backend este listo antes de migrar (max 60 segundos)
echo "Esperando backend..."
for i in $(seq 1 30); do
if docker exec admision_prod_backend php artisan --version > /dev/null 2>&1; then
echo "Backend listo"
break
fi
sleep 2
done
# Ejecutar migraciones si hay pendientes
docker exec admision_prod_backend php artisan migrate --force
# Limpiar imagenes viejas
docker image prune -f

151
.gitignore vendored

@ -1,3 +1,4 @@
# ---> Laravel
/vendor/
node_modules/
npm-debug.log
@ -17,15 +18,151 @@ public_html/hot
storage/*.key
.env
.env.prod
Homestead.yaml
Homestead.json
/.vagrant
.phpunit.result.cache
/public/build
/storage/pail
.env.backup
.env.production
.phpactor.json
auth.json
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# ---> Vue
# gitignore template for Vue.js projects
#
# Recommended template: Node.gitignore
# TODO: where does this rule come from?
docs/_book
# TODO: where does this rule come from?
test/

@ -1,868 +0,0 @@
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Versión del servidor: 8.0.30 - MySQL Community Server - GPL
-- SO del servidor: Win64
-- HeidiSQL Versión: 12.1.0.6537
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-- Volcando estructura de base de datos para admision_2026
CREATE DATABASE IF NOT EXISTS `admision_2026` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `admision_2026`;
-- Volcando estructura para tabla admision_2026.areas
CREATE TABLE IF NOT EXISTS `areas` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(100) NOT NULL,
`codigo` varchar(20) NOT NULL,
`descripcion` varchar(500) DEFAULT NULL,
`activo` tinyint(1) NOT NULL DEFAULT '1',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `codigo` (`codigo`),
KEY `idx_areas_activo` (`activo`),
KEY `idx_areas_codigo` (`codigo`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.areas: ~2 rows (aproximadamente)
DELETE FROM `areas`;
INSERT INTO `areas` (`id`, `nombre`, `codigo`, `descripcion`, `activo`, `created_at`, `updated_at`) VALUES
(3, 'Biomedicas', 'BIO', NULL, 1, '2026-02-13 21:37:24', '2026-02-14 00:52:17'),
(4, 'Ingenierias', 'ING', NULL, 1, '2026-02-13 21:37:42', '2026-02-14 00:52:15');
-- Volcando estructura para tabla admision_2026.areas_admision
CREATE TABLE IF NOT EXISTS `areas_admision` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(150) NOT NULL,
`descripcion` text,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.areas_admision: ~0 rows (aproximadamente)
DELETE FROM `areas_admision`;
-- Volcando estructura para tabla admision_2026.area_curso
CREATE TABLE IF NOT EXISTS `area_curso` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`area_id` bigint unsigned NOT NULL,
`curso_id` bigint unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
KEY `fk_area_curso_area` (`area_id`) USING BTREE,
KEY `fk_area_curso_curso` (`curso_id`) USING BTREE,
CONSTRAINT `fk_area_curso_area` FOREIGN KEY (`area_id`) REFERENCES `areas` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_area_curso_curso` FOREIGN KEY (`curso_id`) REFERENCES `cursos` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.area_curso: ~4 rows (aproximadamente)
DELETE FROM `area_curso`;
INSERT INTO `area_curso` (`id`, `area_id`, `curso_id`, `created_at`, `updated_at`) VALUES
(5, 4, 4, '2026-02-13 21:43:34', '2026-02-13 21:43:34'),
(6, 4, 3, '2026-02-13 21:43:34', '2026-02-13 21:43:34'),
(7, 3, 4, '2026-02-13 21:43:36', '2026-02-13 21:43:36'),
(8, 3, 3, '2026-02-13 21:43:36', '2026-02-13 21:43:36');
-- Volcando estructura para tabla admision_2026.area_proceso
CREATE TABLE IF NOT EXISTS `area_proceso` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`area_id` bigint unsigned NOT NULL,
`proceso_id` bigint unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `area_proceso_unique` (`area_id`,`proceso_id`),
KEY `fk_area_proceso_proceso` (`proceso_id`),
CONSTRAINT `fk_area_proceso_area` FOREIGN KEY (`area_id`) REFERENCES `areas` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_area_proceso_proceso` FOREIGN KEY (`proceso_id`) REFERENCES `procesos` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.area_proceso: ~2 rows (aproximadamente)
DELETE FROM `area_proceso`;
INSERT INTO `area_proceso` (`id`, `area_id`, `proceso_id`, `created_at`, `updated_at`) VALUES
(3, 4, 2, '2026-02-13 21:43:29', '2026-02-13 21:43:29'),
(4, 3, 2, '2026-02-13 21:43:32', '2026-02-13 21:43:32');
-- Volcando estructura para tabla admision_2026.cache
CREATE TABLE IF NOT EXISTS `cache` (
`key` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`value` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`expiration` int NOT NULL,
PRIMARY KEY (`key`),
KEY `cache_expiration_index` (`expiration`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.cache: ~0 rows (aproximadamente)
DELETE FROM `cache`;
-- Volcando estructura para tabla admision_2026.cache_locks
CREATE TABLE IF NOT EXISTS `cache_locks` (
`key` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`owner` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`expiration` int NOT NULL,
PRIMARY KEY (`key`),
KEY `cache_locks_expiration_index` (`expiration`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.cache_locks: ~0 rows (aproximadamente)
DELETE FROM `cache_locks`;
-- Volcando estructura para tabla admision_2026.calificaciones
CREATE TABLE IF NOT EXISTS `calificaciones` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`puntos_correcta` decimal(5,2) NOT NULL DEFAULT '10.00',
`puntos_incorrecta` decimal(5,2) NOT NULL DEFAULT '0.00',
`puntos_nula` decimal(5,2) NOT NULL DEFAULT '0.00',
`puntaje_maximo` decimal(8,2) NOT NULL DEFAULT '1000.00',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.calificaciones: ~0 rows (aproximadamente)
DELETE FROM `calificaciones`;
INSERT INTO `calificaciones` (`id`, `nombre`, `puntos_correcta`, `puntos_incorrecta`, `puntos_nula`, `puntaje_maximo`, `created_at`, `updated_at`) VALUES
(1, 'preu', 10.00, 0.00, 0.00, 1000.00, NULL, NULL);
-- Volcando estructura para tabla admision_2026.cursos
CREATE TABLE IF NOT EXISTS `cursos` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(100) NOT NULL,
`codigo` varchar(20) NOT NULL,
`descripcion` varchar(500) DEFAULT NULL,
`activo` tinyint(1) NOT NULL DEFAULT '1',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `codigo` (`codigo`),
KEY `idx_cursos_activo` (`activo`),
KEY `idx_cursos_codigo` (`codigo`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.cursos: ~2 rows (aproximadamente)
DELETE FROM `cursos`;
INSERT INTO `cursos` (`id`, `nombre`, `codigo`, `descripcion`, `activo`, `created_at`, `updated_at`) VALUES
(3, 'Matematica', 'MAT', NULL, 1, '2026-02-13 21:38:06', '2026-02-13 21:38:06'),
(4, 'Comunicacion', 'COM', NULL, 1, '2026-02-13 21:38:19', '2026-02-13 21:38:19');
-- Volcando estructura para tabla admision_2026.examenes
CREATE TABLE IF NOT EXISTS `examenes` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`postulante_id` bigint unsigned NOT NULL,
`area_proceso_id` bigint unsigned NOT NULL,
`pagado` tinyint(1) NOT NULL DEFAULT '0',
`tipo_pago` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`pago_id` decimal(20,6) DEFAULT '0.000000',
`intentos` int NOT NULL DEFAULT '0',
`estado` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pendiente',
`hora_inicio` timestamp NULL DEFAULT NULL,
`hora_fin` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
KEY `examenes_postulante_id_foreign` (`postulante_id`) USING BTREE,
KEY `examenes_area_proceso_id_foreign` (`area_proceso_id`) USING BTREE,
KEY `examenes_estado_index` (`estado`),
CONSTRAINT `examenes_area_proceso_id_foreign` FOREIGN KEY (`area_proceso_id`) REFERENCES `area_proceso` (`id`) ON DELETE CASCADE,
CONSTRAINT `examenes_postulante_id_foreign` FOREIGN KEY (`postulante_id`) REFERENCES `postulantes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.examenes: ~0 rows (aproximadamente)
DELETE FROM `examenes`;
INSERT INTO `examenes` (`id`, `postulante_id`, `area_proceso_id`, `pagado`, `tipo_pago`, `pago_id`, `intentos`, `estado`, `hora_inicio`, `hora_fin`, `created_at`, `updated_at`) VALUES
(21, 6, 4, 0, NULL, NULL, 1, 'calificado', '2026-02-17 18:42:13', '2026-02-17 18:42:25', '2026-02-17 18:42:11', '2026-02-17 18:42:19');
-- Volcando estructura para tabla admision_2026.failed_jobs
CREATE TABLE IF NOT EXISTS `failed_jobs` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`uuid` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`connection` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`queue` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`exception` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`failed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.failed_jobs: ~0 rows (aproximadamente)
DELETE FROM `failed_jobs`;
-- Volcando estructura para tabla admision_2026.jobs
CREATE TABLE IF NOT EXISTS `jobs` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`queue` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`attempts` tinyint unsigned NOT NULL,
`reserved_at` int unsigned DEFAULT NULL,
`available_at` int unsigned NOT NULL,
`created_at` int unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `jobs_queue_index` (`queue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.jobs: ~0 rows (aproximadamente)
DELETE FROM `jobs`;
-- Volcando estructura para tabla admision_2026.job_batches
CREATE TABLE IF NOT EXISTS `job_batches` (
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`total_jobs` int NOT NULL,
`pending_jobs` int NOT NULL,
`failed_jobs` int NOT NULL,
`failed_job_ids` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`options` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`cancelled_at` int DEFAULT NULL,
`created_at` int NOT NULL,
`finished_at` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.job_batches: ~0 rows (aproximadamente)
DELETE FROM `job_batches`;
-- Volcando estructura para tabla admision_2026.migrations
CREATE TABLE IF NOT EXISTS `migrations` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`migration` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.migrations: ~7 rows (aproximadamente)
DELETE FROM `migrations`;
INSERT INTO `migrations` (`migration`, `batch`) VALUES
('0001_01_01_000000_create_users_table', 1),
('0001_01_01_000001_create_cache_table', 1),
('0001_01_01_000002_create_jobs_table', 1),
('2026_01_27_132900_create_personal_access_tokens_table', 1),
('2026_01_27_133609_create_permission_tables', 1),
('2026_02_15_051618_fix_unique_constraint_proceso_admision_detalles', 1),
('2026_02_20_000001_create_proceso_admision_resultado_archivos_table', 2);
-- Volcando estructura para tabla admision_2026.model_has_permissions
CREATE TABLE IF NOT EXISTS `model_has_permissions` (
`permission_id` bigint unsigned NOT NULL,
`model_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`model_id` bigint unsigned NOT NULL,
PRIMARY KEY (`permission_id`,`model_id`,`model_type`),
KEY `model_has_permissions_model_id_model_type_index` (`model_id`,`model_type`),
CONSTRAINT `model_has_permissions_permission_id_foreign` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.model_has_permissions: ~0 rows (aproximadamente)
DELETE FROM `model_has_permissions`;
-- Volcando estructura para tabla admision_2026.model_has_roles
CREATE TABLE IF NOT EXISTS `model_has_roles` (
`role_id` bigint unsigned NOT NULL,
`model_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`model_id` bigint unsigned NOT NULL,
PRIMARY KEY (`role_id`,`model_id`,`model_type`),
KEY `model_has_roles_model_id_model_type_index` (`model_id`,`model_type`),
CONSTRAINT `model_has_roles_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.model_has_roles: ~0 rows (aproximadamente)
DELETE FROM `model_has_roles`;
INSERT INTO `model_has_roles` (`role_id`, `model_type`, `model_id`) VALUES
(5, 'App\\Models\\User', 5);
-- Volcando estructura para tabla admision_2026.noticias
CREATE TABLE IF NOT EXISTS `noticias` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`titulo` varchar(220) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`slug` varchar(260) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`descripcion_corta` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`contenido` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`categoria` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'General',
`tag_color` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`imagen_path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`imagen_url` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`link_url` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`link_texto` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'Leer más',
`fecha_publicacion` datetime DEFAULT NULL,
`publicado` tinyint(1) NOT NULL DEFAULT '0',
`destacado` tinyint(1) NOT NULL DEFAULT '0',
`orden` int NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_noticias_slug` (`slug`),
KEY `idx_noticias_publicado_fecha` (`publicado`,`fecha_publicacion`),
KEY `idx_noticias_categoria` (`categoria`),
KEY `idx_noticias_destacado` (`destacado`),
KEY `idx_noticias_deleted` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.noticias: ~1 rows (aproximadamente)
DELETE FROM `noticias`;
INSERT INTO `noticias` (`id`, `titulo`, `slug`, `descripcion_corta`, `contenido`, `categoria`, `tag_color`, `imagen_path`, `imagen_url`, `link_url`, `link_texto`, `fecha_publicacion`, `publicado`, `destacado`, `orden`, `created_at`, `updated_at`, `deleted_at`) VALUES
(3, 'noticia 1', 'noticia-1', 'descripcion corta', 'contenido extenso de la noticia', 'noticias', 'blue', 'noticias/KzNdtcm035xM8NQwFad4VDbB3cEoqEfDTdQmwG9Z.png', NULL, NULL, 'Leer más', '2026-02-17 14:51:01', 1, 1, 0, '2026-02-17 19:51:49', '2026-02-17 19:51:49', NULL);
-- Volcando estructura para tabla admision_2026.pagos
CREATE TABLE IF NOT EXISTS `pagos` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`postulante_id` bigint unsigned NOT NULL,
`tipo_pago` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`codigo_pago` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`utilizado` tinyint(1) NOT NULL DEFAULT '0',
`monto` decimal(10,2) NOT NULL,
`original_date` timestamp NULL DEFAULT NULL,
`confirmed_date` timestamp NULL DEFAULT NULL,
`fecha_pago` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `pagos_codigo_pago_unique` (`codigo_pago`) USING BTREE,
KEY `pagos_postulante_id_foreign` (`postulante_id`) USING BTREE,
CONSTRAINT `pagos_postulante_id_foreign` FOREIGN KEY (`postulante_id`) REFERENCES `postulantes` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.pagos: ~0 rows (aproximadamente)
DELETE FROM `pagos`;
-- Volcando estructura para tabla admision_2026.password_reset_tokens
CREATE TABLE IF NOT EXISTS `password_reset_tokens` (
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.password_reset_tokens: ~0 rows (aproximadamente)
DELETE FROM `password_reset_tokens`;
-- Volcando estructura para tabla admision_2026.permissions
CREATE TABLE IF NOT EXISTS `permissions` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`guard_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `permissions_name_guard_name_unique` (`name`,`guard_name`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.permissions: ~4 rows (aproximadamente)
DELETE FROM `permissions`;
INSERT INTO `permissions` (`id`, `name`, `guard_name`, `created_at`, `updated_at`) VALUES
(1, 'ver-preguntas', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(2, 'crear-preguntas', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(3, 'editar-preguntas', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(4, 'eliminar-preguntas', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(5, 'ver-cursos', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(6, 'crear-cursos', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(7, 'editar-cursos', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(8, 'eliminar-cursos', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26');
-- Volcando estructura para tabla admision_2026.personal_access_tokens
CREATE TABLE IF NOT EXISTS `personal_access_tokens` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`tokenable_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`tokenable_id` bigint unsigned NOT NULL,
`name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`abilities` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`last_used_at` timestamp NULL DEFAULT NULL,
`expires_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `personal_access_tokens_token_unique` (`token`),
KEY `personal_access_tokens_tokenable_type_tokenable_id_index` (`tokenable_type`,`tokenable_id`),
KEY `personal_access_tokens_expires_at_index` (`expires_at`)
) ENGINE=InnoDB AUTO_INCREMENT=75 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.personal_access_tokens: ~3 rows (aproximadamente)
DELETE FROM `personal_access_tokens`;
INSERT INTO `personal_access_tokens` (`id`, `tokenable_type`, `tokenable_id`, `name`, `token`, `abilities`, `last_used_at`, `expires_at`, `created_at`, `updated_at`) VALUES
(46, 'App\\Models\\User', 2, 'api_token', 'dc172c99f9d46ff643b75db1fce280cf28ca2184ccc31576bf170e5abe5c0bbe', '["*"]', '2026-02-13 21:33:51', '2026-02-14 09:33:46', '2026-02-13 21:33:46', '2026-02-13 21:33:51');
-- Volcando estructura para tabla admision_2026.postulantes
CREATE TABLE IF NOT EXISTS `postulantes` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`dni` varchar(20) NOT NULL,
`device_id` varchar(100) DEFAULT NULL,
`last_activity` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `dni` (`dni`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.postulantes: ~0 rows (aproximadamente)
DELETE FROM `postulantes`;
INSERT INTO `postulantes` (`id`, `name`, `email`, `password`, `dni`, `device_id`, `last_activity`, `created_at`, `updated_at`) VALUES
(6, 'Elmer Yujra Condori', 'elmer26@gmail.com', '$2y$12$wqDpRA9Ek6mKjsnBWAOvlOn0yUdWV1eln1MaLmuZptWorTvEWG6t6', '73903851', NULL, NULL, '2026-02-13 18:40:08', '2026-02-17 19:02:44');
-- Volcando estructura para tabla admision_2026.preguntas
CREATE TABLE IF NOT EXISTS `preguntas` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`curso_id` bigint unsigned NOT NULL,
`enunciado` longtext NOT NULL,
`enunciado_adicional` longtext,
`opciones` json DEFAULT NULL,
`respuesta_correcta` longtext,
`explicacion` longtext,
`imagenes_explicacion` json DEFAULT NULL,
`imagenes` json DEFAULT NULL,
`nivel_dificultad` varchar(20) DEFAULT NULL,
`activo` tinyint(1) NOT NULL DEFAULT '1',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_preguntas_curso` (`curso_id`),
KEY `idx_preguntas_activo` (`activo`),
CONSTRAINT `fk_preguntas_curso` FOREIGN KEY (`curso_id`) REFERENCES `cursos` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.preguntas: ~7 rows (aproximadamente)
DELETE FROM `preguntas`;
INSERT INTO `preguntas` (`id`, `curso_id`, `enunciado`, `enunciado_adicional`, `opciones`, `respuesta_correcta`, `explicacion`, `imagenes_explicacion`, `imagenes`, `nivel_dificultad`, `activo`, `created_at`, `updated_at`) VALUES
(7, 4, '$$ 2x + 7 = 19 $$', '$$ 2x + 7 = 19 $$', '["$$ 2x + 7 = 19 $$", "$$ 2x + 7 ="]', '$$ 2x + 7 =', '$$ 2x + 7 = 19 $$', '[]', '[]', 'medio', 1, '2026-02-13 21:40:16', '2026-02-13 21:40:16'),
(8, 4, 'Resolver la siguiente integral:\r\n$$\r\n\\int_0^2 x^3\\,dx = \\left[\\frac{x^4}{4}\\right]_0^2 = \\frac{16}{4} = 4\r\n$$', 'Resolver la siguiente integral:\r\n$$\r\n\\int_0^2 x^3\\,dx = \\left[\\frac{x^4}{4}\\right]_0^2 = \\frac{16}{4} = 4\r\n$$', '["FEWEFWEFWEFW", "FEEFW"]', 'FEEFW', 'FEWEFWFEEFWResolver la siguiente integral:\r\n$$\r\n\\int_0^2 x^3\\,dx = \\left[\\frac{x^4}{4}\\right]_0^2 = \\frac{16}{4} = 4\r\n$$', '[]', '["http://127.0.0.1:8000/storage/preguntas/enunciados/7eiL0SNx7z4EpgfK8PNxe09ocxt0GBR8O7dddPVq.png"]', 'medio', 1, '2026-02-13 21:41:34', '2026-02-16 08:00:54'),
(9, 4, 'FEWEFWEFWEFWEFWEFW', NULL, '["$$ \\\\int_0^2 x^3 \\\\, dx $$", "$$ \\\\int_0^2 x^3 \\\\,$$"]', '$$ \\int_0^2 x^3 \\,$$', 'FEEFWEFW', '[]', '[]', 'medio', 1, '2026-02-13 21:41:55', '2026-02-16 08:02:02'),
(10, 4, 'Resolver la siguiente integral:\r\n$$\r\n\\int_0^2 x^3\\,dx = \\left[\\frac{x^4}{4}\\right]_0^2 = \\frac{16}{4} = 4\r\n$$', 'twtwewteWETTWEtwe', '["twetwe", "wttwe", "Resolver la siguiente integral:\\n$$\\n\\\\int_0^2 x^3\\\\,dx = \\\\left[\\\\frac{x^4}{4}\\\\right]_0^2 = \\\\frac{16}{4} = 4\\n$$"]', 'wttwe', 'twtwtwtWETWTEWTEW', '[]', '["http://127.0.0.1:8000/storage/preguntas/enunciados/y26OCN43bCkYNXbK7mx5i675diFvKkD0alAw0Eqo.png"]', 'medio', 1, '2026-02-13 21:42:11', '2026-02-16 08:01:10'),
(11, 3, 'WTTWWTETWTWEETW', 'TWEETWETWTWE', '["TEWETW", "ETWETWTWE", "TWETW"]', 'TWETW', 'ETWETWETW', '[]', '[]', 'medio', 1, '2026-02-13 21:42:43', '2026-02-13 21:42:43'),
(12, 3, 'RWWRRWERWE', 'FWEFWEWEFFWE', '["FWEEFWEFW", "FEWEFW", "FEWEFWEFW"]', 'FEWEFWEFW', 'FWFWEFWEFEW', '[]', '[]', 'medio', 1, '2026-02-13 21:42:58', '2026-02-13 21:42:58'),
(13, 3, 'EFWEFWEFWEFW', 'FEWFEW', '["EFWEFWEW", "EFWEFWEE", "EFWEFW"]', 'EFWEFW', 'EFWEFW', '[]', '[]', 'medio', 1, '2026-02-13 21:43:21', '2026-02-13 21:43:21');
-- Volcando estructura para tabla admision_2026.preguntas_asignadas
CREATE TABLE IF NOT EXISTS `preguntas_asignadas` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`examen_id` bigint unsigned NOT NULL,
`pregunta_id` bigint unsigned NOT NULL,
`orden` int NOT NULL,
`respuesta_usuario` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT 'Clave elegida (A, B, C, D) o texto si es abierta',
`es_correcta` tinyint(1) NOT NULL DEFAULT '2' COMMENT '1 correcta, 0 incorrecta, 2 blanco',
`estado` enum('pendiente','respondida','anulada') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pendiente',
`puntaje` decimal(5,2) NOT NULL DEFAULT '0.00',
`respondida_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_preg_asig_examen` (`examen_id`) USING BTREE,
KEY `idx_preg_asig_pregunta` (`pregunta_id`) USING BTREE,
KEY `idx_preg_asig_estado` (`estado`) USING BTREE,
CONSTRAINT `fk_preg_asig_examen` FOREIGN KEY (`examen_id`) REFERENCES `examenes` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_preg_asig_pregunta` FOREIGN KEY (`pregunta_id`) REFERENCES `preguntas` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.preguntas_asignadas: ~3 rows (aproximadamente)
DELETE FROM `preguntas_asignadas`;
INSERT INTO `preguntas_asignadas` (`id`, `examen_id`, `pregunta_id`, `orden`, `respuesta_usuario`, `es_correcta`, `estado`, `puntaje`, `respondida_at`, `created_at`, `updated_at`) VALUES
(45, 21, 11, 1, 'TEWETW', 0, 'respondida', 0.00, '2026-02-17 18:42:15', '2026-02-17 18:42:12', '2026-02-17 18:42:25'),
(46, 21, 13, 2, 'EFWEFWEW', 0, 'respondida', 0.00, '2026-02-17 18:42:17', '2026-02-17 18:42:13', '2026-02-17 18:42:25'),
(47, 21, 9, 3, '$$ \\int_0^2 x^3 \\, dx $$', 0, 'respondida', 0.00, '2026-02-17 18:42:19', '2026-02-17 18:42:13', '2026-02-17 18:42:25');
-- Volcando estructura para tabla admision_2026.procesos
CREATE TABLE IF NOT EXISTS `procesos` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`descripcion` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`estado` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'borrador',
`duracion` int NOT NULL COMMENT 'Duración total en minutos',
`intentos_maximos` int DEFAULT '1',
`requiere_pago` tinyint(1) NOT NULL DEFAULT '0',
`precio` decimal(8,2) DEFAULT NULL,
`calificacion_id` bigint unsigned DEFAULT NULL,
`slug` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`tipo_simulacro` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'simulacro | test | practica',
`tipo_proceso` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'admision | preuniversitario | universitario',
`activo` tinyint(1) NOT NULL DEFAULT '1',
`publico` tinyint(1) NOT NULL DEFAULT '0',
`fecha_inicio` datetime DEFAULT NULL,
`fecha_fin` datetime DEFAULT NULL,
`tiempo_por_pregunta` int DEFAULT NULL COMMENT 'Segundos por pregunta',
`cantidad_pregunta` int DEFAULT '10',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `slug` (`slug`),
KEY `idx_examenes_estado` (`estado`),
KEY `idx_examenes_activo` (`activo`),
KEY `idx_examenes_publico` (`publico`),
KEY `idx_examenes_tipo_simulacro` (`tipo_simulacro`),
KEY `idx_examenes_tipo_proceso` (`tipo_proceso`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.procesos: ~1 rows (aproximadamente)
DELETE FROM `procesos`;
INSERT INTO `procesos` (`id`, `nombre`, `descripcion`, `estado`, `duracion`, `intentos_maximos`, `requiere_pago`, `precio`, `calificacion_id`, `slug`, `tipo_simulacro`, `tipo_proceso`, `activo`, `publico`, `fecha_inicio`, `fecha_fin`, `tiempo_por_pregunta`, `cantidad_pregunta`, `created_at`, `updated_at`) VALUES
(2, 'test1', 'prueba de admision', 'borrador', 5, 1, 0, NULL, 1, 'test1-698f5330e6eb2', 'admision', 'test', 1, 1, NULL, NULL, NULL, 10, '2026-02-13 21:37:04', '2026-02-17 13:42:01');
-- Volcando estructura para tabla admision_2026.procesos_admision
CREATE TABLE IF NOT EXISTS `procesos_admision` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`titulo` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`subtitulo` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`descripcion` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`slug` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`tipo_proceso` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`modalidad` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`publicado` tinyint(1) NOT NULL DEFAULT '0',
`fecha_publicacion` datetime DEFAULT NULL,
`fecha_inicio_preinscripcion` datetime DEFAULT NULL,
`fecha_fin_preinscripcion` datetime DEFAULT NULL,
`fecha_inicio_inscripcion` datetime DEFAULT NULL,
`fecha_fin_inscripcion` datetime DEFAULT NULL,
`fecha_examen1` datetime DEFAULT NULL,
`fecha_examen2` datetime DEFAULT NULL,
`fecha_resultados` datetime DEFAULT NULL,
`fecha_inicio_biometrico` datetime DEFAULT NULL,
`fecha_fin_biometrico` datetime DEFAULT NULL,
`imagen_path` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`banner_path` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`brochure_path` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`link_preinscripcion` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`link_inscripcion` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`link_resultados` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`link_reglamento` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`estado` enum('nuevo','publicado','en_proceso','finalizado','cancelado') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'nuevo',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_procesos_slug` (`slug`),
KEY `idx_procesos_publico` (`publicado`,`estado`),
KEY `idx_procesos_fechas` (`fecha_inicio_inscripcion`,`fecha_examen1`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.procesos_admision: ~0 rows (aproximadamente)
DELETE FROM `procesos_admision`;
-- Volcando estructura para tabla admision_2026.proceso_admision_detalles
CREATE TABLE IF NOT EXISTS `proceso_admision_detalles` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`proceso_admision_id` bigint unsigned NOT NULL,
`tipo` enum('requisitos','pagos','vacantes','cronograma') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`titulo_detalle` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`descripcion` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`listas` json DEFAULT NULL,
`meta` json DEFAULT NULL,
`url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`imagen_path` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`imagen_path_2` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_detalles_lookup` (`proceso_admision_id`,`tipo`),
CONSTRAINT `fk_detalles_proceso` FOREIGN KEY (`proceso_admision_id`) REFERENCES `procesos_admision` (`id`) ON DELETE CASCADE,
CONSTRAINT `proceso_admision_detalles_chk_1` CHECK (json_valid(`listas`)),
CONSTRAINT `proceso_admision_detalles_chk_2` CHECK (json_valid(`meta`))
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.proceso_admision_detalles: ~4 rows (aproximadamente)
DELETE FROM `proceso_admision_detalles`;
-- Volcando estructura para tabla admision_2026.proceso_admision_resultado_archivos
CREATE TABLE IF NOT EXISTS `proceso_admision_resultado_archivos` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`proceso_admision_id` bigint unsigned NOT NULL,
`nombre` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`file_path` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`orden` tinyint unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_proceso_orden` (`proceso_admision_id`,`orden`),
CONSTRAINT `proceso_admision_resultado_archivos_proceso_admision_id_foreign` FOREIGN KEY (`proceso_admision_id`) REFERENCES `procesos_admision` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.proceso_admision_resultado_archivos: ~0 rows (aproximadamente)
DELETE FROM `proceso_admision_resultado_archivos`;
-- Volcando estructura para tabla admision_2026.reglas_area_proceso
CREATE TABLE IF NOT EXISTS `reglas_area_proceso` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`area_proceso_id` bigint unsigned NOT NULL,
`curso_id` bigint unsigned NOT NULL,
`cantidad_preguntas` int NOT NULL DEFAULT '0',
`orden` int NOT NULL DEFAULT '1',
`nivel_dificultad` varchar(50) DEFAULT 'medio',
`ponderacion` decimal(5,2) DEFAULT '0.00',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `area_proceso_id` (`area_proceso_id`),
KEY `curso_id` (`curso_id`),
CONSTRAINT `reglas_area_proceso_ibfk_1` FOREIGN KEY (`area_proceso_id`) REFERENCES `area_proceso` (`id`),
CONSTRAINT `reglas_area_proceso_ibfk_2` FOREIGN KEY (`curso_id`) REFERENCES `cursos` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.reglas_area_proceso: ~0 rows (aproximadamente)
DELETE FROM `reglas_area_proceso`;
INSERT INTO `reglas_area_proceso` (`id`, `area_proceso_id`, `curso_id`, `cantidad_preguntas`, `orden`, `nivel_dificultad`, `ponderacion`, `created_at`, `updated_at`) VALUES
(10, 3, 4, 1, 1, 'medio', 5.00, '2026-02-13 21:46:46', '2026-02-13 21:46:46'),
(11, 3, 3, 2, 2, 'medio', 5.00, '2026-02-13 21:47:33', '2026-02-13 21:47:33'),
(14, 4, 3, 2, 1, 'medio', 5.00, '2026-02-13 21:48:33', '2026-02-13 21:48:33'),
(15, 4, 4, 1, 2, 'medio', 5.00, '2026-02-13 21:48:33', '2026-02-13 21:48:33');
-- Volcando estructura para tabla admision_2026.resultados_admision
CREATE TABLE IF NOT EXISTS `resultados_admision` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`dni` varchar(20) NOT NULL,
`paterno` varchar(100) NOT NULL,
`materno` varchar(100) NOT NULL,
`nombres` varchar(150) NOT NULL,
`puntaje` decimal(6,2) DEFAULT '0.00',
`vocacional` decimal(6,2) DEFAULT '0.00',
`apto` enum('SI','NO') DEFAULT 'NO',
`obs` text,
`desprograma` tinyint(1) DEFAULT '0',
`idproceso` bigint unsigned NOT NULL,
`idearea` bigint unsigned NOT NULL,
`litho` varchar(50) DEFAULT NULL,
`numlectura` varchar(50) DEFAULT NULL,
`tipo` varchar(50) DEFAULT NULL,
`calificar` tinyint(1) DEFAULT '1',
`aula` varchar(50) DEFAULT NULL,
`respuestas` json DEFAULT NULL,
`puesto` int DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_dni` (`dni`),
KEY `idx_proceso` (`idproceso`),
KEY `idx_area` (`idearea`),
CONSTRAINT `fk_resultado_area_admision` FOREIGN KEY (`idearea`) REFERENCES `areas_admision` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_resultado_proceso_admision` FOREIGN KEY (`idproceso`) REFERENCES `procesos_admision` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.resultados_admision: ~0 rows (aproximadamente)
DELETE FROM `resultados_admision`;
-- Volcando estructura para tabla admision_2026.resultados_admision_carga
CREATE TABLE IF NOT EXISTS `resultados_admision_carga` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`dni` varchar(20) DEFAULT NULL,
`paterno` varchar(100) DEFAULT NULL,
`materno` varchar(100) DEFAULT NULL,
`nombres` varchar(150) DEFAULT NULL,
`idproceso` bigint unsigned NOT NULL,
`idearea` bigint unsigned NOT NULL,
`apto` char(20) DEFAULT NULL,
`puntaje_total` decimal(8,2) DEFAULT NULL,
`puesto` int DEFAULT NULL,
`correctas_aritmetica` int DEFAULT NULL,
`blancas_aritmetica` int DEFAULT NULL,
`puntaje_aritmetica` decimal(6,2) DEFAULT NULL,
`porcentaje_aritmetica` decimal(5,2) DEFAULT NULL,
`correctas_algebra` int DEFAULT NULL,
`blancas_algebra` int DEFAULT NULL,
`puntaje_algebra` decimal(6,2) DEFAULT NULL,
`porcentaje_algebra` decimal(5,2) DEFAULT NULL,
`correctas_geometria` int DEFAULT NULL,
`blancas_geometria` int DEFAULT NULL,
`puntaje_geometria` decimal(6,2) DEFAULT NULL,
`porcentaje_geometria` decimal(5,2) DEFAULT NULL,
`correctas_trigonometria` int DEFAULT NULL,
`blancas_trigonometria` int DEFAULT NULL,
`puntaje_trigonometria` decimal(6,2) DEFAULT NULL,
`porcentaje_trigonometria` decimal(5,2) DEFAULT NULL,
`correctas_fisica` int DEFAULT NULL,
`blancas_fisica` int DEFAULT NULL,
`puntaje_fisica` decimal(6,2) DEFAULT NULL,
`porcentaje_fisica` decimal(5,2) DEFAULT NULL,
`correctas_quimica` int DEFAULT NULL,
`blancas_quimica` int DEFAULT NULL,
`puntaje_quimica` decimal(6,2) DEFAULT NULL,
`porcentaje_quimica` decimal(5,2) DEFAULT NULL,
`correctas_biologia_anatomia` int DEFAULT NULL,
`blancas_biologia_anatomia` int DEFAULT NULL,
`puntaje_biologia_anatomia` decimal(6,2) DEFAULT NULL,
`porcentaje_biologia_anatomia` decimal(5,2) DEFAULT NULL,
`correctas_psicologia_filosofia` int DEFAULT NULL,
`blancas_psicologia_filosofia` int DEFAULT NULL,
`puntaje_psicologia_filosofia` decimal(6,2) DEFAULT NULL,
`porcentaje_psicologia_filosofia` decimal(5,2) DEFAULT NULL,
`correctas_geografia` int DEFAULT NULL,
`blancas_geografia` int DEFAULT NULL,
`puntaje_geografia` decimal(6,2) DEFAULT NULL,
`porcentaje_geografia` decimal(5,2) DEFAULT NULL,
`correctas_historia` int DEFAULT NULL,
`blancas_historia` int DEFAULT NULL,
`puntaje_historia` decimal(6,2) DEFAULT NULL,
`porcentaje_historia` decimal(5,2) DEFAULT NULL,
`correctas_educacion_civica` int DEFAULT NULL,
`blancas_educacion_civica` int DEFAULT NULL,
`puntaje_educacion_civica` decimal(6,2) DEFAULT NULL,
`porcentaje_educacion_civica` decimal(5,2) DEFAULT NULL,
`correctas_economia` int DEFAULT NULL,
`blancas_economia` int DEFAULT NULL,
`puntaje_economia` decimal(6,2) DEFAULT NULL,
`porcentaje_economia` decimal(5,2) DEFAULT NULL,
`correctas_comunicacion` int DEFAULT NULL,
`blancas_comunicacion` int DEFAULT NULL,
`puntaje_comunicacion` decimal(6,2) DEFAULT NULL,
`porcentaje_comunicacion` decimal(5,2) DEFAULT NULL,
`correctas_literatura` int DEFAULT NULL,
`blancas_literatura` int DEFAULT NULL,
`puntaje_literatura` decimal(6,2) DEFAULT NULL,
`porcentaje_literatura` decimal(5,2) DEFAULT NULL,
`correctas_razonamiento_matematico` int DEFAULT NULL,
`blancas_razonamiento_matematico` int DEFAULT NULL,
`puntaje_razonamiento_matematico` decimal(6,2) DEFAULT NULL,
`porcentaje_razonamiento_matematico` decimal(5,2) DEFAULT NULL,
`correctas_razonamiento_verbal` int DEFAULT NULL,
`blancas_razonamiento_verbal` int DEFAULT NULL,
`puntaje_razonamiento_verbal` decimal(6,2) DEFAULT NULL,
`porcentaje_razonamiento_verbal` decimal(5,2) DEFAULT NULL,
`correctas_ingles` int DEFAULT NULL,
`blancas_ingles` int DEFAULT NULL,
`puntaje_ingles` decimal(6,2) DEFAULT NULL,
`porcentaje_ingles` decimal(5,2) DEFAULT NULL,
`correctas_quechua_aimara` int DEFAULT NULL,
`blancas_quechua_aimara` int DEFAULT NULL,
`puntaje_quechua_aimara` decimal(6,2) DEFAULT NULL,
`porcentaje_quechua_aimara` decimal(5,2) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_dni` (`dni`),
KEY `idx_proceso_area` (`idproceso`,`idearea`),
KEY `fk_carga_area` (`idearea`),
CONSTRAINT `fk_carga_area` FOREIGN KEY (`idearea`) REFERENCES `areas_admision` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_carga_proceso` FOREIGN KEY (`idproceso`) REFERENCES `procesos_admision` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Volcando datos para la tabla admision_2026.resultados_admision_carga: ~0 rows (aproximadamente)
DELETE FROM `resultados_admision_carga`;
-- Volcando estructura para tabla admision_2026.resultados_examenes
CREATE TABLE IF NOT EXISTS `resultados_examenes` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`postulante_id` bigint unsigned NOT NULL,
`examen_id` bigint unsigned NOT NULL,
`total_puntos` decimal(8,3) NOT NULL,
`correctas_por_curso` json NOT NULL,
`incorrectas_por_curso` json DEFAULT NULL,
`preguntas_totales_por_curso` json DEFAULT NULL,
`total_correctas` int NOT NULL,
`total_incorrectas` int NOT NULL,
`total_nulas` int NOT NULL,
`porcentaje_correctas` double(5,2) NOT NULL,
`calificacion_sobre_20` double(5,2) NOT NULL,
`orden_merito` int DEFAULT NULL,
`probabilidad_ingreso` float DEFAULT NULL,
`programa_recomendado` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
KEY `resultados_examenes_postulante_id_foreign` (`postulante_id`) USING BTREE,
KEY `resultados_examenes_examen_id_foreign` (`examen_id`) USING BTREE,
CONSTRAINT `resultados_examenes_examen_id_foreign` FOREIGN KEY (`examen_id`) REFERENCES `examenes` (`id`) ON DELETE CASCADE,
CONSTRAINT `resultados_examenes_postulante_id_foreign` FOREIGN KEY (`postulante_id`) REFERENCES `postulantes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.resultados_examenes: ~0 rows (aproximadamente)
DELETE FROM `resultados_examenes`;
INSERT INTO `resultados_examenes` (`id`, `postulante_id`, `examen_id`, `total_puntos`, `correctas_por_curso`, `incorrectas_por_curso`, `preguntas_totales_por_curso`, `total_correctas`, `total_incorrectas`, `total_nulas`, `porcentaje_correctas`, `calificacion_sobre_20`, `orden_merito`, `probabilidad_ingreso`, `programa_recomendado`, `created_at`, `updated_at`) VALUES
(11, 6, 21, 0.000, '{"Matematica": "0 de 2", "Comunicacion": "0 de 1"}', '{"Matematica": 2, "Comunicacion": 1}', '{"Matematica": 2, "Comunicacion": 1}', 0, 3, 0, 0.00, 0.00, 1, NULL, NULL, '2026-02-17 18:42:25', '2026-02-17 18:42:25');
-- Volcando estructura para tabla admision_2026.roles
CREATE TABLE IF NOT EXISTS `roles` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`guard_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `roles_name_guard_name_unique` (`name`,`guard_name`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.roles: ~0 rows (aproximadamente)
DELETE FROM `roles`;
INSERT INTO `roles` (`id`, `name`, `guard_name`, `created_at`, `updated_at`) VALUES
(4, 'usuario', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(5, 'administrador', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26'),
(6, 'superadmin', 'web', '2026-02-13 21:27:26', '2026-02-13 21:27:26');
-- Volcando estructura para tabla admision_2026.role_has_permissions
CREATE TABLE IF NOT EXISTS `role_has_permissions` (
`permission_id` bigint unsigned NOT NULL,
`role_id` bigint unsigned NOT NULL,
PRIMARY KEY (`permission_id`,`role_id`),
KEY `role_has_permissions_role_id_foreign` (`role_id`),
CONSTRAINT `role_has_permissions_permission_id_foreign` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE,
CONSTRAINT `role_has_permissions_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.role_has_permissions: ~0 rows (aproximadamente)
DELETE FROM `role_has_permissions`;
INSERT INTO `role_has_permissions` (`permission_id`, `role_id`) VALUES
(1, 5),
(2, 5),
(3, 5),
(4, 5),
(5, 5),
(6, 5),
(7, 5),
(8, 5),
(1, 6),
(2, 6),
(3, 6),
(4, 6),
(5, 6),
(6, 6),
(7, 6),
(8, 6);
-- Volcando estructura para tabla admision_2026.sessions
CREATE TABLE IF NOT EXISTS `sessions` (
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`user_id` bigint unsigned DEFAULT NULL,
`ip_address` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`user_agent` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`payload` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`last_activity` int NOT NULL,
PRIMARY KEY (`id`),
KEY `sessions_user_id_index` (`user_id`),
KEY `sessions_last_activity_index` (`last_activity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.sessions: ~0 rows (aproximadamente)
DELETE FROM `sessions`;
-- Volcando estructura para tabla admision_2026.users
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Volcando datos para la tabla admision_2026.users: ~1 rows (aproximadamente)
DELETE FROM `users`;
INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(5, 'Elmer Admin', 'elmer20@gmail.com', NULL, '$2y$12$dFWOcwAPv3v3oQzeO/JJbOyP7IgfI6uMSk3XIpWYTOSNxMf9WhqFm', NULL, '2026-02-13 21:36:09', '2026-02-13 21:36:09');
/*!40103 SET TIME_ZONE=IFNULL(@OLD_TIME_ZONE, 'system') */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;

@ -1,12 +0,0 @@
vendor
node_modules
.env
.env.backup
.env.production
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
tests
.git
.phpunit.cache

@ -1,18 +0,0 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[compose.yaml]
indent_size = 4

@ -1,65 +0,0 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:wEHrK9znRe1M/jdkBIM7b+TihyUtHygp8hKeqE57eB4=
APP_DEBUG=true
APP_URL=http://localhost:8000
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=admision_2026
DB_USERNAME=root
DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

@ -1,11 +0,0 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

24
back/.gitignore vendored

@ -1,24 +0,0 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

@ -1,84 +0,0 @@
# Stage 1: Composer dependencies
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install \
--no-dev \
--no-interaction \
--no-scripts \
--prefer-dist \
--optimize-autoloader \
--ignore-platform-reqs
# Stage 2: PHP-FPM production image
FROM php:8.4-fpm-alpine
# Install system dependencies
RUN apk add --no-cache \
libpng-dev \
libjpeg-turbo-dev \
freetype-dev \
libzip-dev \
libxml2-dev \
curl-dev \
oniguruma-dev \
icu-dev
# Install PHP extensions
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install \
pdo_mysql \
bcmath \
mbstring \
gd \
curl \
zip \
xml \
intl \
opcache
# Configure OPcache for production
RUN echo "opcache.enable=1" >> /usr/local/etc/php/conf.d/opcache.ini \
&& echo "opcache.memory_consumption=128" >> /usr/local/etc/php/conf.d/opcache.ini \
&& echo "opcache.interned_strings_buffer=8" >> /usr/local/etc/php/conf.d/opcache.ini \
&& echo "opcache.max_accelerated_files=10000" >> /usr/local/etc/php/conf.d/opcache.ini \
&& echo "opcache.validate_timestamps=0" >> /usr/local/etc/php/conf.d/opcache.ini
# PHP production settings
RUN echo "upload_max_filesize=20M" >> /usr/local/etc/php/conf.d/uploads.ini \
&& echo "post_max_size=25M" >> /usr/local/etc/php/conf.d/uploads.ini \
&& echo "memory_limit=128M" >> /usr/local/etc/php/conf.d/uploads.ini \
&& echo "max_execution_time=60" >> /usr/local/etc/php/conf.d/uploads.ini
# PHP-FPM pool settings para 100 usuarios concurrentes
RUN sed -i 's/pm.max_children = 5/pm.max_children = 15/' /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's/pm.start_servers = 2/pm.start_servers = 5/' /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's/pm.min_spare_servers = 1/pm.min_spare_servers = 3/' /usr/local/etc/php-fpm.d/www.conf \
&& sed -i 's/pm.max_spare_servers = 3/pm.max_spare_servers = 10/' /usr/local/etc/php-fpm.d/www.conf
WORKDIR /var/www/html
# Copy application code
COPY . .
# Copy vendor from composer stage
COPY --from=vendor /app/vendor ./vendor
# Set permissions
RUN chown -R www-data:www-data storage bootstrap/cache \
&& chmod -R 775 storage bootstrap/cache
# View cache (no depende de .env, se puede hacer en build)
RUN php artisan view:cache
# Entrypoint: cachear config y rutas con las variables reales de .env.prod
RUN printf '#!/bin/sh\nphp artisan config:cache\nphp artisan route:cache\nexec "$@"\n' > /usr/local/bin/entrypoint.sh \
&& chmod +x /usr/local/bin/entrypoint.sh
EXPOSE 9000
ENTRYPOINT ["entrypoint.sh"]
CMD ["php-fpm"]

@ -1,59 +0,0 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

@ -1,28 +0,0 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Auth\AuthenticationException; // <- importante importarlo
class Handler extends ExceptionHandler
{
// ... otras propiedades y métodos
/**
* Convert an authentication exception into a response.
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
// Si la petición espera JSON (API)
if ($request->expectsJson()) {
return response()->json(['error' => 'No autenticado.'], 401);
}
// Para web (redirección normal)
return redirect()->guest(route('login'));
}
// ... otros métodos
}

@ -1,472 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Models\Curso;
use App\Models\Proceso;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class AreaController extends Controller
{
public function index(Request $request)
{
$query = Area::withCount(['cursos', 'procesos']);
if ($request->filled('search')) {
$search = $request->search;
$query->where(function ($q) use ($search) {
$q->where('nombre', 'like', "%{$search}%")
->orWhere('codigo', 'like', "%{$search}%");
});
}
if (!is_null($request->activo)) {
$query->where('activo', $request->activo);
}
$areas = $query
->orderBy('created_at', 'desc')
->paginate($request->get('per_page', 10));
return response()->json([
'success' => true,
'data' => $areas
]);
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'nombre' => 'required|string|min:3|max:100',
'codigo' => 'required|string|min:2|max:20|regex:/^[A-Z0-9]+$/|unique:areas,codigo',
'descripcion' => 'nullable|string|max:500',
'activo' => 'boolean',
], [
'codigo.regex' => 'El código solo puede contener letras mayúsculas y números'
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$area = Area::create([
'nombre' => $request->nombre,
'codigo' => strtoupper($request->codigo),
'descripcion' => $request->descripcion,
'activo' => $request->activo ?? true,
]);
return response()->json([
'success' => true,
'message' => 'Área creada correctamente',
'data' => $area
], 201);
}
public function show($id)
{
$area = Area::with(['cursos', 'examenes'])->find($id);
if (!$area) {
return response()->json([
'success' => false,
'message' => 'Área no encontrada'
], 404);
}
return response()->json([
'success' => true,
'data' => $area
]);
}
public function update(Request $request, $id)
{
$area = Area::find($id);
if (!$area) {
return response()->json([
'success' => false,
'message' => 'Área no encontrada'
], 404);
}
$validator = Validator::make($request->all(), [
'nombre' => 'required|string|min:3|max:100',
'codigo' => 'required|string|min:2|max:20|regex:/^[A-Z0-9]+$/|unique:areas,codigo,' . $id,
'descripcion' => 'nullable|string|max:500',
'activo' => 'boolean',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$area->update([
'nombre' => $request->nombre,
'codigo' => strtoupper($request->codigo),
'descripcion' => $request->descripcion,
'activo' => $request->activo ?? $area->activo,
]);
return response()->json([
'success' => true,
'message' => 'Área actualizada correctamente',
'data' => $area
]);
}
public function toggleEstado($id)
{
$area = Area::find($id);
if (!$area) {
return response()->json([
'success' => false,
'message' => 'Área no encontrada'
], 404);
}
$area->activo = !$area->activo;
$area->save();
return response()->json([
'success' => true,
'message' => $area->activo ? 'Área activada' : 'Área desactivada',
'data' => $area
]);
}
public function destroy($id)
{
$area = Area::with(['cursos', 'examenes'])->find($id);
if (!$area) {
return response()->json([
'success' => false,
'message' => 'Área no encontrada'
], 404);
}
if ($area->cursos()->count() > 0 || $area->examenes()->count() > 0) {
return response()->json([
'success' => false,
'message' => 'No se puede eliminar un área con cursos o exámenes asociados'
], 409);
}
$area->delete();
return response()->json([
'success' => true,
'message' => 'Área eliminada correctamente'
]);
}
public function vincularCursosArea(Request $request, $areaId)
{
try {
$user = auth()->user();
if (!$user->hasRole('administrador')) {
return response()->json(['success' => false, 'message' => 'No autorizado'], 403);
}
$area = Area::find($areaId);
if (!$area) {
return response()->json(['success' => false, 'message' => 'Área no encontrada'], 404);
}
$validator = Validator::make($request->all(), [
'cursos' => 'required|array',
'cursos.*' => 'required|integer|exists:cursos,id'
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
$area->cursos()->sync($request->cursos);
$area->load('cursos:id,nombre,codigo');
return response()->json([
'success' => true,
'message' => 'Cursos vinculados a la área exitosamente',
'data' => $area
]);
} catch (\Exception $e) {
Log::error('Error vinculando cursos a área', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'area_id' => $areaId,
'request_data' => $request->all()
]);
return response()->json(['success' => false, 'message' => 'Error al vincular cursos: ' . $e->getMessage()], 500);
}
}
public function getCursosPorArea(Request $request, $areaId)
{
try {
$user = auth()->user();
if (!$user->hasRole('administrador')) {
return response()->json(['success' => false, 'message' => 'No autorizado'], 403);
}
$area = Area::find($areaId);
if (!$area) {
return response()->json(['success' => false, 'message' => 'Área no encontrada'], 404);
}
$todosLosCursos = Curso::select('id', 'nombre', 'codigo')
->orderBy('nombre')
->get();
$cursosVinculadosIds = $area->cursos->pluck('id')->toArray();
return response()->json([
'success' => true,
'data' => [
'todos_los_cursos' => $todosLosCursos,
'cursos_vinculados' => $cursosVinculadosIds
]
]);
} catch (\Exception $e) {
Log::error('Error obteniendo cursos por área', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'area_id' => $areaId
]);
return response()->json(['success' => false, 'message' => 'Error al cargar cursos: ' . $e->getMessage()], 500);
}
}
public function desvincularCursoArea(Request $request, $areaId)
{
try {
$user = auth()->user();
if (!$user->hasRole('administrador')) {
return response()->json(['success' => false, 'message' => 'No autorizado'], 403);
}
$area = Area::find($areaId);
if (!$area) {
return response()->json(['success' => false, 'message' => 'Área no encontrada'], 404);
}
$validator = Validator::make($request->all(), [
'curso_id' => 'required|exists:cursos,id'
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
$area->cursos()->detach($request->curso_id);
return response()->json([
'success' => true,
'message' => 'Curso desvinculado de la área exitosamente'
]);
} catch (\Exception $e) {
Log::error('Error desvinculando curso de área', [
'error' => $e->getMessage()
]);
return response()->json(['success' => false, 'message' => 'Error al desvincular curso de la área'], 500);
}
}
public function vincularProcesosArea(Request $request, $areaId)
{
try {
$user = auth()->user();
if (!$user->hasRole('administrador')) {
return response()->json([
'success' => false,
'message' => 'No autorizado'
], 403);
}
$area = Area::find($areaId);
if (!$area) {
return response()->json([
'success' => false,
'message' => 'Área no encontrada'
], 404);
}
$validator = Validator::make($request->all(), [
'procesos' => 'required|array',
'procesos.*' => 'required|integer|exists:procesos,id',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$area->procesos()->sync($request->procesos);
$area->load('procesos:id,nombre,tipo_proceso');
return response()->json([
'success' => true,
'message' => 'Procesos vinculados a la área exitosamente',
'data' => $area
]);
} catch (\Exception $e) {
Log::error('Error vinculando procesos a área', [
'error' => $e->getMessage(),
'area_id' => $areaId,
'request' => $request->all(),
]);
return response()->json([
'success' => false,
'message' => 'Error al vincular procesos'
], 500);
}
}
public function getProcesosPorArea(Request $request, $areaId)
{
try {
$user = auth()->user();
if (!$user->hasRole('administrador')) {
return response()->json([
'success' => false,
'message' => 'No autorizado'
], 403);
}
$area = Area::find($areaId);
if (!$area) {
return response()->json([
'success' => false,
'message' => 'Área no encontrada'
], 404);
}
$todosLosProcesos = Proceso::select(
'id',
'nombre',
'tipo_proceso',
'activo'
)
->orderBy('nombre')
->get();
$procesosVinculadosIds = $area
->procesos
->pluck('id')
->toArray();
return response()->json([
'success' => true,
'data' => [
'todos_los_procesos' => $todosLosProcesos,
'procesos_vinculados' => $procesosVinculadosIds
]
]);
} catch (\Exception $e) {
Log::error('Error obteniendo procesos por área', [
'error' => $e->getMessage(),
'area_id'=> $areaId
]);
return response()->json([
'success' => false,
'message' => 'Error al cargar procesos'
], 500);
}
}
public function desvincularProcesoArea(Request $request, $areaId)
{
try {
$user = auth()->user();
if (!$user->hasRole('administrador')) {
return response()->json([
'success' => false,
'message' => 'No autorizado'
], 403);
}
$area = Area::find($areaId);
if (!$area) {
return response()->json([
'success' => false,
'message' => 'Área no encontrada'
], 404);
}
$validator = Validator::make($request->all(), [
'proceso_id' => 'required|exists:procesos,id'
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$area->procesos()->detach($request->proceso_id);
return response()->json([
'success' => true,
'message' => 'Proceso desvinculado de la área exitosamente'
]);
} catch (\Exception $e) {
Log::error('Error desvinculando proceso de área', [
'error' => $e->getMessage()
]);
return response()->json([
'success' => false,
'message' => 'Error al desvincular proceso'
], 500);
}
}
}

@ -1,109 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\Calificacion;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class CalificacionController extends Controller
{
// ✅ Listar todas
public function index()
{
$calificaciones = Calificacion::all();
return response()->json([
'success' => true,
'data' => $calificaciones
]);
}
// ✅ Guardar nueva
public function store(Request $request)
{
$request->validate([
'nombre' => 'required|string|max:255',
'puntos_correcta' => 'required|numeric',
'puntos_incorrecta' => 'required|numeric',
'puntos_nula' => 'required|numeric',
'puntaje_maximo' => 'required|numeric',
]);
$calificacion = Calificacion::create($request->all());
return response()->json([
'success' => true,
'message' => 'Calificación creada correctamente',
'data' => $calificacion
]);
}
// ✅ Mostrar una
public function show($id)
{
$calificacion = Calificacion::find($id);
if (!$calificacion) {
return response()->json([
'success' => false,
'message' => 'No encontrada'
], 404);
}
return response()->json([
'success' => true,
'data' => $calificacion
]);
}
// ✅ Actualizar
public function update(Request $request, $id)
{
$calificacion = Calificacion::find($id);
if (!$calificacion) {
return response()->json([
'success' => false,
'message' => 'No encontrada'
], 404);
}
$request->validate([
'nombre' => 'required|string|max:255',
'puntos_correcta' => 'required|numeric',
'puntos_incorrecta' => 'required|numeric',
'puntos_nula' => 'required|numeric',
'puntaje_maximo' => 'required|numeric',
]);
$calificacion->update($request->all());
return response()->json([
'success' => true,
'message' => 'Calificación actualizada correctamente',
'data' => $calificacion
]);
}
// ✅ Eliminar
public function destroy($id)
{
$calificacion = Calificacion::find($id);
if (!$calificacion) {
return response()->json([
'success' => false,
'message' => 'No encontrada'
], 404);
}
$calificacion->delete();
return response()->json([
'success' => true,
'message' => 'Calificación eliminada correctamente'
]);
}
}

@ -1,156 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\Comunicado;
use App\Models\ComunicadoImagen;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
class ComunicadoController extends Controller
{
// Admin: lista paginada
public function index(Request $request)
{
$comunicados = Comunicado::with('imagenes')
->orderByDesc('created_at')
->paginate(10);
return response()->json($comunicados);
}
// Admin: crear comunicado
public function store(Request $request)
{
$request->validate([
'titulo' => 'required|string|max:255',
'fecha_inicio' => 'nullable|date',
'fecha_fin' => 'nullable|date|after_or_equal:fecha_inicio',
'url_accion' => 'nullable|url|max:500',
'texto_boton' => 'nullable|string|max:60',
'imagenes' => 'required|array|min:1',
'imagenes.*' => 'required|file|mimes:jpg,jpeg,png,webp|max:5120',
]);
$comunicado = Comunicado::create([
'titulo' => $request->titulo,
'activo' => false,
'fecha_inicio' => $request->fecha_inicio,
'fecha_fin' => $request->fecha_fin,
'url_accion' => $request->url_accion,
'texto_boton' => $request->texto_boton,
]);
foreach ($request->file('imagenes') as $orden => $imagen) {
$filename = uniqid() . '.' . $imagen->getClientOriginalExtension();
$path = "comunicados/{$comunicado->id}/{$filename}";
Storage::disk('public')->put($path, file_get_contents($imagen->getRealPath()));
ComunicadoImagen::create([
'comunicado_id' => $comunicado->id,
'imagen_path' => $path,
'orden' => $orden + 1,
]);
}
return response()->json($comunicado->load('imagenes'), 201);
}
// Admin: actualizar comunicado
public function update(Request $request, int $id)
{
$comunicado = Comunicado::findOrFail($id);
$request->validate([
'titulo' => 'sometimes|required|string|max:255',
'fecha_inicio' => 'nullable|date',
'fecha_fin' => 'nullable|date|after_or_equal:fecha_inicio',
'url_accion' => 'nullable|url|max:500',
'texto_boton' => 'nullable|string|max:60',
'imagenes' => 'sometimes|array|min:1',
'imagenes.*' => 'file|mimes:jpg,jpeg,png,webp|max:5120',
]);
$comunicado->update($request->only('titulo', 'fecha_inicio', 'fecha_fin', 'url_accion', 'texto_boton'));
// Si se enviaron nuevas imágenes, AGREGAR a las existentes (no reemplazar)
if ($request->hasFile('imagenes')) {
$maxOrden = $comunicado->imagenes()->max('orden') ?? 0;
foreach ($request->file('imagenes') as $idx => $imagen) {
$filename = uniqid() . '.' . $imagen->getClientOriginalExtension();
$path = "comunicados/{$comunicado->id}/{$filename}";
Storage::disk('public')->put($path, file_get_contents($imagen->getRealPath()));
ComunicadoImagen::create([
'comunicado_id' => $comunicado->id,
'imagen_path' => $path,
'orden' => $maxOrden + $idx + 1,
]);
}
}
return response()->json($comunicado->load('imagenes'));
}
// Admin: eliminar comunicado
public function destroy(int $id)
{
$comunicado = Comunicado::with('imagenes')->findOrFail($id);
foreach ($comunicado->imagenes as $img) {
Storage::disk('public')->delete($img->imagen_path);
}
$comunicado->delete();
return response()->json(['message' => 'Comunicado eliminado correctamente.']);
}
// Admin: activar/desactivar (uno activo a la vez)
public function toggleActivo(int $id)
{
$comunicado = Comunicado::findOrFail($id);
if ($comunicado->activo) {
// Si ya estaba activo, simplemente lo desactiva
$comunicado->update(['activo' => false]);
} else {
// Desactiva todos los demás y activa este
Comunicado::where('activo', true)->update(['activo' => false]);
$comunicado->update(['activo' => true]);
}
return response()->json($comunicado->load('imagenes'));
}
// Admin: eliminar una imagen individual
public function destroyImagen(int $imagenId)
{
$imagen = ComunicadoImagen::findOrFail($imagenId);
Storage::disk('public')->delete($imagen->imagen_path);
$imagen->delete();
return response()->json(['message' => 'Imagen eliminada correctamente.']);
}
// Público: devuelve el comunicado activo con sus imágenes (respeta vigencia)
public function activo()
{
$hoy = Carbon::today();
$comunicado = Comunicado::with('imagenes')
->where('activo', true)
->where(function ($q) use ($hoy) {
$q->whereNull('fecha_inicio')->orWhere('fecha_inicio', '<=', $hoy);
})
->where(function ($q) use ($hoy) {
$q->whereNull('fecha_fin')->orWhere('fecha_fin', '>=', $hoy);
})
->first();
return response()->json($comunicado);
}
}

@ -1,174 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\Curso;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class CursoController extends Controller
{
public function index(Request $request)
{
$query = Curso::query();
if ($request->filled('search')) {
$search = $request->search;
$query->where(function ($q) use ($search) {
$q->where('nombre', 'like', "%{$search}%")
->orWhere('codigo', 'like', "%{$search}%");
});
}
if ($request->filled('activo')) {
$query->where('activo', $request->activo);
}
$cursos = $query
->orderBy('created_at', 'desc')
->paginate($request->get('per_page', 10));
return response()->json([
'success' => true,
'data' => $cursos
]);
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'nombre' => 'required|string|min:3|max:100',
'codigo' => 'required|string|min:2|max:20|regex:/^[A-Z0-9]+$/|unique:cursos,codigo',
'activo' => 'boolean',
], [
'codigo.regex' => 'El código solo puede contener letras mayúsculas y números'
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$curso = Curso::create([
'nombre' => $request->nombre,
'codigo' => strtoupper($request->codigo),
'activo' => $request->activo ?? true,
]);
return response()->json([
'success' => true,
'message' => 'Curso creado correctamente',
'data' => $curso
], 201);
}
public function show($id)
{
$curso = Curso::with('areas')->find($id);
if (!$curso) {
return response()->json([
'success' => false,
'message' => 'Curso no encontrado'
], 404);
}
return response()->json([
'success' => true,
'data' => $curso
]);
}
public function update(Request $request, $id)
{
$curso = Curso::find($id);
if (!$curso) {
return response()->json([
'success' => false,
'message' => 'Curso no encontrado'
], 404);
}
$validator = Validator::make($request->all(), [
'nombre' => 'required|string|min:3|max:100',
'codigo' => 'required|string|min:2|max:20|regex:/^[A-Z0-9]+$/|unique:cursos,codigo,' . $id,
'activo' => 'boolean',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$curso->update([
'nombre' => $request->nombre,
'codigo' => strtoupper($request->codigo),
'activo' => $request->activo ?? $curso->activo,
]);
return response()->json([
'success' => true,
'message' => 'Curso actualizado correctamente',
'data' => $curso
]);
}
public function toggleEstado($id)
{
$curso = Curso::find($id);
if (!$curso) {
return response()->json([
'success' => false,
'message' => 'Curso no encontrado'
], 404);
}
$curso->activo = !$curso->activo;
$curso->save();
return response()->json([
'success' => true,
'message' => $curso->activo ? 'Curso activado' : 'Curso desactivado',
'data' => $curso
]);
}
public function destroy($id)
{
$curso = Curso::with(['areas', 'preguntas'])->find($id);
if (!$curso) {
return response()->json([
'success' => false,
'message' => 'Curso no encontrado'
], 404);
}
if ($curso->areas()->count() > 0 || $curso->preguntas()->count() > 0) {
return response()->json([
'success' => false,
'message' => 'No se puede eliminar un curso con áreas o preguntas asociadas'
], 409);
}
$curso->delete();
return response()->json([
'success' => true,
'message' => 'Curso eliminado correctamente'
]);
}
}

@ -1,209 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\Noticia;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class NoticiaController extends Controller
{
// GET /api/noticias
public function index(Request $request)
{
$perPage = (int) $request->get('per_page', 9);
$query = Noticia::query();
if ($request->filled('publicado')) {
$query->where('publicado', $request->boolean('publicado'));
}
if ($request->filled('categoria')) {
$query->where('categoria', (string) $request->get('categoria'));
}
if ($request->filled('q')) {
$q = trim((string) $request->get('q'));
$query->where(function ($sub) use ($q) {
$sub->where('titulo', 'like', "%{$q}%")
->orWhere('descripcion_corta', 'like', "%{$q}%");
});
}
$data = $query
->orderByDesc('destacado')
->orderByDesc('fecha_publicacion')
->orderByDesc('orden')
->orderByDesc('id')
->paginate($perPage);
return response()->json([
'success' => true,
'data' => $data->items(), // incluye imagen_url por el accessor/appends
'meta' => [
'current_page' => $data->currentPage(),
'last_page' => $data->lastPage(),
'per_page' => $data->perPage(),
'total' => $data->total(),
],
]);
}
// GET /api/noticias/{noticia}
public function show(Noticia $noticia)
{
return response()->json([
'success' => true,
'data' => $noticia, // incluye imagen_url por el accessor/appends
]);
}
// GET /api/noticias-publicas/{noticia} (o la ruta que uses)
public function showPublic(Noticia $noticia)
{
abort_unless($noticia->publicado, 404);
return response()->json([
'success' => true,
'data' => $noticia,
]);
}
// POST /api/noticias (multipart/form-data si viene imagen)
public function store(Request $request)
{
$data = $request->validate([
'titulo' => ['required', 'string', 'max:220'],
'slug' => ['nullable', 'string', 'max:260', 'unique:noticias,slug'],
'descripcion_corta' => ['nullable', 'string', 'max:500'],
'contenido' => ['nullable', 'string'],
'categoria' => ['nullable', 'string', 'max:80'],
'tag_color' => ['nullable', 'string', 'max:30'],
// ✅ dos formas de imagen
'imagen' => ['nullable', 'file', 'mimes:jpg,jpeg,png,webp', 'max:4096'],
'imagen_url' => ['nullable', 'url', 'max:600'],
'link_url' => ['nullable', 'url', 'max:600'],
'link_texto' => ['nullable', 'string', 'max:120'],
'fecha_publicacion' => ['nullable', 'date'],
'publicado' => ['nullable', 'boolean'],
'destacado' => ['nullable', 'boolean'],
'orden' => ['nullable', 'integer'],
]);
// slug por defecto (igual tu modelo lo genera, pero aquí lo dejamos por consistencia)
if (empty($data['slug'])) {
$data['slug'] = Str::slug($data['titulo']);
}
// si viene archivo, manda a storage y prioriza archivo
if ($request->hasFile('imagen')) {
$path = $request->file('imagen')->store('noticias', 'public');
$data['imagen_path'] = $path;
$data['imagen_url'] = null; // ✅ evita conflicto con url externa
} else {
// si viene imagen_url externa, no debe haber imagen_path
$data['imagen_path'] = null;
}
// si publican sin fecha, poner ahora
if (!empty($data['publicado']) && empty($data['fecha_publicacion'])) {
$data['fecha_publicacion'] = now();
}
$noticia = Noticia::create($data);
return response()->json([
'success' => true,
'data' => $noticia->fresh(),
], 201);
}
// PUT/PATCH /api/noticias/{noticia}
public function update(Request $request, Noticia $noticia)
{
$data = $request->validate([
'titulo' => ['sometimes', 'required', 'string', 'max:220'],
'slug' => ['sometimes', 'nullable', 'string', 'max:260', 'unique:noticias,slug,' . $noticia->id],
'descripcion_corta' => ['sometimes', 'nullable', 'string', 'max:500'],
'contenido' => ['sometimes', 'nullable', 'string'],
'categoria' => ['sometimes', 'nullable', 'string', 'max:80'],
'tag_color' => ['sometimes', 'nullable', 'string', 'max:30'],
// ✅ dos formas de imagen
'imagen' => ['sometimes', 'nullable', 'file', 'mimes:jpg,jpeg,png,webp', 'max:4096'],
'imagen_url' => ['sometimes', 'nullable', 'url', 'max:600'],
'link_url' => ['sometimes', 'nullable', 'url', 'max:600'],
'link_texto' => ['sometimes', 'nullable', 'string', 'max:120'],
'fecha_publicacion' => ['sometimes', 'nullable', 'date'],
'publicado' => ['sometimes', 'boolean'],
'destacado' => ['sometimes', 'boolean'],
'orden' => ['sometimes', 'integer'],
]);
// Si llega imagen archivo, reemplaza la anterior y limpia imagen_url externa
if ($request->hasFile('imagen')) {
if ($noticia->imagen_path && Storage::disk('public')->exists($noticia->imagen_path)) {
Storage::disk('public')->delete($noticia->imagen_path);
}
$path = $request->file('imagen')->store('noticias', 'public');
$data['imagen_path'] = $path;
$data['imagen_url'] = null; // ✅ prioridad archivo
}
// Si llega imagen_url (externa), borra la imagen física anterior y limpia imagen_path
if (array_key_exists('imagen_url', $data) && !empty($data['imagen_url'])) {
if ($noticia->imagen_path && Storage::disk('public')->exists($noticia->imagen_path)) {
Storage::disk('public')->delete($noticia->imagen_path);
}
$data['imagen_path'] = null;
}
// Si explícitamente mandan imagen_url = null (quitar url) y no mandan archivo,
// no tocamos imagen_path (se queda como está). Si quieres que también limpie path,
// dime y lo cambiamos.
// si se marca publicado y no hay fecha, set now
if (
array_key_exists('publicado', $data) &&
$data['publicado'] &&
empty($noticia->fecha_publicacion) &&
empty($data['fecha_publicacion'])
) {
$data['fecha_publicacion'] = now();
}
// si cambian titulo y slug no vino, regenerar slug (opcional)
if (array_key_exists('titulo', $data) && !array_key_exists('slug', $data)) {
$data['slug'] = Str::slug($data['titulo']);
}
$noticia->update($data);
return response()->json([
'success' => true,
'data' => $noticia->fresh(),
]);
}
// DELETE /api/noticias/{noticia}
public function destroy(Noticia $noticia)
{
if ($noticia->imagen_path && Storage::disk('public')->exists($noticia->imagen_path)) {
Storage::disk('public')->delete($noticia->imagen_path);
}
$noticia->delete();
return response()->json([
'success' => true,
'message' => 'Noticia eliminada correctamente',
]);
}
}

@ -1,64 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\Postulante;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostulanteController extends Controller
{
public function obtenerPostulantes(Request $request)
{
$query = Postulante::query();
if ($request->buscar) {
$query->where(function ($q) use ($request) {
$q->where('name', 'like', "%{$request->buscar}%")
->orWhere('email', 'like', "%{$request->buscar}%")
->orWhere('dni', 'like', "%{$request->buscar}%");
});
}
$postulantes = $query->orderBy('id', 'desc')
->paginate(20);
return response()->json([
'success' => true,
'data' => $postulantes
]);
}
public function actualizarPostulante(Request $request, $id)
{
$postulante = Postulante::findOrFail($id);
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:postulantes,email,' . $postulante->id,
'dni' => 'required|string|max:20|unique:postulantes,dni,' . $postulante->id,
'password' => 'nullable|string|min:6'
]);
$postulante->update([
'name' => $request->name,
'email' => $request->email,
'dni' => $request->dni,
]);
// 🔹 Solo si envían nueva contraseña
if ($request->filled('password')) {
$postulante->password = $request->password;
$postulante->save();
}
return response()->json([
'success' => true,
'message' => 'Postulante actualizado correctamente',
'data' => $postulante
]);
}
}

@ -1,287 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\Pregunta;
use App\Models\Curso;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class PreguntaController extends Controller
{
public function getPreguntasCurso($cursoId, Request $request)
{
try {
$query = Pregunta::where('curso_id', $cursoId);
if ($request->filled('nivel_dificultad')) {
$query->where('nivel_dificultad', $request->nivel_dificultad);
}
if ($request->filled('search')) {
$query->where('enunciado', 'like', '%' . $request->search . '%');
}
if ($request->filled('activo') && $request->activo !== '') {
$query->where('activo', $request->activo === 'true');
}
$preguntas = $query
->orderBy('created_at', 'desc')
->paginate($request->get('per_page', 15));
$estadisticas = [
'total' => Pregunta::where('curso_id', $cursoId)->count(),
'facil' => Pregunta::where('curso_id', $cursoId)->where('nivel_dificultad', 'facil')->count(),
'medio' => Pregunta::where('curso_id', $cursoId)->where('nivel_dificultad', 'medio')->count(),
'dificil' => Pregunta::where('curso_id', $cursoId)->where('nivel_dificultad', 'dificil')->count(),
];
return response()->json([
'success' => true,
'data' => [
'preguntas' => $preguntas,
'estadisticas' => $estadisticas
]
]);
} catch (\Exception $e) {
Log::error('Error obteniendo preguntas', ['error' => $e->getMessage()]);
return response()->json([
'success' => false,
'message' => 'Error al cargar preguntas'
], 500);
}
}
public function getPregunta($id)
{
$pregunta = Pregunta::find($id);
if (!$pregunta) {
return response()->json([
'success' => false,
'message' => 'Pregunta no encontrada'
], 404);
}
$pregunta->imagenes = collect($pregunta->imagenes ?? [])->map(fn($path) => $path ? url(Storage::url($path)) : null);
$pregunta->imagenes_explicacion = collect($pregunta->imagenes_explicacion ?? [])->map(fn($path) => $path ? url(Storage::url($path)) : null);
return response()->json([
'success' => true,
'data' => $pregunta
]);
}
public function agregarPreguntaCurso(Request $request)
{
try {
$user = auth()->user();
if (!$user->hasRole('administrador')) {
return response()->json(['success' => false, 'message' => 'No autorizado'], 403);
}
$validator = Validator::make($request->all(), [
'curso_id' => 'required|exists:cursos,id',
'enunciado' => 'required|string',
'enunciado_adicional' => 'nullable|string',
'opciones' => 'required',
'respuesta_correcta' => 'required|string',
'explicacion' => 'nullable|string',
'nivel_dificultad' => 'required|in:facil,medio,dificil',
'activo' => 'boolean',
'imagenes' => 'nullable|array',
'imagenes.*' => 'image|mimes:jpg,jpeg,png,gif,webp|max:2048',
'imagenes_explicacion' => 'nullable|array',
'imagenes_explicacion.*' => 'image|mimes:jpg,jpeg,png,gif,webp|max:2048',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
$opciones = is_string($request->opciones) ? json_decode($request->opciones, true) : $request->opciones;
$opcionesValidas = array_map('trim', $opciones);
if (!in_array($request->respuesta_correcta, $opcionesValidas)) {
return response()->json(['success' => false, 'errors' => ['respuesta_correcta' => ['La respuesta correcta debe estar entre las opciones']]] ,422);
}
$imagenesUrls = [];
if ($request->hasFile('imagenes')) {
foreach ($request->file('imagenes') as $imagen) {
$path = $imagen->store('preguntas/enunciados', 'public');
$imagenesUrls[] = url(Storage::url($path));
}
}
// Procesar imágenes de la explicación
$imagenesExplicacionUrls = [];
if ($request->hasFile('imagenes_explicacion')) {
foreach ($request->file('imagenes_explicacion') as $imagen) {
$path = $imagen->store('preguntas/explicaciones', 'public');
$imagenesExplicacionUrls[] = url(Storage::url($path));
}
}
$pregunta = Pregunta::create([
'curso_id' => $request->curso_id,
'enunciado' => $request->enunciado,
'enunciado_adicional' => $request->enunciado_adicional,
'opciones' => $opcionesValidas,
'respuesta_correcta' => $request->respuesta_correcta,
'explicacion' => $request->explicacion,
'nivel_dificultad' => $request->nivel_dificultad,
'activo' => $request->boolean('activo'),
'imagenes' => $imagenesUrls,
'imagenes_explicacion' => $imagenesExplicacionUrls,
]);
return response()->json(['success' => true, 'message' => 'Pregunta creada correctamente', 'data' => $pregunta], 201);
} catch (\Exception $e) {
Log::error('Error creando pregunta', ['error' => $e->getMessage()]);
return response()->json(['success' => false, 'message' => 'Error al crear la pregunta'], 500);
}
}
public function actualizarPregunta(Request $request, $id)
{
try {
$user = auth()->user();
if (!$user->hasRole('administrador')) {
return response()->json(['success' => false, 'message' => 'No autorizado'], 403);
}
$pregunta = Pregunta::find($id);
if (!$pregunta) {
return response()->json(['success' => false, 'message' => 'Pregunta no encontrada'], 404);
}
// Validación
$validator = Validator::make($request->all(), [
'curso_id' => 'required|exists:cursos,id',
'enunciado' => 'required|string',
'enunciado_adicional' => 'nullable|string',
'opciones' => 'required',
'respuesta_correcta' => 'required|string',
'explicacion' => 'nullable|string',
'nivel_dificultad' => 'required|in:facil,medio,dificil',
'activo' => 'boolean',
'imagenes' => 'nullable|array',
'imagenes.*' => 'image|mimes:jpg,jpeg,png,gif,webp|max:2048',
'imagenes_explicacion' => 'nullable|array',
'imagenes_explicacion.*' => 'image|mimes:jpg,jpeg,png,gif,webp|max:2048',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
$opciones = is_string($request->opciones) ? json_decode($request->opciones, true) : $request->opciones;
$opcionesValidas = array_map('trim', $opciones);
if (!in_array($request->respuesta_correcta, $opcionesValidas)) {
return response()->json([
'success' => false,
'errors' => ['respuesta_correcta' => ['La respuesta correcta debe estar entre las opciones']]
], 422);
}
$imagenesActuales = $request->input('imagenes_existentes', $pregunta->imagenes ?? []);
if (is_string($imagenesActuales)) {
$imagenesActuales = json_decode($imagenesActuales, true) ?? [];
}
if ($request->hasFile('imagenes')) {
foreach ($request->file('imagenes') as $imagen) {
$path = $imagen->store('preguntas/enunciados', 'public');
$imagenesActuales[] = url(Storage::url($path));
}
}
$imagenesExplicacionActuales = $request->input('imagenes_explicacion_existentes', $pregunta->imagenes_explicacion ?? []);
if (is_string($imagenesExplicacionActuales)) {
$imagenesExplicacionActuales = json_decode($imagenesExplicacionActuales, true) ?? [];
}
if ($request->hasFile('imagenes_explicacion')) {
foreach ($request->file('imagenes_explicacion') as $imagen) {
$path = $imagen->store('preguntas/explicaciones', 'public');
$imagenesExplicacionActuales[] = url(Storage::url($path));
}
}
$pregunta->update([
'curso_id' => $request->curso_id,
'enunciado' => $request->enunciado,
'enunciado_adicional' => $request->enunciado_adicional,
'opciones' => $opcionesValidas,
'respuesta_correcta' => $request->respuesta_correcta,
'explicacion' => $request->explicacion,
'nivel_dificultad' => $request->nivel_dificultad,
'activo' => $request->boolean('activo'),
'imagenes' => $imagenesActuales,
'imagenes_explicacion' => $imagenesExplicacionActuales,
]);
return response()->json([
'success' => true,
'message' => 'Pregunta actualizada correctamente',
'data' => $pregunta
]);
} catch (\Exception $e) {
Log::error('Error actualizando pregunta', ['error' => $e->getMessage()]);
return response()->json([
'success' => false,
'message' => 'Error al actualizar la pregunta'
], 500);
}
}
public function eliminarPregunta($id)
{
$pregunta = Pregunta::find($id);
if (!$pregunta) {
return response()->json([
'success' => false,
'message' => 'Pregunta no encontrada'
], 404);
}
if ($pregunta->imagenes) {
foreach ($pregunta->imagenes as $imagen) {
Storage::disk('public')->delete($imagen);
}
}
if ($pregunta->imagenes_explicacion) {
foreach ($pregunta->imagenes_explicacion as $imagen) {
Storage::disk('public')->delete($imagen);
}
}
$pregunta->delete();
return response()->json([
'success' => true,
'message' => 'Pregunta eliminada correctamente'
]);
}
}

@ -1,197 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\ProcesoAdmision;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
class ProcesoAdmisionController extends Controller
{
public function index(Request $request)
{
$q = ProcesoAdmision::query();
if ($request->filled('q')) {
$term = $request->string('q');
$q->where(function ($sub) use ($term) {
$sub->where('titulo', 'like', "%{$term}%")
->orWhere('slug', 'like', "%{$term}%");
});
}
if ($request->filled('estado')) {
$q->where('estado', $request->string('estado'));
}
if ($request->filled('publicado')) {
$q->where('publicado', (bool) $request->boolean('publicado'));
}
if ($request->boolean('include_detalles')) {
$q->with(['detalles' => fn($d) => $d->orderBy('id', 'desc')]);
}
$q->orderByDesc('id');
$perPage = (int) $request->input('per_page', 15);
return response()->json($q->paginate($perPage));
}
public function show(Request $request, $id)
{
$q = ProcesoAdmision::query();
if ($request->boolean('include_detalles')) {
$q->with('detalles');
}
return response()->json($q->findOrFail($id));
}
public function store(Request $request)
{
$data = $request->validate([
'titulo' => ['required','string','max:255'],
'subtitulo' => ['nullable','string','max:255'],
'descripcion' => ['nullable','string'],
'slug' => ['nullable','string','max:120', 'unique:procesos_admision,slug'],
'tipo_proceso' => ['nullable','string','max:60'],
'modalidad' => ['nullable','string','max:50'],
'publicado' => ['sometimes','boolean'],
'fecha_publicacion' => ['nullable','date'],
'fecha_inicio_preinscripcion' => ['nullable','date'],
'fecha_fin_preinscripcion' => ['nullable','date','after_or_equal:fecha_inicio_preinscripcion'],
'fecha_inicio_inscripcion' => ['nullable','date'],
'fecha_fin_inscripcion' => ['nullable','date','after_or_equal:fecha_inicio_inscripcion'],
'fecha_examen1' => ['nullable','date'],
'fecha_examen2' => ['nullable','date','after_or_equal:fecha_examen1'],
'fecha_resultados' => ['nullable','date'],
'fecha_inicio_biometrico' => ['nullable','date'],
'fecha_fin_biometrico' => ['nullable','date','after_or_equal:fecha_inicio_biometrico'],
'link_preinscripcion' => ['nullable','string','max:500'],
'link_inscripcion' => ['nullable','string','max:500'],
'link_resultados' => ['nullable','string','max:500'],
'link_reglamento' => ['nullable','string','max:500'],
'estado' => ['sometimes', Rule::in(['nuevo','publicado','en_proceso','finalizado','cancelado'])],
'imagen' => ['nullable','image','mimes:jpg,jpeg,png,webp','max:10240'],
'banner' => ['nullable','image','mimes:jpg,jpeg,png,webp','max:10240'],
'brochure' => ['nullable','file','mimes:pdf','max:10240'],
]);
if (empty($data['slug'])) {
$data['slug'] = Str::slug($data['titulo']);
}
$data['publicado'] = $data['publicado'] ?? false;
if ($request->hasFile('imagen')) {
$data['imagen_path'] = $request->file('imagen')->store('admisiones/procesos', 'public');
}
if ($request->hasFile('banner')) {
$data['banner_path'] = $request->file('banner')->store('admisiones/procesos', 'public');
}
if ($request->hasFile('brochure')) {
$data['brochure_path'] = $request->file('brochure')->store('admisiones/procesos', 'public');
}
$proceso = ProcesoAdmision::create($data);
return response()->json($proceso, 201);
}
public function update(Request $request, $id)
{
$proceso = ProcesoAdmision::findOrFail($id);
$data = $request->validate([
'titulo' => ['sometimes','string','max:255'],
'subtitulo' => ['sometimes','nullable','string','max:255'],
'descripcion' => ['sometimes','nullable','string'],
'slug' => ['sometimes','nullable','string','max:120', Rule::unique('procesos_admision','slug')->ignore($proceso->id)],
'tipo_proceso' => ['sometimes','nullable','string','max:60'],
'modalidad' => ['sometimes','nullable','string','max:50'],
'publicado' => ['sometimes','boolean'],
'fecha_publicacion' => ['sometimes','nullable','date'],
'fecha_inicio_preinscripcion' => ['sometimes','nullable','date'],
'fecha_fin_preinscripcion' => ['sometimes','nullable','date','after_or_equal:fecha_inicio_preinscripcion'],
'fecha_inicio_inscripcion' => ['sometimes','nullable','date'],
'fecha_fin_inscripcion' => ['sometimes','nullable','date','after_or_equal:fecha_inicio_inscripcion'],
'fecha_examen1' => ['sometimes','nullable','date'],
'fecha_examen2' => ['sometimes','nullable','date','after_or_equal:fecha_examen1'],
'fecha_resultados' => ['sometimes','nullable','date'],
'fecha_inicio_biometrico' => ['sometimes','nullable','date'],
'fecha_fin_biometrico' => ['sometimes','nullable','date','after_or_equal:fecha_inicio_biometrico'],
'link_preinscripcion' => ['sometimes','nullable','string','max:500'],
'link_inscripcion' => ['sometimes','nullable','string','max:500'],
'link_resultados' => ['sometimes','nullable','string','max:500'],
'link_reglamento' => ['sometimes','nullable','string','max:500'],
'estado' => ['sometimes', Rule::in(['nuevo','publicado','en_proceso','finalizado','cancelado'])],
'imagen' => ['sometimes','nullable','image','mimes:jpg,jpeg,png,webp','max:10240'],
'banner' => ['sometimes','nullable','image','mimes:jpg,jpeg,png,webp','max:10240'],
'brochure' => ['sometimes','nullable','file','mimes:pdf','max:10240'],
]);
if (array_key_exists('slug', $data) && empty($data['slug'])) {
$data['slug'] = Str::slug($data['titulo'] ?? $proceso->titulo);
}
// FormData envía strings vacíos; los convertimos a null para limpiar el campo en DB
foreach (['link_preinscripcion', 'link_inscripcion', 'link_resultados', 'link_reglamento'] as $key) {
if (array_key_exists($key, $data) && $data[$key] === '') {
$data[$key] = null;
}
}
if ($request->hasFile('imagen')) {
if ($proceso->imagen_path) Storage::disk('public')->delete($proceso->imagen_path);
$data['imagen_path'] = $request->file('imagen')->store('admisiones/procesos', 'public');
}
if ($request->hasFile('banner')) {
if ($proceso->banner_path) Storage::disk('public')->delete($proceso->banner_path);
$data['banner_path'] = $request->file('banner')->store('admisiones/procesos', 'public');
}
if ($request->hasFile('brochure')) {
if ($proceso->brochure_path) Storage::disk('public')->delete($proceso->brochure_path);
$data['brochure_path'] = $request->file('brochure')->store('admisiones/procesos', 'public');
}
$proceso->update($data);
return response()->json($proceso->fresh());
}
public function destroy($id)
{
$proceso = ProcesoAdmision::findOrFail($id);
if ($proceso->imagen_path) Storage::disk('public')->delete($proceso->imagen_path);
if ($proceso->banner_path) Storage::disk('public')->delete($proceso->banner_path);
if ($proceso->brochure_path) Storage::disk('public')->delete($proceso->brochure_path);
$proceso->delete();
return response()->json(['message' => 'Proceso eliminado']);
}
}

@ -1,144 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\ProcesoAdmision;
use App\Models\ProcesoAdmisionDetalle;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
class ProcesoAdmisionDetalleController extends Controller
{
public function index(Request $request, $procesoId)
{
ProcesoAdmision::findOrFail($procesoId);
$q = ProcesoAdmisionDetalle::query()->where('proceso_admision_id', $procesoId);
if ($request->filled('tipo')) {
$q->where('tipo', $request->string('tipo'));
}
return response()->json($q->orderByDesc('id')->get());
}
public function store(Request $request, $procesoId)
{
ProcesoAdmision::findOrFail($procesoId);
// ✅ Convertir JSON string -> array antes de validar (cuando llega desde FormData)
if ($request->has('listas') && is_string($request->input('listas'))) {
$decoded = json_decode($request->input('listas'), true);
if (json_last_error() === JSON_ERROR_NONE) {
$request->merge(['listas' => $decoded]);
}
}
if ($request->has('meta') && is_string($request->input('meta'))) {
$decoded = json_decode($request->input('meta'), true);
if (json_last_error() === JSON_ERROR_NONE) {
$request->merge(['meta' => $decoded]);
}
}
$data = $request->validate([
'tipo' => ['required', Rule::in(['requisitos','pagos','vacantes','cronograma'])],
'titulo_detalle' => ['required','string','max:255'],
'descripcion' => ['nullable','string'],
'listas' => ['nullable','array'],
'meta' => ['nullable','array'],
'url' => ['nullable','string','max:500'],
'imagen' => ['nullable','image','mimes:jpg,jpeg,png,webp','max:10240'],
'imagen_2' => ['nullable','image','mimes:jpg,jpeg,png,webp','max:10240'],
]);
$data['proceso_admision_id'] = (int) $procesoId;
if ($request->hasFile('imagen')) {
$data['imagen_path'] = $request->file('imagen')->store('admisiones/detalles', 'public');
}
if ($request->hasFile('imagen_2')) {
$data['imagen_path_2'] = $request->file('imagen_2')->store('admisiones/detalles', 'public');
}
$detalle = ProcesoAdmisionDetalle::create($data);
return response()->json($detalle, 201);
}
public function show($id)
{
return response()->json(ProcesoAdmisionDetalle::findOrFail($id));
}
public function update(Request $request, $id)
{
$detalle = ProcesoAdmisionDetalle::findOrFail($id);
// ✅ Convertir JSON string -> array antes de validar (cuando llega desde FormData)
if ($request->has('listas') && is_string($request->input('listas'))) {
$decoded = json_decode($request->input('listas'), true);
if (json_last_error() === JSON_ERROR_NONE) {
$request->merge(['listas' => $decoded]);
}
}
if ($request->has('meta') && is_string($request->input('meta'))) {
$decoded = json_decode($request->input('meta'), true);
if (json_last_error() === JSON_ERROR_NONE) {
$request->merge(['meta' => $decoded]);
}
}
$data = $request->validate([
'tipo' => ['sometimes', Rule::in(['requisitos','pagos','vacantes','cronograma'])],
'titulo_detalle' => ['sometimes','string','max:255'],
'descripcion' => ['sometimes','nullable','string'],
'listas' => ['sometimes','nullable','array'],
'meta' => ['sometimes','nullable','array'],
'url' => ['sometimes','nullable','string','max:500'],
'imagen' => ['sometimes','nullable','image','mimes:jpg,jpeg,png,webp','max:10240'],
'imagen_2' => ['sometimes','nullable','image','mimes:jpg,jpeg,png,webp','max:10240'],
]);
if ($request->hasFile('imagen')) {
if ($detalle->imagen_path) Storage::disk('public')->delete($detalle->imagen_path);
$data['imagen_path'] = $request->file('imagen')->store('admisiones/detalles', 'public');
}
if ($request->hasFile('imagen_2')) {
if ($detalle->imagen_path_2) Storage::disk('public')->delete($detalle->imagen_path_2);
$data['imagen_path_2'] = $request->file('imagen_2')->store('admisiones/detalles', 'public');
}
$detalle->update($data);
return response()->json($detalle->fresh());
}
public function destroy($id)
{
$detalle = ProcesoAdmisionDetalle::findOrFail($id);
if ($detalle->imagen_path) Storage::disk('public')->delete($detalle->imagen_path);
if ($detalle->imagen_path_2) Storage::disk('public')->delete($detalle->imagen_path_2);
$detalle->delete();
return response()->json(['message' => 'Detalle eliminado']);
}
}

@ -1,71 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\ProcesoAdmisionResultadoArchivo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class ProcesoAdmisionResultadoArchivoController extends Controller
{
public function index(int $procesoId)
{
$archivos = ProcesoAdmisionResultadoArchivo::where('proceso_admision_id', $procesoId)
->orderBy('orden')
->get();
return response()->json($archivos);
}
public function store(Request $request, int $procesoId)
{
$request->validate([
'orden' => 'required|integer|min:1|max:6',
'nombre' => 'required|string|max:255',
'archivo' => 'required|file|mimes:txt|max:10240',
]);
// Máximo 6 archivos por proceso
$count = ProcesoAdmisionResultadoArchivo::where('proceso_admision_id', $procesoId)->count();
if ($count >= 6) {
return response()->json(['message' => 'Máximo 6 archivos por proceso.'], 422);
}
// No puede haber dos archivos con el mismo orden en el mismo proceso
$existe = ProcesoAdmisionResultadoArchivo::where('proceso_admision_id', $procesoId)
->where('orden', $request->orden)
->exists();
if ($existe) {
return response()->json(['message' => 'Ya existe un archivo para ese slot.'], 422);
}
$contenido = file_get_contents($request->file('archivo')->getRealPath());
$encoding = mb_detect_encoding($contenido, ['UTF-8', 'Windows-1252', 'ISO-8859-1'], true);
$contenidoUtf8 = ($encoding === 'UTF-8')
? $contenido
: mb_convert_encoding($contenido, 'UTF-8', $encoding ?: 'Windows-1252');
$filename = uniqid() . '.txt';
$path = "proceso-resultados/{$procesoId}/{$filename}";
\Storage::disk('public')->put($path, $contenidoUtf8);
$archivo = ProcesoAdmisionResultadoArchivo::create([
'proceso_admision_id' => $procesoId,
'nombre' => $request->nombre,
'file_path' => $path,
'orden' => $request->orden,
]);
return response()->json($archivo, 201);
}
public function destroy(int $id)
{
$archivo = ProcesoAdmisionResultadoArchivo::findOrFail($id);
Storage::disk('public')->delete($archivo->file_path);
$archivo->delete();
return response()->json(['message' => 'Eliminado correctamente.']);
}
}

@ -1,148 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\Proceso;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class ProcesoController extends Controller
{
public function index(Request $request)
{
$query = Proceso::query();
if ($request->filled('search')) {
$query->where('nombre', 'like', '%' . $request->search . '%');
}
if ($request->filled('activo')) {
$query->where('activo', $request->boolean('activo'));
}
if ($request->filled('publico')) {
$query->where('publico', $request->boolean('publico'));
}
if ($request->filled('tipo_proceso')) {
$query->where('tipo_proceso', $request->tipo_proceso);
}
$procesos = $query
->orderBy('created_at', 'desc')
->paginate($request->get('per_page', 10));
return response()->json($procesos);
}
public function store(Request $request)
{
$data = $request->validate([
'nombre' => 'required|string|max:255',
'descripcion' => 'nullable|string',
'estado' => 'nullable|string|max:50',
'duracion' => 'nullable|integer|min:1',
'intentos_maximos' => 'nullable|integer|min:1',
'requiere_pago' => 'boolean',
'precio' => 'nullable|numeric|min:0',
'calificacion_id' => 'nullable|exists:calificaciones,id',
'tipo_simulacro' => 'nullable|string|max:50',
'tipo_proceso' => 'nullable|string|max:50',
'activo' => 'boolean',
'publico' => 'boolean',
'fecha_inicio' => 'nullable|date',
'fecha_fin' => 'nullable|date|after_or_equal:fecha_inicio',
'tiempo_por_pregunta' => 'nullable|integer|min:1',
]);
$data['slug'] = Str::slug($data['nombre']) . '-' . uniqid();
$proceso = Proceso::create($data);
return response()->json([
'message' => 'Proceso creado correctamente',
'data' => $proceso
], 201);
}
public function show($id)
{
$proceso = Proceso::findOrFail($id);
return response()->json($proceso);
}
public function update(Request $request, $id)
{
$proceso = Proceso::findOrFail($id);
$data = $request->validate([
'nombre' => 'required|string|max:255',
'descripcion' => 'nullable|string',
'estado' => 'nullable|string|max:50',
'duracion' => 'nullable|integer|min:1',
'intentos_maximos' => 'nullable|integer|min:1',
'requiere_pago' => 'boolean',
'precio' => 'nullable|numeric|min:0',
'calificacion_id' => 'nullable|exists:calificaciones,id',
'tipo_simulacro' => 'nullable|string|max:50',
'tipo_proceso' => 'nullable|string|max:50',
'activo' => 'boolean',
'publico' => 'boolean',
'fecha_inicio' => 'nullable|date',
'fecha_fin' => 'nullable|date|after_or_equal:fecha_inicio',
'tiempo_por_pregunta' => 'nullable|integer|min:1',
]);
if ($data['nombre'] !== $proceso->nombre) {
$data['slug'] = Str::slug($data['nombre']) . '-' . uniqid();
}
$proceso->update($data);
return response()->json([
'message' => 'Proceso actualizado correctamente',
'data' => $proceso
]);
}
public function destroy($id)
{
$proceso = Proceso::findOrFail($id);
$proceso->delete();
return response()->json([
'message' => 'Proceso eliminado correctamente'
]);
}
public function toggleActivo($id)
{
$proceso = Proceso::findOrFail($id);
$proceso->activo = !$proceso->activo;
$proceso->save();
return response()->json([
'message' => 'Estado actualizado',
'activo' => $proceso->activo
]);
}
}

@ -1,300 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AreaProceso;
use App\Models\Proceso;
use App\Models\ReglaAreaProceso;
use Illuminate\Support\Facades\DB;
class ReglaAreaProcesoController extends Controller
{
public function areasProcesos()
{
$areasProcesos = DB::table('area_proceso as ap')
->leftJoin('reglas_area_proceso as r', 'ap.id', '=', 'r.area_proceso_id')
->leftJoin('area_curso as ac', 'ap.area_id', '=', 'ac.area_id')
->leftJoin('cursos as c', 'ac.curso_id', '=', 'c.id')
->join('areas as a', 'ap.area_id', '=', 'a.id')
->join('procesos as p', 'ap.proceso_id', '=', 'p.id')
->select(
'ap.id',
'ap.area_id',
'ap.proceso_id',
'a.nombre as area_nombre',
'p.nombre as proceso_nombre',
DB::raw('COUNT(DISTINCT r.id) as reglas_count'),
DB::raw('COUNT(DISTINCT c.id) as cursos_count')
)
->groupBy('ap.id', 'ap.area_id', 'ap.proceso_id', 'a.nombre', 'p.nombre')
->get();
return response()->json([
'areaProcesos' => $areasProcesos
]);
}
public function index($areaProcesoId)
{
$areaProceso = DB::table('area_proceso as ap')
->join('areas as a', 'a.id', '=', 'ap.area_id')
->join('procesos as p', 'p.id', '=', 'ap.proceso_id')
->where('ap.id', $areaProcesoId)
->select('ap.id as area_proceso_id', 'a.id as area_id', 'a.nombre as area_nombre',
'p.id as proceso_id', 'p.nombre as proceso_nombre', 'p.duracion as cantidad_total_preguntas')
->first();
if (!$areaProceso) {
return response()->json(['error' => 'AreaProceso no encontrado'], 404);
}
$cursos = DB::table('area_curso as ac')
->join('cursos as c', 'c.id', '=', 'ac.curso_id')
->where('ac.area_id', $areaProceso->area_id)
->select('c.id as curso_id', 'c.nombre as nombre')
->get();
$reglasExistentes = DB::table('reglas_area_proceso')
->where('area_proceso_id', $areaProcesoId)
->get();
$reglas = $cursos->map(function ($curso) use ($reglasExistentes) {
$regla = $reglasExistentes->firstWhere('curso_id', $curso->curso_id);
return [
'curso_id' => $curso->curso_id,
'nombre' => $curso->nombre,
'regla_id' => $regla->id ?? null,
'orden' => $regla->orden ?? null,
'cantidad_preguntas' => $regla->cantidad_preguntas ?? null,
'nivel_dificultad' => $regla->nivel_dificultad ?? 'medio',
'ponderacion' => $regla->ponderacion ?? null,
];
})->sortBy('orden')->values();
return response()->json([
'area_proceso_id' => $areaProceso->area_proceso_id,
'proceso' => [
'id' => $areaProceso->proceso_id,
'nombre' => $areaProceso->proceso_nombre,
'cantidad_total_preguntas' => $areaProceso->cantidad_total_preguntas,
],
'cursos' => $reglas,
'total_preguntas_asignadas' => $reglasExistentes->sum('cantidad_preguntas'),
]);
}
public function store(Request $request, $areaProcesoId)
{
$request->validate([
'curso_id' => 'required|exists:cursos,id',
'cantidad_preguntas' => 'required|integer|min:0',
'orden' => 'required|integer|min:1',
'nivel_dificultad' => 'nullable|string|in:bajo,medio,alto',
'ponderacion' => 'nullable|numeric|min:0|max:100',
]);
$areaProceso = DB::table('area_proceso as ap')
->join('procesos as p', 'ap.proceso_id', '=', 'p.id')
->where('ap.id', $areaProcesoId)
->select('p.cantidad_pregunta')
->first();
if (!$areaProceso) {
return response()->json([
'error' => 'No se encontró el proceso asociado al área'
], 404);
}
$totalPreguntasProceso = $areaProceso->cantidad_pregunta;
$totalAsignado = DB::table('reglas_area_proceso')
->where('area_proceso_id', $areaProcesoId)
->where('curso_id', '!=', $request->curso_id)
->sum('cantidad_preguntas');
$totalNuevo = $totalAsignado + $request->cantidad_preguntas;
if ($totalNuevo > $totalPreguntasProceso) {
return response()->json([
'error' => 'Excede la cantidad total de preguntas del proceso. Disponible: ' .
($totalPreguntasProceso - $totalAsignado)
], 422);
}
DB::table('reglas_area_proceso')->updateOrInsert(
[
'area_proceso_id' => $areaProcesoId,
'curso_id' => $request->curso_id,
],
[
'cantidad_preguntas' => $request->cantidad_preguntas,
'orden' => $request->orden,
'nivel_dificultad' => $request->nivel_dificultad ?? 'medio',
'ponderacion' => $request->ponderacion ?? 0,
'updated_at' => now(),
'created_at' => now(),
]
);
$totalAsignadoFinal = DB::table('reglas_area_proceso')
->where('area_proceso_id', $areaProcesoId)
->sum('cantidad_preguntas');
return response()->json([
'success' => true,
'message' => 'Regla guardada correctamente',
'total_preguntas_asignadas' => $totalAsignadoFinal,
'preguntas_disponibles' => $totalPreguntasProceso - $totalAsignadoFinal,
]);
}
public function update(Request $request, $reglaId)
{
$request->validate([
'cantidad_preguntas' => 'required|integer|min:0',
'orden' => 'required|integer|min:1',
'nivel_dificultad' => 'nullable|string|in:bajo,medio,alto',
'ponderacion' => 'nullable|numeric|min:0|max:100',
]);
$regla = DB::table('reglas_area_proceso')
->where('id', $reglaId)
->first();
if (!$regla) {
return response()->json([
'error' => 'La regla no existe'
], 404);
}
$areaProceso = DB::table('area_proceso as ap')
->join('procesos as p', 'ap.proceso_id', '=', 'p.id')
->where('ap.id', $regla->area_proceso_id)
->select('p.cantidad_pregunta')
->first();
if (!$areaProceso) {
return response()->json([
'error' => 'No se encontró el proceso asociado al área'
], 404);
}
$totalPreguntasProceso = $areaProceso->cantidad_pregunta;
$totalAsignado = DB::table('reglas_area_proceso')
->where('area_proceso_id', $regla->area_proceso_id)
->where('id', '!=', $reglaId)
->sum('cantidad_preguntas');
$totalNuevo = $totalAsignado + $request->cantidad_preguntas;
if ($totalNuevo > $totalPreguntasProceso) {
return response()->json([
'error' => 'Excede la cantidad total de preguntas del proceso. Disponible: ' .
($totalPreguntasProceso - $totalAsignado)
], 422);
}
DB::table('reglas_area_proceso')
->where('id', $reglaId)
->update([
'cantidad_preguntas' => $request->cantidad_preguntas,
'orden' => $request->orden,
'nivel_dificultad' => $request->nivel_dificultad ?? 'medio',
'ponderacion' => $request->ponderacion ?? 0,
'updated_at' => now(),
]);
$totalAsignadoFinal = DB::table('reglas_area_proceso')
->where('area_proceso_id', $regla->area_proceso_id)
->sum('cantidad_preguntas');
return response()->json([
'success' => true,
'message' => 'Regla actualizada correctamente',
'total_preguntas_asignadas' => $totalAsignadoFinal,
'preguntas_disponibles' => $totalPreguntasProceso - $totalAsignadoFinal,
]);
}
public function destroy($reglaId)
{
$regla = ReglaAreaProceso::findOrFail($reglaId);
$areaProcesoId = $regla->area_proceso_id;
$regla->delete();
return response()->json([
'success' => true,
'message' => 'Regla eliminada correctamente',
'total_preguntas_asignadas' => ReglaAreaProceso::where('area_proceso_id', $areaProcesoId)
->sum('cantidad_preguntas'),
]);
}
public function storeMultiple(Request $request, $areaProcesoId)
{
$request->validate([
'reglas' => 'required|array',
'reglas.*.curso_id' => 'required|exists:cursos,id',
'reglas.*.cantidad_preguntas' => 'required|integer|min:0',
'reglas.*.orden' => 'required|integer|min:1',
'reglas.*.nivel_dificultad' => 'nullable|string|in:bajo,medio,alto',
'reglas.*.ponderacion' => 'nullable|numeric|min:0|max:100',
]);
$areaProceso = DB::table('area_proceso as ap')
->join('procesos as p', 'ap.proceso_id', '=', 'p.id')
->where('ap.id', $areaProcesoId)
->select('p.cantidad_pregunta')
->first();
$totalPreguntasProceso = $areaProceso->cantidad_pregunta ?? 0;
$totalNuevo = collect($request->reglas)->sum('cantidad_preguntas');
if ($totalNuevo > $totalPreguntasProceso) {
return response()->json([
'error' => 'Excede la cantidad total de preguntas del proceso. Máximo permitido: ' . $totalPreguntasProceso
], 422);
}
DB::table('reglas_area_proceso')->where('area_proceso_id', $areaProcesoId)->delete();
$insertData = collect($request->reglas)->map(function ($r) use ($areaProcesoId) {
return [
'area_proceso_id' => $areaProcesoId,
'curso_id' => $r['curso_id'],
'cantidad_preguntas' => $r['cantidad_preguntas'],
'orden' => $r['orden'],
'nivel_dificultad' => $r['nivel_dificultad'] ?? 'medio',
'ponderacion' => $r['ponderacion'] ?? 0,
'created_at' => now(),
'updated_at' => now(),
];
})->toArray();
if (!empty($insertData)) {
DB::table('reglas_area_proceso')->insert($insertData);
}
return response()->json([
'success' => true,
'message' => 'Reglas guardadas correctamente',
'total_preguntas_asignadas' => $totalNuevo,
'preguntas_disponibles' => $totalPreguntasProceso - $totalNuevo,
]);
}
}

@ -1,237 +0,0 @@
<?php
namespace App\Http\Controllers\Administracion;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Spatie\Permission\Models\Role;
class UserController extends Controller
{
public function index(Request $request)
{
try {
$query = User::with('roles');
if ($request->filled('buscar')) {
$query->where(function ($q) use ($request) {
$q->where('name', 'like', "%{$request->buscar}%")
->orWhere('email', 'like', "%{$request->buscar}%");
});
}
if ($request->filled('rol')) {
$query->whereHas('roles', function ($q) use ($request) {
$q->where('name', $request->rol);
});
}
$usuarios = $query->orderBy('id', 'desc')->paginate(15);
$usuarios->getCollection()->transform(function ($user) {
return [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'created_at' => $user->created_at,
];
});
return response()->json([
'success' => true,
'data' => $usuarios,
]);
} catch (\Exception $e) {
Log::error('Error al listar usuarios', ['error' => $e->getMessage()]);
return response()->json(['success' => false, 'message' => 'Error al obtener usuarios'], 500);
}
}
public function store(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255|regex:/^[\pL\s\-]+$/u',
'email' => 'required|email|unique:users,email|max:255',
'password' => 'required|string|min:8|confirmed',
'rol' => 'required|string|exists:roles,name',
], [
'name.regex' => 'El nombre solo puede contener letras y espacios.',
'rol.exists' => 'El rol seleccionado no existe.',
'email.unique' => 'Este correo ya está registrado.',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
$user = User::create([
'name' => strip_tags(trim($request->name)),
'email' => strtolower(trim($request->email)),
'password' => Hash::make($request->password),
]);
$user->assignRole($request->rol);
Log::info('Usuario creado por admin', [
'admin_id' => $request->user()->id,
'nuevo_user_id' => $user->id,
]);
return response()->json([
'success' => true,
'message' => 'Usuario creado correctamente',
'data' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'created_at' => $user->created_at,
],
], 201);
} catch (\Exception $e) {
Log::error('Error al crear usuario', ['error' => $e->getMessage()]);
return response()->json(['success' => false, 'message' => 'Error al crear usuario'], 500);
}
}
public function update(Request $request, $id)
{
try {
$user = User::findOrFail($id);
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255|regex:/^[\pL\s\-]+$/u',
'email' => 'required|email|max:255|unique:users,email,' . $user->id,
'rol' => 'required|string|exists:roles,name',
], [
'name.regex' => 'El nombre solo puede contener letras y espacios.',
'rol.exists' => 'El rol seleccionado no existe.',
'email.unique' => 'Este correo ya está registrado.',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
$user->update([
'name' => strip_tags(trim($request->name)),
'email' => strtolower(trim($request->email)),
]);
$user->syncRoles([$request->rol]);
Log::info('Usuario actualizado', [
'admin_id' => $request->user()->id,
'user_id' => $user->id,
]);
return response()->json([
'success' => true,
'message' => 'Usuario actualizado correctamente',
'data' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'created_at' => $user->created_at,
],
]);
} catch (\Exception $e) {
Log::error('Error al actualizar usuario', ['error' => $e->getMessage()]);
return response()->json(['success' => false, 'message' => 'Error al actualizar usuario'], 500);
}
}
public function changePassword(Request $request, $id)
{
try {
$user = User::findOrFail($id);
$authUser = $request->user();
$rules = ['password' => 'required|string|min:8|confirmed'];
if ($authUser->id === $user->id) {
$rules['current_password'] = 'required|string';
}
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
if ($authUser->id === $user->id) {
if (!Hash::check($request->current_password, $user->password)) {
return response()->json([
'success' => false,
'errors' => ['current_password' => ['La contraseña actual no es correcta']],
], 422);
}
} else {
// Al cambiar la contraseña de otro usuario, revocar sus tokens
$user->tokens()->delete();
}
$user->update(['password' => Hash::make($request->password)]);
Log::info('Contraseña cambiada', [
'admin_id' => $authUser->id,
'user_id' => $user->id,
]);
return response()->json([
'success' => true,
'message' => 'Contraseña actualizada correctamente',
]);
} catch (\Exception $e) {
Log::error('Error al cambiar contraseña', ['error' => $e->getMessage()]);
return response()->json(['success' => false, 'message' => 'Error al cambiar contraseña'], 500);
}
}
public function destroy(Request $request, $id)
{
try {
$user = User::findOrFail($id);
if ($request->user()->id === $user->id) {
return response()->json([
'success' => false,
'message' => 'No puedes eliminar tu propia cuenta',
], 403);
}
$user->tokens()->delete();
$user->delete();
Log::info('Usuario eliminado', [
'admin_id' => $request->user()->id,
'user_id' => $id,
]);
return response()->json([
'success' => true,
'message' => 'Usuario eliminado correctamente',
]);
} catch (\Exception $e) {
Log::error('Error al eliminar usuario', ['error' => $e->getMessage()]);
return response()->json(['success' => false, 'message' => 'Error al eliminar usuario'], 500);
}
}
public function roles()
{
try {
$roles = Role::orderBy('name')->get(['id', 'name']);
return response()->json(['success' => true, 'data' => $roles]);
} catch (\Exception $e) {
return response()->json(['success' => false, 'message' => 'Error al obtener roles'], 500);
}
}
}

@ -1,229 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class AuthController extends Controller
{
/**
* Registro de usuario
*/
public function register(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255|regex:/^[\pL\s\-]+$/u',
'email' => 'required|email|unique:users,email|max:255',
'password' => [
'required',
'string',
'min:8',
'confirmed',
'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/'
],
], [
'password.regex' => 'La contraseña debe contener al menos una mayúscula, una minúscula, un número y un carácter especial.',
'name.regex' => 'El nombre solo puede contener letras y espacios.',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$user = User::create([
'name' => strip_tags(trim($request->name)),
'email' => strtolower(trim($request->email)),
'password' => Hash::make($request->password),
'email_verified_at' => null,
]);
$user->assignRole('administrador');
Log::info('Usuario registrado', ['user_id' => $user->id, 'email' => $user->email]);
$token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;
return response()->json([
'success' => true,
'message' => 'Usuario registrado exitosamente',
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'permissions' => $user->getAllPermissions()->pluck('name')
],
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => 12 * 60 * 60
], 201);
} catch (\Exception $e) {
Log::error('Error en registro', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return response()->json([
'success' => false,
'message' => 'Error en el servidor. Por favor, intente más tarde.'
], 500);
}
}
public function login(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'email' => 'required|email|max:255',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$credentials = [
'email' => strtolower(trim($request->email)),
'password' => $request->password
];
if (!Auth::attempt($credentials)) {
Log::warning('Intento de login fallido', ['email' => $request->email]);
return response()->json([
'success' => false,
'message' => 'Credenciales inválidas'
], 401);
}
$user = User::where('email', $credentials['email'])->firstOrFail();
// Verificar si el usuario está activo (puedes agregar un campo 'is_active' después)
// if (!$user->is_active) {
// return response()->json(['error' => 'Cuenta desactivada'], 403);
// }
$user->tokens()->delete();
$token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;
Log::info('Login exitoso', ['user_id' => $user->id]);
return response()->json([
'success' => true,
'message' => 'Login exitoso',
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'permissions' => $user->getAllPermissions()->pluck('name')
],
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => 12 * 60 * 60
]);
} catch (\Exception $e) {
Log::error('Error en login', [
'error' => $e->getMessage(),
'email' => $request->email
]);
return response()->json([
'success' => false,
'message' => 'Error en el servidor. Por favor, intente más tarde.'
], 500);
}
}
public function logout(Request $request)
{
try {
if ($request->user()) {
Log::info('Logout exitoso', ['user_id' => $request->user()->id]);
$request->user()->tokens()->delete();
}
return response()->json([
'success' => true,
'message' => 'Sesión cerrada correctamente'
]);
} catch (\Exception $e) {
Log::error('Error en logout', ['error' => $e->getMessage()]);
return response()->json([
'success' => false,
'message' => 'Error al cerrar sesión'
], 500);
}
}
public function me(Request $request)
{
try {
$user = $request->user();
if (!$user) {
return response()->json([
'success' => false,
'message' => 'Usuario no autenticado'
], 401);
}
return response()->json([
'success' => true,
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'permissions' => $user->getAllPermissions()->pluck('name')
]
]);
} catch (\Exception $e) {
Log::error('Error obteniendo usuario', ['error' => $e->getMessage()]);
return response()->json([
'success' => false,
'message' => 'Error obteniendo información del usuario'
], 500);
}
}
public function refresh(Request $request)
{
$user = $request->user();
$user->tokens()->delete();
$token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;
return response()->json([
'success' => true,
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => 12 * 60 * 60
]);
}
}

@ -1,8 +0,0 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
}

@ -1,746 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\Postulante;
use App\Models\Proceso;
use App\Models\Area;
use App\Models\Curso;
use App\Models\Pregunta;
use App\Models\Alternativa;
use App\Models\Examen;
use App\Models\PreguntaAsignada;
use App\Models\AlternativaAsignada;
use App\Models\DetalleResultado;
use App\Models\RespuestaPostulante;
use App\Models\ResultadoExamen;
use App\Models\Recomendaciones;
use App\Models\Pago;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;
use App\Services\ExamenService;
use Illuminate\Support\Facades\DB;
class ExamenController extends Controller
{
protected $examenService;
public function __construct(ExamenService $examenService)
{
$this->examenService = $examenService;
}
public function procesoexamen(Request $request)
{
$postulante = $request->user();
$procesos = Proceso::where('activo', 1)
->whereNotExists(function ($q) use ($postulante) {
$q->select(\DB::raw(1))
->from('examenes')
->join('area_proceso', 'area_proceso.id', '=', 'examenes.area_proceso_id')
->whereColumn('area_proceso.proceso_id', 'procesos.id')
->where('examenes.postulante_id', $postulante->id);
})
->select('id', 'nombre', 'requiere_pago')
->get();
return response()->json($procesos);
}
public function areas(Request $request)
{
$procesoId = $request->query('proceso_id');
$areas = Area::select('areas.id', 'areas.nombre')
->whereHas('procesos', function ($query) use ($procesoId) {
$query->where('procesos.id', $procesoId)
->where('procesos.activo', 1);
})
->with(['procesos' => function ($q) use ($procesoId) {
$q->where('procesos.id', $procesoId)
->select('procesos.id')
->withPivot('id', 'proceso_id', 'area_id');
}])
->get()
->map(function ($area) {
$pivot = $area->procesos->first()->pivot;
return [
'area_id' => $area->id,
'nombre' => $area->nombre,
'area_proceso_id' => $pivot->id,
];
});
return response()->json($areas);
}
public function crearExamen(Request $request)
{
$postulante = $request->user();
$request->validate([
'area_proceso_id' => 'required|exists:area_proceso,id',
]);
// 🔥 Obtener TODO desde el pivot
$areaProceso = \DB::table('area_proceso')
->join('procesos', 'procesos.id', '=', 'area_proceso.proceso_id')
->join('areas', 'areas.id', '=', 'area_proceso.area_id')
->where('area_proceso.id', $request->area_proceso_id)
->select(
'area_proceso.id',
'area_proceso.area_id',
'area_proceso.proceso_id',
'procesos.requiere_pago'
)
->first();
if (!$areaProceso) {
return response()->json(['message' => 'Relación área-proceso inválida'], 400);
}
$yaDioProceso = Examen::join('area_proceso', 'area_proceso.id', '=', 'examenes.area_proceso_id')
->where('examenes.postulante_id', $postulante->id)
->where('area_proceso.proceso_id', $areaProceso->proceso_id)
->exists();
if ($yaDioProceso) {
return response()->json([
'message' => 'Ya rendiste un examen para este proceso'
], 400);
}
$pagado = 0;
$pagoId = null;
// 💰 Validación de pago
if ($areaProceso->requiere_pago) {
$request->validate([
'tipo_pago' => 'required|in:pyto_peru,banco_nacion,caja',
'codigo_pago' => 'required',
]);
$response = $this->validarPago(
$request->tipo_pago,
$request->codigo_pago,
$postulante->dni
);
if (!$response['estado']) {
return response()->json(['message' => 'Pago inválido'], 400);
}
$pago = Pago::firstOrCreate(
[
'codigo_pago' => $request->codigo_pago,
'tipo_pago' => $request->tipo_pago,
],
[
'postulante_id' => $postulante->id,
'monto' => $response['monto'],
'fecha_pago' => $response['fecha_pago'],
]
);
if ($pago->utilizado) {
return response()->json(['message' => 'Pago ya utilizado'], 400);
}
$pago->update(['utilizado' => true]);
$pagado = 1;
$pagoId = $pago->id;
}
// 🧠 Crear / actualizar examen
$examen = Examen::updateOrCreate(
['postulante_id' => $postulante->id,
'area_proceso_id' => $areaProceso->id, // 🔥 pivot
'pagado' => $pagado,
'tipo_pago' => $request->tipo_pago ?? null,
'pago_id' => $pagoId,
]
);
return response()->json([
'success' => true,
'examen_id' => $examen->id,
'mensaje' => 'Examen creado correctamente',
]);
}
public function validarPago($tipoPago, $codigoPago, $dni)
{
return match ($tipoPago) {
'pyto_peru' => $this->validarPagoPytoPeru($codigoPago, $dni),
'banco_nacion' => $this->validarPagoBancoNacion($codigoPago, $dni),
'caja' => $this->validarPagoCaja($codigoPago, $dni),
default => ['estado' => false],
};
}
private function validarPagoBancoNacion($secuencia, $dni)
{
$url = 'https://inscripciones.admision.unap.edu.pe/api/get-pagos-banco-secuencia';
$response = Http::post($url, [
'secuencia' => $secuencia,
]);
if (!$response->successful()) {
\Log::error('Error en la solicitud a la API', ['status' => $response->status(), 'body' => $response->body()]);
return ['estado' => false, 'message' => 'Error en la solicitud a la API'];
}
$data = $response->json();
if (isset($data['estado']) && $data['estado'] === true) {
foreach ($data['datos'] as $pago) {
if (isset($pago['dni']) && trim($pago['dni']) == trim($dni)) {
return [
'estado' => true,
'monto' => $pago['imp_pag'],
'fecha_pago' => $pago['fch_pag'],
];
}
}
}
return ['estado' => false, 'message' => 'Datos no válidos o no encontrados'];
}
private function validarPagoPytoPeru($authorizationCode, $dni)
{
$url = "https://service2.unap.edu.pe/PAYMENTS_MNG/v1/{$dni}/8/";
$response = Http::get($url);
if ($response->successful()) {
$data = $response->json();
if (isset($data['data'][0]['autorizationCode']) && $data['data'][0]['autorizationCode'] === $authorizationCode) {
return [
'estado' => true,
'monto' => $data['data'][0]['total'],
'fecha_pago' => $data['data'][0]['confirmedDate'],
];
}
}
return ['estado' => false, 'message' => 'El código de autorización no coincide.'];
}
private function validarPagoCaja($codigoPago, $dni)
{
$url = "https://inscripciones.admision.unap.edu.pe/api/get-pago-caja/{$dni}/{$codigoPago}";
$response = Http::get($url);
if (!$response->successful()) {
\Log::error('Error API Caja', [
'status' => $response->status(),
'body' => $response->body()
]);
return ['estado' => false, 'message' => 'Error en la API de Caja'];
}
$data = $response->json();
if (
isset($data['paymentTitle'], $data['paymentAmount'], $data['paymentDatetime']) &&
trim($data['paymentTitle']) === trim($codigoPago)
) {
return [
'estado' => true,
'monto' => (float) $data['paymentAmount'],
'fecha_pago' => $data['paymentDatetime'],
];
}
return ['estado' => false, 'message' => 'Pago no válido o no encontrado'];
}
public function miExamenActual(Request $request)
{
$postulante = $request->user();
$examen = Examen::join('area_proceso', 'area_proceso.id', '=', 'examenes.area_proceso_id')
->join('areas', 'areas.id', '=', 'area_proceso.area_id')
->join('procesos', 'procesos.id', '=', 'area_proceso.proceso_id')
->where('examenes.postulante_id', $postulante->id)
->select(
'examenes.id',
'examenes.pagado',
'examenes.tipo_pago',
'examenes.intentos',
'areas.id as area_id',
'areas.nombre as area_nombre',
'procesos.id as proceso_id',
'procesos.nombre as proceso_nombre',
'procesos.intentos_maximos as proceso_intentos_maximos'
)
->latest('examenes.created_at')
->first();
if (!$examen) {
return response()->json([
'success' => true,
'mensaje' => 'No tienes exámenes asignados actualmente',
'examen' => null
]);
}
return response()->json([
'success' => true,
'examen' => [
'id' => $examen->id,
'intentos' => $examen->intentos,
'intentos_maximos' => $examen->proceso_intentos_maximos,
'proceso' => [
'id' => $examen->proceso_id,
'nombre' => $examen->proceso_nombre,
],
'area' => [
'id' => $examen->area_id,
'nombre' => $examen->area_nombre,
],
'pagado' => $examen->pagado,
'tipo_pago' => $examen->tipo_pago ?? null,
]
]);
}
public function generarPreguntas($examenId)
{
$examen = Examen::findOrFail($examenId);
$postulante = request()->user();
if ($examen->postulante_id !== $postulante->id) {
return response()->json([
'success' => false,
'message' => 'No autorizado'
], 403);
}
if ($examen->preguntasAsignadas()->exists()) {
return response()->json([
'success' => true,
'message' => 'El examen ya tiene preguntas generadas',
'ya_tiene_preguntas' => true,
'total_preguntas' => $examen->preguntasAsignadas()->count()
]);
}
$resultado = $this->examenService->generarPreguntasExamen($examen);
if (!$resultado['success']) {
return response()->json($resultado, 400);
}
return response()->json([
'success' => true,
'message' => 'Preguntas generadas exitosamente',
'ya_tiene_preguntas' => false,
'total_preguntas' => $examen->preguntasAsignadas()->count()
]);
}
public function iniciarExamen(Request $request)
{
$request->validate([
'examen_id' => 'required|exists:examenes,id'
]);
$examen = Examen::findOrFail($request->examen_id);
$postulante = $request->user();
if ($examen->postulante_id !== $postulante->id) {
return response()->json([
'success' => false,
'message' => 'No autorizado'
], 403);
}
$areaProceso = \DB::table('area_proceso')
->join('procesos', 'area_proceso.proceso_id', '=', 'procesos.id')
->join('areas', 'area_proceso.area_id', '=', 'areas.id')
->where('area_proceso.id', $examen->area_proceso_id)
->select(
'procesos.id as proceso_id',
'procesos.nombre as proceso_nombre',
'procesos.duracion as proceso_duracion',
'procesos.intentos_maximos as proceso_intentos_maximos',
'areas.nombre as area_nombre'
)
->first();
if (!$examen->preguntasAsignadas()->exists()) {
return response()->json([
'success' => false,
'message' => 'El examen no tiene preguntas generadas'
], 400);
}
if ($areaProceso && $examen->intentos >= $areaProceso->proceso_intentos_maximos) {
return response()->json([
'success' => false,
'message' => 'Has alcanzado el número máximo de intentos para este proceso'
], 403);
}
$examen->increment('intentos');
$examen->update([
'hora_inicio' => now(),
'estado' => 'en_progreso'
]);
$preguntas = $this->examenService->obtenerPreguntasExamen($examen);
return response()->json([
'success' => true,
'examen' => [
'id' => $examen->id,
'estado' => $examen->estado,
'hora_inicio' => $examen->hora_inicio,
'intentos' => $examen->intentos,
'intentos_maximos' => $areaProceso->proceso_intentos_maximos ?? null,
'proceso' => $areaProceso->proceso_nombre ?? null,
'duracion' => $areaProceso->proceso_duracion ?? null,
'area' => $areaProceso->area_nombre ?? null
],
'preguntas' => $preguntas
]);
}
public function responderPregunta($preguntaAsignadaId, Request $request)
{
$request->validate([
'respuesta' => 'nullable|string'
]);
$preguntaAsignada = PreguntaAsignada::with(['examen', 'pregunta'])
->findOrFail($preguntaAsignadaId);
$postulante = $request->user();
if ($preguntaAsignada->examen->postulante_id !== $postulante->id) {
return response()->json([
'success' => false,
'message' => 'No autorizado'
], 403);
}
$resultado = $this->examenService->guardarRespuesta(
$preguntaAsignada,
$request->respuesta
);
return response()->json($resultado);
}
public function finalizarExamen($examenId)
{
$examen = Examen::findOrFail($examenId);
$postulante = request()->user();
// Validar que el examen le pertenezca al postulante autenticado
if ((int) $examen->postulante_id !== (int) $postulante->id) {
return response()->json([
'success' => false,
'message' => 'No autorizado'
], 403);
}
// (Opcional) Evitar finalizar 2 veces
if ($examen->estado === 'finalizado') {
return response()->json([
'success' => false,
'message' => 'El examen ya está finalizado'
], 409);
}
// Finalizar examen
$examen->update([
'estado' => 'finalizado',
'hora_fin' => now(),
]);
return response()->json([
'success' => true,
'message' => 'Examen finalizado exitosamente'
]);
}
public function calificarExamen($examenId, Request $request)
{
$postulante = $request->user();
if (!$postulante) {
return response()->json(['success' => false, 'mensaje' => 'No autenticado.'], 401);
}
return DB::transaction(function () use ($examenId, $postulante) {
// 1) Validar examen del postulante
$examen = DB::table('examenes')
->where('id', $examenId)
->where('postulante_id', $postulante->id)
->first();
if (!$examen) {
return response()->json([
'success' => false,
'mensaje' => 'No se encontró un examen para este postulante.'
], 404);
}
// 2) Si ya está calificado, devolver existente (y opcionalmente recalcular orden)
$existente = DB::table('resultados_examenes')
->where('examen_id', $examen->id)
->first();
if ($existente) {
// Obtener proceso_id para poder recalcular si deseas (opcional)
$procesoId = DB::table('area_proceso')
->where('id', $examen->area_proceso_id)
->value('proceso_id');
if ($procesoId) $this->recalcularOrdenMerito($procesoId);
return response()->json([
'success' => true,
'mensaje' => 'Examen ya calificado.',
'total_puntos' => (float)$existente->total_puntos,
'total_correctas' => (int)$existente->total_correctas,
'total_incorrectas' => (int)$existente->total_incorrectas,
'total_nulas' => (int)$existente->total_nulas,
'porcentaje_correctas' => (float)$existente->porcentaje_correctas,
'calificacion_sobre_20' => (float)$existente->calificacion_sobre_20,
'orden_merito' => $existente->orden_merito,
'correctas_por_curso' => json_decode($existente->correctas_por_curso, true),
'incorrectas_por_curso' => json_decode($existente->incorrectas_por_curso ?? '[]', true),
'preguntas_totales_por_curso' => json_decode($existente->preguntas_totales_por_curso ?? '[]', true),
]);
}
// 3) Obtener configuración de calificación desde proceso -> calificaciones
$cfg = DB::table('area_proceso as ap')
->join('procesos as pr', 'pr.id', '=', 'ap.proceso_id')
->join('calificaciones as ca', 'ca.id', '=', 'pr.calificacion_id')
->where('ap.id', $examen->area_proceso_id)
->select(
'pr.id as proceso_id',
'ca.puntos_correcta',
'ca.puntos_incorrecta',
'ca.puntos_nula',
'ca.puntaje_maximo'
)
->first();
if (!$cfg) {
return response()->json([
'success' => false,
'mensaje' => 'No se ha definido un tipo de calificación para este proceso.'
], 400);
}
$puntosCorrecta = (float) $cfg->puntos_correcta;
$puntosIncorrecta = (float) $cfg->puntos_incorrecta;
$puntosNula = (float) $cfg->puntos_nula;
$puntajeMaximo = (float) $cfg->puntaje_maximo;
// 4) Traer preguntas asignadas con su pregunta y curso
$items = DB::table('preguntas_asignadas as pa')
->join('preguntas as p', 'p.id', '=', 'pa.pregunta_id')
->join('cursos as c', 'c.id', '=', 'p.curso_id')
->where('pa.examen_id', $examen->id)
->select(
'pa.id as pa_id',
'pa.estado as pa_estado',
'pa.respuesta_usuario',
'p.respuesta_correcta',
'c.nombre as curso_nombre'
)
->get();
if ($items->isEmpty()) {
return response()->json([
'success' => false,
'mensaje' => 'El examen no tiene preguntas asignadas.'
], 422);
}
// 5) Calificar y actualizar cada pregunta_asignada
$totalPuntos = 0.0;
$totalCorrectas = 0;
$totalIncorrectas = 0;
$totalNulas = 0;
$correctasPorCurso = [];
$incorrectasPorCurso = [];
$preguntasTotalesPorCurso = [];
foreach ($items as $row) {
$curso = $row->curso_nombre;
$preguntasTotalesPorCurso[$curso] = ($preguntasTotalesPorCurso[$curso] ?? 0) + 1;
$correctasPorCurso[$curso] = $correctasPorCurso[$curso] ?? 0;
$incorrectasPorCurso[$curso] = $incorrectasPorCurso[$curso] ?? 0;
$nuevoEsCorrecta = 2; // 2 = blanco
$nuevoPuntaje = $puntosNula; // nula/blanco
if ($row->pa_estado === 'anulada') {
// anulada => nula
$nuevoEsCorrecta = 2;
$nuevoPuntaje = $puntosNula;
$totalNulas++;
} else {
$ru = trim((string) $row->respuesta_usuario);
$rc = trim((string) $row->respuesta_correcta);
if ($ru === '') {
// blanco
$nuevoEsCorrecta = 2;
$nuevoPuntaje = $puntosNula;
$totalNulas++;
} else {
$ruN = mb_strtoupper($ru);
$rcN = mb_strtoupper($rc);
if ($rcN !== '' && $ruN === $rcN) {
$nuevoEsCorrecta = 1;
$nuevoPuntaje = $puntosCorrecta;
$totalCorrectas++;
$correctasPorCurso[$curso]++;
} else {
$nuevoEsCorrecta = 0;
$nuevoPuntaje = $puntosIncorrecta;
$totalIncorrectas++;
$incorrectasPorCurso[$curso]++;
}
}
}
$totalPuntos += (float) $nuevoPuntaje;
DB::table('preguntas_asignadas')
->where('id', $row->pa_id)
->update([
'es_correcta' => $nuevoEsCorrecta,
'puntaje' => $nuevoPuntaje,
'updated_at' => now(),
]);
}
// 6) Resumen
$totalPreguntas = (int) $items->count();
$porcentajeCorrectas = $totalPreguntas > 0 ? ($totalCorrectas / $totalPreguntas) * 100 : 0;
$calificacionSobre20 = ($puntajeMaximo > 0)
? ($totalPuntos / $puntajeMaximo) * 20
: 0;
$correctasPorCursoFormato = [];
foreach ($correctasPorCurso as $curso => $corr) {
$y = $preguntasTotalesPorCurso[$curso] ?? 0;
$correctasPorCursoFormato[$curso] = "{$corr} de {$y}";
}
// 7) Guardar resultado en resultados_examenes
$resultadoId = DB::table('resultados_examenes')->insertGetId([
'postulante_id' => $postulante->id,
'examen_id' => $examen->id,
'total_puntos' => round($totalPuntos, 3),
'correctas_por_curso' => json_encode($correctasPorCursoFormato),
'incorrectas_por_curso' => json_encode($incorrectasPorCurso),
'preguntas_totales_por_curso' => json_encode($preguntasTotalesPorCurso),
'total_correctas' => $totalCorrectas,
'total_incorrectas' => $totalIncorrectas,
'total_nulas' => $totalNulas,
'porcentaje_correctas' => round($porcentajeCorrectas, 2),
'calificacion_sobre_20' => round($calificacionSobre20, 2),
'created_at' => now(),
'updated_at' => now(),
]);
// 8) Recalcular orden de mérito por proceso
$this->recalcularOrdenMerito($cfg->proceso_id);
// 9) Leer orden_merito ya asignado (opcional)
$orden = DB::table('resultados_examenes')->where('id', $resultadoId)->value('orden_merito');
DB::table('examenes')->where('id', $examen->id)->update([
'estado' => 'calificado',
'hora_fin' => now(),
]);
return response()->json([
'success' => true,
'mensaje' => 'Examen calificado exitosamente.',
'examen_id' => $examen->id,
'proceso_id' => $cfg->proceso_id,
'total_puntos' => round($totalPuntos, 2),
'total_correctas' => $totalCorrectas,
'total_incorrectas' => $totalIncorrectas,
'total_nulas' => $totalNulas,
'porcentaje_correctas' => round($porcentajeCorrectas, 2),
'calificacion_sobre_20' => round($calificacionSobre20, 2),
'orden_merito' => $orden,
'correctas_por_curso' => $correctasPorCursoFormato,
'incorrectas_por_curso' => $incorrectasPorCurso,
'preguntas_totales_por_curso' => $preguntasTotalesPorCurso,
]);
});
}
public function recalcularOrdenMerito($procesoId): void
{
DB::statement("
UPDATE resultados_examenes r
JOIN (
SELECT
r2.id,
ROW_NUMBER() OVER (
ORDER BY
r2.total_puntos DESC,
COALESCE(r2.updated_at, r2.created_at) ASC
) AS nuevo_orden
FROM resultados_examenes r2
JOIN examenes e ON e.id = r2.examen_id
JOIN area_proceso ap ON ap.id = e.area_proceso_id
WHERE ap.proceso_id = ?
) x ON x.id = r.id
SET r.orden_merito = x.nuevo_orden
", [$procesoId]);
}
}

@ -1,417 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Postulante;
use App\Models\ResultadoAdmision;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Http;
class PostulanteAuthController extends Controller
{
/**
* Registro de postulante (normal) con DNI
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255|regex:/^[\pL\s\-]+$/u',
'email' => 'required|email|unique:postulantes,email|max:255',
'password' => [
'required',
'string',
'min:8',
'confirmed',
'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/'
],
'dni' => 'required|string|max:20|unique:postulantes,dni',
], [
'password.regex' => 'La contraseña debe contener al menos una mayúscula, una minúscula, un número y un carácter especial.',
'name.regex' => 'El nombre solo puede contener letras y espacios.',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
$postulante = Postulante::create([
'name' => strip_tags(trim($request->name)),
'email' => strtolower(trim($request->email)),
'password' => $request->password,
'dni' => $request->dni,
]);
Log::info('Postulante registrado', ['id' => $postulante->id, 'dni' => $postulante->dni]);
return response()->json(['success' => true, 'message' => 'Postulante registrado exitosamente', 'postulante' => $postulante], 201);
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|max:255',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
}
$email = strtolower(trim($request->email));
$postulante = Postulante::where('email', $email)->first();
if (!$postulante || !Hash::check($request->password, $postulante->password)) {
Log::warning('Intento de login fallido', ['email' => $email]);
return response()->json([
'success' => false,
'message' => 'Credenciales inválidas'
], 401);
}
$deviceId = $request->header('Device-Id') ?? Str::random(10);
// Revocar tokens antiguos
$postulante->tokens()->delete();
// Crear token
$token = $postulante
->createToken($deviceId, ['*'], now()->addHour())
->plainTextToken;
$postulante->update([
'device_id' => $deviceId,
'last_activity' => now()
]);
Log::info('Login exitoso', ['id' => $postulante->id]);
return response()->json([
'success' => true,
'message' => 'Login exitoso',
'postulante' => [
'id' => $postulante->id,
'name' => $postulante->name,
'email' => $postulante->email,
'dni' => $postulante->dni
],
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => 3600
]);
}
/**
* Logout
*/
public function logout(Request $request)
{
$postulante = $request->user();
if ($postulante) {
$postulante->tokens()->delete();
$postulante->device_id = null;
$postulante->last_activity = null;
$postulante->save();
}
return response()->json(['success' => true, 'message' => 'Sesión cerrada correctamente']);
}
/**
* Información del postulante logueado
*/
public function me(Request $request)
{
$postulante = $request->user();
if (!$postulante) {
return response()->json(['success' => false, 'message' => 'No autenticado'], 401);
}
// Actualizar última actividad al hacer request
$postulante->update(['last_activity' => now()]);
return response()->json([
'success' => true,
'postulante' => [
'id' => $postulante->id,
'name' => $postulante->name,
'email' => $postulante->email,
'dni' => $postulante->dni
]
]);
}
public function obtenerPagosPostulante(Request $request)
{
$postulante = $request->user(); // o Auth::guard('postulante')->user();
if (!$postulante) {
return response()->json([
'success' => false,
'message' => 'No autenticado'
], 401);
}
$dni = trim($postulante->dni);
$pagos = [];
// // ===============================
// // 1⃣ PAGOS PYTO PERÚ
// // ===============================
// $urlPyto = "https://service2.unap.edu.pe/PAYMENTS_MNG/v1/{$dni}/8/";
// $responsePyto = Http::get($urlPyto);
// if ($responsePyto->successful()) {
// $dataPyto = $responsePyto->json();
// if (!empty($dataPyto['data'])) {
// foreach ($dataPyto['data'] as $pago) {
// $pagos[] = [
// 'tipo' => 'pyto_peru',
// 'codigo' => $pago['autorizationCode'] ?? null,
// 'monto' => $pago['total'] ?? null,
// 'fecha_pago' => $pago['confirmedDate'] ?? null,
// 'estado' => true,
// 'raw' => $pago // devuelve toda la info original
// ];
// }
// }
// }
// ===============================
// 2⃣ PAGOS CAJA
// ===============================
$urlCaja = "https://inscripciones.admision.unap.edu.pe/api/get-pagos-caja-dni/{$dni}";
$responseCaja = Http::get($urlCaja);
if ($responseCaja->successful()) {
$dataCaja = $responseCaja->json();
if (!empty($dataCaja)) {
foreach ($dataCaja as $pago) {
$pagos[] = [
'tipo' => 'caja',
'codigo' => $pago['paymentTitle'] ?? null,
'monto' => $pago['paymentAmount'] ?? null,
'fecha_pago' => $pago['paymentDatetime'] ?? null,
'estado' => true,
'raw' => $pago
];
}
}
}
// ===============================
// 3⃣ BANCO NACIÓN
// ===============================
$urlBanco = 'https://inscripciones.admision.unap.edu.pe/api/get-pagos-banco';
$responseBanco = Http::post($urlBanco, [
'dni' => $dni,
]);
if ($responseBanco->successful()) {
$dataBanco = $responseBanco->json();
if (!empty($dataBanco['datos'])) {
foreach ($dataBanco['datos'] as $pago) {
$pagos[] = [
'tipo' => 'banco_nacion',
'codigo' => $pago['secuencia'] ?? null,
'monto' => $pago['imp_pag'] ?? null,
'fecha_pago' => $pago['fch_pag'] ?? null,
'estado' => true,
'raw' => $pago
];
}
}
}
return response()->json([
'success' => true,
'postulante' => [
'id' => $postulante->id,
'name' => $postulante->name,
'dni' => $dni,
'email' => $postulante->email,
],
'total_pagos' => count($pagos),
'pagos' => $pagos
]);
}
public function misProcesos(Request $request)
{
$dni = $request->user()->dni;
$procesos = ResultadoAdmision::select(
'procesos_admision.id',
'procesos_admision.titulo',
'resultados_admision.puntaje',
'resultados_admision.apto'
)
->join('procesos_admision', 'procesos_admision.id', '=', 'resultados_admision.idproceso')
->where('resultados_admision.dni', $dni)
->distinct()
->get();
return response()->json([
'success' => true,
'data' => $procesos
]);
}
public function obtenerAvanceProcesoPostulante(Request $request, $idProceso)
{
$postulante = $request->user();
if (!$postulante) {
return response()->json([
'success' => false,
'message' => 'No autenticado'
], 401);
}
$dni = trim($postulante->dni);
if (!$dni) {
return response()->json([
'success' => false,
'message' => 'El postulante no tiene DNI registrado'
], 422);
}
$url = "https://inscripciones.admision.unap.edu.pe/api/get-avance-proceso-postulante/{$idProceso}/{$dni}";
try {
$response = Http::timeout(15)->get($url);
if (!$response->successful()) {
return response()->json([
'success' => false,
'message' => 'No se pudo obtener el avance del proceso',
'status_http' => $response->status(),
'error' => $response->json() ?? $response->body(),
], 502);
}
$payload = $response->json();
// Tu API externa devuelve: { estado: true/false, datos: {...} }
if (!isset($payload['estado']) || $payload['estado'] !== true) {
return response()->json([
'success' => false,
'message' => 'La API devolvió estado false',
'raw' => $payload
], 404);
}
$datos = $payload['datos'] ?? [];
return response()->json([
'success' => true,
'data' => [
'dni' => $datos['dni'] ?? $dni,
'id_proceso' => $datos['id_proceso'] ?? (int)$idProceso,
'avance' => $datos['avance'] ?? null,
'estado' => $datos['estado'] ?? null,
'observacion' => $datos['observacion'] ?? '',
],
'raw' => $payload, // si no lo quieres, elimínalo
]);
} catch (\Throwable $e) {
Log::error('Error al consultar avance del proceso', [
'idProceso' => $idProceso,
'dni' => $dni,
'error' => $e->getMessage(),
]);
return response()->json([
'success' => false,
'message' => 'Error interno consultando avance del proceso'
], 500);
}
}
public function miObservacion(Request $request)
{
$postulante = $request->user();
if (!$postulante) {
return response()->json([
'success' => false,
'message' => 'No autenticado'
], 401);
}
$dni = trim($postulante->dni);
if (!$dni) {
return response()->json([
'success' => false,
'message' => 'El postulante no tiene DNI registrado'
], 422);
}
$url = "https://test-admision.unap.edu.pe/service_observados/api/v1/observaciones/dni/{$dni}";
try {
$response = Http::timeout(15)->get($url);
if (!$response->successful()) {
return response()->json([
'success' => false,
'message' => 'No se pudo consultar observaciones',
'status_http' => $response->status(),
], 502);
}
$payload = $response->json();
// si no viene, asumimos false
$esObservado = (bool)($payload['es_observado'] ?? false);
// opcional: traer una observación "principal"
$detalle = null;
if (!empty($payload['observados']) && is_array($payload['observados'])) {
$o = $payload['observados'][0];
$detalle = [
'tipo_observacion' => $o['tipo_observacion'] ?? null,
'categoria' => $o['categoria'] ?? null,
'observaciones' => $o['observaciones'] ?? null,
'fecha_sancion' => $o['fecha_sancion'] ?? null,
'fecha_fin' => $o['fecha_fin'] ?? null,
];
}
return response()->json([
'success' => true,
'dni' => $dni,
'es_observado' => $esObservado,
'mensaje' => $esObservado
? 'Usted tiene una observación. Acérquese a la Dirección de Admisión para regularizar su situación.'
: 'Usted está apto para postular en este proceso.',
'detalle' => $detalle, // si no lo quieres, bórralo
]);
} catch (\Throwable $e) {
Log::error('Error consultando observaciones del postulante', [
'dni' => $dni,
'error' => $e->getMessage()
]);
return response()->json([
'success' => false,
'message' => 'Error interno consultando observaciones'
], 500);
}
}
}

@ -1,101 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\ProcesoAdmision;
use Illuminate\Support\Carbon;
use Illuminate\Http\Request;
class WebController extends Controller
{
public function GetProcesoAdmision()
{
$procesos = ProcesoAdmision::select(
'id',
'titulo',
'subtitulo',
'descripcion',
'slug',
'tipo_proceso',
'modalidad',
'publicado',
'fecha_publicacion',
'fecha_inicio_preinscripcion',
'fecha_fin_preinscripcion',
'fecha_inicio_inscripcion',
'fecha_fin_inscripcion',
'fecha_examen1',
'fecha_examen2',
'fecha_resultados',
'fecha_inicio_biometrico',
'fecha_fin_biometrico',
'imagen_path',
'banner_path',
'brochure_path',
'link_preinscripcion',
'link_inscripcion',
'link_resultados',
'link_reglamento',
'estado',
'created_at',
'updated_at'
)
->with([
'detalles' => function ($query) {
$query->select(
'id',
'proceso_admision_id',
'tipo',
'titulo_detalle',
'descripcion',
'listas',
'meta',
'url',
'imagen_path',
'imagen_path_2',
'created_at',
'updated_at'
);
}
])
->where('publicado', 1)
->latest()
->get();
return response()->json([
'success' => true,
'data' => $procesos
]);
}
public function obtenerProcesosDisponiblesPreinscripcion(Request $request)
{
$now = Carbon::now();
$postulante = $request->user();
$procesos = ProcesoAdmision::query()
->select([
'id',
'titulo',
'slug',
'link_preinscripcion',
'fecha_inicio_preinscripcion',
'fecha_fin_preinscripcion',
])
->where('publicado', 1)
->whereIn('estado', ['nuevo','publicado','en_proceso'])
->whereNotNull('link_preinscripcion')
->whereNotNull('fecha_inicio_preinscripcion')
->whereNotNull('fecha_fin_preinscripcion')
->where('fecha_inicio_preinscripcion', '<=', $now)
->where('fecha_fin_preinscripcion', '>=', $now)
->orderByDesc('fecha_inicio_preinscripcion')
->orderBy('titulo')
->get();
return response()->json([
'success' => true,
'data' => $procesos
]);
}
}

@ -1,59 +0,0 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* Global HTTP middleware stack.
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Http\Middleware\HandleCors::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*/
protected $middlewareGroups = [
'web' => [
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* Route middleware aliases.
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
// 🔥 SPATIE (ESTO ES LO IMPORTANTE)
'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
];
}

@ -1,38 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;
class CheckRole
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next, ...$roles): Response
{
$user = Auth::user();
if (!$user) {
return response()->json([
'success' => false,
'message' => 'No autenticado'
], 401);
}
// Verificar si el usuario tiene alguno de los roles requeridos
foreach ($roles as $role) {
if ($user->hasRole($role)) {
return $next($request);
}
}
return response()->json([
'success' => false,
'message' => 'No autorizado para esta acción'
], 403);
}
}

@ -1,20 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureTokenIsValid
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
return $next($request);
}
}

@ -1,103 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Area extends Model
{
use HasFactory;
protected $table = 'areas';
protected $fillable = [
'nombre',
'codigo',
'activo',
];
protected $casts = [
'activo' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
public function examenes()
{
return $this->belongsToMany(
Examen::class,
'examen_area',
'area_id',
'examen_id'
)->withTimestamps();
}
public function scopeActivas($query)
{
return $query->where('activo', true);
}
public function scopeInactivas($query)
{
return $query->where('activo', false);
}
public function scopePorCodigo($query, $codigo)
{
return $query->where('codigo', strtoupper($codigo));
}
public function scopePorNombre($query, $nombre)
{
return $query->where('nombre', 'like', "%{$nombre}%");
}
public function scopeDeAcademia($query, $academiaId)
{
return $query->where('academia_id', $academiaId);
}
/* ================= ACCESSORS ================= */
public function getEstadoAttribute()
{
return $this->activo ? 'Activo' : 'Inactivo';
}
public function getEstadisticasAttribute()
{
return [
'total_cursos' => $this->cursos()->count(),
'total_examenes' => $this->examenes()->count(),
];
}
public function getCursosCountAttribute()
{
return $this->cursos()->count();
}
public function getExamenesCountAttribute()
{
return $this->examenes()->count();
}
public function cursos()
{
return $this->belongsToMany(Curso::class, 'area_curso')->withTimestamps();
}
public function procesos()
{
return $this->belongsToMany(Proceso::class, 'area_proceso')
->withPivot('id')
->withTimestamps();
}
}

@ -1,26 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AreaAdmision extends Model
{
protected $table = 'areas_admision';
protected $fillable = [
'nombre',
'descripcion',
'estado'
];
protected $casts = [
'estado' => 'boolean'
];
public function resultados()
{
return $this->hasMany(ResultadoAdmision::class, 'idearea');
}
}

@ -1,26 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Calificacion extends Model
{
use HasFactory;
protected $table = 'calificaciones';
protected $fillable = [
'nombre',
'puntos_correcta',
'puntos_incorrecta',
'puntos_nula',
'puntaje_maximo',
];
public function procesos()
{
return $this->hasMany(Proceso::class);
}
}

@ -1,28 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comunicado extends Model
{
protected $fillable = [
'titulo',
'activo',
'fecha_inicio',
'fecha_fin',
'url_accion',
'texto_boton',
];
protected $casts = [
'activo' => 'boolean',
'fecha_inicio' => 'date',
'fecha_fin' => 'date',
];
public function imagenes(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(ComunicadoImagen::class)->orderBy('orden');
}
}

@ -1,35 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class ComunicadoImagen extends Model
{
protected $table = 'comunicado_imagenes';
protected $fillable = [
'comunicado_id',
'imagen_path',
'orden',
];
protected $casts = [
'orden' => 'integer',
];
protected $appends = ['imagen_url'];
public function getImagenUrlAttribute(): ?string
{
return $this->imagen_path
? Storage::disk('public')->url($this->imagen_path)
: null;
}
public function comunicado(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Comunicado::class);
}
}

@ -1,40 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Curso extends Model
{
use HasFactory;
protected $table = 'cursos';
protected $fillable = [
'nombre',
'codigo',
'activo',
];
protected $casts = [
'activo' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
public function areas()
{
return $this->belongsToMany(Area::class, 'area_curso')
->withTimestamps();
}
public function preguntas()
{
return $this->hasMany(Pregunta::class);
}
}

@ -1,76 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Examen extends Model
{
use HasFactory;
protected $table = 'examenes';
protected $fillable = [
'postulante_id',
'area_proceso_id',
'pagado',
'tipo_pago',
'pago_id',
'intentos',
'hora_inicio',
'estado',
'hora_fin',
];
protected $casts = [
'pagado' => 'boolean',
'hora_inicio' => 'datetime',
'hora_fin' => 'datetime',
];
public function postulante()
{
return $this->belongsTo(Postulante::class, 'postulante_id');
}
// public function area()
// {
// return $this->belongsTo(Area::class, 'area_id');
// }
public function areaProceso()
{
return $this->belongsTo(AreaProceso::class, 'area_proceso_id');
}
public function pago()
{
return $this->belongsTo(Pago::class, 'pago_id');
}
// Accesos rápidos opcionales
public function area()
{
return $this->hasOneThrough(
Area::class,
AreaProceso::class,
'id',
'id',
'area_proceso_id',
'area_id'
);
}
public function proceso()
{
return $this->areaProceso->proceso;
}
public function preguntasAsignadas()
{
return $this->hasMany(PreguntaAsignada::class, 'examen_id');
}
}

@ -1,66 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class Noticia extends Model
{
use SoftDeletes;
protected $table = 'noticias';
protected $fillable = [
'titulo',
'slug',
'descripcion_corta',
'contenido',
'categoria',
'tag_color',
'imagen_path',
'imagen_url', // ✅ agrega esto si también lo guardas en BD
'link_url',
'link_texto',
'fecha_publicacion',
'publicado',
'destacado',
'orden',
];
protected $casts = [
'fecha_publicacion' => 'datetime',
'publicado' => 'boolean',
'destacado' => 'boolean',
'orden' => 'integer',
];
// ✅ se incluirá en el JSON
protected $appends = ['imagen_url'];
public function getImagenUrlAttribute(): ?string
{
// 1) Si en BD hay una URL externa, úsala
if (!empty($this->attributes['imagen_url'])) {
return $this->attributes['imagen_url'];
}
// 2) Si hay imagen en storage, genera URL absoluta
if (!empty($this->imagen_path)) {
return url(Storage::disk('public')->url($this->imagen_path));
}
return null;
}
protected static function booted(): void
{
static::saving(function (Noticia $noticia) {
if (!$noticia->slug) {
$noticia->slug = Str::slug($noticia->titulo);
}
});
}
}

@ -1,23 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pago extends Model
{
use HasFactory;
protected $fillable = [
'postulante_id',
'tipo_pago',
'codigo_pago',
'monto',
'utilizado',
'original_date',
'confirmed_date',
'fecha_pago',
];
}

@ -1,42 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable; // Para usar login
use Laravel\Sanctum\HasApiTokens; // Para tokens API
use Illuminate\Notifications\Notifiable;
class Postulante extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $table = 'postulantes';
protected $fillable = [
'name',
'email',
'password',
'dni',
'device_id',
'last_activity'
];
protected $hidden = [
'password',
'device_id',
'tokens'
];
protected $casts = [
'last_activity' => 'datetime',
];
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
}

@ -1,62 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pregunta extends Model
{
use HasFactory;
protected $table = 'preguntas';
protected $fillable = [
'curso_id',
'enunciado',
'imagenes',
'enunciado_adicional',
'opciones',
'respuesta_correcta',
'explicacion',
'imagenes_explicacion',
'nivel_dificultad',
'activo',
];
protected $casts = [
'opciones' => 'array',
'imagenes' => 'array',
'imagenes_explicacion' => 'array',
'activo' => 'boolean',
];
public function curso()
{
return $this->belongsTo(Curso::class);
}
public function scopeActivas($query)
{
return $query->where('activo', true);
}
public function scopeDeCurso($query, $cursoId)
{
return $query->where('curso_id', $cursoId);
}
public function scopeBuscar($query, $texto)
{
return $query->where(function ($q) use ($texto) {
$q->where('enunciado', 'like', "%{$texto}%")
->orWhere('enunciado_adicional', 'like', "%{$texto}%")
->orWhere('explicacion', 'like', "%{$texto}%");
});
}
}

@ -1,39 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class PreguntaAsignada extends Model
{
protected $table = 'preguntas_asignadas';
protected $fillable = [
'examen_id',
'pregunta_id',
'orden',
'respuesta_usuario',
'es_correcta',
'estado',
'puntaje',
'respondida_at'
];
protected $casts = [
'es_correcta' => 'integer',
'puntaje' => 'decimal:2'
];
protected $dates = ['respondida_at'];
public function examen(): BelongsTo
{
return $this->belongsTo(Examen::class);
}
public function pregunta(): BelongsTo
{
return $this->belongsTo(Pregunta::class);
}
}

@ -1,125 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Proceso extends Model
{
use HasFactory;
protected $table = 'procesos';
protected $fillable = [
'nombre',
'descripcion',
'estado',
'duracion',
'intentos_maximos',
'requiere_pago',
'precio',
'calificacion_id',
'slug',
'tipo_simulacro',
'tipo_proceso',
'activo',
'publico',
'fecha_inicio',
'fecha_fin',
'tiempo_por_pregunta',
'cantidad_pregunta',
];
protected $casts = [
'requiere_pago' => 'boolean',
'activo' => 'boolean',
'publico' => 'boolean',
'duracion' => 'integer',
'intentos_maximos' => 'integer',
'tiempo_por_pregunta' => 'integer',
'precio' => 'decimal:2',
'fecha_inicio' => 'datetime',
'fecha_fin' => 'datetime',
];
// Examen → Calificación (opcional)
public function calificacion()
{
return $this->belongsTo(Calificacion::class);
}
/* =============================
| SCOPES
============================= */
public function scopeActivos($query)
{
return $query->where('activo', true);
}
public function scopePublicos($query)
{
return $query->where('publico', true);
}
public function scopePorProceso($query, $proceso)
{
return $query->where('tipo_proceso', $proceso);
}
/* =============================
| ACCESSORS
============================= */
public function getEstaDisponibleAttribute(): bool
{
$now = now();
if (!$this->activo) {
return false;
}
if ($this->fecha_inicio && $now->lt($this->fecha_inicio)) {
return false;
}
if ($this->fecha_fin && $now->gt($this->fecha_fin)) {
return false;
}
return true;
}
protected static function booted()
{
static::creating(function ($examen) {
if (empty($examen->slug)) {
$examen->slug = Str::slug($examen->nombre) . '-' . uniqid();
}
});
}
public function areas()
{
return $this->belongsToMany(
Area::class,
'area_proceso'
)
->withPivot('id')
->withTimestamps();
}
}

@ -1,77 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Storage;
class ProcesoAdmision extends Model
{
protected $table = 'procesos_admision';
protected $fillable = [
'titulo','subtitulo','descripcion','slug',
'tipo_proceso','modalidad',
'publicado','fecha_publicacion',
'fecha_inicio_preinscripcion','fecha_fin_preinscripcion',
'fecha_inicio_inscripcion','fecha_fin_inscripcion',
'fecha_examen1','fecha_examen2',
'fecha_resultados',
'fecha_inicio_biometrico','fecha_fin_biometrico',
'imagen_path','banner_path','brochure_path',
'link_preinscripcion','link_inscripcion','link_resultados','link_reglamento',
'estado',
];
protected $casts = [
'publicado' => 'boolean',
'fecha_publicacion' => 'datetime',
'fecha_inicio_preinscripcion' => 'datetime',
'fecha_fin_preinscripcion' => 'datetime',
'fecha_inicio_inscripcion' => 'datetime',
'fecha_fin_inscripcion' => 'datetime',
'fecha_examen1' => 'datetime',
'fecha_examen2' => 'datetime',
'fecha_resultados' => 'datetime',
'fecha_inicio_biometrico' => 'datetime',
'fecha_fin_biometrico' => 'datetime',
];
protected $appends = ['imagen_url','banner_url','brochure_url'];
public function detalles(): HasMany
{
return $this->hasMany(ProcesoAdmisionDetalle::class, 'proceso_admision_id');
}
public function getImagenUrlAttribute(): ?string
{
return $this->imagen_path ? Storage::disk('public')->url($this->imagen_path) : null;
}
public function getBannerUrlAttribute(): ?string
{
return $this->banner_path ? Storage::disk('public')->url($this->banner_path) : null;
}
public function getBrochureUrlAttribute(): ?string
{
return $this->brochure_path ? Storage::disk('public')->url($this->brochure_path) : null;
}
public function resultados()
{
return $this->hasMany(ResultadoAdmision::class, 'idproceso');
}
public function resultadoArchivos()
{
return $this->hasMany(ProcesoAdmisionResultadoArchivo::class, 'proceso_admision_id')
->orderBy('orden');
}
}

@ -1,46 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
class ProcesoAdmisionDetalle extends Model
{
protected $table = 'proceso_admision_detalles';
protected $fillable = [
'proceso_admision_id',
'tipo',
'titulo_detalle',
'descripcion',
'listas',
'meta',
'url',
'imagen_path',
'imagen_path_2',
];
protected $casts = [
'listas' => 'array',
'meta' => 'array',
];
protected $appends = ['imagen_url','imagen_url_2'];
public function proceso(): BelongsTo
{
return $this->belongsTo(ProcesoAdmision::class, 'proceso_admision_id');
}
public function getImagenUrlAttribute(): ?string
{
return $this->imagen_path ? Storage::disk('public')->url($this->imagen_path) : null;
}
public function getImagenUrl2Attribute(): ?string
{
return $this->imagen_path_2 ? Storage::disk('public')->url($this->imagen_path_2) : null;
}
}

@ -1,36 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class ProcesoAdmisionResultadoArchivo extends Model
{
protected $table = 'proceso_admision_resultado_archivos';
protected $fillable = [
'proceso_admision_id',
'nombre',
'file_path',
'orden',
];
protected $casts = [
'orden' => 'integer',
];
protected $appends = ['archivo_url'];
public function getArchivoUrlAttribute(): ?string
{
return $this->file_path
? Storage::disk('public')->url($this->file_path)
: null;
}
public function proceso(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(ProcesoAdmision::class, 'proceso_admision_id');
}
}

@ -1,32 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ReglaAreaProceso extends Model
{
use HasFactory;
protected $table = 'reglas_area_proceso';
protected $fillable = [
'area_proceso_id',
'curso_id',
'cantidad_preguntas',
'orden',
'nivel_dificultad',
'ponderacion',
];
public function areaProceso()
{
return $this->belongsTo(AreaProceso::class);
}
public function curso()
{
return $this->belongsTo(Curso::class);
}
}

@ -1,57 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ResultadoAdmision extends Model
{
protected $table = 'resultados_admision';
protected $fillable = [
'dni',
'paterno',
'materno',
'nombres',
'puntaje',
'vocacional',
'apto',
'obs',
'desprograma',
'idproceso',
'idearea',
'litho',
'numlectura',
'tipo',
'calificar',
'aula',
'respuestas',
'puesto'
];
protected $casts = [
'puntaje' => 'decimal:2',
'vocacional' => 'decimal:2',
'desprograma' => 'boolean',
'calificar' => 'boolean',
'respuestas' => 'array'
];
public function proceso()
{
return $this->belongsTo(ProcesoAdmision::class, 'idproceso');
}
public function area()
{
return $this->belongsTo(AreaAdmision::class, 'idearea');
}
public function detalleCursos()
{
return $this->hasOne(ResultadoAdmisionCarga::class, 'dni', 'dni')
->whereColumn('idproceso', 'resultados_admision.idproceso')
->whereColumn('idearea', 'resultados_admision.idearea');
}
}

@ -1,126 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ResultadoAdmisionCarga extends Model
{
protected $table = 'resultados_admision_carga';
protected $primaryKey = 'id';
public $timestamps = false;
protected $guarded = [];
protected $casts = [
'puntaje_total' => 'decimal:2',
'puesto' => 'integer',
'correctas_aritmetica' => 'integer',
'blancas_aritmetica' => 'integer',
'puntaje_aritmetica' => 'decimal:2',
'porcentaje_aritmetica' => 'decimal:2',
'correctas_algebra' => 'integer',
'blancas_algebra' => 'integer',
'puntaje_algebra' => 'decimal:2',
'porcentaje_algebra' => 'decimal:2',
'correctas_geometria' => 'integer',
'blancas_geometria' => 'integer',
'puntaje_geometria' => 'decimal:2',
'porcentaje_geometria' => 'decimal:2',
'correctas_trigonometria' => 'integer',
'blancas_trigonometria' => 'integer',
'puntaje_trigonometria' => 'decimal:2',
'porcentaje_trigonometria' => 'decimal:2',
'correctas_fisica' => 'integer',
'blancas_fisica' => 'integer',
'puntaje_fisica' => 'decimal:2',
'porcentaje_fisica' => 'decimal:2',
'correctas_quimica' => 'integer',
'blancas_quimica' => 'integer',
'puntaje_quimica' => 'decimal:2',
'porcentaje_quimica' => 'decimal:2',
'correctas_biologia_anatomia' => 'integer',
'blancas_biologia_anatomia' => 'integer',
'puntaje_biologia_anatomia' => 'decimal:2',
'porcentaje_biologia_anatomia' => 'decimal:2',
'correctas_psicologia_filosofia' => 'integer',
'blancas_psicologia_filosofia' => 'integer',
'puntaje_psicologia_filosofia' => 'decimal:2',
'porcentaje_psicologia_filosofia' => 'decimal:2',
'correctas_geografia' => 'integer',
'blancas_geografia' => 'integer',
'puntaje_geografia' => 'decimal:2',
'porcentaje_geografia' => 'decimal:2',
'correctas_historia' => 'integer',
'blancas_historia' => 'integer',
'puntaje_historia' => 'decimal:2',
'porcentaje_historia' => 'decimal:2',
'correctas_educacion_civica' => 'integer',
'blancas_educacion_civica' => 'integer',
'puntaje_educacion_civica' => 'decimal:2',
'porcentaje_educacion_civica' => 'decimal:2',
'correctas_economia' => 'integer',
'blancas_economia' => 'integer',
'puntaje_economia' => 'decimal:2',
'porcentaje_economia' => 'decimal:2',
'correctas_comunicacion' => 'integer',
'blancas_comunicacion' => 'integer',
'puntaje_comunicacion' => 'decimal:2',
'porcentaje_comunicacion' => 'decimal:2',
'correctas_literatura' => 'integer',
'blancas_literatura' => 'integer',
'puntaje_literatura' => 'decimal:2',
'porcentaje_literatura' => 'decimal:2',
'correctas_razonamiento_matematico' => 'integer',
'blancas_razonamiento_matematico' => 'integer',
'puntaje_razonamiento_matematico' => 'decimal:2',
'porcentaje_razonamiento_matematico' => 'decimal:2',
'correctas_razonamiento_verbal' => 'integer',
'blancas_razonamiento_verbal' => 'integer',
'puntaje_razonamiento_verbal' => 'decimal:2',
'porcentaje_razonamiento_verbal' => 'decimal:2',
'correctas_ingles' => 'integer',
'blancas_ingles' => 'integer',
'puntaje_ingles' => 'decimal:2',
'porcentaje_ingles' => 'decimal:2',
'correctas_quechua_aimara' => 'integer',
'blancas_quechua_aimara' => 'integer',
'puntaje_quechua_aimara' => 'decimal:2',
'porcentaje_quechua_aimara' => 'decimal:2',
];
public function proceso()
{
return $this->belongsTo(ProcesoAdmision::class, 'idproceso');
}
public function area()
{
return $this->belongsTo(AreaAdmision::class, 'idearea');
}
}

@ -1,37 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ResultadoExamen extends Model
{
protected $table = 'resultados_examenes';
protected $fillable = [
'postulante_id',
'examen_id',
'total_puntos',
'correctas_por_curso',
'incorrectas_por_curso',
'preguntas_totales_por_curso',
'total_correctas',
'total_incorrectas',
'total_nulas',
'porcentaje_correctas',
'calificacion_sobre_20',
'orden_merito',
'probabilidad_ingreso',
'programa_recomendado',
];
public function postulante()
{
return $this->belongsTo(Postulante::class);
}
public function examen()
{
return $this->belongsTo(Examen::class);
}
}

@ -1,72 +0,0 @@
<?php
namespace App\Models;
use Laravel\Sanctum\HasApiTokens;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use App\Models\Academia;
use App\Models\IntentoExamen;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasApiTokens, HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
// 👇 RELACIÓN CLAVE
public function academias()
{
return $this->belongsToMany(
Academia::class,
'academia_user',
'user_id',
'academia_id'
)->withTimestamps();
}
public function intentosExamen()
{
return $this->hasMany(IntentoExamen::class, 'user_id', 'id');
}
public function academia()
{
return $this->hasOne(Academia::class, 'superadmin_id');
}
}

@ -1,24 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

@ -1,170 +0,0 @@
<?php
namespace App\Services;
use App\Models\Examen;
use App\Models\Pregunta;
use App\Models\ReglaAreaProceso;
use App\Models\PreguntaAsignada;
use Illuminate\Support\Facades\DB;
class ExamenService
{
/**
* Generar preguntas según reglas
*/
public function generarPreguntasExamen(Examen $examen): array
{
if ($examen->preguntasAsignadas()->exists()) {
return [
'success' => false,
'message' => 'El examen ya tiene preguntas'
];
}
$reglas = ReglaAreaProceso::where('area_proceso_id', $examen->area_proceso_id)
->orderBy('orden')
->get();
if ($reglas->isEmpty()) {
return [
'success' => false,
'message' => 'No hay reglas configuradas'
];
}
DB::beginTransaction();
try {
$orden = 1;
foreach ($reglas as $regla) {
$preguntas = Pregunta::where('curso_id', $regla->curso_id)
->where('activo', 1)
// ✅ sin filtro por nivel_dificultad (trae todo)
->inRandomOrder()
->limit($regla->cantidad_preguntas)
->get();
if ($preguntas->count() < $regla->cantidad_preguntas) {
throw new \Exception("Preguntas insuficientes para curso {$regla->curso_id}");
}
foreach ($preguntas as $pregunta) {
PreguntaAsignada::create([
'examen_id' => $examen->id,
'pregunta_id' => $pregunta->id,
'orden' => $orden++,
'puntaje_base' => $regla->ponderacion,
'estado' => 'pendiente',
]);
}
}
DB::commit();
return ['success' => true];
} catch (\Throwable $e) {
DB::rollBack();
return ['success' => false, 'message' => $e->getMessage()];
}
}
public function obtenerPreguntasExamen(Examen $examen): array
{
// Traemos preguntas con curso
$preguntas = $examen->preguntasAsignadas()
->with('pregunta.curso')
->get()
->sortBy('orden');
// Traemos datos del área-proceso directamente desde la DB
$areaProceso = \DB::table('area_proceso')
->join('procesos', 'area_proceso.proceso_id', '=', 'procesos.id')
->join('areas', 'area_proceso.area_id', '=', 'areas.id')
->where('area_proceso.id', $examen->area_proceso_id)
->select(
'procesos.nombre as proceso_nombre',
'procesos.duracion as proceso_duracion',
'procesos.intentos_maximos as proceso_intentos_maximos',
'areas.nombre as area_nombre'
)
->first();
return $preguntas->map(fn($pa) => [
'id' => $pa->id,
'orden' => $pa->orden,
'enunciado' => $pa->pregunta->enunciado,
'extra' => $pa->pregunta->enunciado_adicional,
'opciones' => $this->mezclarOpciones($pa->pregunta->opciones),
'imagenes' => $pa->pregunta->imagenes,
'estado' => $pa->estado,
'respuesta' => $pa->pregunta->respuesta_correcta,
'curso' => $pa->pregunta->curso->nombre ?? null,
'proceso' => $areaProceso->proceso_nombre ?? null,
'duracion' => $areaProceso->proceso_duracion ?? null,
'intentos_maximos'=> $areaProceso->proceso_intentos_maximos ?? null,
'area' => $areaProceso->area_nombre ?? null
])->values()->toArray();
}
public function guardarRespuesta(PreguntaAsignada $pa, ?string $respuesta): array
{
if ($pa->estado === 'respondida') {
return ['success' => false, 'message' => 'Ya respondida'];
}
// 🔹 Si está en blanco
if (empty($respuesta)) {
$pa->update([
'respuesta_usuario' => null,
'es_correcta' => 2, // 2 = blanco
'puntaje_obtenido' => 0,
'estado' => 'respondida',
'respondida_at' => now()
]);
return [
'success' => true,
'correcta' => 2,
'puntaje' => 0
];
}
// 🔹 Si respondió algo
$esCorrecta = $respuesta === $pa->pregunta->respuesta_correcta;
$pa->update([
'respuesta_usuario' => $respuesta,
'es_correcta' => $esCorrecta ? 1 : 0,
'puntaje_obtenido' => $esCorrecta ? $pa->puntaje_base : 0,
'estado' => 'respondida',
'respondida_at' => now()
]);
return [
'success' => true,
'correcta' => $esCorrecta ? 1 : 0,
'puntaje' => $pa->puntaje_obtenido
];
}
private function mezclarOpciones(?array $opciones): array
{
if (!$opciones) return [];
$keys = array_keys($opciones);
shuffle($keys);
return array_map(fn ($k) => [
'key' => $k,
'texto' => $opciones[$k]
], $keys);
}
}

@ -1,18 +0,0 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

@ -1,29 +0,0 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// ✅ ALIAS DE MIDDLEWARE (REEMPLAZA Kernel)
$middleware->alias([
'role' => RoleMiddleware::class,
'permission' => PermissionMiddleware::class,
'role_or_permission' => RoleOrPermissionMiddleware::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})
->create();

@ -1,2 +0,0 @@
*
!.gitignore

@ -1,5 +0,0 @@
<?php
return [
App\Providers\AppServiceProvider::class,
];

@ -1,92 +0,0 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": [
"laravel",
"framework"
],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"laravel/sanctum": "^4.2",
"laravel/tinker": "^2.10.1",
"simplesoftwareio/simple-qrcode": "^4.2",
"spatie/laravel-permission": "^6.24"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.3"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"npm run dev\" --names='server,queue,vite'"
],
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8691
back/composer.lock generated

File diff suppressed because it is too large Load Diff

@ -1,126 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'America/Lima',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

@ -1,125 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'postulante' => [
'driver' => 'sanctum',
'provider' => 'postulantes',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
'postulantes' => [
'driver' => 'eloquent',
'model' => App\Models\Postulante::class,
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

@ -1,117 +0,0 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
];

@ -1,183 +0,0 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];

@ -1,80 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

@ -1,132 +0,0 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

@ -1,118 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
];

@ -1,202 +0,0 @@
<?php
return [
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => Spatie\Permission\Models\Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => Spatie\Permission\Models\Role::class,
],
'table_names' => [
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'roles' => 'roles',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your permissions. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'permissions' => 'permissions',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your models permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_permissions' => 'model_has_permissions',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your models roles. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_roles' => 'model_has_roles',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'role_has_permissions' => 'role_has_permissions',
],
'column_names' => [
/*
* Change this if you want to name the related pivots other than defaults
*/
'role_pivot_key' => null, // default 'role_id',
'permission_pivot_key' => null, // default 'permission_id',
/*
* Change this if you want to name the related model primary key other than
* `model_id`.
*
* For example, this would be nice if your primary keys are all UUIDs. In
* that case, name this `model_uuid`.
*/
'model_morph_key' => 'model_id',
/*
* Change this if you want to use the teams feature and your related model's
* foreign key is other than `team_id`.
*/
'team_foreign_key' => 'team_id',
],
/*
* When set to true, the method for checking permissions will be registered on the gate.
* Set this to false if you want to implement custom logic for checking permissions.
*/
'register_permission_check_method' => true,
/*
* When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered
* this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated
* NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it.
*/
'register_octane_reset_listener' => false,
/*
* Events will fire when a role or permission is assigned/unassigned:
* \Spatie\Permission\Events\RoleAttached
* \Spatie\Permission\Events\RoleDetached
* \Spatie\Permission\Events\PermissionAttached
* \Spatie\Permission\Events\PermissionDetached
*
* To enable, set to true, and then create listeners to watch these events.
*/
'events_enabled' => false,
/*
* Teams Feature.
* When set to true the package implements teams using the 'team_foreign_key'.
* If you want the migrations to register the 'team_foreign_key', you must
* set this to true before doing the migration.
* If you already did the migration then you must make a new migration to also
* add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions'
* (view the latest version of this package's migration file)
*/
'teams' => false,
/*
* The class to use to resolve the permissions team id
*/
'team_resolver' => \Spatie\Permission\DefaultTeamResolver::class,
/*
* Passport Client Credentials Grant
* When set to true the package will use Passports Client to check permissions
*/
'use_passport_client_credentials' => false,
/*
* When set to true, the required permission names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_permission_in_exception' => false,
/*
* When set to true, the required role names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_role_in_exception' => false,
/*
* By default wildcard permission lookups are disabled.
* See documentation to understand supported syntax.
*/
'enable_wildcard_permission' => false,
/*
* The class to use for interpreting wildcard permissions.
* If you need to modify delimiters, override the class and specify its name here.
*/
// 'wildcard_permission' => Spatie\Permission\WildcardPermission::class,
/* Cache-specific settings */
'cache' => [
/*
* By default all permissions are cached for 24 hours to speed up performance.
* When permissions or roles are updated the cache is flushed automatically.
*/
'expiration_time' => \DateInterval::createFromDateString('24 hours'),
/*
* The cache key used to store all permissions.
*/
'key' => 'spatie.permission.cache',
/*
* You may optionally indicate a specific cache driver to use for permission and
* role caching using any of the `store` drivers listed in the cache.php config
* file. Using 'default' here means to use the `default` set in cache.php.
*/
'store' => 'default',
],
];

@ -1,129 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

@ -1,84 +0,0 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],
];

@ -1,38 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

@ -1,217 +0,0 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];

@ -1 +0,0 @@
*.sqlite*

@ -1,44 +0,0 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

@ -1,49 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

@ -1,35 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

@ -1,57 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

@ -1,33 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

@ -1,134 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$teams = config('permission.teams');
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';
$pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), Exception::class, 'Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
Schema::create($tableNames['permissions'], static function (Blueprint $table) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // permission id
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
$table->unique(['name', 'guard_name']);
});
Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
$table->unsignedBigInteger($pivotPermission);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
$table->unsignedBigInteger($pivotRole);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
$table->unsignedBigInteger($pivotPermission);
$table->unsignedBigInteger($pivotRole);
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$tableNames = config('permission.table_names');
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
Schema::drop($tableNames['role_has_permissions']);
Schema::drop($tableNames['model_has_roles']);
Schema::drop($tableNames['model_has_permissions']);
Schema::drop($tableNames['roles']);
Schema::drop($tableNames['permissions']);
}
};

@ -1,29 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('proceso_admision_resultado_archivos', function (Blueprint $table) {
$table->id();
$table->foreignId('proceso_admision_id')
->constrained('procesos_admision')
->onDelete('cascade');
$table->string('nombre');
$table->string('file_path');
$table->unsignedTinyInteger('orden');
$table->timestamps();
$table->unique(['proceso_admision_id', 'orden'], 'uniq_proceso_orden');
});
}
public function down(): void
{
Schema::dropIfExists('proceso_admision_resultado_archivos');
}
};

@ -1,25 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('comunicados', function (Blueprint $table) {
$table->id();
$table->string('titulo');
$table->boolean('activo')->default(false);
$table->date('fecha_inicio')->nullable();
$table->date('fecha_fin')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('comunicados');
}
};

@ -1,24 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('comunicado_imagenes', function (Blueprint $table) {
$table->id();
$table->foreignId('comunicado_id')->constrained('comunicados')->cascadeOnDelete();
$table->string('imagen_path');
$table->integer('orden')->default(1);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('comunicado_imagenes');
}
};

@ -1,23 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('comunicados', function (Blueprint $table) {
$table->string('url_accion')->nullable()->after('fecha_fin');
$table->string('texto_boton')->nullable()->after('url_accion');
});
}
public function down(): void
{
Schema::table('comunicados', function (Blueprint $table) {
$table->dropColumn(['url_accion', 'texto_boton']);
});
}
};

@ -1,27 +0,0 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
$this->call([
RoleSeeder::class,
]);
User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
]);
}
}

@ -1,58 +0,0 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;
class RoleSeeder extends Seeder
{
public function run(): void
{
// 🔥 Limpiar cache de permisos para evitar conflictos
app()[PermissionRegistrar::class]->forgetCachedPermissions();
/* ================= PERMISOS ================= */
$permissions = [
// Ejemplo: CRUD de preguntas
'ver-preguntas',
'crear-preguntas',
'editar-preguntas',
'eliminar-preguntas',
// Ejemplo: CRUD de cursos
'ver-cursos',
'crear-cursos',
'editar-cursos',
'eliminar-cursos',
];
foreach ($permissions as $permission) {
Permission::firstOrCreate([
'name' => $permission,
'guard_name' => 'web',
]);
}
/* ================= ROLES ================= */
$roles = [
'usuario' => [], // rol básico sin permisos
'administrador' => $permissions, // asigna todos los permisos al administrador
'superadmin' => $permissions, // opcionalmente igual que administrador
];
foreach ($roles as $roleName => $rolePermissions) {
$role = Role::firstOrCreate([
'name' => $roleName,
'guard_name' => 'web',
]);
// Asignar permisos si los hay
if (!empty($rolePermissions)) {
$role->syncPermissions($rolePermissions);
}
}
}
}

3532
back/package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -1,17 +0,0 @@
{
"$schema": "https://www.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"axios": "^1.11.0",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0",
"vite": "^7.0.7"
}
}

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/>
</php>
</phpunit>

@ -1,25 +0,0 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

@ -1,20 +0,0 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());

@ -1,2 +0,0 @@
User-agent: *
Disallow:

@ -1,11 +0,0 @@
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save