New booking dashboard
This commit is contained in:
@@ -11,6 +11,7 @@ enum DayOfWeek {
|
|||||||
enum CourtBookingStatus {
|
enum CourtBookingStatus {
|
||||||
CONFIRMED
|
CONFIRMED
|
||||||
CANCELLED
|
CANCELLED
|
||||||
|
COMPLETED
|
||||||
}
|
}
|
||||||
|
|
||||||
model Sport {
|
model Sport {
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TYPE "CourtBookingStatus" ADD VALUE 'COMPLETED';
|
||||||
@@ -31,7 +31,8 @@ export type DayOfWeek = (typeof DayOfWeek)[keyof typeof DayOfWeek]
|
|||||||
|
|
||||||
export const CourtBookingStatus = {
|
export const CourtBookingStatus = {
|
||||||
CONFIRMED: 'CONFIRMED',
|
CONFIRMED: 'CONFIRMED',
|
||||||
CANCELLED: 'CANCELLED'
|
CANCELLED: 'CANCELLED',
|
||||||
|
COMPLETED: 'COMPLETED'
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
export type CourtBookingStatus = (typeof CourtBookingStatus)[keyof typeof CourtBookingStatus]
|
export type CourtBookingStatus = (typeof CourtBookingStatus)[keyof typeof CourtBookingStatus]
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,40 @@
|
|||||||
|
import { zValidator } from '@hono/zod-validator'
|
||||||
|
import {
|
||||||
|
createAdminBookingSchema,
|
||||||
|
listAdminBookingsQuerySchema,
|
||||||
|
updateAdminBookingStatusSchema,
|
||||||
|
} from '@repo/api-contract'
|
||||||
|
import { Hono } from 'hono'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { requireAuth } from '@/middlewares/require-auth.middleware'
|
||||||
|
import { createAdminBookingHandler } from '@/modules/admin-booking/handlers/create-admin-booking.handler'
|
||||||
|
import { listAdminBookingsHandler } from '@/modules/admin-booking/handlers/list-admin-bookings.handler'
|
||||||
|
import { updateAdminBookingStatusHandler } from '@/modules/admin-booking/handlers/update-admin-booking-status.handler'
|
||||||
|
import type { AppEnv } from '@/types/hono'
|
||||||
|
|
||||||
|
export const adminBookingRoutes = new Hono<AppEnv>()
|
||||||
|
const complexIdParamsSchema = z.object({ complexId: z.uuid() })
|
||||||
|
const bookingIdParamsSchema = z.object({ id: z.uuid() })
|
||||||
|
|
||||||
|
adminBookingRoutes.use('*', requireAuth)
|
||||||
|
|
||||||
|
adminBookingRoutes.get(
|
||||||
|
'/complex/:complexId',
|
||||||
|
zValidator('param', complexIdParamsSchema),
|
||||||
|
zValidator('query', listAdminBookingsQuerySchema),
|
||||||
|
listAdminBookingsHandler,
|
||||||
|
)
|
||||||
|
|
||||||
|
adminBookingRoutes.post(
|
||||||
|
'/complex/:complexId',
|
||||||
|
zValidator('param', complexIdParamsSchema),
|
||||||
|
zValidator('json', createAdminBookingSchema),
|
||||||
|
createAdminBookingHandler,
|
||||||
|
)
|
||||||
|
|
||||||
|
adminBookingRoutes.patch(
|
||||||
|
'/:id/status',
|
||||||
|
zValidator('param', bookingIdParamsSchema),
|
||||||
|
zValidator('json', updateAdminBookingStatusSchema),
|
||||||
|
updateAdminBookingStatusHandler,
|
||||||
|
)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { CreateAdminBookingInput } from '@repo/api-contract'
|
||||||
|
import {
|
||||||
|
AdminBookingServiceError,
|
||||||
|
createAdminBooking,
|
||||||
|
} from '@/modules/admin-booking/services/admin-booking.service'
|
||||||
|
import type { AppContext } from '@/types/hono'
|
||||||
|
|
||||||
|
type ComplexIdParams = { complexId: string }
|
||||||
|
|
||||||
|
export async function createAdminBookingHandler(c: AppContext) {
|
||||||
|
const { complexId } = c.req.valid('param' as never) as ComplexIdParams
|
||||||
|
const payload = c.req.valid('json' as never) as CreateAdminBookingInput
|
||||||
|
const appUserId = c.get('appUserId')
|
||||||
|
|
||||||
|
try {
|
||||||
|
const booking = await createAdminBooking(appUserId, complexId, payload)
|
||||||
|
return c.json(booking, 201)
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AdminBookingServiceError) {
|
||||||
|
return c.json({ message: error.message }, error.status)
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { ListAdminBookingsQuery } from '@repo/api-contract'
|
||||||
|
import {
|
||||||
|
AdminBookingServiceError,
|
||||||
|
listAdminBookings,
|
||||||
|
} from '@/modules/admin-booking/services/admin-booking.service'
|
||||||
|
import type { AppContext } from '@/types/hono'
|
||||||
|
|
||||||
|
type ComplexIdParams = { complexId: string }
|
||||||
|
|
||||||
|
export async function listAdminBookingsHandler(c: AppContext) {
|
||||||
|
const { complexId } = c.req.valid('param' as never) as ComplexIdParams
|
||||||
|
const query = c.req.valid('query' as never) as ListAdminBookingsQuery
|
||||||
|
const appUserId = c.get('appUserId')
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await listAdminBookings(appUserId, complexId, query)
|
||||||
|
return c.json(response)
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AdminBookingServiceError) {
|
||||||
|
return c.json({ message: error.message }, error.status)
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { UpdateAdminBookingStatusInput } from '@repo/api-contract'
|
||||||
|
import {
|
||||||
|
AdminBookingServiceError,
|
||||||
|
updateAdminBookingStatus,
|
||||||
|
} from '@/modules/admin-booking/services/admin-booking.service'
|
||||||
|
import type { AppContext } from '@/types/hono'
|
||||||
|
|
||||||
|
type BookingIdParams = { id: string }
|
||||||
|
|
||||||
|
export async function updateAdminBookingStatusHandler(c: AppContext) {
|
||||||
|
const { id } = c.req.valid('param' as never) as BookingIdParams
|
||||||
|
const payload = c.req.valid('json' as never) as UpdateAdminBookingStatusInput
|
||||||
|
const appUserId = c.get('appUserId')
|
||||||
|
|
||||||
|
try {
|
||||||
|
const booking = await updateAdminBookingStatus(appUserId, id, payload)
|
||||||
|
return c.json(booking)
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AdminBookingServiceError) {
|
||||||
|
return c.json({ message: error.message }, error.status)
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,527 @@
|
|||||||
|
import type {
|
||||||
|
AdminBooking,
|
||||||
|
CreateAdminBookingInput,
|
||||||
|
ListAdminBookingsQuery,
|
||||||
|
UpdateAdminBookingStatusInput,
|
||||||
|
} from '@repo/api-contract'
|
||||||
|
import { randomInt } from 'node:crypto'
|
||||||
|
import { v7 as uuidv7 } from 'uuid'
|
||||||
|
import { CourtBookingStatus } from '@/generated/prisma/enums'
|
||||||
|
import { db } from '@/lib/prisma'
|
||||||
|
import { evaluatePlanUsage, parsePlanRules } from '@/modules/plan/services/plan-rules.service'
|
||||||
|
|
||||||
|
type Slot = {
|
||||||
|
startTime: string
|
||||||
|
endTime: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const DAY_OF_WEEK_BY_INDEX = [
|
||||||
|
'SUNDAY',
|
||||||
|
'MONDAY',
|
||||||
|
'TUESDAY',
|
||||||
|
'WEDNESDAY',
|
||||||
|
'THURSDAY',
|
||||||
|
'FRIDAY',
|
||||||
|
'SATURDAY',
|
||||||
|
] as const
|
||||||
|
const BOOKING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
|
||||||
|
const BOOKING_CODE_LENGTH = 6
|
||||||
|
|
||||||
|
export class AdminBookingServiceError extends Error {
|
||||||
|
status: 400 | 403 | 404 | 409
|
||||||
|
|
||||||
|
constructor(message: string, status: 400 | 403 | 404 | 409) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'AdminBookingServiceError'
|
||||||
|
this.status = status
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toMinutes(value: string): number {
|
||||||
|
const [hours, minutes] = value.split(':').map((part) => Number(part))
|
||||||
|
return hours * 60 + minutes
|
||||||
|
}
|
||||||
|
|
||||||
|
function minutesToTime(minutes: number): string {
|
||||||
|
const safeMinutes = Math.max(0, minutes)
|
||||||
|
const hours = Math.floor(safeMinutes / 60)
|
||||||
|
const mins = safeMinutes % 60
|
||||||
|
return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseIsoDate(date: string): Date {
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date)
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
throw new AdminBookingServiceError('La fecha debe tener formato YYYY-MM-DD.', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
const year = Number(match[1])
|
||||||
|
const month = Number(match[2])
|
||||||
|
const day = Number(match[3])
|
||||||
|
|
||||||
|
const bookingDate = new Date(Date.UTC(year, month - 1, day))
|
||||||
|
|
||||||
|
if (
|
||||||
|
Number.isNaN(bookingDate.getTime()) ||
|
||||||
|
bookingDate.getUTCFullYear() !== year ||
|
||||||
|
bookingDate.getUTCMonth() + 1 !== month ||
|
||||||
|
bookingDate.getUTCDate() !== day
|
||||||
|
) {
|
||||||
|
throw new AdminBookingServiceError('La fecha enviada no es valida.', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
return bookingDate
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDayOfWeek(date: Date) {
|
||||||
|
const dayOfWeek = DAY_OF_WEEK_BY_INDEX[date.getUTCDay()]
|
||||||
|
|
||||||
|
if (!dayOfWeek) {
|
||||||
|
throw new AdminBookingServiceError('No se pudo resolver el dia de la semana.', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
return dayOfWeek
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatIsoDate(date: Date): string {
|
||||||
|
return date.toISOString().slice(0, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateBookingCode(): string {
|
||||||
|
let code = ''
|
||||||
|
|
||||||
|
for (let index = 0; index < BOOKING_CODE_LENGTH; index += 1) {
|
||||||
|
code += BOOKING_CODE_ALPHABET[randomInt(0, BOOKING_CODE_ALPHABET.length)]
|
||||||
|
}
|
||||||
|
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildSlots(
|
||||||
|
availability: Array<{
|
||||||
|
startTime: string
|
||||||
|
endTime: string
|
||||||
|
}>,
|
||||||
|
slotDurationMinutes: number,
|
||||||
|
): Slot[] {
|
||||||
|
const slots: Slot[] = []
|
||||||
|
|
||||||
|
for (const range of availability) {
|
||||||
|
const start = toMinutes(range.startTime)
|
||||||
|
const end = toMinutes(range.endTime)
|
||||||
|
|
||||||
|
for (
|
||||||
|
let current = start;
|
||||||
|
current + slotDurationMinutes <= end;
|
||||||
|
current += slotDurationMinutes
|
||||||
|
) {
|
||||||
|
slots.push({
|
||||||
|
startTime: minutesToTime(current),
|
||||||
|
endTime: minutesToTime(current + slotDurationMinutes),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return slots
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureComplexAccess(complexId: string, appUserId: string) {
|
||||||
|
const complexUser = await db.complexUser.findUnique({
|
||||||
|
where: {
|
||||||
|
complexId_userId: {
|
||||||
|
complexId,
|
||||||
|
userId: appUserId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
complex: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
complexName: true,
|
||||||
|
plan: {
|
||||||
|
select: {
|
||||||
|
rules: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!complexUser) {
|
||||||
|
throw new AdminBookingServiceError('No tienes permisos para administrar este complejo.', 403)
|
||||||
|
}
|
||||||
|
|
||||||
|
return complexUser.complex
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapBookingResponse(booking: {
|
||||||
|
id: string
|
||||||
|
bookingCode: string
|
||||||
|
bookingDate: Date
|
||||||
|
startTime: string
|
||||||
|
endTime: string
|
||||||
|
customerName: string
|
||||||
|
customerPhone: string
|
||||||
|
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED'
|
||||||
|
createdAt: Date
|
||||||
|
updatedAt: Date
|
||||||
|
court: {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
complex: {
|
||||||
|
id: string
|
||||||
|
complexName: string
|
||||||
|
}
|
||||||
|
sport: {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
slug: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}): AdminBooking {
|
||||||
|
return {
|
||||||
|
id: booking.id,
|
||||||
|
bookingCode: booking.bookingCode,
|
||||||
|
complexId: booking.court.complex.id,
|
||||||
|
complexName: booking.court.complex.complexName,
|
||||||
|
courtId: booking.court.id,
|
||||||
|
courtName: booking.court.name,
|
||||||
|
sport: {
|
||||||
|
id: booking.court.sport.id,
|
||||||
|
name: booking.court.sport.name,
|
||||||
|
slug: booking.court.sport.slug,
|
||||||
|
},
|
||||||
|
date: formatIsoDate(booking.bookingDate),
|
||||||
|
startTime: booking.startTime,
|
||||||
|
endTime: booking.endTime,
|
||||||
|
customerName: booking.customerName,
|
||||||
|
customerPhone: booking.customerPhone,
|
||||||
|
status: booking.status,
|
||||||
|
createdAt: booking.createdAt.toISOString(),
|
||||||
|
updatedAt: booking.updatedAt.toISOString(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listAdminBookings(
|
||||||
|
appUserId: string,
|
||||||
|
complexId: string,
|
||||||
|
query: ListAdminBookingsQuery,
|
||||||
|
) {
|
||||||
|
await ensureComplexAccess(complexId, appUserId)
|
||||||
|
const fromDate = parseIsoDate(query.fromDate)
|
||||||
|
|
||||||
|
const bookings = await db.courtBooking.findMany({
|
||||||
|
where: {
|
||||||
|
bookingDate: {
|
||||||
|
gte: fromDate,
|
||||||
|
},
|
||||||
|
court: {
|
||||||
|
complexId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
slug: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
complex: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
complexName: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [{ bookingDate: 'asc' }, { startTime: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
bookings: bookings.map((booking) => mapBookingResponse(booking)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAdminBooking(
|
||||||
|
appUserId: string,
|
||||||
|
complexId: string,
|
||||||
|
input: CreateAdminBookingInput,
|
||||||
|
) {
|
||||||
|
const complex = await ensureComplexAccess(complexId, appUserId)
|
||||||
|
const bookingDate = parseIsoDate(input.date)
|
||||||
|
const dayOfWeek = getDayOfWeek(bookingDate)
|
||||||
|
|
||||||
|
const court = await db.court.findFirst({
|
||||||
|
where: {
|
||||||
|
id: input.courtId,
|
||||||
|
complexId,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
availabilities: {
|
||||||
|
where: {
|
||||||
|
dayOfWeek,
|
||||||
|
},
|
||||||
|
orderBy: {
|
||||||
|
startTime: 'asc',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
sport: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
slug: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!court) {
|
||||||
|
throw new AdminBookingServiceError('La cancha seleccionada no existe en el complejo.', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
const validSlots = buildSlots(court.availabilities, court.slotDurationMinutes)
|
||||||
|
const selectedStartMinutes = toMinutes(input.startTime)
|
||||||
|
const selectedEndMinutes = selectedStartMinutes + court.slotDurationMinutes
|
||||||
|
const selectedSlot = {
|
||||||
|
startTime: input.startTime,
|
||||||
|
endTime: minutesToTime(selectedEndMinutes),
|
||||||
|
}
|
||||||
|
|
||||||
|
const slotExists = validSlots.some(
|
||||||
|
(slot) => slot.startTime === selectedSlot.startTime && slot.endTime === selectedSlot.endTime,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!slotExists) {
|
||||||
|
throw new AdminBookingServiceError(
|
||||||
|
'El horario seleccionado no esta disponible para esa cancha.',
|
||||||
|
409,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||||
|
try {
|
||||||
|
const booking = await db.$transaction(async (tx) => {
|
||||||
|
if (complex.plan) {
|
||||||
|
const rules = parsePlanRules(complex.plan.rules)
|
||||||
|
const bookingsForDate = await tx.courtBooking.count({
|
||||||
|
where: {
|
||||||
|
bookingDate,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
court: {
|
||||||
|
complexId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const courtsCount = await tx.court.count({
|
||||||
|
where: {
|
||||||
|
complexId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const violations = evaluatePlanUsage(rules, {
|
||||||
|
courtsCount,
|
||||||
|
bookingsToday: bookingsForDate,
|
||||||
|
})
|
||||||
|
|
||||||
|
const maxBookingsViolation = violations.find(
|
||||||
|
(violation) => violation.code === 'MAX_BOOKINGS_PER_DAY_REACHED',
|
||||||
|
)
|
||||||
|
|
||||||
|
if (maxBookingsViolation) {
|
||||||
|
throw new AdminBookingServiceError(maxBookingsViolation.message, 409)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const overlappingBooking = await tx.courtBooking.findFirst({
|
||||||
|
where: {
|
||||||
|
courtId: court.id,
|
||||||
|
bookingDate,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
startTime: {
|
||||||
|
lt: selectedSlot.endTime,
|
||||||
|
},
|
||||||
|
endTime: {
|
||||||
|
gt: selectedSlot.startTime,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (overlappingBooking) {
|
||||||
|
throw new AdminBookingServiceError('El horario seleccionado ya fue reservado.', 409)
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.courtBooking.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
bookingCode: generateBookingCode(),
|
||||||
|
courtId: court.id,
|
||||||
|
bookingDate,
|
||||||
|
startTime: selectedSlot.startTime,
|
||||||
|
endTime: selectedSlot.endTime,
|
||||||
|
customerName: input.customerName.trim(),
|
||||||
|
customerPhone: input.customerPhone.trim(),
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
slug: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
complex: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
complexName: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return mapBookingResponse(booking)
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AdminBookingServiceError) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
|
||||||
|
const prismaError = error as {
|
||||||
|
code?: string
|
||||||
|
meta?: {
|
||||||
|
target?: string[] | string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (prismaError.code === 'P2002') {
|
||||||
|
const targets = Array.isArray(prismaError.meta?.target)
|
||||||
|
? prismaError.meta?.target
|
||||||
|
: [prismaError.meta?.target]
|
||||||
|
const isBookingCodeCollision = targets.some((target) =>
|
||||||
|
String(target).includes('booking_code'),
|
||||||
|
)
|
||||||
|
|
||||||
|
if (isBookingCodeCollision) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new AdminBookingServiceError('El horario seleccionado ya fue reservado.', 409)
|
||||||
|
}
|
||||||
|
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new AdminBookingServiceError(
|
||||||
|
'No se pudo generar un codigo de reserva unico. Intenta nuevamente.',
|
||||||
|
409,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateAdminBookingStatus(
|
||||||
|
appUserId: string,
|
||||||
|
bookingId: string,
|
||||||
|
input: UpdateAdminBookingStatusInput,
|
||||||
|
) {
|
||||||
|
const booking = await db.courtBooking.findFirst({
|
||||||
|
where: {
|
||||||
|
id: bookingId,
|
||||||
|
court: {
|
||||||
|
complex: {
|
||||||
|
users: {
|
||||||
|
some: {
|
||||||
|
userId: appUserId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
slug: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
complex: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
complexName: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!booking) {
|
||||||
|
throw new AdminBookingServiceError('Reserva no encontrada.', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.status === 'CANCELLED' && booking.status !== 'CONFIRMED') {
|
||||||
|
throw new AdminBookingServiceError(
|
||||||
|
'Solo se pueden cancelar reservas en estado confirmada.',
|
||||||
|
409,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.status === 'COMPLETED' && booking.status !== 'CONFIRMED') {
|
||||||
|
throw new AdminBookingServiceError(
|
||||||
|
'Solo se pueden marcar como cumplidas las reservas confirmadas.',
|
||||||
|
409,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await db.courtBooking.update({
|
||||||
|
where: { id: booking.id },
|
||||||
|
data: {
|
||||||
|
status:
|
||||||
|
input.status === 'COMPLETED'
|
||||||
|
? CourtBookingStatus.COMPLETED
|
||||||
|
: CourtBookingStatus.CANCELLED,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
slug: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
complex: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
complexName: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return mapBookingResponse(updated)
|
||||||
|
}
|
||||||
@@ -234,7 +234,7 @@ function mapBookingResponse(input: {
|
|||||||
endTime: string
|
endTime: string
|
||||||
customerName: string
|
customerName: string
|
||||||
customerPhone: string
|
customerPhone: string
|
||||||
status: 'CONFIRMED' | 'CANCELLED'
|
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED'
|
||||||
court: {
|
court: {
|
||||||
id: string
|
id: string
|
||||||
name: string
|
name: string
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { registerApiRoutes } from '@repo/api-contract'
|
|||||||
import type { Hono } from 'hono'
|
import type { Hono } from 'hono'
|
||||||
import { serveStatic } from 'hono/bun'
|
import { serveStatic } from 'hono/bun'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
|
import { adminBookingRoutes } from '@/modules/admin-booking/admin-booking.routes'
|
||||||
import { complexRoutes } from '@/modules/complex/complex.routes'
|
import { complexRoutes } from '@/modules/complex/complex.routes'
|
||||||
import { courtRoutes } from '@/modules/court/court.routes'
|
import { courtRoutes } from '@/modules/court/court.routes'
|
||||||
import { onboardingRoutes } from '@/modules/onboarding/onboarding.routes'
|
import { onboardingRoutes } from '@/modules/onboarding/onboarding.routes'
|
||||||
@@ -22,6 +23,7 @@ export function registerRoutes(app: Hono<AppEnv>) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
app.route('/api/public-bookings', publicBookingRoutes)
|
app.route('/api/public-bookings', publicBookingRoutes)
|
||||||
|
app.route('/api/admin-bookings', adminBookingRoutes)
|
||||||
|
|
||||||
app.use('*', serveStatic({ root: './public' }))
|
app.use('*', serveStatic({ root: './public' }))
|
||||||
app.get('*', async (c) => {
|
app.get('*', async (c) => {
|
||||||
|
|||||||
@@ -1,67 +1,552 @@
|
|||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
import type { AdminBooking } from '@repo/api-contract'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { ApiClientError, apiClient } from '@/lib/api-client'
|
||||||
|
import {
|
||||||
|
getCurrentComplexSlug,
|
||||||
|
setCurrentComplexSlug as persistCurrentComplexSlug,
|
||||||
|
} from '@/lib/current-complex'
|
||||||
|
|
||||||
const emailSchema = z.object({
|
const manualBookingSchema = z.object({
|
||||||
email: z.string().email('Ingresa un email válido.'),
|
customerName: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(2, 'Ingresa un nombre valido.')
|
||||||
|
.max(120, 'El nombre no puede superar los 120 caracteres.'),
|
||||||
|
customerPhone: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(6, 'Ingresa un telefono valido.')
|
||||||
|
.max(30, 'El telefono no puede superar los 30 caracteres.'),
|
||||||
})
|
})
|
||||||
|
|
||||||
type EmailForm = z.infer<typeof emailSchema>
|
type ManualBookingForm = z.infer<typeof manualBookingSchema>
|
||||||
|
|
||||||
|
function toIsoDateLocal(date: Date) {
|
||||||
|
const year = date.getFullYear()
|
||||||
|
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||||
|
const day = String(date.getDate()).padStart(2, '0')
|
||||||
|
return `${year}-${month}-${day}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractMessage(error: unknown, fallback: string) {
|
||||||
|
if (error instanceof ApiClientError) {
|
||||||
|
return error.message || fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateLabel(dateIso: string) {
|
||||||
|
const [year, month, day] = dateIso.split('-').map(Number)
|
||||||
|
|
||||||
|
if (!year || !month || !day) return dateIso
|
||||||
|
|
||||||
|
const date = new Date(year, month - 1, day)
|
||||||
|
return new Intl.DateTimeFormat('es-AR', {
|
||||||
|
weekday: 'long',
|
||||||
|
day: '2-digit',
|
||||||
|
month: 'long',
|
||||||
|
}).format(date)
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusLabel(status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED') {
|
||||||
|
if (status === 'COMPLETED') return 'Cumplida'
|
||||||
|
if (status === 'CANCELLED') return 'Cancelada'
|
||||||
|
return 'Confirmada'
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusClassName(status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED') {
|
||||||
|
if (status === 'COMPLETED') {
|
||||||
|
return 'border-emerald-200 bg-emerald-50 text-emerald-700'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status === 'CANCELLED') {
|
||||||
|
return 'border-rose-200 bg-rose-50 text-rose-700'
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'border-sky-200 bg-sky-50 text-sky-700'
|
||||||
|
}
|
||||||
|
|
||||||
export function HomePage() {
|
export function HomePage() {
|
||||||
const {
|
const queryClient = useQueryClient()
|
||||||
register,
|
const todayIso = useMemo(() => toIsoDateLocal(new Date()), [])
|
||||||
handleSubmit,
|
|
||||||
watch,
|
const [currentComplexSlug, setCurrentComplexSlug] = useState<string | null>(null)
|
||||||
formState: { errors, isValid, isSubmitSuccessful },
|
const [fromDate, setFromDate] = useState(todayIso)
|
||||||
} = useForm<EmailForm>({
|
const [manualDate, setManualDate] = useState(todayIso)
|
||||||
resolver: zodResolver(emailSchema),
|
const [selectedSportId, setSelectedSportId] = useState<string | undefined>()
|
||||||
mode: 'onChange',
|
const [selectedCourtId, setSelectedCourtId] = useState<string>('')
|
||||||
defaultValues: {
|
const [selectedStartTime, setSelectedStartTime] = useState<string>('')
|
||||||
email: '',
|
|
||||||
|
useEffect(() => {
|
||||||
|
setCurrentComplexSlug(getCurrentComplexSlug())
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const myComplexesQuery = useQuery({
|
||||||
|
queryKey: ['my-complexes'],
|
||||||
|
queryFn: () => apiClient.complexes.listMine(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const selectedComplex = useMemo(() => {
|
||||||
|
const complexes = myComplexesQuery.data ?? []
|
||||||
|
|
||||||
|
if (complexes.length === 0) return null
|
||||||
|
|
||||||
|
if (currentComplexSlug) {
|
||||||
|
const match = complexes.find((complex) => complex.complexSlug === currentComplexSlug)
|
||||||
|
|
||||||
|
if (match) return match
|
||||||
|
}
|
||||||
|
|
||||||
|
return complexes[0]
|
||||||
|
}, [currentComplexSlug, myComplexesQuery.data])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selectedComplex) return
|
||||||
|
|
||||||
|
setCurrentComplexSlug(selectedComplex.complexSlug)
|
||||||
|
persistCurrentComplexSlug(selectedComplex.complexSlug)
|
||||||
|
}, [selectedComplex])
|
||||||
|
|
||||||
|
const bookingsQuery = useQuery({
|
||||||
|
queryKey: ['admin-bookings', selectedComplex?.id, fromDate],
|
||||||
|
enabled: Boolean(selectedComplex?.id),
|
||||||
|
queryFn: () =>
|
||||||
|
apiClient.adminBookings.listByComplex(selectedComplex?.id as string, {
|
||||||
|
fromDate,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
const manualAvailabilityQuery = useQuery({
|
||||||
|
queryKey: ['manual-booking-availability', selectedComplex?.complexSlug, manualDate, selectedSportId],
|
||||||
|
enabled: Boolean(selectedComplex?.complexSlug && manualDate),
|
||||||
|
queryFn: () =>
|
||||||
|
apiClient.publicBookings.getAvailability(selectedComplex?.complexSlug as string, {
|
||||||
|
date: manualDate,
|
||||||
|
...(selectedSportId ? { sportId: selectedSportId } : {}),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const availability = manualAvailabilityQuery.data
|
||||||
|
|
||||||
|
if (!availability) return
|
||||||
|
|
||||||
|
if (!availability.sportSelectionRequired) {
|
||||||
|
if (availability.sports[0] && !selectedSportId) {
|
||||||
|
setSelectedSportId(availability.sports[0].id)
|
||||||
|
}
|
||||||
|
} else if (
|
||||||
|
selectedSportId &&
|
||||||
|
!availability.sports.some((sport) => sport.id === selectedSportId)
|
||||||
|
) {
|
||||||
|
setSelectedSportId(undefined)
|
||||||
|
}
|
||||||
|
}, [manualAvailabilityQuery.data, selectedSportId])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!manualAvailabilityQuery.data) return
|
||||||
|
|
||||||
|
if (
|
||||||
|
selectedCourtId &&
|
||||||
|
!manualAvailabilityQuery.data.courts.some((court) => court.courtId === selectedCourtId)
|
||||||
|
) {
|
||||||
|
setSelectedCourtId('')
|
||||||
|
setSelectedStartTime('')
|
||||||
|
}
|
||||||
|
}, [manualAvailabilityQuery.data, selectedCourtId])
|
||||||
|
|
||||||
|
const selectedCourt = useMemo(() => {
|
||||||
|
return manualAvailabilityQuery.data?.courts.find((court) => court.courtId === selectedCourtId)
|
||||||
|
}, [manualAvailabilityQuery.data?.courts, selectedCourtId])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selectedCourt) {
|
||||||
|
setSelectedStartTime('')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!selectedCourt.availableSlots.some((slot) => slot.startTime === selectedStartTime)) {
|
||||||
|
setSelectedStartTime('')
|
||||||
|
}
|
||||||
|
}, [selectedCourt, selectedStartTime])
|
||||||
|
|
||||||
|
const groupedBookings = useMemo(() => {
|
||||||
|
const groups = new Map<string, AdminBooking[]>()
|
||||||
|
|
||||||
|
for (const booking of bookingsQuery.data?.bookings ?? []) {
|
||||||
|
const current = groups.get(booking.date) ?? []
|
||||||
|
current.push(booking)
|
||||||
|
groups.set(booking.date, current)
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...groups.entries()]
|
||||||
|
}, [bookingsQuery.data?.bookings])
|
||||||
|
|
||||||
|
const updateStatusMutation = useMutation({
|
||||||
|
mutationFn: (payload: { bookingId: string; status: 'CANCELLED' | 'COMPLETED' }) =>
|
||||||
|
apiClient.adminBookings.updateStatus(payload.bookingId, { status: payload.status }),
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex?.id] })
|
||||||
|
void queryClient.invalidateQueries({
|
||||||
|
queryKey: ['manual-booking-availability', selectedComplex?.complexSlug],
|
||||||
|
})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const emailValue = watch('email')
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
formState: { errors, isSubmitting, isValid },
|
||||||
|
} = useForm<ManualBookingForm>({
|
||||||
|
resolver: zodResolver(manualBookingSchema),
|
||||||
|
mode: 'onChange',
|
||||||
|
defaultValues: {
|
||||||
|
customerName: '',
|
||||||
|
customerPhone: '',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const onSubmit = (_data: EmailForm) => {
|
const createManualBookingMutation = useMutation({
|
||||||
// Demo form: no-op; success state is managed by react-hook-form.
|
mutationFn: async (values: ManualBookingForm) => {
|
||||||
|
if (!selectedComplex?.id) {
|
||||||
|
throw new Error('No se encontró el complejo actual.')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!selectedCourtId || !selectedStartTime) {
|
||||||
|
throw new Error('Debes seleccionar cancha y horario.')
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiClient.adminBookings.create(selectedComplex.id, {
|
||||||
|
date: manualDate,
|
||||||
|
courtId: selectedCourtId,
|
||||||
|
startTime: selectedStartTime,
|
||||||
|
customerName: values.customerName,
|
||||||
|
customerPhone: values.customerPhone,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
onSuccess: async () => {
|
||||||
|
reset()
|
||||||
|
setSelectedCourtId('')
|
||||||
|
setSelectedStartTime('')
|
||||||
|
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex?.id] })
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: ['manual-booking-availability', selectedComplex?.complexSlug],
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const onSubmitManualBooking = async (values: ManualBookingForm) => {
|
||||||
|
await createManualBookingMutation.mutateAsync(values)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (myComplexesQuery.isLoading) {
|
||||||
|
return (
|
||||||
|
<main className="mx-auto w-full max-w-6xl px-6 py-8">
|
||||||
|
<p className="text-sm text-muted-foreground">Cargando panel...</p>
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (myComplexesQuery.isError) {
|
||||||
|
return (
|
||||||
|
<main className="mx-auto w-full max-w-6xl px-6 py-8">
|
||||||
|
<p className="text-sm text-destructive">
|
||||||
|
{extractMessage(myComplexesQuery.error, 'No pudimos cargar tus complejos.')}
|
||||||
|
</p>
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!selectedComplex) {
|
||||||
|
return (
|
||||||
|
<main className="mx-auto w-full max-w-6xl px-6 py-8">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
No tienes complejos asignados todavía.
|
||||||
|
</p>
|
||||||
|
</main>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto flex min-h-[60vh] w-full max-w-6xl items-center justify-center px-6">
|
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 py-6">
|
||||||
<section className="w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
|
<section className="rounded-xl border bg-card p-5 shadow-sm">
|
||||||
<h1 className="mb-2 text-2xl font-semibold">Frontend listo</h1>
|
<h1 className="text-2xl font-semibold">Panel de reservas</h1>
|
||||||
<p className="mb-4 text-sm text-muted-foreground">
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
React + Vite + TypeScript + shadcn + zod + react-hook-form.
|
Gestiona turnos del día y futuros para {selectedComplex.complexName}.
|
||||||
</p>
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit(onSubmit)}>
|
<section className="rounded-xl border bg-card p-5 shadow-sm">
|
||||||
<Field data-invalid={Boolean(errors.email)}>
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
<Field>
|
||||||
|
<FieldLabel htmlFor="fromDate">Mostrar desde</FieldLabel>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="fromDate"
|
||||||
type="email"
|
type="date"
|
||||||
placeholder="tu@email.com"
|
value={fromDate}
|
||||||
aria-invalid={Boolean(errors.email)}
|
min={todayIso}
|
||||||
{...register('email')}
|
onChange={(event) => {
|
||||||
|
setFromDate(event.target.value)
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<FieldError errors={[errors.email]} />
|
|
||||||
</Field>
|
</Field>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Button type="submit" className="mt-3 w-full" disabled={!isValid}>
|
{bookingsQuery.isLoading && (
|
||||||
Continuar
|
<p className="mt-4 text-sm text-muted-foreground">Cargando reservas...</p>
|
||||||
</Button>
|
)}
|
||||||
</form>
|
|
||||||
|
|
||||||
{isSubmitSuccessful && !errors.email && emailValue && (
|
{bookingsQuery.isError && (
|
||||||
<p className="mt-3 text-sm text-emerald-600">
|
<p className="mt-4 text-sm text-destructive">
|
||||||
Email válido según esquema zod.
|
{extractMessage(bookingsQuery.error, 'No pudimos cargar las reservas.')}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!bookingsQuery.isLoading &&
|
||||||
|
!bookingsQuery.isError &&
|
||||||
|
groupedBookings.length === 0 && (
|
||||||
|
<p className="mt-4 text-sm text-muted-foreground">
|
||||||
|
No hay reservas para la fecha seleccionada en adelante.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-4">
|
||||||
|
{groupedBookings.map(([date, bookings]) => (
|
||||||
|
<article key={date} className="rounded-lg border bg-background p-3">
|
||||||
|
<h2 className="text-sm font-semibold capitalize">{formatDateLabel(date)}</h2>
|
||||||
|
<div className="mt-3 space-y-2">
|
||||||
|
{bookings.map((booking) => {
|
||||||
|
const canManage = booking.status === 'CONFIRMED'
|
||||||
|
const isMutating = updateStatusMutation.isPending
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={booking.id}
|
||||||
|
className="flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium">
|
||||||
|
{booking.startTime} - {booking.endTime} · {booking.courtName}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{booking.customerName} ({booking.customerPhone}) · Código {booking.bookingCode}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span
|
||||||
|
className={`inline-flex rounded-full border px-2 py-1 text-xs font-medium ${statusClassName(booking.status)}`}
|
||||||
|
>
|
||||||
|
{statusLabel(booking.status)}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{canManage && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={isMutating}
|
||||||
|
onClick={() => {
|
||||||
|
updateStatusMutation.mutate({
|
||||||
|
bookingId: booking.id,
|
||||||
|
status: 'COMPLETED',
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Marcar cumplida
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="destructive"
|
||||||
|
disabled={isMutating}
|
||||||
|
onClick={() => {
|
||||||
|
updateStatusMutation.mutate({
|
||||||
|
bookingId: booking.id,
|
||||||
|
status: 'CANCELLED',
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{updateStatusMutation.isError && (
|
||||||
|
<p className="mt-4 text-sm text-destructive">
|
||||||
|
{extractMessage(updateStatusMutation.error, 'No pudimos actualizar la reserva.')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-xl border bg-card p-5 shadow-sm">
|
||||||
|
<h2 className="text-lg font-semibold">Reserva manual</h2>
|
||||||
|
<p className="mt-1 text-sm text-muted-foreground">
|
||||||
|
Crea un turno para atención telefónica o mostrador.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-4 grid gap-3 md:grid-cols-3">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="manualDate">Fecha</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="manualDate"
|
||||||
|
type="date"
|
||||||
|
min={todayIso}
|
||||||
|
value={manualDate}
|
||||||
|
onChange={(event) => {
|
||||||
|
setManualDate(event.target.value)
|
||||||
|
setSelectedCourtId('')
|
||||||
|
setSelectedStartTime('')
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
{manualAvailabilityQuery.data?.sportSelectionRequired && (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Deporte</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={selectedSportId ?? ''}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setSelectedSportId(value)
|
||||||
|
setSelectedCourtId('')
|
||||||
|
setSelectedStartTime('')
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Selecciona un deporte" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{manualAvailabilityQuery.data?.sports.map((sport) => (
|
||||||
|
<SelectItem key={sport.id} value={sport.id}>
|
||||||
|
{sport.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Cancha</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={selectedCourtId}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setSelectedCourtId(value)
|
||||||
|
setSelectedStartTime('')
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Selecciona una cancha" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{(manualAvailabilityQuery.data?.courts ?? []).map((court) => (
|
||||||
|
<SelectItem key={court.courtId} value={court.courtId}>
|
||||||
|
{court.courtName} · {court.sport.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-3">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Horario</FieldLabel>
|
||||||
|
<Select value={selectedStartTime} onValueChange={setSelectedStartTime}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Selecciona un horario" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{(selectedCourt?.availableSlots ?? []).map((slot) => (
|
||||||
|
<SelectItem key={slot.startTime} value={slot.startTime}>
|
||||||
|
{slot.startTime} - {slot.endTime}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{manualAvailabilityQuery.isLoading && (
|
||||||
|
<p className="mt-3 text-sm text-muted-foreground">Cargando horarios disponibles...</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{manualAvailabilityQuery.isError && (
|
||||||
|
<p className="mt-3 text-sm text-destructive">
|
||||||
|
{extractMessage(
|
||||||
|
manualAvailabilityQuery.error,
|
||||||
|
'No pudimos cargar disponibilidad para la reserva manual.',
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form className="mt-4 grid gap-3 md:grid-cols-2" onSubmit={handleSubmit(onSubmitManualBooking)}>
|
||||||
|
<Field data-invalid={Boolean(errors.customerName)}>
|
||||||
|
<FieldLabel htmlFor="customerName">Nombre</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="customerName"
|
||||||
|
placeholder="Ej: Juan Perez"
|
||||||
|
aria-invalid={Boolean(errors.customerName)}
|
||||||
|
{...register('customerName')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[errors.customerName]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={Boolean(errors.customerPhone)}>
|
||||||
|
<FieldLabel htmlFor="customerPhone">Teléfono</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="customerPhone"
|
||||||
|
type="tel"
|
||||||
|
placeholder="Ej: 3875551234"
|
||||||
|
aria-invalid={Boolean(errors.customerPhone)}
|
||||||
|
{...register('customerPhone')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[errors.customerPhone]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
{createManualBookingMutation.isError && (
|
||||||
|
<p className="text-sm text-destructive md:col-span-2">
|
||||||
|
{extractMessage(
|
||||||
|
createManualBookingMutation.error,
|
||||||
|
'No pudimos crear la reserva manual.',
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="md:col-span-2"
|
||||||
|
disabled={!isValid || isSubmitting || !selectedCourtId || !selectedStartTime}
|
||||||
|
>
|
||||||
|
{createManualBookingMutation.isPending ? 'Guardando...' : 'Crear reserva manual'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import axios, { AxiosError } from 'axios'
|
import axios, { AxiosError } from 'axios'
|
||||||
import type {
|
import type {
|
||||||
|
AdminBooking,
|
||||||
|
CreateAdminBookingInput,
|
||||||
Court,
|
Court,
|
||||||
CreateCourtInput,
|
CreateCourtInput,
|
||||||
CreatePublicBookingInput,
|
CreatePublicBookingInput,
|
||||||
@@ -20,6 +22,7 @@ import type {
|
|||||||
PublicBooking,
|
PublicBooking,
|
||||||
PublicBookingConfirmation,
|
PublicBookingConfirmation,
|
||||||
Sport,
|
Sport,
|
||||||
|
UpdateAdminBookingStatusInput,
|
||||||
UpdateCourtInput,
|
UpdateCourtInput,
|
||||||
UpdateComplexPayload,
|
UpdateComplexPayload,
|
||||||
UpdateComplexResponse,
|
UpdateComplexResponse,
|
||||||
@@ -261,6 +264,39 @@ export const apiClient = {
|
|||||||
return response.data
|
return response.data
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
adminBookings: {
|
||||||
|
listByComplex: async (
|
||||||
|
complexId: string,
|
||||||
|
params: {
|
||||||
|
fromDate: string
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const response = await http.get<{ bookings: AdminBooking[] }>(
|
||||||
|
`/api/admin-bookings/complex/${complexId}`,
|
||||||
|
{
|
||||||
|
params,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
create: async (complexId: string, payload: CreateAdminBookingInput) => {
|
||||||
|
const response = await http.post<AdminBooking>(
|
||||||
|
`/api/admin-bookings/complex/${complexId}`,
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
updateStatus: async (
|
||||||
|
bookingId: string,
|
||||||
|
payload: UpdateAdminBookingStatusInput,
|
||||||
|
) => {
|
||||||
|
const response = await http.patch<AdminBooking>(
|
||||||
|
`/api/admin-bookings/${bookingId}/status`,
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ApiClient = typeof apiClient
|
export type ApiClient = typeof apiClient
|
||||||
|
|||||||
67
packages/api-contract/src/admin-booking.ts
Normal file
67
packages/api-contract/src/admin-booking.ts
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
const TIME_REGEX = /^([01]\d|2[0-3]):([0-5]\d)$/
|
||||||
|
const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/
|
||||||
|
const BOOKING_CODE_REGEX = /^[A-Z0-9]{6,8}$/
|
||||||
|
|
||||||
|
export const bookingStatusSchema = z.enum(['CONFIRMED', 'CANCELLED', 'COMPLETED'])
|
||||||
|
|
||||||
|
export const adminBookingSportSchema = z.object({
|
||||||
|
id: z.uuid(),
|
||||||
|
name: z.string(),
|
||||||
|
slug: z.string(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const adminBookingSchema = z.object({
|
||||||
|
id: z.uuid(),
|
||||||
|
bookingCode: z.string().regex(BOOKING_CODE_REGEX),
|
||||||
|
complexId: z.uuid(),
|
||||||
|
complexName: z.string(),
|
||||||
|
courtId: z.uuid(),
|
||||||
|
courtName: z.string(),
|
||||||
|
sport: adminBookingSportSchema,
|
||||||
|
date: z.string().regex(ISO_DATE_REGEX),
|
||||||
|
startTime: z.string().regex(TIME_REGEX),
|
||||||
|
endTime: z.string().regex(TIME_REGEX),
|
||||||
|
customerName: z.string(),
|
||||||
|
customerPhone: z.string(),
|
||||||
|
status: bookingStatusSchema,
|
||||||
|
createdAt: z.string().datetime(),
|
||||||
|
updatedAt: z.string().datetime(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const listAdminBookingsQuerySchema = z.object({
|
||||||
|
fromDate: z.string().regex(ISO_DATE_REGEX, 'La fecha debe tener formato YYYY-MM-DD.'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const listAdminBookingsResponseSchema = z.object({
|
||||||
|
bookings: z.array(adminBookingSchema),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const createAdminBookingSchema = z.object({
|
||||||
|
date: z.string().regex(ISO_DATE_REGEX, 'La fecha debe tener formato YYYY-MM-DD.'),
|
||||||
|
courtId: z.uuid('El courtId debe ser un UUID valido.'),
|
||||||
|
startTime: z.string().regex(TIME_REGEX, 'La hora debe tener formato HH:mm.'),
|
||||||
|
customerName: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(2, 'El nombre debe tener al menos 2 caracteres.')
|
||||||
|
.max(120, 'El nombre no puede superar los 120 caracteres.'),
|
||||||
|
customerPhone: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(6, 'El telefono debe tener al menos 6 caracteres.')
|
||||||
|
.max(30, 'El telefono no puede superar los 30 caracteres.'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const updateAdminBookingStatusSchema = z.object({
|
||||||
|
status: z.enum(['CANCELLED', 'COMPLETED']),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type BookingStatus = z.infer<typeof bookingStatusSchema>
|
||||||
|
export type AdminBookingSport = z.infer<typeof adminBookingSportSchema>
|
||||||
|
export type AdminBooking = z.infer<typeof adminBookingSchema>
|
||||||
|
export type ListAdminBookingsQuery = z.infer<typeof listAdminBookingsQuerySchema>
|
||||||
|
export type ListAdminBookingsResponse = z.infer<typeof listAdminBookingsResponseSchema>
|
||||||
|
export type CreateAdminBookingInput = z.infer<typeof createAdminBookingSchema>
|
||||||
|
export type UpdateAdminBookingStatusInput = z.infer<typeof updateAdminBookingStatusSchema>
|
||||||
@@ -55,6 +55,24 @@ export type {
|
|||||||
CreateCourtInput,
|
CreateCourtInput,
|
||||||
UpdateCourtInput,
|
UpdateCourtInput,
|
||||||
} from './court'
|
} from './court'
|
||||||
|
export {
|
||||||
|
adminBookingSchema,
|
||||||
|
adminBookingSportSchema,
|
||||||
|
bookingStatusSchema,
|
||||||
|
createAdminBookingSchema,
|
||||||
|
listAdminBookingsQuerySchema,
|
||||||
|
listAdminBookingsResponseSchema,
|
||||||
|
updateAdminBookingStatusSchema,
|
||||||
|
} from './admin-booking'
|
||||||
|
export type {
|
||||||
|
AdminBooking,
|
||||||
|
AdminBookingSport,
|
||||||
|
BookingStatus,
|
||||||
|
CreateAdminBookingInput,
|
||||||
|
ListAdminBookingsQuery,
|
||||||
|
ListAdminBookingsResponse,
|
||||||
|
UpdateAdminBookingStatusInput,
|
||||||
|
} from './admin-booking'
|
||||||
export {
|
export {
|
||||||
createPublicBookingSchema,
|
createPublicBookingSchema,
|
||||||
publicAvailabilityCourtSchema,
|
publicAvailabilityCourtSchema,
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ export const publicBookingSchema = z.object({
|
|||||||
endTime: z.string().regex(TIME_REGEX),
|
endTime: z.string().regex(TIME_REGEX),
|
||||||
customerName: z.string(),
|
customerName: z.string(),
|
||||||
customerPhone: z.string(),
|
customerPhone: z.string(),
|
||||||
status: z.enum(['CONFIRMED', 'CANCELLED']),
|
status: z.enum(['CONFIRMED', 'CANCELLED', 'COMPLETED']),
|
||||||
createdAt: z.string().datetime(),
|
createdAt: z.string().datetime(),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -84,7 +84,7 @@ export const publicBookingConfirmationSchema = z.object({
|
|||||||
endTime: z.string().regex(TIME_REGEX),
|
endTime: z.string().regex(TIME_REGEX),
|
||||||
courtName: z.string(),
|
courtName: z.string(),
|
||||||
sport: publicBookingSportSchema,
|
sport: publicBookingSportSchema,
|
||||||
status: z.enum(['CONFIRMED', 'CANCELLED']),
|
status: z.enum(['CONFIRMED', 'CANCELLED', 'COMPLETED']),
|
||||||
createdAt: z.string().datetime(),
|
createdAt: z.string().datetime(),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user