FASE 1 COMPLETADA: Fundamentos y Core del Backend

- API REST completa con Node.js + Express + TypeScript
- Autenticación JWT con roles (Player/Admin)
- CRUD completo de canchas
- Sistema de reservas con validaciones
- Base de datos SQLite con Prisma ORM
- Notificaciones por email (Nodemailer)
- Seed de datos de prueba
- Documentación de arquitectura

Endpoints implementados:
- Auth: register, login, refresh, me
- Courts: CRUD + disponibilidad
- Bookings: CRUD + confirmación/cancelación

Credenciales de prueba:
- admin@padel.com / admin123
- user@padel.com / user123
This commit is contained in:
2026-01-31 08:11:53 +00:00
parent a83f4f39e9
commit b558372810
35 changed files with 7428 additions and 10 deletions

BIN
backend/prisma/dev.db Normal file

Binary file not shown.

View File

@@ -0,0 +1,82 @@
-- CreateTable
CREATE TABLE "users" (
"id" TEXT NOT NULL PRIMARY KEY,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"firstName" TEXT NOT NULL,
"lastName" TEXT NOT NULL,
"phone" TEXT,
"avatarUrl" TEXT,
"role" TEXT NOT NULL DEFAULT 'PLAYER',
"playerLevel" TEXT NOT NULL DEFAULT 'BEGINNER',
"handPreference" TEXT NOT NULL DEFAULT 'RIGHT',
"positionPreference" TEXT NOT NULL DEFAULT 'BOTH',
"bio" TEXT,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"isVerified" BOOLEAN NOT NULL DEFAULT false,
"lastLogin" DATETIME,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
-- CreateTable
CREATE TABLE "courts" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT NOT NULL,
"description" TEXT,
"type" TEXT NOT NULL DEFAULT 'PANORAMIC',
"isIndoor" BOOLEAN NOT NULL DEFAULT false,
"hasLighting" BOOLEAN NOT NULL DEFAULT true,
"hasParking" BOOLEAN NOT NULL DEFAULT false,
"pricePerHour" INTEGER NOT NULL DEFAULT 2000,
"imageUrl" TEXT,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
-- CreateTable
CREATE TABLE "court_schedules" (
"id" TEXT NOT NULL PRIMARY KEY,
"dayOfWeek" INTEGER NOT NULL,
"openTime" TEXT NOT NULL,
"closeTime" TEXT NOT NULL,
"priceOverride" INTEGER,
"courtId" TEXT NOT NULL,
CONSTRAINT "court_schedules_courtId_fkey" FOREIGN KEY ("courtId") REFERENCES "courts" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "bookings" (
"id" TEXT NOT NULL PRIMARY KEY,
"date" DATETIME NOT NULL,
"startTime" TEXT NOT NULL,
"endTime" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'PENDING',
"totalPrice" INTEGER NOT NULL,
"notes" TEXT,
"userId" TEXT NOT NULL,
"courtId" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
CONSTRAINT "bookings_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "bookings_courtId_fkey" FOREIGN KEY ("courtId") REFERENCES "courts" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
-- CreateIndex
CREATE UNIQUE INDEX "courts_name_key" ON "courts"("name");
-- CreateIndex
CREATE UNIQUE INDEX "court_schedules_courtId_dayOfWeek_key" ON "court_schedules"("courtId", "dayOfWeek");
-- CreateIndex
CREATE INDEX "bookings_userId_idx" ON "bookings"("userId");
-- CreateIndex
CREATE INDEX "bookings_courtId_idx" ON "bookings"("courtId");
-- CreateIndex
CREATE INDEX "bookings_date_idx" ON "bookings"("date");

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "sqlite"

View File

@@ -0,0 +1,131 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
// Modelo de Usuario
model User {
id String @id @default(uuid())
email String @unique
password String
// Datos personales
firstName String
lastName String
phone String?
avatarUrl String?
// Datos de juego (usamos String para simular enums en SQLite)
role String @default("PLAYER") // PLAYER, ADMIN, SUPERADMIN
playerLevel String @default("BEGINNER") // BEGINNER, ELEMENTARY, INTERMEDIATE, ADVANCED, COMPETITION, PROFESSIONAL
handPreference String @default("RIGHT") // RIGHT, LEFT, BOTH
positionPreference String @default("BOTH") // DRIVE, BACKHAND, BOTH
bio String?
// Estado
isActive Boolean @default(true)
isVerified Boolean @default(false)
lastLogin DateTime?
// Relaciones
bookings Booking[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("users")
}
// Modelo de Cancha
model Court {
id String @id @default(uuid())
name String @unique
description String?
// Características
type String @default("PANORAMIC") // PANORAMIC, OUTDOOR, INDOOR, SINGLE
isIndoor Boolean @default(false)
hasLighting Boolean @default(true)
hasParking Boolean @default(false)
// Precio por hora (en centavos para evitar decimales)
pricePerHour Int @default(2000)
// Imagen
imageUrl String?
// Estado
isActive Boolean @default(true)
// Relaciones
bookings Booking[]
schedules CourtSchedule[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("courts")
}
// Modelo de Horarios de Cancha (días y horas de operación)
model CourtSchedule {
id String @id @default(uuid())
// Día de la semana (0=Domingo, 1=Lunes, ..., 6=Sábado)
dayOfWeek Int
// Horario
openTime String
closeTime String
// Precio especial para esta franja (opcional)
priceOverride Int?
// Relación
court Court @relation(fields: [courtId], references: [id], onDelete: Cascade)
courtId String
@@unique([courtId, dayOfWeek])
@@map("court_schedules")
}
// Modelo de Reserva
model Booking {
id String @id @default(uuid())
// Fecha y hora
date DateTime
startTime String
endTime String
// Estado (PENDING, CONFIRMED, CANCELLED, COMPLETED, NO_SHOW)
status String @default("PENDING")
// Precio
totalPrice Int
// Notas
notes String?
// Relaciones
user User @relation(fields: [userId], references: [id])
userId String
court Court @relation(fields: [courtId], references: [id])
courtId String
// Timestamps
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([userId])
@@index([courtId])
@@index([date])
@@map("bookings")
}

121
backend/prisma/seed.ts Normal file
View File

@@ -0,0 +1,121 @@
import { PrismaClient } from '@prisma/client';
import { hashPassword } from '../src/utils/password';
import { UserRole, PlayerLevel, CourtType } from '../src/utils/constants';
const prisma = new PrismaClient();
async function main() {
console.log('🌱 Seeding database...');
// Crear usuario admin
const adminPassword = await hashPassword('admin123');
const admin = await prisma.user.upsert({
where: { email: 'admin@padel.com' },
update: {},
create: {
email: 'admin@padel.com',
password: adminPassword,
firstName: 'Admin',
lastName: 'Sistema',
role: UserRole.ADMIN,
playerLevel: PlayerLevel.PROFESSIONAL,
isActive: true,
},
});
console.log('✅ Admin creado:', admin.email);
// Crear usuario de prueba
const userPassword = await hashPassword('user123');
const user = await prisma.user.upsert({
where: { email: 'user@padel.com' },
update: {},
create: {
email: 'user@padel.com',
password: userPassword,
firstName: 'Juan',
lastName: 'García',
role: UserRole.PLAYER,
playerLevel: PlayerLevel.INTERMEDIATE,
isActive: true,
},
});
console.log('✅ Usuario creado:', user.email);
// Crear canchas
const courts = [
{
name: 'Cancha 1 - Panorámica',
description: 'Cancha panorámica premium con cristal 360°',
type: CourtType.PANORAMIC,
isIndoor: true,
hasLighting: true,
pricePerHour: 2500,
},
{
name: 'Cancha 2 - Panorámica',
description: 'Cancha panorámica premium con cristal 360°',
type: CourtType.PANORAMIC,
isIndoor: true,
hasLighting: true,
pricePerHour: 2500,
},
{
name: 'Cancha 3 - Exterior',
description: 'Cancha exterior con iluminación nocturna',
type: CourtType.OUTDOOR,
isIndoor: false,
hasLighting: true,
pricePerHour: 2000,
},
{
name: 'Cancha 4 - Cubierta',
description: 'Cancha cubierta sin cristal',
type: CourtType.INDOOR,
isIndoor: true,
hasLighting: true,
pricePerHour: 2200,
},
];
for (const courtData of courts) {
const court = await prisma.court.upsert({
where: { name: courtData.name },
update: {},
create: courtData,
});
console.log('✅ Cancha creada:', court.name);
// Crear horarios para cada cancha (Lunes a Domingo, 8:00 - 23:00)
for (let day = 0; day <= 6; day++) {
await prisma.courtSchedule.upsert({
where: {
courtId_dayOfWeek: {
courtId: court.id,
dayOfWeek: day,
},
},
update: {},
create: {
courtId: court.id,
dayOfWeek: day,
openTime: '08:00',
closeTime: '23:00',
},
});
}
}
console.log('\n🎾 Database seeded successfully!');
console.log('\nCredenciales de prueba:');
console.log(' Admin: admin@padel.com / admin123');
console.log(' User: user@padel.com / user123');
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});