31 Commits

Author SHA1 Message Date
Jose Selesan
78df95e985 Refactor Dockerfile and entrypoint.sh for improved backend build process 2026-06-01 15:02:06 -03:00
6738db8c60 Merge pull request 'new-public-booking' (#14) from new-public-booking into development
Reviewed-on: https://gitea.2pidev.com/jselesan/playzer/pulls/14
2026-05-28 13:03:13 +00:00
Jose Selesan
8acb81e6b4 Refactor UserAvatar component to simplify image handling and remove error state management 2026-05-22 11:58:25 -03:00
Jose Selesan
91125e82f5 Improve sport selector UI with visual button components
Replace dropdown select with interactive pill buttons for sport selection

- Added SportSelector component with icon-based visual buttons (desktop)
- Added MobileSportSelector component for mobile-optimized layout
- Added getSportIcon() function to map sport names to appropriate icons
- Improved visual feedback with emerald highlight on selection
- Better hover states and transitions for improved UX
- Works on both desktop and mobile views

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-19 16:43:39 -03:00
Jose Selesan
e9bd759fa5 Add navigation for previous and next days in public booking 2026-05-19 11:02:32 -03:00
Jose Selesan
57416bf53a Added complex data 2026-05-19 10:35:23 -03:00
Jose Selesan
0b6041d146 Better complex show 2026-05-19 09:42:31 -03:00
Jose Selesan
900e6146e7 Stepper improvement 2026-05-19 09:32:26 -03:00
Jose Selesan
e905052cc1 Added Stepper component 2026-05-19 09:21:21 -03:00
Jose Selesan
c1d910708a New UI for public booking 2026-05-19 09:06:03 -03:00
b8abf224cf Merge pull request 'Fixed mobile bottom toolbar' (#13) from mobile-fixes into development
Reviewed-on: https://gitea.2pidev.com/jselesan/playzer/pulls/13
2026-05-08 15:01:32 +00:00
Jose Selesan
b47f00651e Fixed mobile bottom toolbar 2026-05-08 12:00:52 -03:00
a9c74d2f9c Merge pull request 'mobile-booking-admin' (#12) from mobile-booking-admin into development
Reviewed-on: https://gitea.2pidev.com/jselesan/playzer/pulls/12
2026-05-08 14:10:17 +00:00
Jose Selesan
d1b5bea1bc Fix lint 2026-05-08 11:07:21 -03:00
Jose Selesan
ab22ec86ec Improved mobile layout 2026-05-08 11:02:03 -03:00
Jose Selesan
65295236c5 Mobile booking view 2026-05-08 10:56:58 -03:00
Jose Selesan
f104161bbd Fixed build error 2026-05-06 20:30:23 -03:00
Jose Selesan
844dac206c Auto show current time indicator 2026-05-06 20:26:31 -03:00
be48b4b295 Merge pull request 'improve-booking-logic' (#11) from improve-booking-logic into development
Reviewed-on: https://gitea.2pidev.com/jselesan/playzer/pulls/11
2026-05-06 20:12:39 +00:00
Jose Selesan
1059d767d5 View no shows in booking panel 2026-05-06 17:10:23 -03:00
Jose Selesan
7be776f189 Close dialog on status change 2026-05-06 17:03:42 -03:00
Jose Selesan
41a217e8a9 Added booking logs to keep track of cancelled bookings and no shows 2026-05-06 16:54:48 -03:00
bb48d9c164 Merge pull request 'ui-v2' (#10) from ui-v2 into development
Reviewed-on: https://gitea.2pidev.com/jselesan/playzer/pulls/10
2026-05-06 18:32:24 +00:00
Jose Selesan
01688cf042 Booking tools 2026-05-06 15:31:02 -03:00
Jose Selesan
b97eb9c8a4 Minor changes 2026-05-05 18:40:41 -03:00
Jose Selesan
c089215835 New booking panel 2026-05-05 10:16:38 -03:00
Jose Selesan
546a020003 New header and backgroud style 2026-05-04 14:33:58 -03:00
38b2294aad Merge pull request 'add-result-pattern' (#9) from add-result-pattern into development
Reviewed-on: https://gitea.2pidev.com/jselesan/playzer/pulls/9
2026-04-27 19:17:41 +00:00
Jose Selesan
c9ecdd2c77 Add interface design references and principles; implement sport service tests
- Introduced critique, example, principles, and validation documents for interface design.
- Enhanced backend service with coverage threshold and fixed variable declaration in sport service.
- Added comprehensive tests for create, update, and list sports functionalities.
2026-04-24 10:40:25 -03:00
Jose Selesan
21d0c27f4d feat: enhance createSport functionality with conflict handling and result management
Co-authored-by: Copilot <copilot@github.com>
2026-04-23 16:46:46 -03:00
Jose Selesan
20d6018836 feat: implement error handling and validation middleware, enhance result handling
Co-authored-by: Copilot <copilot@github.com>
2026-04-23 16:35:57 -03:00
109 changed files with 7847 additions and 3200 deletions

View File

@@ -1,211 +0,0 @@
# Design System - Playzer
## Direction
**Feel:** Technical but warm. Like a well-organized sports facility — functional, clean, but with life. Not cold like a trading terminal, not playful like a toy app.
**Users:** Owners and employees managing sports complex bookings. They're juggling schedules, phone calls, and walk-ins. The interface should stay out of the way while they're working.
---
## Domain
**Concepts:**
- Turno (booking slot) — A scheduled time block
- Cancha (court) — Sports court/pitch
- Horario — Time slot
- Complex — The sports facility
- Estado — Booking status (confirmed, cancelled, etc.)
**Color world:**
- Court green (grass/tennis)
- Clay tan (paddle court)
- Pool blue (swimming)
- Wood grain (locker rooms)
- Concrete gray (tech floor)
**Signature:**
- Status pills use subtle borders + background tint, not bold badges
- Status communicates without demanding attention — whisper-level hierarchy
---
## Decisions
### Depth
**Approach:** Borders-only with surface elevation shifts
- No drop shadows
- Higher elevation = slightly lighter surface (in dark: lighter = higher)
- Subtle rgba borders define edges quietly
### Spacing
**Base unit:** 4px
- Micro: 2-4px (icon gaps)
- Component: 8-12px (inside buttons, badges)
- Section: 16-24px (between groups)
- Major: 32-40px (between distinct areas)
### Typography
**Font:** Geist Variable
**Scale:**
- Display: 28px / semibold / -0.02em tracking
- Heading: 20px / semibold / -0.01em tracking
- Body: 14px / normal / 0 tracking
- Label: 12px / medium / 0 tracking
- Caption: 11px / normal / 0.02em tracking
### Border Radius
**Scale:**
- `sm`: 4px (inputs, small badges)
- `md`: 6px (buttons, cards)
- `lg`: 10px (dialogs, large cards)
- `xl`: 14px (modals)
### Borders
**Progression:**
- Subtle: `oklch(1 0 0 / 8%)` (background edges)
- Default: `oklch(1 0 0 / 12%)` (card borders)
- Emphasis: `oklch(1 0 0 / 20%)` (active states)
### Status Semantic Colors
**Light mode:**
- Confirmed: `bg-emerald-50 border-emerald-200 text-emerald-700`
- Pending: `bg-amber-50 border-amber-200 text-amber-700`
- Cancelled: `bg-rose-50 border-rose-200 text-rose-700`
- No-show: `bg-orange-50 border-orange-200 text-orange-700`
- Completed: `bg-sky-50 border-sky-200 text-sky-700`
**Dark mode:**
- Slight desaturation, lower opacity backgrounds
---
## Patterns
### Card
- Background: `bg-card`
- Border: `border` token
- Radius: `md`
- Padding: `p-4` (compact) / `p-5` (default)
### Status Badge
```tsx
<span className="inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium">
{icon}
{label}
</span>
```
### Input
- Background: `bg-input` (darker than surface)
- No heavy borders by default
- Focus ring via `ring-3 ring-ring/50`
### Layout
- Sidebar: Same background as main, subtle border separation
- Content: Max-width 6xl, centered
- Padding: `px-4 sm:px-6`
---
## TODO
- [x] Status tokens in CSS variables
- [x] Refactor status badges to use semantic classes
- [x] StatusBadge component created
- [x] Home panel redesign with metrics + timeline
---
## Home Page Patterns (v2)
### Structure
- Header + URL Card: 2-column grid (lg:)
- Main: Timeline de reservas
- Sidebar: Stats grid consolidado (sticky)
### URL Card (destacada)
```tsx
<div className="group relative overflow-hidden rounded-2xl border border-blue-200/60 bg-blue-50/50 p-5">
<div className="absolute inset-0 bg-gradient-to-br from-blue-50/80 to-blue-100/30" />
<div className="relative flex items-center justify-between gap-4">
<div className="min-w-0 flex-1">
<p className="text-[11px] font-semibold uppercase tracking-[0.28em] text-blue-600/70">
Reserva online
</p>
<a href={url} className="mt-1 block truncate text-sm font-medium text-blue-700 underline-offset-2 hover:underline">
{url}
</a>
</div>
<button className="relative flex shrink-0 items-center gap-2 rounded-lg bg-blue-500/10 px-3 py-2 text-sm font-medium text-blue-700 transition-colors hover:bg-blue-500/20">
<Copy className="size-4" />
<span>Copiar</span>
</button>
</div>
</div>
```
### Stats Pills (header)
```tsx
<span className="rounded-full border border-emerald-200/60 bg-emerald-50/60 px-3 py-1 text-xs font-medium text-emerald-700">
{count} hoy
</span>
```
### Stats Sidebar (grid 2x2)
```tsx
<section className="space-y-3 rounded-2xl border border-border/70 bg-card p-4">
<h2 className="text-xs font-semibold uppercase tracking-[0.28em] text-muted-foreground">
Resumen
</h2>
<div className="grid grid-cols-2 gap-3">
<div className="rounded-xl border border-border/50 bg-background/80 p-3">
<p className="text-xs text-muted-foreground">Total</p>
<p className="mt-1 text-xl font-semibold tracking-tight">{value}</p>
</div>
<div className="rounded-xl border border-emerald-200/40 bg-emerald-50/40 p-3">
<p className="text-xs text-emerald-700/80">Hoy</p>
<p className="mt-1 text-xl font-semibold tracking-tight text-emerald-700">{value}</p>
</div>
{/* ... confirmed (blue), completed (sky) */}
</div>
</section>
```
### Timeline Item (v2 - mejorado)
```tsx
<div className={[
'group flex items-center justify-between gap-3 rounded-xl border border-border/70 bg-card/60 p-3.5 transition-all hover:bg-muted/50',
isPast && 'opacity-50',
isNow && 'border-l-2 border-l-emerald-500 bg-emerald-50/30',
].join(' ')}>
<div className="flex min-w-0 flex-1 items-center gap-3">
<div className="flex w-14 flex-col items-center">
<span className="text-sm font-medium tabular-nums">{startTime}</span>
<span className="text-[11px] text-muted-foreground">{endTime}</span>
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{courtName}</p>
<p className="truncate text-xs text-muted-foreground">{customer}</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<StatusBadge status={...} />
<div className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
<Button size="icon-xs" variant="ghost" title="Marcar cumplida"><Check className="size-3.5" /></Button>
<Button size="icon-xs" variant="ghost" title="Cancelar">×</Button>
</div>
</div>
</div>
```
### Date Group Header
```tsx
<div className="flex items-center gap-3">
<h2 className="text-sm font-semibold capitalize">{dateLabel}</h2>
<div className="h-px flex-1 border-t border-dashed border-border/40" />
<span className="shrink-0 rounded-full border border-border/70 bg-background px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground">
{count}
</span>
</div>
```

View File

@@ -32,25 +32,19 @@ COPY packages/api-contract/package.json packages/api-contract/
RUN bun install RUN bun install
# ============================================================================= # =============================================================================
# Stage 4: Prisma Generate # Stage 4: Build Backend (prisma generate + tsc)
# ============================================================================= # =============================================================================
FROM deps-backend AS prisma FROM deps-backend AS build-backend
WORKDIR /app WORKDIR /app
ARG DATABASE_URL ARG DATABASE_URL
ENV DATABASE_URL=${DATABASE_URL} ENV DATABASE_URL=${DATABASE_URL:-postgresql://dummy:dummy@localhost:5432/dummy}
COPY apps/backend ./apps/backend COPY apps/backend ./apps/backend
RUN bun --cwd apps/backend prisma:generate
# =============================================================================
# Stage 5: Build Backend
# =============================================================================
FROM prisma AS build-backend
WORKDIR /app
COPY packages ./packages COPY packages ./packages
RUN bun --cwd apps/backend prisma:generate
RUN bun --cwd apps/backend build RUN bun --cwd apps/backend build
# ============================================================================= # =============================================================================
# Stage 6: Runner - Production image # Stage 5: Runner - Production image
# ============================================================================= # =============================================================================
FROM oven/bun:1.3.11 AS runner FROM oven/bun:1.3.11 AS runner
WORKDIR /app WORKDIR /app
@@ -60,7 +54,7 @@ COPY --from=build-backend /app/node_modules ./node_modules
COPY --from=build-frontend /app/apps/frontend/dist ./apps/backend/public COPY --from=build-frontend /app/apps/frontend/dist ./apps/backend/public
COPY --from=build-backend /app/apps/backend ./apps/backend COPY --from=build-backend /app/apps/backend ./apps/backend
COPY --from=build-backend /app/packages ./packages COPY --from=build-backend /app/packages ./packages
COPY package.json ./ COPY package.json bun.lock ./
COPY entrypoint.sh /app/entrypoint.sh COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh RUN chmod +x /app/entrypoint.sh

View File

@@ -1,2 +1,3 @@
[test] [test]
preload = ["./test/support/prisma.mock.ts"] preload = ["./test/support/prisma.mock.ts"]
coverageThreshold = 0.8

View File

@@ -12,6 +12,7 @@ enum CourtBookingStatus {
CONFIRMED CONFIRMED
CANCELLED CANCELLED
COMPLETED COMPLETED
NOSHOW
} }
model Sport { model Sport {
@@ -82,7 +83,6 @@ model CourtBooking {
bookingDate DateTime @map("booking_date") @db.Date bookingDate DateTime @map("booking_date") @db.Date
startTime String @map("start_time") @db.VarChar(5) startTime String @map("start_time") @db.VarChar(5)
endTime String @map("end_time") @db.VarChar(5) endTime String @map("end_time") @db.VarChar(5)
price Decimal? @map("price") @db.Decimal(19, 2)
customerName String @map("customer_name") @db.VarChar(120) customerName String @map("customer_name") @db.VarChar(120)
customerPhone String @map("customer_phone") @db.VarChar(30) customerPhone String @map("customer_phone") @db.VarChar(30)
status CourtBookingStatus @default(CONFIRMED) status CourtBookingStatus @default(CONFIRMED)
@@ -95,3 +95,20 @@ model CourtBooking {
@@index([bookingDate]) @@index([bookingDate])
@@map("court_bookings") @@map("court_bookings")
} }
model CourtBookingLog {
id String @id @db.Uuid
bookingCode String @map("booking_code") @db.VarChar(8)
courtId String @map("court_id") @db.Uuid
bookingDate DateTime @map("booking_date") @db.Date
startTime String @map("start_time") @db.VarChar(5)
endTime String @map("end_time") @db.VarChar(5)
previousStatus CourtBookingStatus @map("previous_status")
newStatus CourtBookingStatus @map("new_status")
customerName String @map("customer_name") @db.VarChar(120)
customerPhone String @map("customer_phone") @db.VarChar(30)
changedAt DateTime @default(now()) @map("changed_at")
@@map("court_booking_logs")
@@index([courtId, newStatus])
}

View File

@@ -1,2 +0,0 @@
-- AlterTable
ALTER TABLE "court_bookings" ADD COLUMN "price" DECIMAL(19,2);

View File

@@ -0,0 +1,17 @@
-- CreateTable
CREATE TABLE "court_booking_logs" (
"id" UUID NOT NULL,
"booking_code" UUID NOT NULL,
"court_id" UUID NOT NULL,
"booking_date" DATE NOT NULL,
"start_time" VARCHAR(5) NOT NULL,
"end_time" VARCHAR(5) NOT NULL,
"previous_status" "CourtBookingStatus" NOT NULL,
"new_status" "CourtBookingStatus" NOT NULL,
"changed_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "court_booking_logs_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "court_booking_logs_court_id_new_status_idx" ON "court_booking_logs"("court_id", "new_status");

View File

@@ -0,0 +1,13 @@
/*
Warnings:
- Added the required column `customer_name` to the `court_booking_logs` table without a default value. This is not possible if the table is not empty.
- Added the required column `customer_phone` to the `court_booking_logs` table without a default value. This is not possible if the table is not empty.
*/
-- AlterEnum
ALTER TYPE "CourtBookingStatus" ADD VALUE 'NOSHOW';
-- AlterTable
ALTER TABLE "court_booking_logs" ADD COLUMN "customer_name" VARCHAR(120) NOT NULL,
ADD COLUMN "customer_phone" VARCHAR(30) NOT NULL;

View File

@@ -0,0 +1,9 @@
/*
Warnings:
- Changed the type of `booking_code` on the `court_booking_logs` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
*/
-- AlterTable
ALTER TABLE "court_booking_logs" DROP COLUMN "booking_code",
ADD COLUMN "booking_code" VARCHAR(8) NOT NULL;

View File

@@ -3,10 +3,15 @@ import type { AppEnv } from '@/types/hono';
import { Hono } from 'hono'; import { Hono } from 'hono';
import { cors } from 'hono/cors'; import { cors } from 'hono/cors';
import { requestId } from 'hono/request-id'; import { requestId } from 'hono/request-id';
import { errorHandler } from './lib/http/error-handler';
import { requestIdMiddleware } from './lib/http/request-id';
export function createApp() { export function createApp() {
const app = new Hono<AppEnv>(); const app = new Hono<AppEnv>();
app.use('*', requestIdMiddleware);
app.use('*', errorHandler);
const allowedOrigins = (Bun.env.CORS_ORIGIN ?? 'http://localhost:5173,http://127.0.0.1:5173') const allowedOrigins = (Bun.env.CORS_ORIGIN ?? 'http://localhost:5173,http://127.0.0.1:5173')
.split(',') .split(',')
.map((value) => value.trim()) .map((value) => value.trim())

View File

@@ -77,6 +77,11 @@ export type CourtPriceRule = Prisma.CourtPriceRuleModel
* *
*/ */
export type CourtBooking = Prisma.CourtBookingModel export type CourtBooking = Prisma.CourtBookingModel
/**
* Model CourtBookingLog
*
*/
export type CourtBookingLog = Prisma.CourtBookingLogModel
/** /**
* Model OnboardingRequest * Model OnboardingRequest
* *

View File

@@ -101,6 +101,11 @@ export type CourtPriceRule = Prisma.CourtPriceRuleModel
* *
*/ */
export type CourtBooking = Prisma.CourtBookingModel export type CourtBooking = Prisma.CourtBookingModel
/**
* Model CourtBookingLog
*
*/
export type CourtBookingLog = Prisma.CourtBookingLogModel
/** /**
* Model OnboardingRequest * Model OnboardingRequest
* *

View File

@@ -280,17 +280,6 @@ export type EnumDayOfWeekNullableWithAggregatesFilter<$PrismaModel = never> = {
_max?: Prisma.NestedEnumDayOfWeekNullableFilter<$PrismaModel> _max?: Prisma.NestedEnumDayOfWeekNullableFilter<$PrismaModel>
} }
export type DecimalNullableFilter<$PrismaModel = never> = {
equals?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel> | null
in?: runtime.Decimal[] | runtime.DecimalJsLike[] | number[] | string[] | Prisma.ListDecimalFieldRefInput<$PrismaModel> | null
notIn?: runtime.Decimal[] | runtime.DecimalJsLike[] | number[] | string[] | Prisma.ListDecimalFieldRefInput<$PrismaModel> | null
lt?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
lte?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
gt?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
gte?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
not?: Prisma.NestedDecimalNullableFilter<$PrismaModel> | runtime.Decimal | runtime.DecimalJsLike | number | string | null
}
export type EnumCourtBookingStatusFilter<$PrismaModel = never> = { export type EnumCourtBookingStatusFilter<$PrismaModel = never> = {
equals?: $Enums.CourtBookingStatus | Prisma.EnumCourtBookingStatusFieldRefInput<$PrismaModel> equals?: $Enums.CourtBookingStatus | Prisma.EnumCourtBookingStatusFieldRefInput<$PrismaModel>
in?: $Enums.CourtBookingStatus[] | Prisma.ListEnumCourtBookingStatusFieldRefInput<$PrismaModel> in?: $Enums.CourtBookingStatus[] | Prisma.ListEnumCourtBookingStatusFieldRefInput<$PrismaModel>
@@ -298,22 +287,6 @@ export type EnumCourtBookingStatusFilter<$PrismaModel = never> = {
not?: Prisma.NestedEnumCourtBookingStatusFilter<$PrismaModel> | $Enums.CourtBookingStatus not?: Prisma.NestedEnumCourtBookingStatusFilter<$PrismaModel> | $Enums.CourtBookingStatus
} }
export type DecimalNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel> | null
in?: runtime.Decimal[] | runtime.DecimalJsLike[] | number[] | string[] | Prisma.ListDecimalFieldRefInput<$PrismaModel> | null
notIn?: runtime.Decimal[] | runtime.DecimalJsLike[] | number[] | string[] | Prisma.ListDecimalFieldRefInput<$PrismaModel> | null
lt?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
lte?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
gt?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
gte?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
not?: Prisma.NestedDecimalNullableWithAggregatesFilter<$PrismaModel> | runtime.Decimal | runtime.DecimalJsLike | number | string | null
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
_avg?: Prisma.NestedDecimalNullableFilter<$PrismaModel>
_sum?: Prisma.NestedDecimalNullableFilter<$PrismaModel>
_min?: Prisma.NestedDecimalNullableFilter<$PrismaModel>
_max?: Prisma.NestedDecimalNullableFilter<$PrismaModel>
}
export type EnumCourtBookingStatusWithAggregatesFilter<$PrismaModel = never> = { export type EnumCourtBookingStatusWithAggregatesFilter<$PrismaModel = never> = {
equals?: $Enums.CourtBookingStatus | Prisma.EnumCourtBookingStatusFieldRefInput<$PrismaModel> equals?: $Enums.CourtBookingStatus | Prisma.EnumCourtBookingStatusFieldRefInput<$PrismaModel>
in?: $Enums.CourtBookingStatus[] | Prisma.ListEnumCourtBookingStatusFieldRefInput<$PrismaModel> in?: $Enums.CourtBookingStatus[] | Prisma.ListEnumCourtBookingStatusFieldRefInput<$PrismaModel>
@@ -652,17 +625,6 @@ export type NestedEnumDayOfWeekNullableWithAggregatesFilter<$PrismaModel = never
_max?: Prisma.NestedEnumDayOfWeekNullableFilter<$PrismaModel> _max?: Prisma.NestedEnumDayOfWeekNullableFilter<$PrismaModel>
} }
export type NestedDecimalNullableFilter<$PrismaModel = never> = {
equals?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel> | null
in?: runtime.Decimal[] | runtime.DecimalJsLike[] | number[] | string[] | Prisma.ListDecimalFieldRefInput<$PrismaModel> | null
notIn?: runtime.Decimal[] | runtime.DecimalJsLike[] | number[] | string[] | Prisma.ListDecimalFieldRefInput<$PrismaModel> | null
lt?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
lte?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
gt?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
gte?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
not?: Prisma.NestedDecimalNullableFilter<$PrismaModel> | runtime.Decimal | runtime.DecimalJsLike | number | string | null
}
export type NestedEnumCourtBookingStatusFilter<$PrismaModel = never> = { export type NestedEnumCourtBookingStatusFilter<$PrismaModel = never> = {
equals?: $Enums.CourtBookingStatus | Prisma.EnumCourtBookingStatusFieldRefInput<$PrismaModel> equals?: $Enums.CourtBookingStatus | Prisma.EnumCourtBookingStatusFieldRefInput<$PrismaModel>
in?: $Enums.CourtBookingStatus[] | Prisma.ListEnumCourtBookingStatusFieldRefInput<$PrismaModel> in?: $Enums.CourtBookingStatus[] | Prisma.ListEnumCourtBookingStatusFieldRefInput<$PrismaModel>
@@ -670,22 +632,6 @@ export type NestedEnumCourtBookingStatusFilter<$PrismaModel = never> = {
not?: Prisma.NestedEnumCourtBookingStatusFilter<$PrismaModel> | $Enums.CourtBookingStatus not?: Prisma.NestedEnumCourtBookingStatusFilter<$PrismaModel> | $Enums.CourtBookingStatus
} }
export type NestedDecimalNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel> | null
in?: runtime.Decimal[] | runtime.DecimalJsLike[] | number[] | string[] | Prisma.ListDecimalFieldRefInput<$PrismaModel> | null
notIn?: runtime.Decimal[] | runtime.DecimalJsLike[] | number[] | string[] | Prisma.ListDecimalFieldRefInput<$PrismaModel> | null
lt?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
lte?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
gt?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
gte?: runtime.Decimal | runtime.DecimalJsLike | number | string | Prisma.DecimalFieldRefInput<$PrismaModel>
not?: Prisma.NestedDecimalNullableWithAggregatesFilter<$PrismaModel> | runtime.Decimal | runtime.DecimalJsLike | number | string | null
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
_avg?: Prisma.NestedDecimalNullableFilter<$PrismaModel>
_sum?: Prisma.NestedDecimalNullableFilter<$PrismaModel>
_min?: Prisma.NestedDecimalNullableFilter<$PrismaModel>
_max?: Prisma.NestedDecimalNullableFilter<$PrismaModel>
}
export type NestedEnumCourtBookingStatusWithAggregatesFilter<$PrismaModel = never> = { export type NestedEnumCourtBookingStatusWithAggregatesFilter<$PrismaModel = never> = {
equals?: $Enums.CourtBookingStatus | Prisma.EnumCourtBookingStatusFieldRefInput<$PrismaModel> equals?: $Enums.CourtBookingStatus | Prisma.EnumCourtBookingStatusFieldRefInput<$PrismaModel>
in?: $Enums.CourtBookingStatus[] | Prisma.ListEnumCourtBookingStatusFieldRefInput<$PrismaModel> in?: $Enums.CourtBookingStatus[] | Prisma.ListEnumCourtBookingStatusFieldRefInput<$PrismaModel>

View File

@@ -33,7 +33,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' COMPLETED: 'COMPLETED',
NOSHOW: 'NOSHOW'
} 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

View File

@@ -396,6 +396,7 @@ export const ModelName = {
CourtAvailability: 'CourtAvailability', CourtAvailability: 'CourtAvailability',
CourtPriceRule: 'CourtPriceRule', CourtPriceRule: 'CourtPriceRule',
CourtBooking: 'CourtBooking', CourtBooking: 'CourtBooking',
CourtBookingLog: 'CourtBookingLog',
OnboardingRequest: 'OnboardingRequest', OnboardingRequest: 'OnboardingRequest',
PasswordResetRequest: 'PasswordResetRequest', PasswordResetRequest: 'PasswordResetRequest',
Plan: 'Plan' Plan: 'Plan'
@@ -414,7 +415,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
omit: GlobalOmitOptions omit: GlobalOmitOptions
} }
meta: { meta: {
modelProps: "user" | "session" | "account" | "verification" | "complex" | "complexUser" | "complexInvitation" | "sport" | "court" | "courtAvailability" | "courtPriceRule" | "courtBooking" | "onboardingRequest" | "passwordResetRequest" | "plan" modelProps: "user" | "session" | "account" | "verification" | "complex" | "complexUser" | "complexInvitation" | "sport" | "court" | "courtAvailability" | "courtPriceRule" | "courtBooking" | "courtBookingLog" | "onboardingRequest" | "passwordResetRequest" | "plan"
txIsolationLevel: TransactionIsolationLevel txIsolationLevel: TransactionIsolationLevel
} }
model: { model: {
@@ -1306,6 +1307,80 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
} }
} }
} }
CourtBookingLog: {
payload: Prisma.$CourtBookingLogPayload<ExtArgs>
fields: Prisma.CourtBookingLogFieldRefs
operations: {
findUnique: {
args: Prisma.CourtBookingLogFindUniqueArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload> | null
}
findUniqueOrThrow: {
args: Prisma.CourtBookingLogFindUniqueOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
}
findFirst: {
args: Prisma.CourtBookingLogFindFirstArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload> | null
}
findFirstOrThrow: {
args: Prisma.CourtBookingLogFindFirstOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
}
findMany: {
args: Prisma.CourtBookingLogFindManyArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>[]
}
create: {
args: Prisma.CourtBookingLogCreateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
}
createMany: {
args: Prisma.CourtBookingLogCreateManyArgs<ExtArgs>
result: BatchPayload
}
createManyAndReturn: {
args: Prisma.CourtBookingLogCreateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>[]
}
delete: {
args: Prisma.CourtBookingLogDeleteArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
}
update: {
args: Prisma.CourtBookingLogUpdateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
}
deleteMany: {
args: Prisma.CourtBookingLogDeleteManyArgs<ExtArgs>
result: BatchPayload
}
updateMany: {
args: Prisma.CourtBookingLogUpdateManyArgs<ExtArgs>
result: BatchPayload
}
updateManyAndReturn: {
args: Prisma.CourtBookingLogUpdateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>[]
}
upsert: {
args: Prisma.CourtBookingLogUpsertArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
}
aggregate: {
args: Prisma.CourtBookingLogAggregateArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AggregateCourtBookingLog>
}
groupBy: {
args: Prisma.CourtBookingLogGroupByArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.CourtBookingLogGroupByOutputType>[]
}
count: {
args: Prisma.CourtBookingLogCountArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.CourtBookingLogCountAggregateOutputType> | number
}
}
}
OnboardingRequest: { OnboardingRequest: {
payload: Prisma.$OnboardingRequestPayload<ExtArgs> payload: Prisma.$OnboardingRequestPayload<ExtArgs>
fields: Prisma.OnboardingRequestFieldRefs fields: Prisma.OnboardingRequestFieldRefs
@@ -1728,7 +1803,6 @@ export const CourtBookingScalarFieldEnum = {
bookingDate: 'bookingDate', bookingDate: 'bookingDate',
startTime: 'startTime', startTime: 'startTime',
endTime: 'endTime', endTime: 'endTime',
price: 'price',
customerName: 'customerName', customerName: 'customerName',
customerPhone: 'customerPhone', customerPhone: 'customerPhone',
status: 'status', status: 'status',
@@ -1739,6 +1813,23 @@ export const CourtBookingScalarFieldEnum = {
export type CourtBookingScalarFieldEnum = (typeof CourtBookingScalarFieldEnum)[keyof typeof CourtBookingScalarFieldEnum] export type CourtBookingScalarFieldEnum = (typeof CourtBookingScalarFieldEnum)[keyof typeof CourtBookingScalarFieldEnum]
export const CourtBookingLogScalarFieldEnum = {
id: 'id',
bookingCode: 'bookingCode',
courtId: 'courtId',
bookingDate: 'bookingDate',
startTime: 'startTime',
endTime: 'endTime',
previousStatus: 'previousStatus',
newStatus: 'newStatus',
customerName: 'customerName',
customerPhone: 'customerPhone',
changedAt: 'changedAt'
} as const
export type CourtBookingLogScalarFieldEnum = (typeof CourtBookingLogScalarFieldEnum)[keyof typeof CourtBookingLogScalarFieldEnum]
export const OnboardingRequestScalarFieldEnum = { export const OnboardingRequestScalarFieldEnum = {
id: 'id', id: 'id',
fullName: 'fullName', fullName: 'fullName',
@@ -2069,6 +2160,7 @@ export type GlobalOmitConfig = {
courtAvailability?: Prisma.CourtAvailabilityOmit courtAvailability?: Prisma.CourtAvailabilityOmit
courtPriceRule?: Prisma.CourtPriceRuleOmit courtPriceRule?: Prisma.CourtPriceRuleOmit
courtBooking?: Prisma.CourtBookingOmit courtBooking?: Prisma.CourtBookingOmit
courtBookingLog?: Prisma.CourtBookingLogOmit
onboardingRequest?: Prisma.OnboardingRequestOmit onboardingRequest?: Prisma.OnboardingRequestOmit
passwordResetRequest?: Prisma.PasswordResetRequestOmit passwordResetRequest?: Prisma.PasswordResetRequestOmit
plan?: Prisma.PlanOmit plan?: Prisma.PlanOmit

View File

@@ -63,6 +63,7 @@ export const ModelName = {
CourtAvailability: 'CourtAvailability', CourtAvailability: 'CourtAvailability',
CourtPriceRule: 'CourtPriceRule', CourtPriceRule: 'CourtPriceRule',
CourtBooking: 'CourtBooking', CourtBooking: 'CourtBooking',
CourtBookingLog: 'CourtBookingLog',
OnboardingRequest: 'OnboardingRequest', OnboardingRequest: 'OnboardingRequest',
PasswordResetRequest: 'PasswordResetRequest', PasswordResetRequest: 'PasswordResetRequest',
Plan: 'Plan' Plan: 'Plan'
@@ -245,7 +246,6 @@ export const CourtBookingScalarFieldEnum = {
bookingDate: 'bookingDate', bookingDate: 'bookingDate',
startTime: 'startTime', startTime: 'startTime',
endTime: 'endTime', endTime: 'endTime',
price: 'price',
customerName: 'customerName', customerName: 'customerName',
customerPhone: 'customerPhone', customerPhone: 'customerPhone',
status: 'status', status: 'status',
@@ -256,6 +256,23 @@ export const CourtBookingScalarFieldEnum = {
export type CourtBookingScalarFieldEnum = (typeof CourtBookingScalarFieldEnum)[keyof typeof CourtBookingScalarFieldEnum] export type CourtBookingScalarFieldEnum = (typeof CourtBookingScalarFieldEnum)[keyof typeof CourtBookingScalarFieldEnum]
export const CourtBookingLogScalarFieldEnum = {
id: 'id',
bookingCode: 'bookingCode',
courtId: 'courtId',
bookingDate: 'bookingDate',
startTime: 'startTime',
endTime: 'endTime',
previousStatus: 'previousStatus',
newStatus: 'newStatus',
customerName: 'customerName',
customerPhone: 'customerPhone',
changedAt: 'changedAt'
} as const
export type CourtBookingLogScalarFieldEnum = (typeof CourtBookingLogScalarFieldEnum)[keyof typeof CourtBookingLogScalarFieldEnum]
export const OnboardingRequestScalarFieldEnum = { export const OnboardingRequestScalarFieldEnum = {
id: 'id', id: 'id',
fullName: 'fullName', fullName: 'fullName',

View File

@@ -20,6 +20,7 @@ export type * from './models/Court'
export type * from './models/CourtAvailability' export type * from './models/CourtAvailability'
export type * from './models/CourtPriceRule' export type * from './models/CourtPriceRule'
export type * from './models/CourtBooking' export type * from './models/CourtBooking'
export type * from './models/CourtBookingLog'
export type * from './models/OnboardingRequest' export type * from './models/OnboardingRequest'
export type * from './models/PasswordResetRequest' export type * from './models/PasswordResetRequest'
export type * from './models/Plan' export type * from './models/Plan'

View File

@@ -20,20 +20,10 @@ export type CourtBookingModel = runtime.Types.Result.DefaultSelection<Prisma.$Co
export type AggregateCourtBooking = { export type AggregateCourtBooking = {
_count: CourtBookingCountAggregateOutputType | null _count: CourtBookingCountAggregateOutputType | null
_avg: CourtBookingAvgAggregateOutputType | null
_sum: CourtBookingSumAggregateOutputType | null
_min: CourtBookingMinAggregateOutputType | null _min: CourtBookingMinAggregateOutputType | null
_max: CourtBookingMaxAggregateOutputType | null _max: CourtBookingMaxAggregateOutputType | null
} }
export type CourtBookingAvgAggregateOutputType = {
price: runtime.Decimal | null
}
export type CourtBookingSumAggregateOutputType = {
price: runtime.Decimal | null
}
export type CourtBookingMinAggregateOutputType = { export type CourtBookingMinAggregateOutputType = {
id: string | null id: string | null
bookingCode: string | null bookingCode: string | null
@@ -41,7 +31,6 @@ export type CourtBookingMinAggregateOutputType = {
bookingDate: Date | null bookingDate: Date | null
startTime: string | null startTime: string | null
endTime: string | null endTime: string | null
price: runtime.Decimal | null
customerName: string | null customerName: string | null
customerPhone: string | null customerPhone: string | null
status: $Enums.CourtBookingStatus | null status: $Enums.CourtBookingStatus | null
@@ -56,7 +45,6 @@ export type CourtBookingMaxAggregateOutputType = {
bookingDate: Date | null bookingDate: Date | null
startTime: string | null startTime: string | null
endTime: string | null endTime: string | null
price: runtime.Decimal | null
customerName: string | null customerName: string | null
customerPhone: string | null customerPhone: string | null
status: $Enums.CourtBookingStatus | null status: $Enums.CourtBookingStatus | null
@@ -71,7 +59,6 @@ export type CourtBookingCountAggregateOutputType = {
bookingDate: number bookingDate: number
startTime: number startTime: number
endTime: number endTime: number
price: number
customerName: number customerName: number
customerPhone: number customerPhone: number
status: number status: number
@@ -81,14 +68,6 @@ export type CourtBookingCountAggregateOutputType = {
} }
export type CourtBookingAvgAggregateInputType = {
price?: true
}
export type CourtBookingSumAggregateInputType = {
price?: true
}
export type CourtBookingMinAggregateInputType = { export type CourtBookingMinAggregateInputType = {
id?: true id?: true
bookingCode?: true bookingCode?: true
@@ -96,7 +75,6 @@ export type CourtBookingMinAggregateInputType = {
bookingDate?: true bookingDate?: true
startTime?: true startTime?: true
endTime?: true endTime?: true
price?: true
customerName?: true customerName?: true
customerPhone?: true customerPhone?: true
status?: true status?: true
@@ -111,7 +89,6 @@ export type CourtBookingMaxAggregateInputType = {
bookingDate?: true bookingDate?: true
startTime?: true startTime?: true
endTime?: true endTime?: true
price?: true
customerName?: true customerName?: true
customerPhone?: true customerPhone?: true
status?: true status?: true
@@ -126,7 +103,6 @@ export type CourtBookingCountAggregateInputType = {
bookingDate?: true bookingDate?: true
startTime?: true startTime?: true
endTime?: true endTime?: true
price?: true
customerName?: true customerName?: true
customerPhone?: true customerPhone?: true
status?: true status?: true
@@ -170,18 +146,6 @@ export type CourtBookingAggregateArgs<ExtArgs extends runtime.Types.Extensions.I
* Count returned CourtBookings * Count returned CourtBookings
**/ **/
_count?: true | CourtBookingCountAggregateInputType _count?: true | CourtBookingCountAggregateInputType
/**
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
*
* Select which fields to average
**/
_avg?: CourtBookingAvgAggregateInputType
/**
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
*
* Select which fields to sum
**/
_sum?: CourtBookingSumAggregateInputType
/** /**
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
* *
@@ -215,8 +179,6 @@ export type CourtBookingGroupByArgs<ExtArgs extends runtime.Types.Extensions.Int
take?: number take?: number
skip?: number skip?: number
_count?: CourtBookingCountAggregateInputType | true _count?: CourtBookingCountAggregateInputType | true
_avg?: CourtBookingAvgAggregateInputType
_sum?: CourtBookingSumAggregateInputType
_min?: CourtBookingMinAggregateInputType _min?: CourtBookingMinAggregateInputType
_max?: CourtBookingMaxAggregateInputType _max?: CourtBookingMaxAggregateInputType
} }
@@ -228,15 +190,12 @@ export type CourtBookingGroupByOutputType = {
bookingDate: Date bookingDate: Date
startTime: string startTime: string
endTime: string endTime: string
price: runtime.Decimal | null
customerName: string customerName: string
customerPhone: string customerPhone: string
status: $Enums.CourtBookingStatus status: $Enums.CourtBookingStatus
createdAt: Date createdAt: Date
updatedAt: Date updatedAt: Date
_count: CourtBookingCountAggregateOutputType | null _count: CourtBookingCountAggregateOutputType | null
_avg: CourtBookingAvgAggregateOutputType | null
_sum: CourtBookingSumAggregateOutputType | null
_min: CourtBookingMinAggregateOutputType | null _min: CourtBookingMinAggregateOutputType | null
_max: CourtBookingMaxAggregateOutputType | null _max: CourtBookingMaxAggregateOutputType | null
} }
@@ -266,7 +225,6 @@ export type CourtBookingWhereInput = {
bookingDate?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string bookingDate?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
startTime?: Prisma.StringFilter<"CourtBooking"> | string startTime?: Prisma.StringFilter<"CourtBooking"> | string
endTime?: Prisma.StringFilter<"CourtBooking"> | string endTime?: Prisma.StringFilter<"CourtBooking"> | string
price?: Prisma.DecimalNullableFilter<"CourtBooking"> | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFilter<"CourtBooking"> | string customerName?: Prisma.StringFilter<"CourtBooking"> | string
customerPhone?: Prisma.StringFilter<"CourtBooking"> | string customerPhone?: Prisma.StringFilter<"CourtBooking"> | string
status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus
@@ -282,7 +240,6 @@ export type CourtBookingOrderByWithRelationInput = {
bookingDate?: Prisma.SortOrder bookingDate?: Prisma.SortOrder
startTime?: Prisma.SortOrder startTime?: Prisma.SortOrder
endTime?: Prisma.SortOrder endTime?: Prisma.SortOrder
price?: Prisma.SortOrderInput | Prisma.SortOrder
customerName?: Prisma.SortOrder customerName?: Prisma.SortOrder
customerPhone?: Prisma.SortOrder customerPhone?: Prisma.SortOrder
status?: Prisma.SortOrder status?: Prisma.SortOrder
@@ -302,7 +259,6 @@ export type CourtBookingWhereUniqueInput = Prisma.AtLeast<{
bookingDate?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string bookingDate?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
startTime?: Prisma.StringFilter<"CourtBooking"> | string startTime?: Prisma.StringFilter<"CourtBooking"> | string
endTime?: Prisma.StringFilter<"CourtBooking"> | string endTime?: Prisma.StringFilter<"CourtBooking"> | string
price?: Prisma.DecimalNullableFilter<"CourtBooking"> | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFilter<"CourtBooking"> | string customerName?: Prisma.StringFilter<"CourtBooking"> | string
customerPhone?: Prisma.StringFilter<"CourtBooking"> | string customerPhone?: Prisma.StringFilter<"CourtBooking"> | string
status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus
@@ -318,17 +274,14 @@ export type CourtBookingOrderByWithAggregationInput = {
bookingDate?: Prisma.SortOrder bookingDate?: Prisma.SortOrder
startTime?: Prisma.SortOrder startTime?: Prisma.SortOrder
endTime?: Prisma.SortOrder endTime?: Prisma.SortOrder
price?: Prisma.SortOrderInput | Prisma.SortOrder
customerName?: Prisma.SortOrder customerName?: Prisma.SortOrder
customerPhone?: Prisma.SortOrder customerPhone?: Prisma.SortOrder
status?: Prisma.SortOrder status?: Prisma.SortOrder
createdAt?: Prisma.SortOrder createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder updatedAt?: Prisma.SortOrder
_count?: Prisma.CourtBookingCountOrderByAggregateInput _count?: Prisma.CourtBookingCountOrderByAggregateInput
_avg?: Prisma.CourtBookingAvgOrderByAggregateInput
_max?: Prisma.CourtBookingMaxOrderByAggregateInput _max?: Prisma.CourtBookingMaxOrderByAggregateInput
_min?: Prisma.CourtBookingMinOrderByAggregateInput _min?: Prisma.CourtBookingMinOrderByAggregateInput
_sum?: Prisma.CourtBookingSumOrderByAggregateInput
} }
export type CourtBookingScalarWhereWithAggregatesInput = { export type CourtBookingScalarWhereWithAggregatesInput = {
@@ -341,7 +294,6 @@ export type CourtBookingScalarWhereWithAggregatesInput = {
bookingDate?: Prisma.DateTimeWithAggregatesFilter<"CourtBooking"> | Date | string bookingDate?: Prisma.DateTimeWithAggregatesFilter<"CourtBooking"> | Date | string
startTime?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string startTime?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string
endTime?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string endTime?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string
price?: Prisma.DecimalNullableWithAggregatesFilter<"CourtBooking"> | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string customerName?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string
customerPhone?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string customerPhone?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string
status?: Prisma.EnumCourtBookingStatusWithAggregatesFilter<"CourtBooking"> | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusWithAggregatesFilter<"CourtBooking"> | $Enums.CourtBookingStatus
@@ -355,7 +307,6 @@ export type CourtBookingCreateInput = {
bookingDate: Date | string bookingDate: Date | string
startTime: string startTime: string
endTime: string endTime: string
price?: runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName: string customerName: string
customerPhone: string customerPhone: string
status?: $Enums.CourtBookingStatus status?: $Enums.CourtBookingStatus
@@ -371,7 +322,6 @@ export type CourtBookingUncheckedCreateInput = {
bookingDate: Date | string bookingDate: Date | string
startTime: string startTime: string
endTime: string endTime: string
price?: runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName: string customerName: string
customerPhone: string customerPhone: string
status?: $Enums.CourtBookingStatus status?: $Enums.CourtBookingStatus
@@ -385,7 +335,6 @@ export type CourtBookingUpdateInput = {
bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
startTime?: Prisma.StringFieldUpdateOperationsInput | string startTime?: Prisma.StringFieldUpdateOperationsInput | string
endTime?: Prisma.StringFieldUpdateOperationsInput | string endTime?: Prisma.StringFieldUpdateOperationsInput | string
price?: Prisma.NullableDecimalFieldUpdateOperationsInput | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFieldUpdateOperationsInput | string customerName?: Prisma.StringFieldUpdateOperationsInput | string
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
@@ -401,7 +350,6 @@ export type CourtBookingUncheckedUpdateInput = {
bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
startTime?: Prisma.StringFieldUpdateOperationsInput | string startTime?: Prisma.StringFieldUpdateOperationsInput | string
endTime?: Prisma.StringFieldUpdateOperationsInput | string endTime?: Prisma.StringFieldUpdateOperationsInput | string
price?: Prisma.NullableDecimalFieldUpdateOperationsInput | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFieldUpdateOperationsInput | string customerName?: Prisma.StringFieldUpdateOperationsInput | string
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
@@ -416,7 +364,6 @@ export type CourtBookingCreateManyInput = {
bookingDate: Date | string bookingDate: Date | string
startTime: string startTime: string
endTime: string endTime: string
price?: runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName: string customerName: string
customerPhone: string customerPhone: string
status?: $Enums.CourtBookingStatus status?: $Enums.CourtBookingStatus
@@ -430,7 +377,6 @@ export type CourtBookingUpdateManyMutationInput = {
bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
startTime?: Prisma.StringFieldUpdateOperationsInput | string startTime?: Prisma.StringFieldUpdateOperationsInput | string
endTime?: Prisma.StringFieldUpdateOperationsInput | string endTime?: Prisma.StringFieldUpdateOperationsInput | string
price?: Prisma.NullableDecimalFieldUpdateOperationsInput | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFieldUpdateOperationsInput | string customerName?: Prisma.StringFieldUpdateOperationsInput | string
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
@@ -445,7 +391,6 @@ export type CourtBookingUncheckedUpdateManyInput = {
bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
startTime?: Prisma.StringFieldUpdateOperationsInput | string startTime?: Prisma.StringFieldUpdateOperationsInput | string
endTime?: Prisma.StringFieldUpdateOperationsInput | string endTime?: Prisma.StringFieldUpdateOperationsInput | string
price?: Prisma.NullableDecimalFieldUpdateOperationsInput | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFieldUpdateOperationsInput | string customerName?: Prisma.StringFieldUpdateOperationsInput | string
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
@@ -476,7 +421,6 @@ export type CourtBookingCountOrderByAggregateInput = {
bookingDate?: Prisma.SortOrder bookingDate?: Prisma.SortOrder
startTime?: Prisma.SortOrder startTime?: Prisma.SortOrder
endTime?: Prisma.SortOrder endTime?: Prisma.SortOrder
price?: Prisma.SortOrder
customerName?: Prisma.SortOrder customerName?: Prisma.SortOrder
customerPhone?: Prisma.SortOrder customerPhone?: Prisma.SortOrder
status?: Prisma.SortOrder status?: Prisma.SortOrder
@@ -484,10 +428,6 @@ export type CourtBookingCountOrderByAggregateInput = {
updatedAt?: Prisma.SortOrder updatedAt?: Prisma.SortOrder
} }
export type CourtBookingAvgOrderByAggregateInput = {
price?: Prisma.SortOrder
}
export type CourtBookingMaxOrderByAggregateInput = { export type CourtBookingMaxOrderByAggregateInput = {
id?: Prisma.SortOrder id?: Prisma.SortOrder
bookingCode?: Prisma.SortOrder bookingCode?: Prisma.SortOrder
@@ -495,7 +435,6 @@ export type CourtBookingMaxOrderByAggregateInput = {
bookingDate?: Prisma.SortOrder bookingDate?: Prisma.SortOrder
startTime?: Prisma.SortOrder startTime?: Prisma.SortOrder
endTime?: Prisma.SortOrder endTime?: Prisma.SortOrder
price?: Prisma.SortOrder
customerName?: Prisma.SortOrder customerName?: Prisma.SortOrder
customerPhone?: Prisma.SortOrder customerPhone?: Prisma.SortOrder
status?: Prisma.SortOrder status?: Prisma.SortOrder
@@ -510,7 +449,6 @@ export type CourtBookingMinOrderByAggregateInput = {
bookingDate?: Prisma.SortOrder bookingDate?: Prisma.SortOrder
startTime?: Prisma.SortOrder startTime?: Prisma.SortOrder
endTime?: Prisma.SortOrder endTime?: Prisma.SortOrder
price?: Prisma.SortOrder
customerName?: Prisma.SortOrder customerName?: Prisma.SortOrder
customerPhone?: Prisma.SortOrder customerPhone?: Prisma.SortOrder
status?: Prisma.SortOrder status?: Prisma.SortOrder
@@ -518,10 +456,6 @@ export type CourtBookingMinOrderByAggregateInput = {
updatedAt?: Prisma.SortOrder updatedAt?: Prisma.SortOrder
} }
export type CourtBookingSumOrderByAggregateInput = {
price?: Prisma.SortOrder
}
export type CourtBookingCreateNestedManyWithoutCourtInput = { export type CourtBookingCreateNestedManyWithoutCourtInput = {
create?: Prisma.XOR<Prisma.CourtBookingCreateWithoutCourtInput, Prisma.CourtBookingUncheckedCreateWithoutCourtInput> | Prisma.CourtBookingCreateWithoutCourtInput[] | Prisma.CourtBookingUncheckedCreateWithoutCourtInput[] create?: Prisma.XOR<Prisma.CourtBookingCreateWithoutCourtInput, Prisma.CourtBookingUncheckedCreateWithoutCourtInput> | Prisma.CourtBookingCreateWithoutCourtInput[] | Prisma.CourtBookingUncheckedCreateWithoutCourtInput[]
connectOrCreate?: Prisma.CourtBookingCreateOrConnectWithoutCourtInput | Prisma.CourtBookingCreateOrConnectWithoutCourtInput[] connectOrCreate?: Prisma.CourtBookingCreateOrConnectWithoutCourtInput | Prisma.CourtBookingCreateOrConnectWithoutCourtInput[]
@@ -564,14 +498,6 @@ export type CourtBookingUncheckedUpdateManyWithoutCourtNestedInput = {
deleteMany?: Prisma.CourtBookingScalarWhereInput | Prisma.CourtBookingScalarWhereInput[] deleteMany?: Prisma.CourtBookingScalarWhereInput | Prisma.CourtBookingScalarWhereInput[]
} }
export type NullableDecimalFieldUpdateOperationsInput = {
set?: runtime.Decimal | runtime.DecimalJsLike | number | string | null
increment?: runtime.Decimal | runtime.DecimalJsLike | number | string
decrement?: runtime.Decimal | runtime.DecimalJsLike | number | string
multiply?: runtime.Decimal | runtime.DecimalJsLike | number | string
divide?: runtime.Decimal | runtime.DecimalJsLike | number | string
}
export type EnumCourtBookingStatusFieldUpdateOperationsInput = { export type EnumCourtBookingStatusFieldUpdateOperationsInput = {
set?: $Enums.CourtBookingStatus set?: $Enums.CourtBookingStatus
} }
@@ -582,7 +508,6 @@ export type CourtBookingCreateWithoutCourtInput = {
bookingDate: Date | string bookingDate: Date | string
startTime: string startTime: string
endTime: string endTime: string
price?: runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName: string customerName: string
customerPhone: string customerPhone: string
status?: $Enums.CourtBookingStatus status?: $Enums.CourtBookingStatus
@@ -596,7 +521,6 @@ export type CourtBookingUncheckedCreateWithoutCourtInput = {
bookingDate: Date | string bookingDate: Date | string
startTime: string startTime: string
endTime: string endTime: string
price?: runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName: string customerName: string
customerPhone: string customerPhone: string
status?: $Enums.CourtBookingStatus status?: $Enums.CourtBookingStatus
@@ -640,7 +564,6 @@ export type CourtBookingScalarWhereInput = {
bookingDate?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string bookingDate?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
startTime?: Prisma.StringFilter<"CourtBooking"> | string startTime?: Prisma.StringFilter<"CourtBooking"> | string
endTime?: Prisma.StringFilter<"CourtBooking"> | string endTime?: Prisma.StringFilter<"CourtBooking"> | string
price?: Prisma.DecimalNullableFilter<"CourtBooking"> | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFilter<"CourtBooking"> | string customerName?: Prisma.StringFilter<"CourtBooking"> | string
customerPhone?: Prisma.StringFilter<"CourtBooking"> | string customerPhone?: Prisma.StringFilter<"CourtBooking"> | string
status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus
@@ -654,7 +577,6 @@ export type CourtBookingCreateManyCourtInput = {
bookingDate: Date | string bookingDate: Date | string
startTime: string startTime: string
endTime: string endTime: string
price?: runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName: string customerName: string
customerPhone: string customerPhone: string
status?: $Enums.CourtBookingStatus status?: $Enums.CourtBookingStatus
@@ -668,7 +590,6 @@ export type CourtBookingUpdateWithoutCourtInput = {
bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
startTime?: Prisma.StringFieldUpdateOperationsInput | string startTime?: Prisma.StringFieldUpdateOperationsInput | string
endTime?: Prisma.StringFieldUpdateOperationsInput | string endTime?: Prisma.StringFieldUpdateOperationsInput | string
price?: Prisma.NullableDecimalFieldUpdateOperationsInput | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFieldUpdateOperationsInput | string customerName?: Prisma.StringFieldUpdateOperationsInput | string
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
@@ -682,7 +603,6 @@ export type CourtBookingUncheckedUpdateWithoutCourtInput = {
bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
startTime?: Prisma.StringFieldUpdateOperationsInput | string startTime?: Prisma.StringFieldUpdateOperationsInput | string
endTime?: Prisma.StringFieldUpdateOperationsInput | string endTime?: Prisma.StringFieldUpdateOperationsInput | string
price?: Prisma.NullableDecimalFieldUpdateOperationsInput | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFieldUpdateOperationsInput | string customerName?: Prisma.StringFieldUpdateOperationsInput | string
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
@@ -696,7 +616,6 @@ export type CourtBookingUncheckedUpdateManyWithoutCourtInput = {
bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string bookingDate?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
startTime?: Prisma.StringFieldUpdateOperationsInput | string startTime?: Prisma.StringFieldUpdateOperationsInput | string
endTime?: Prisma.StringFieldUpdateOperationsInput | string endTime?: Prisma.StringFieldUpdateOperationsInput | string
price?: Prisma.NullableDecimalFieldUpdateOperationsInput | runtime.Decimal | runtime.DecimalJsLike | number | string | null
customerName?: Prisma.StringFieldUpdateOperationsInput | string customerName?: Prisma.StringFieldUpdateOperationsInput | string
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
@@ -713,7 +632,6 @@ export type CourtBookingSelect<ExtArgs extends runtime.Types.Extensions.Internal
bookingDate?: boolean bookingDate?: boolean
startTime?: boolean startTime?: boolean
endTime?: boolean endTime?: boolean
price?: boolean
customerName?: boolean customerName?: boolean
customerPhone?: boolean customerPhone?: boolean
status?: boolean status?: boolean
@@ -729,7 +647,6 @@ export type CourtBookingSelectCreateManyAndReturn<ExtArgs extends runtime.Types.
bookingDate?: boolean bookingDate?: boolean
startTime?: boolean startTime?: boolean
endTime?: boolean endTime?: boolean
price?: boolean
customerName?: boolean customerName?: boolean
customerPhone?: boolean customerPhone?: boolean
status?: boolean status?: boolean
@@ -745,7 +662,6 @@ export type CourtBookingSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.
bookingDate?: boolean bookingDate?: boolean
startTime?: boolean startTime?: boolean
endTime?: boolean endTime?: boolean
price?: boolean
customerName?: boolean customerName?: boolean
customerPhone?: boolean customerPhone?: boolean
status?: boolean status?: boolean
@@ -761,7 +677,6 @@ export type CourtBookingSelectScalar = {
bookingDate?: boolean bookingDate?: boolean
startTime?: boolean startTime?: boolean
endTime?: boolean endTime?: boolean
price?: boolean
customerName?: boolean customerName?: boolean
customerPhone?: boolean customerPhone?: boolean
status?: boolean status?: boolean
@@ -769,7 +684,7 @@ export type CourtBookingSelectScalar = {
updatedAt?: boolean updatedAt?: boolean
} }
export type CourtBookingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "bookingCode" | "courtId" | "bookingDate" | "startTime" | "endTime" | "price" | "customerName" | "customerPhone" | "status" | "createdAt" | "updatedAt", ExtArgs["result"]["courtBooking"]> export type CourtBookingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "bookingCode" | "courtId" | "bookingDate" | "startTime" | "endTime" | "customerName" | "customerPhone" | "status" | "createdAt" | "updatedAt", ExtArgs["result"]["courtBooking"]>
export type CourtBookingInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = { export type CourtBookingInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
court?: boolean | Prisma.CourtDefaultArgs<ExtArgs> court?: boolean | Prisma.CourtDefaultArgs<ExtArgs>
} }
@@ -792,7 +707,6 @@ export type $CourtBookingPayload<ExtArgs extends runtime.Types.Extensions.Intern
bookingDate: Date bookingDate: Date
startTime: string startTime: string
endTime: string endTime: string
price: runtime.Decimal | null
customerName: string customerName: string
customerPhone: string customerPhone: string
status: $Enums.CourtBookingStatus status: $Enums.CourtBookingStatus
@@ -1228,7 +1142,6 @@ export interface CourtBookingFieldRefs {
readonly bookingDate: Prisma.FieldRef<"CourtBooking", 'DateTime'> readonly bookingDate: Prisma.FieldRef<"CourtBooking", 'DateTime'>
readonly startTime: Prisma.FieldRef<"CourtBooking", 'String'> readonly startTime: Prisma.FieldRef<"CourtBooking", 'String'>
readonly endTime: Prisma.FieldRef<"CourtBooking", 'String'> readonly endTime: Prisma.FieldRef<"CourtBooking", 'String'>
readonly price: Prisma.FieldRef<"CourtBooking", 'Decimal'>
readonly customerName: Prisma.FieldRef<"CourtBooking", 'String'> readonly customerName: Prisma.FieldRef<"CourtBooking", 'String'>
readonly customerPhone: Prisma.FieldRef<"CourtBooking", 'String'> readonly customerPhone: Prisma.FieldRef<"CourtBooking", 'String'>
readonly status: Prisma.FieldRef<"CourtBooking", 'CourtBookingStatus'> readonly status: Prisma.FieldRef<"CourtBooking", 'CourtBookingStatus'>

View File

@@ -0,0 +1,58 @@
// lib/errors.ts
export type ValidationIssue = {
path: string;
message: string;
};
export type AppError =
| {
type: 'validation';
message: string;
issues?: ValidationIssue[];
}
| {
type: 'not_found';
message: string;
}
| {
type: 'conflict';
message: string;
}
| {
type: 'unauthorized';
message: string;
}
| {
type: 'forbidden';
message: string;
}
| {
type: 'unexpected';
message: string;
};
export const Errors = {
validation(message: string, issues?: ValidationIssue[]): AppError {
return { type: 'validation', message, issues };
},
notFound(message = 'Resource not found'): AppError {
return { type: 'not_found', message };
},
conflict(message: string): AppError {
return { type: 'conflict', message };
},
unauthorized(message = 'Unauthorized'): AppError {
return { type: 'unauthorized', message };
},
forbidden(message = 'Forbidden'): AppError {
return { type: 'forbidden', message };
},
unexpected(message = 'Unexpected error'): AppError {
return { type: 'unexpected', message };
},
};

View File

@@ -0,0 +1,20 @@
// http/error-handler.ts
import type { MiddlewareHandler } from 'hono';
import { logger } from '../logger';
import { unexpectedProblem } from './problem-builders';
export const errorHandler: MiddlewareHandler = async (c, next) => {
try {
await next();
} catch (error) {
const requestId = c.get('requestId') as string | undefined;
const instance = requestId ? `/requests/${requestId}` : undefined;
logger.error({
requestId,
error,
});
return c.json(unexpectedProblem({ instance }), 500);
}
};

View File

@@ -0,0 +1,20 @@
import type { Result } from '@/lib/result';
import type { Context } from 'hono';
import type { ContentfulStatusCode } from 'hono/utils/http-status';
import { mapAppErrorToProblem } from './problem-mapper';
export function handleResult<T>(
c: Context,
result: Result<T>,
successStatus: ContentfulStatusCode = 200
) {
if (!result.ok) {
const requestId = c.get('requestId') as string | undefined;
const instance = requestId ? `/requests/${requestId}` : undefined;
const problem = mapAppErrorToProblem(result.error, instance);
return c.json(problem, problem.status);
}
return c.json(result.value, successStatus);
}

View File

@@ -0,0 +1,29 @@
// http/problem-builders.ts
import type { ProblemDetails } from './problem-details';
export function validationProblem(params: {
detail?: string;
instance?: string;
errors?: Record<string, string[]>;
}): ProblemDetails {
return {
type: 'https://api.myapp.dev/problems/validation',
title: 'Bad Request',
status: 400,
detail: params.detail ?? 'Invalid request data',
instance: params.instance,
errors: params.errors,
};
}
export function unexpectedProblem(params?: {
instance?: string;
}): ProblemDetails {
return {
type: 'https://api.myapp.dev/problems/unexpected',
title: 'Internal Server Error',
status: 500,
detail: 'Internal server error',
instance: params?.instance,
};
}

View File

@@ -0,0 +1,10 @@
import type { ContentfulStatusCode } from 'hono/utils/http-status';
export type ProblemDetails = {
type: string;
title: string;
status: ContentfulStatusCode;
detail?: string;
instance?: string;
errors?: Record<string, string[]>;
};

View File

@@ -0,0 +1,52 @@
import type { AppError } from '@/lib/errors';
import type { ContentfulStatusCode } from 'hono/utils/http-status';
import type { ProblemDetails } from './problem-details';
function statusFromError(error: AppError): ContentfulStatusCode {
switch (error.type) {
case 'validation':
return 400;
case 'unauthorized':
return 401;
case 'forbidden':
return 403;
case 'not_found':
return 404;
case 'conflict':
return 409;
case 'unexpected':
return 500;
default:
return 500;
}
}
function titleFromStatus(status: ContentfulStatusCode): string {
switch (status) {
case 400:
return 'Bad Request';
case 401:
return 'Unauthorized';
case 403:
return 'Forbidden';
case 404:
return 'Not Found';
case 409:
return 'Conflict';
default:
return 'Internal Server Error';
}
}
export function mapAppErrorToProblem(error: AppError, instance?: string): ProblemDetails {
const status = statusFromError(error);
return {
type: `https://api.myapp.dev/problems/${error.type}`,
title: titleFromStatus(status),
status,
detail: status === 500 ? 'Internal server error' : error.message,
instance,
};
}

View File

@@ -0,0 +1,16 @@
import type { MiddlewareHandler } from 'hono';
type Env = {
Variables: {
requestId: string;
};
};
export const requestIdMiddleware: MiddlewareHandler<Env> = async (c, next) => {
const requestId = crypto.randomUUID();
c.set('requestId', requestId);
c.header('X-Request-Id', requestId);
await next();
};

View File

@@ -0,0 +1,48 @@
import { zValidator } from '@hono/zod-validator';
import type { ZodSchema } from 'zod';
import { validationProblem } from './problem-builders';
import { zodIssuesToRecord } from './zod-issues';
type ValidationTarget = 'json' | 'query' | 'param' | 'header' | 'form';
function makeValidator<TSchema extends ZodSchema>(target: ValidationTarget, schema: TSchema) {
return zValidator(target, schema, (result, c) => {
if (result.success) {
return;
}
const requestId = c.get('requestId') as string | undefined;
const instance = requestId ? `/requests/${requestId}` : undefined;
return c.json(
validationProblem({
detail: `Invalid ${target} data`,
instance,
errors: zodIssuesToRecord(result.error.issues),
}),
400
);
});
}
export const validate = {
json<TSchema extends ZodSchema>(schema: TSchema) {
return makeValidator('json', schema);
},
query<TSchema extends ZodSchema>(schema: TSchema) {
return makeValidator('query', schema);
},
param<TSchema extends ZodSchema>(schema: TSchema) {
return makeValidator('param', schema);
},
header<TSchema extends ZodSchema>(schema: TSchema) {
return makeValidator('header', schema);
},
form<TSchema extends ZodSchema>(schema: TSchema) {
return makeValidator('form', schema);
},
};

View File

@@ -0,0 +1,16 @@
type IssueLike = {
path: PropertyKey[];
message: string;
};
export function zodIssuesToRecord(issues: IssueLike[]): Record<string, string[]> {
const out: Record<string, string[]> = {};
for (const issue of issues) {
const key = issue.path.length ? issue.path.join('.') : 'root';
out[key] ??= [];
out[key].push(issue.message);
}
return out;
}

View File

@@ -0,0 +1,12 @@
// lib/result.ts
import type { AppError } from '@/lib/errors';
export type Result<T, E = AppError> = { ok: true; value: T } | { ok: false; error: E };
export function ok<T>(value: T): Result<T> {
return { ok: true, value };
}
export function err<E>(error: E): Result<never, E> {
return { ok: false, error };
}

View File

@@ -164,7 +164,7 @@ function mapBookingResponse(booking: {
endTime: string; endTime: string;
customerName: string; customerName: string;
customerPhone: string; customerPhone: string;
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED'; status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NOSHOW';
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
court: { court: {
@@ -494,34 +494,42 @@ export async function updateAdminBookingStatus(
); );
} }
const updated = await db.courtBooking.update({ if (input.status === 'NOSHOW' && booking.status !== 'CONFIRMED') {
where: { id: booking.id }, throw new AdminBookingServiceError(
'Solo se pueden marcar como no show las reservas confirmadas.',
409
);
}
await db.courtBookingLog.create({
data: { data: {
status: id: uuidv7(),
input.status === 'COMPLETED' ? CourtBookingStatus.COMPLETED : CourtBookingStatus.CANCELLED, bookingCode: booking.bookingCode,
}, courtId: booking.court.id,
include: { bookingDate: booking.bookingDate,
court: { startTime: booking.startTime,
select: { endTime: booking.endTime,
id: true, customerName: booking.customerName,
name: true, customerPhone: booking.customerPhone,
sport: { previousStatus: booking.status,
select: { newStatus: input.status,
id: true, changedAt: new Date(),
name: true,
slug: true,
},
},
complex: {
select: {
id: true,
complexName: true,
},
},
},
},
}, },
}); });
return mapBookingResponse(updated); if (input.status === 'COMPLETED' || input.status === 'NOSHOW') {
await db.courtBooking.update({
where: { id: booking.id },
data: {
status: input.status,
},
});
} else {
// if the booking is cancelled we delete it to free up the slot, but we keep a log of it with the cancelled status
await db.courtBooking.delete({
where: { id: booking.id },
});
}
return mapBookingResponse({ ...booking, status: input.status });
} }

View File

@@ -202,10 +202,6 @@ async function getComplexWithBookingData(complexSlug: string) {
availabilities: { availabilities: {
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }], orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
}, },
priceRules: {
where: { isActive: true },
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
},
}, },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
}, },
@@ -237,10 +233,9 @@ function mapBookingResponse(input: {
createdAt: Date; createdAt: Date;
startTime: string; startTime: string;
endTime: string; endTime: string;
price: number;
customerName: string; customerName: string;
customerPhone: string; customerPhone: string;
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED'; status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NOSHOW';
court: { court: {
id: string; id: string;
name: string; name: string;
@@ -266,7 +261,6 @@ function mapBookingResponse(input: {
date: formatIsoDate(input.bookingDate), date: formatIsoDate(input.bookingDate),
startTime: input.startTime, startTime: input.startTime,
endTime: input.endTime, endTime: input.endTime,
price: input.price,
customerName: input.customerName, customerName: input.customerName,
customerPhone: input.customerPhone, customerPhone: input.customerPhone,
status: input.status, status: input.status,
@@ -290,7 +284,6 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
bookingDate: true, bookingDate: true,
startTime: true, startTime: true,
endTime: true, endTime: true,
price: true,
status: true, status: true,
createdAt: true, createdAt: true,
court: { court: {
@@ -332,7 +325,6 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
slug: booking.court.sport.slug, slug: booking.court.sport.slug,
}, },
status: booking.status, status: booking.status,
price: Number(booking.price),
createdAt: booking.createdAt.toISOString(), createdAt: booking.createdAt.toISOString(),
}; };
} }
@@ -405,50 +397,6 @@ export async function listPublicAvailability(complexSlug: string, query: PublicA
(slot) => !occupiedSlots.some((occupied) => hasOverlap(slot, occupied)) (slot) => !occupiedSlots.some((occupied) => hasOverlap(slot, occupied))
); );
const basePrice = Number(court.basePrice);
const priceRuleMap = new Map<string, number>();
for (const rule of court.priceRules) {
const ruleDay = rule.dayOfWeek;
const ruleStart = rule.startTime;
const ruleEnd = rule.endTime;
const price = Number(rule.price);
if (ruleStart && ruleEnd && ruleDay) {
const startMin = toMinutes(ruleStart);
const endMin = toMinutes(ruleEnd);
for (let mins = startMin; mins < endMin; mins += 30) {
priceRuleMap.set(`${ruleDay}-${minutesToTime(mins)}`, price);
}
} else if (ruleDay && !ruleStart && !ruleEnd) {
priceRuleMap.set(`day-${ruleDay}`, price);
}
}
const calcPrice = (startTime: string) => {
if (!basePrice || basePrice <= 0) {
return 0;
}
const timeKey = `${dayOfWeek}-${startTime}`;
const dayKey = `day-${dayOfWeek}`;
return priceRuleMap.get(timeKey) ?? priceRuleMap.get(dayKey) ?? basePrice;
};
const price =
availableSlots.length > 0
? (() => {
const prices = availableSlots.map((slot) => calcPrice(slot.startTime));
const validPrices = prices.filter((p) => p > 0);
if (validPrices.length === 0) {
return undefined;
}
return {
min: Math.min(...validPrices),
max: Math.max(...validPrices),
};
})()
: undefined;
return { return {
courtId: court.id, courtId: court.id,
courtName: court.name, courtName: court.name,
@@ -460,7 +408,6 @@ export async function listPublicAvailability(complexSlug: string, query: PublicA
slotDurationMinutes: court.slotDurationMinutes, slotDurationMinutes: court.slotDurationMinutes,
availabilityDay: dayOfWeek, availabilityDay: dayOfWeek,
availableSlots, availableSlots,
price,
}; };
}) })
.filter((court) => court.availableSlots.length > 0); .filter((court) => court.availableSlots.length > 0);
@@ -529,60 +476,6 @@ export async function createPublicBooking(complexSlug: string, input: CreatePubl
); );
} }
function calcBookingPrice(
court: {
basePrice: number | null;
priceRules: Array<{
dayOfWeek: string | null;
startTime: string | null;
endTime: string | null;
price: number;
}>;
},
dayOfWeek: string,
startTime: string
): number {
if (!court.basePrice) {
return 0;
}
const slotMinutes = toMinutes(startTime);
const exactMatch = court.priceRules.find((rule) => {
if (!rule.dayOfWeek || rule.dayOfWeek !== dayOfWeek) {
return false;
}
if (!rule.startTime || !rule.endTime) {
return false;
}
const ruleStart = toMinutes(rule.startTime);
const ruleEnd = toMinutes(rule.endTime);
return slotMinutes >= ruleStart && slotMinutes < ruleEnd;
});
if (exactMatch) {
return Number(exactMatch.price);
}
const dayMatch = court.priceRules.find((rule) => {
if (!rule.dayOfWeek || rule.dayOfWeek !== dayOfWeek) {
return false;
}
if (rule.startTime || rule.endTime) {
return false;
}
return true;
});
if (dayMatch) {
return Number(dayMatch.price);
}
return Number(court.basePrice);
}
const bookingPrice = calcBookingPrice(selectedCourt, dayOfWeek, selectedSlot.startTime);
for (let attempt = 0; attempt < 5; attempt += 1) { for (let attempt = 0; attempt < 5; attempt += 1) {
try { try {
const booking = await db.$transaction(async (tx) => { const booking = await db.$transaction(async (tx) => {
@@ -638,7 +531,6 @@ export async function createPublicBooking(complexSlug: string, input: CreatePubl
bookingDate, bookingDate,
startTime: selectedSlot.startTime, startTime: selectedSlot.startTime,
endTime: selectedSlot.endTime, endTime: selectedSlot.endTime,
price: bookingPrice,
customerName: input.customerName.trim(), customerName: input.customerName.trim(),
customerPhone: input.customerPhone.trim(), customerPhone: input.customerPhone.trim(),
status: 'CONFIRMED', status: 'CONFIRMED',
@@ -650,7 +542,6 @@ export async function createPublicBooking(complexSlug: string, input: CreatePubl
createdAt: true, createdAt: true,
startTime: true, startTime: true,
endTime: true, endTime: true,
price: true,
customerName: true, customerName: true,
customerPhone: true, customerPhone: true,
status: true, status: true,
@@ -665,7 +556,6 @@ export async function createPublicBooking(complexSlug: string, input: CreatePubl
createdAt: booking.createdAt, createdAt: booking.createdAt,
startTime: booking.startTime, startTime: booking.startTime,
endTime: booking.endTime, endTime: booking.endTime,
price: Number(booking.price),
customerName: booking.customerName, customerName: booking.customerName,
customerPhone: booking.customerPhone, customerPhone: booking.customerPhone,
status: booking.status, status: booking.status,

View File

@@ -1,18 +1,10 @@
import { Prisma } from '@/generated/prisma/client'; import { Prisma } from '@/generated/prisma/client';
import { handleResult } from '@/lib/http/handle-result';
import { createSport } from '@/modules/sport/services/sport.service'; import { createSport } from '@/modules/sport/services/sport.service';
import type { AppContext } from '@/types/hono'; import type { AppContext } from '@/types/hono';
import type { CreateSportInput } from '@repo/api-contract'; import type { CreateSportInput } from '@repo/api-contract';
export async function createSportHandler(c: AppContext) { export async function createSportHandler(c: AppContext) {
const payload = c.req.valid('json' as never) as CreateSportInput; const payload = c.req.valid('json' as never) as CreateSportInput;
return handleResult(c, await createSport(payload), 201);
try {
const sport = await createSport(payload);
return c.json(sport, 201);
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
return c.json({ message: 'No se pudo crear el deporte.' }, 409);
}
throw error;
}
} }

View File

@@ -1,7 +1,8 @@
import { handleResult } from '@/lib/http/handle-result';
import { listSports } from '@/modules/sport/services/sport.service'; import { listSports } from '@/modules/sport/services/sport.service';
import type { AppContext } from '@/types/hono'; import type { AppContext } from '@/types/hono';
export async function listSportsHandler(c: AppContext) { export async function listSportsHandler(c: AppContext) {
const sports = await listSports(); const sports = await listSports();
return c.json(sports); return handleResult(c, sports);
} }

View File

@@ -1,5 +1,7 @@
import { Prisma } from '@/generated/prisma/client'; import { Prisma, Sport } from '@/generated/prisma/client';
import { Errors } from '@/lib/errors';
import { db } from '@/lib/prisma'; import { db } from '@/lib/prisma';
import { Result, err, ok } from '@/lib/result';
import { v7 as uuidv7 } from 'uuid'; import { v7 as uuidv7 } from 'uuid';
export type CreateSportInput = { export type CreateSportInput = {
@@ -51,16 +53,25 @@ async function buildUniqueSlug(source: string, excludeSportId?: string): Promise
} }
} }
export async function listSports() { export async function listSports(): Promise<Result<Sport[]>> {
return db.sport.findMany({ const sports = await db.sport.findMany({
orderBy: { name: 'asc' }, orderBy: { name: 'asc' },
}); });
return ok(sports);
} }
export async function createSport(input: CreateSportInput) { export async function createSport(input: CreateSportInput) {
const slug = await buildUniqueSlug(input.name); const slug = await buildUniqueSlug(input.name);
return db.sport.create({ const existing = await db.sport.count({
where: { slug },
});
if (existing > 0) {
return err(Errors.conflict('Ya existe un deporte con ese nombre.'));
}
const created = await db.sport.create({
data: { data: {
id: uuidv7(), id: uuidv7(),
name: input.name.trim(), name: input.name.trim(),
@@ -68,6 +79,8 @@ export async function createSport(input: CreateSportInput) {
isActive: true, isActive: true,
}, },
}); });
return ok(created);
} }
export async function getSportById(id: string) { export async function getSportById(id: string) {

View File

@@ -1,3 +1,4 @@
import { validate } from '@/lib/http/validate';
import { requireAuth } from '@/middlewares/require-auth.middleware'; import { requireAuth } from '@/middlewares/require-auth.middleware';
import { requireSuperAdmin } from '@/middlewares/require-super-admin.middleware'; import { requireSuperAdmin } from '@/middlewares/require-super-admin.middleware';
import { createSportHandler } from '@/modules/sport/handlers/create-sport.handler'; import { createSportHandler } from '@/modules/sport/handlers/create-sport.handler';
@@ -8,18 +9,17 @@ import { zValidator } from '@hono/zod-validator';
import { createSportSchema, updateSportSchema } from '@repo/api-contract'; import { createSportSchema, updateSportSchema } from '@repo/api-contract';
import { Hono } from 'hono'; import { Hono } from 'hono';
import { z } from 'zod'; import { z } from 'zod';
export const sportRoutes = new Hono<AppEnv>(); export const sportRoutes = new Hono<AppEnv>();
const sportIdParamsSchema = z.object({ id: z.uuid() }); const sportIdParamsSchema = z.object({ id: z.uuid() });
sportRoutes.use('*', requireAuth); sportRoutes.use('*', requireAuth);
sportRoutes.get('/', listSportsHandler); sportRoutes.get('/', listSportsHandler);
sportRoutes.post('/', requireSuperAdmin, zValidator('json', createSportSchema), createSportHandler); sportRoutes.post('/', requireSuperAdmin, validate.json(createSportSchema), createSportHandler);
sportRoutes.patch( sportRoutes.patch(
'/:id', '/:id',
requireSuperAdmin, requireSuperAdmin,
zValidator('param', sportIdParamsSchema), validate.param(sportIdParamsSchema),
zValidator('json', updateSportSchema), validate.json(updateSportSchema),
updateSportHandler updateSportHandler
); );

View File

@@ -0,0 +1,95 @@
import { beforeEach, expect, mock, test } from 'bun:test';
import { Errors } from '@/lib/errors';
import { err, ok } from '@/lib/result';
import type { CreateSportInput } from '@repo/api-contract';
const createSportMock = mock(async (_input: CreateSportInput) =>
ok({
id: 'sport-1',
name: 'Tenis',
slug: 'tenis',
isActive: true,
createdAt: '2026-04-23T00:00:00.000Z',
updatedAt: '2026-04-23T00:00:00.000Z',
})
);
mock.module('@/modules/sport/services/sport.service', () => ({
__esModule: true,
createSport: createSportMock,
}));
const { createSportHandler } = await import('@/modules/sport/handlers/create-sport.handler');
type HandlerContext = {
get: (key: 'requestId') => string | undefined;
req: {
valid: () => unknown;
};
json: ReturnType<typeof mock>;
};
function createContext(body: unknown) {
const json = mock((payload: unknown, init?: unknown) => ({
payload,
init,
}));
const c = {
get: () => undefined,
req: {
valid: () => body,
},
json,
} as unknown as HandlerContext;
return { c, json };
}
beforeEach(() => {
createSportMock.mockReset();
mock.clearAllMocks();
});
test('returns 201 with the created sport', async () => {
const createdSport = {
id: 'sport-1',
name: 'Tenis',
slug: 'tenis',
isActive: true,
createdAt: '2026-04-23T00:00:00.000Z',
updatedAt: '2026-04-23T00:00:00.000Z',
} as const;
createSportMock.mockResolvedValue(ok(createdSport));
const payload: CreateSportInput = { name: ' Tenis ' };
const { c, json } = createContext(payload);
const response = await createSportHandler(c as never);
expect(createSportMock).toHaveBeenCalledWith(payload);
expect(json.mock.calls[0]?.[0]).toEqual(createdSport);
expect(json.mock.calls[0]?.[1]).toBe(201);
expect(response).toBeDefined();
});
test('returns a conflict problem when the service rejects with a conflict error', async () => {
createSportMock.mockResolvedValue(err(Errors.conflict('Ya existe un deporte con ese nombre.')));
const payload: CreateSportInput = { name: 'Tenis' };
const { c, json } = createContext(payload);
const response = await createSportHandler(c as never);
expect(createSportMock).toHaveBeenCalledWith(payload);
expect(json.mock.calls[0]?.[0]).toEqual({
type: 'https://api.myapp.dev/problems/conflict',
title: 'Conflict',
status: 409,
detail: 'Ya existe un deporte con ese nombre.',
});
expect(json.mock.calls[0]?.[1]).toBe(409);
expect(response).toBeDefined();
});

View File

@@ -0,0 +1,199 @@
import { beforeEach, expect, mock, test } from 'bun:test';
import { createPrismaMock } from 'bun-mock-prisma';
import type { PrismaClient } from '@/generated/prisma/client';
import type { PrismaClientMock } from 'bun-mock-prisma';
const prismaMock = createPrismaMock<PrismaClient>() as PrismaClientMock<PrismaClient>;
const uuidV7Mock = mock(() => '00000000-0000-4000-8000-000000000001');
mock.module('@/lib/prisma', () => ({
__esModule: true,
db: {
sport: prismaMock.sport,
},
}));
mock.module('uuid', () => ({
__esModule: true,
v7: uuidV7Mock,
}));
const { createSport, getSportById, listSports, updateSport } = await import(
'@/modules/sport/services/sport.service'
);
beforeEach(() => {
prismaMock._reset();
mock.clearAllMocks();
});
test('listSports returns sports ordered by name', async () => {
const sports = [
{
id: 'sport-2',
name: 'Tenis',
slug: 'tenis',
isActive: true,
createdAt: new Date('2026-04-22T00:00:00.000Z'),
updatedAt: new Date('2026-04-22T00:00:00.000Z'),
},
{
id: 'sport-1',
name: 'Básquet',
slug: 'basquet',
isActive: true,
createdAt: new Date('2026-04-21T00:00:00.000Z'),
updatedAt: new Date('2026-04-21T00:00:00.000Z'),
},
];
prismaMock.sport.findMany.mockResolvedValue(sports as never);
const result = await listSports();
expect(prismaMock.sport.findMany).toHaveBeenCalledWith({
orderBy: { name: 'asc' },
});
expect(result).toEqual({
ok: true,
value: sports,
});
});
test('getSportById returns the requested sport', async () => {
const sport = {
id: 'sport-1',
name: 'Tenis',
slug: 'tenis',
isActive: true,
createdAt: new Date('2026-04-22T00:00:00.000Z'),
updatedAt: new Date('2026-04-22T00:00:00.000Z'),
};
prismaMock.sport.findUnique.mockResolvedValue(sport as never);
const result = await getSportById('sport-1');
expect(prismaMock.sport.findUnique).toHaveBeenCalledWith({
where: { id: 'sport-1' },
});
expect(result).toEqual(sport);
});
test('createSport trims the name and creates a unique slug', async () => {
const createdSport = {
id: '00000000-0000-4000-8000-000000000001',
name: 'Fútbol 7!!',
slug: 'futbol-7',
isActive: true,
createdAt: new Date('2026-04-23T00:00:00.000Z'),
updatedAt: new Date('2026-04-23T00:00:00.000Z'),
};
prismaMock.sport.findFirst.mockResolvedValue(null as never);
prismaMock.sport.count.mockResolvedValue(0 as never);
prismaMock.sport.create.mockResolvedValue(createdSport as never);
const result = await createSport({ name: ' Fútbol 7!! ' });
expect(uuidV7Mock).toHaveBeenCalledTimes(1);
expect(prismaMock.sport.findFirst).toHaveBeenCalledWith({
where: { slug: 'futbol-7' },
select: { id: true },
});
expect(prismaMock.sport.count).toHaveBeenCalledWith({
where: { slug: 'futbol-7' },
});
expect(prismaMock.sport.create).toHaveBeenCalledWith({
data: {
id: '00000000-0000-4000-8000-000000000001',
name: 'Fútbol 7!!',
slug: 'futbol-7',
isActive: true,
},
});
expect(result).toEqual({
ok: true,
value: createdSport,
});
});
test('createSport retries with a numeric suffix when the slug already exists', async () => {
const createdSport = {
id: '00000000-0000-4000-8000-000000000001',
name: 'Tenis',
slug: 'tenis-2',
isActive: true,
createdAt: new Date('2026-04-23T00:00:00.000Z'),
updatedAt: new Date('2026-04-23T00:00:00.000Z'),
};
prismaMock.sport.findFirst
.mockResolvedValueOnce({ id: 'existing-sport' } as never)
.mockResolvedValueOnce(null as never);
prismaMock.sport.count.mockResolvedValue(0 as never);
prismaMock.sport.create.mockResolvedValue(createdSport as never);
const result = await createSport({ name: 'Tenis' });
expect(prismaMock.sport.findFirst).toHaveBeenNthCalledWith(1, {
where: { slug: 'tenis' },
select: { id: true },
});
expect(prismaMock.sport.findFirst).toHaveBeenNthCalledWith(2, {
where: { slug: 'tenis-2' },
select: { id: true },
});
expect(prismaMock.sport.create).toHaveBeenCalledWith({
data: {
id: '00000000-0000-4000-8000-000000000001',
name: 'Tenis',
slug: 'tenis-2',
isActive: true,
},
});
expect(result).toEqual({
ok: true,
value: createdSport,
});
});
test('updateSport updates the name, slug and active flag', async () => {
const updatedSport = {
id: 'sport-1',
name: 'Básquet 3x3',
slug: 'basquet-3x3',
isActive: false,
createdAt: new Date('2026-04-21T00:00:00.000Z'),
updatedAt: new Date('2026-04-23T00:00:00.000Z'),
};
prismaMock.sport.findFirst.mockResolvedValue(null as never);
prismaMock.sport.update.mockResolvedValue(updatedSport as never);
const result = await updateSport('sport-1', {
name: 'Básquet 3x3',
isActive: false,
});
expect(prismaMock.sport.findFirst).toHaveBeenCalledWith({
where: {
slug: 'basquet-3x3',
id: {
not: 'sport-1',
},
},
select: { id: true },
});
expect(prismaMock.sport.update).toHaveBeenCalledWith({
where: { id: 'sport-1' },
data: {
name: 'Básquet 3x3',
slug: 'basquet-3x3',
isActive: false,
},
});
expect(result).toEqual(updatedSport);
});

View File

@@ -2,11 +2,11 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="iimage/x-icon" href="/src/assets/playzer-favicon-transparent.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PlayZer</title> <title>PlayZer</title>
</head> </head>
<body> <body lass="bg-background text-foreground antialiased">
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>

View File

@@ -15,12 +15,10 @@
"@better-auth/infra": "^0.2.4", "@better-auth/infra": "^0.2.4",
"@fontsource-variable/geist": "^5.2.8", "@fontsource-variable/geist": "^5.2.8",
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^5.2.2",
"@phosphor-icons/react": "^2.1.10",
"@radix-ui/react-label": "^2.1.8", "@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.2", "@radix-ui/react-popover": "^1.1.2",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.2.4",
"@repo/api-contract": "workspace:*", "@repo/api-contract": "workspace:*",
"@tabler/icons-react": "^3.41.1",
"@tanstack/react-query": "^5.96.1", "@tanstack/react-query": "^5.96.1",
"@tanstack/react-query-devtools": "^5.96.1", "@tanstack/react-query-devtools": "^5.96.1",
"@tanstack/react-router": "^1.168.10", "@tanstack/react-router": "^1.168.10",

View File

@@ -1,182 +0,0 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg) scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg) scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: "";
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}

View File

@@ -1,34 +0,0 @@
import { type LucideProps } from 'lucide-react';
import { forwardRef } from 'react';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const SoccerBallIcon = forwardRef<any, LucideProps>(({ className, ...props }, ref) => (
<svg
ref={ref}
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
className={className}
{...props}
>
<circle cx="12" cy="12" r="10" />
<path d="M12 2c.8 2.2 2.2 4.2 4 5.8" />
<path d="M12 2c-.8 2.2-2.2 4.2-4 5.8" />
<path d="M2 12c2.2.8 4.2 2.2 5.8 4" />
<path d="M2 12c2.2-.8 4.2-2.2 5.8-4" />
<path d="M22 12c-2.2.8-4.2 2.2-5.8 4" />
<path d="M22 12c-2.2-.8-4.2-2.2-5.8-4" />
<path d="M12 22c.8-2.2 2.2-4.2 4-5.8" />
<path d="M12 22c-.8-2.2-2.2-4.2-4-5.8" />
</svg>
));
export { SoccerBallIcon as FootballIcon };

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 206 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 372 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 607 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 810 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 1.2 MiB

View File

@@ -0,0 +1,488 @@
import {
CalendarDays,
Check,
Laptop,
LogOut,
Menu,
Moon,
Settings,
Sun,
User,
X,
} from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import PlayzerIcon from '@/assets/playzer-favicon-512-transparent.png';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Link, useLocation, useNavigate } from '@tanstack/react-router';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { UserAvatar } from '@/components/user-avatar';
import { apiClient } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { acceptStoredPendingInvite } from '@/lib/invitations';
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
import { useTheme } from '@/lib/theme';
interface NavItemProps {
to: '/' | '/about';
label: string;
isMobile?: boolean;
onClick?: () => void;
}
function NavItem({ to, label, isMobile, onClick }: NavItemProps) {
const location = useLocation();
const currentPath = location.pathname;
const isActive = to === '/' ? currentPath === '/' : currentPath.startsWith(to);
return (
<Link to={to} onClick={onClick}>
<Button
variant="ghost"
size={isMobile ? 'default' : 'sm'}
className={[
'rounded-none transition-all duration-200 hover:bg-transparent',
'focus-visible:ring-2 focus-visible:ring-primary/50',
isMobile && 'w-full justify-start rounded-2xl',
isActive
? 'text-primary relative after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-primary'
: 'text-muted-foreground hover:text-foreground relative hover:after:absolute hover:after:bottom-0 hover:after:left-0 hover:after:right-0 hover:after:h-0.5 hover:after:bg-primary/50',
]
.filter(Boolean)
.join(' ')}
>
{label}
</Button>
</Link>
);
}
export function Header() {
const [open, setOpen] = useState(false);
const navigate = useNavigate();
const queryClient = useQueryClient();
const { user, isAuthenticated, displayName, avatarUrl, signOut } = useAuth();
const { theme, setTheme } = useTheme();
const { currentComplexSlug, setCurrentComplex } = useCurrentComplexStore();
const processedInviteForUser = useRef<string | null>(null);
const myComplexesQuery = useQuery({
queryKey: ['my-complexes'],
enabled: isAuthenticated,
queryFn: () => apiClient.complexes.listMine(),
});
useEffect(() => {
if (!isAuthenticated) {
processedInviteForUser.current = null;
return;
}
const userKey = user?.email ?? displayName ?? 'authenticated-user';
if (processedInviteForUser.current === userKey) {
return;
}
processedInviteForUser.current = userKey;
void (async () => {
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
await queryClient.invalidateQueries({ queryKey: ['my-complexes'] });
})();
}, [displayName, isAuthenticated, queryClient, user?.email]);
const complexSlug = currentComplexSlug || myComplexesQuery.data?.[0]?.complexSlug;
const currentComplexName = useMemo(() => {
const complexes = myComplexesQuery.data ?? [];
if (complexes.length === 0) return 'Mi complejo';
const selected = complexes.find((complex) => complex.complexSlug === complexSlug);
return selected?.complexName ?? complexes[0]?.complexName ?? 'Mi complejo';
}, [complexSlug, myComplexesQuery.data]);
const menuItems = [
{ label: 'Inicio', to: '/' },
{ label: 'About', to: '/about' },
] as const;
const handleSelectComplex = async (complexId: string, nextSlug: string) => {
await apiClient.complexes.select({ complexId });
setCurrentComplex(nextSlug);
await queryClient.invalidateQueries({ queryKey: ['current-complex'] });
};
const handleSignOut = async () => {
await signOut();
await navigate({ to: '/login' });
};
const handleOpenBookingCreate = async () => {
if (location.pathname !== '/') {
await navigate({ to: '/' });
}
window.setTimeout(() => {
window.dispatchEvent(new Event('playzer:open-booking-create'));
}, 0);
};
return (
<header className="sticky top-0 z-50 w-full border-b border-border/60 bg-background/60 dark:border-primary/20 dark:bg-[#030a10]/90 backdrop-blur-xl">
<div className="absolute inset-0 -z-10 bg-gradient-to-b from-background/85 to-background/45 dark:from-[#030a10]/95 dark:to-[#030a10]/70" />
<div className="mx-auto flex h-16 w-full max-w-7xl items-center gap-4 px-3 sm:px-6 lg:px-8">
<Link to="/" className="group flex items-center gap-3">
<div className="flex size-10 items-center justify-center shadow-primary/10 ">
<img src={PlayzerIcon} alt="Playzer" className="size-7" />
</div>
<span className="bg-gradient-to-r from-primary via-primary to-reserved bg-clip-text text-xl font-bold tracking-tight text-transparent">
Playzer
</span>
</Link>
<nav className="hidden absolute left-1/2 -translate-x-1/2 items-center gap-1 md:flex">
{menuItems.map((item) => (
<NavItem key={item.label} to={item.to} label={item.label} />
))}
</nav>
<div className="flex-1" />
<div className="hidden items-center gap-2 md:flex">
<Button
className="rounded-2xl px-5 shadow-lg shadow-primary/20"
onClick={() => {
void handleOpenBookingCreate();
}}
>
<CalendarDays className="mr-2 size-4" />
Reservar ahora
</Button>
</div>
{isAuthenticated ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="hidden size-10 rounded-full ring-2 ring-transparent transition-all duration-200 hover:ring-primary/30 focus:outline-none md:flex"
>
<UserAvatar
src={avatarUrl}
alt={displayName}
fallbackText={displayName}
className="size-10 border border-border/60 shadow-lg shadow-black/10"
/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="w-64 rounded-2xl border-border/60 bg-popover/95 p-2 shadow-xl shadow-black/20 backdrop-blur-xl"
>
<DropdownMenuLabel className="px-2 py-2">
<div className="flex items-center gap-3">
<UserAvatar
src={avatarUrl}
alt={displayName}
fallbackText={displayName}
className="size-9"
/>
<div className="flex min-w-0 flex-col">
<span className="truncate text-sm font-medium">{displayName}</span>
<span className="truncate text-xs text-muted-foreground">{user?.email}</span>
<span className="truncate text-xs text-muted-foreground">
{currentComplexName}
</span>
</div>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
<>
<DropdownMenuLabel className="px-2 text-xs font-normal text-muted-foreground">
Cambiar complejo
</DropdownMenuLabel>
{myComplexesQuery.data.map((complex) => (
<DropdownMenuItem
key={complex.id}
className="cursor-pointer rounded-xl"
onSelect={() => {
void handleSelectComplex(complex.id, complex.complexSlug);
}}
>
<span className="mr-2 flex size-4 items-center justify-center">
{complex.complexSlug === complexSlug && <Check className="size-4" />}
</span>
{complex.complexName}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
</>
)}
<DropdownMenuLabel className="px-2 text-xs font-normal text-muted-foreground">
Apariencia
</DropdownMenuLabel>
<DropdownMenuRadioGroup
value={theme}
onValueChange={(value) => setTheme(value as 'light' | 'dark' | 'system')}
>
<DropdownMenuRadioItem value="light" className="cursor-pointer rounded-xl">
<Sun className="mr-2 size-4" />
Light
</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="dark" className="cursor-pointer rounded-xl">
<Moon className="mr-2 size-4" />
Dark
</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="system" className="cursor-pointer rounded-xl">
<Laptop className="mr-2 size-4" />
System
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
<DropdownMenuSeparator />
<DropdownMenuItem
className="cursor-pointer rounded-xl"
onSelect={() => {
void navigate({ to: '/profile' });
}}
>
<User className="mr-2 size-4" />
Mi Perfil
</DropdownMenuItem>
{currentComplexSlug && (
<DropdownMenuItem
className="cursor-pointer rounded-xl"
onSelect={() => {
void navigate({
to: '/complex/$slug/edit',
params: { slug: currentComplexSlug },
});
}}
>
<Settings className="mr-2 size-4" />
Configuración
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
className="cursor-pointer rounded-xl text-destructive focus:bg-destructive/10 focus:text-destructive"
onSelect={() => {
void handleSignOut();
}}
>
<LogOut className="mr-2 size-4" />
Cerrar sesión
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : (
<Button asChild size="sm" variant="outline" className="hidden rounded-2xl md:inline-flex">
<Link to="/login">Login</Link>
</Button>
)}
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button variant="outline" size="icon" className="rounded-2xl md:hidden">
{open ? <X className="size-5" /> : <Menu className="size-5" />}
</Button>
</SheetTrigger>
<SheetContent
side="right"
className="w-[88vw] border-border/60 bg-background/95 p-5 backdrop-blur-xl sm:max-w-sm"
>
<div className="mt-6 flex flex-col gap-6">
<div className="rounded-3xl border border-border/60 bg-card/70 p-4 shadow-xl shadow-black/10">
<div className="flex items-center gap-3">
<UserAvatar
src={avatarUrl}
alt={displayName}
fallbackText={displayName}
className="size-11"
/>
<div className="min-w-0">
<p className="truncate text-sm font-medium">{displayName}</p>
<p className="truncate text-xs text-muted-foreground">{user?.email}</p>
{isAuthenticated && (
<p className="truncate text-xs text-muted-foreground">{currentComplexName}</p>
)}
</div>
</div>
</div>
<nav className="flex flex-col gap-1">
{menuItems.map((item) => (
<NavItem
key={item.label}
to={item.to}
label={item.label}
isMobile
onClick={() => setOpen(false)}
/>
))}
</nav>
<Button
className="rounded-2xl shadow-lg shadow-primary/20"
onClick={() => {
setOpen(false);
void handleOpenBookingCreate();
}}
>
<CalendarDays className="mr-2 size-4" />
Reservar ahora
</Button>
<div className="border-t border-border/60 pt-4">
<div className="mb-2 flex items-center justify-between px-2">
<p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Cuenta
</p>
</div>
<nav className="flex flex-col gap-1">
{!isAuthenticated && (
<Button
variant="ghost"
className="justify-start rounded-2xl"
onClick={() => {
setOpen(false);
void navigate({ to: '/login' });
}}
>
Login
</Button>
)}
<div className="py-1">
<p className="px-3 py-1 text-xs text-muted-foreground">Apariencia</p>
{[
{ value: 'light', label: 'Light', icon: Sun },
{ value: 'dark', label: 'Dark', icon: Moon },
{ value: 'system', label: 'System', icon: Laptop },
].map((item) => {
const Icon = item.icon;
return (
<Button
key={item.value}
variant="ghost"
className="w-full justify-start rounded-2xl"
onClick={() => setTheme(item.value as 'light' | 'dark' | 'system')}
>
<span className="mr-2 flex size-4 items-center justify-center">
{theme === item.value ? (
<Check className="size-4" />
) : (
<Icon className="size-4" />
)}
</span>
{item.label}
</Button>
);
})}
</div>
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
<div className="py-1">
<p className="px-3 py-1 text-xs text-muted-foreground">Cambiar complejo</p>
{myComplexesQuery.data.map((complex) => (
<Button
key={complex.id}
variant="ghost"
className="w-full justify-start rounded-2xl"
onClick={() => {
setOpen(false);
void handleSelectComplex(complex.id, complex.complexSlug);
}}
>
<span className="mr-2 flex size-4 items-center justify-center">
{complex.complexSlug === complexSlug && <Check className="size-4" />}
</span>
{complex.complexName}
</Button>
))}
</div>
)}
{isAuthenticated && (
<Button
variant="ghost"
className="justify-start rounded-2xl"
onClick={() => {
setOpen(false);
void navigate({ to: '/profile' });
}}
>
<User className="mr-2 size-4" />
Mi Perfil
</Button>
)}
{currentComplexSlug && (
<Button
variant="ghost"
className="justify-start rounded-2xl"
onClick={() => {
setOpen(false);
void navigate({
to: '/complex/$slug/edit',
params: { slug: currentComplexSlug },
});
}}
>
<Settings className="mr-2 size-4" />
Configuración
</Button>
)}
{isAuthenticated && (
<Button
variant="ghost"
className="justify-start rounded-2xl text-destructive hover:bg-destructive/10 hover:text-destructive"
onClick={() => {
setOpen(false);
void handleSignOut();
}}
>
<LogOut className="mr-2 size-4" />
Cerrar sesión
</Button>
)}
</nav>
</div>
</div>
</SheetContent>
</Sheet>
</div>
<div className="h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
</header>
);
}

View File

@@ -0,0 +1,46 @@
import { useIsMobile } from '@/hooks/use-mobile';
import { useLocation } from '@tanstack/react-router';
import type { ReactNode } from 'react';
import { Header } from './header';
interface LayoutProps {
children: ReactNode;
}
export function Layout({ children }: LayoutProps) {
const isMobile = useIsMobile();
const location = useLocation();
const isMobileHome = isMobile && location.pathname === '/';
return (
<div className="relative min-h-dvh overflow-x-hidden bg-background text-foreground">
<Background />
{!isMobileHome && <Header />}
<main
className={
isMobileHome
? 'relative z-10 mx-auto w-full max-w-7xl'
: 'relative z-10 mx-auto w-full max-w-7xl px-3 py-6 sm:px-6 lg:px-8'
}
>
{children}
</main>
</div>
);
}
function Background() {
return (
<div className="pointer-events-none fixed inset-0 -z-10 overflow-hidden">
<div className="absolute inset-0 bg-gradient-to-b from-[#040b11] to-[#09131c]" />
<div className="absolute left-0 top-0 h-[420px] w-[420px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary/20 blur-3xl" />
<div className="absolute right-0 top-24 h-[360px] w-[360px] translate-x-1/3 rounded-full bg-reserved/15 blur-3xl" />
<div className="absolute bottom-0 left-1/2 h-[300px] w-[300px] -translate-x-1/2 translate-y-1/3 rounded-full bg-accent/10 blur-3xl" />
<div className="absolute inset-0 bg-[linear-gradient(to_right,oklch(1_0_0/0.055)_1px,transparent_1px),linear-gradient(to_bottom,oklch(1_0_0/0.055)_1px,transparent_1px)] bg-[size:64px_64px]" />
<div className="absolute inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,#09131c_78%)]" />
</div>
);
}

View File

@@ -1,113 +0,0 @@
import React from 'react';
// Types for the component
type Slot = {
startTime: string;
endTime: string;
};
type Court = {
courtId: string;
courtName: string;
sport: { id: string; name: string; slug: string };
slotDurationMinutes: number;
availableSlots: Slot[];
};
type SelectedSlot = {
courtId: string;
startTime: string;
} | null;
type AvailabilityHeatMapProps = {
courts: Court[];
selectedSlot: SelectedSlot;
onSelectSlot: (payload: {
courtId: string;
courtName: string;
sportId: string;
sportName: string;
startTime: string;
endTime: string;
price?: { min: number; max: number };
}) => void;
};
/**
* AvailabilityHeatMap
*
* A visual heatmap style component that displays each court as a card and colours the
* slot buttons according to how many slots are available for that court. The colour scale
* goes from green (few slots) to red (many slots), providing an immediate visual cue of
* density the signature element requested for the bookings panel.
*/
export default function AvailabilityHeatMap({
courts,
selectedSlot,
onSelectSlot,
}: AvailabilityHeatMapProps) {
// Determine the maximum number of slots among all courts to normalise the heat scale.
const maxSlots = Math.max(1, ...courts.map((c) => c.availableSlots.length));
// Convert a slot count into an HSL colour ranging from green (low) to red (high).
const slotCountToHue = (count: number) => {
const ratio = count / maxSlots; // 0 => green, 1 => red
const hue = Math.round(120 - 120 * ratio); // 120° (green) to 0° (red)
return `hsl(${hue}, 70%, 55%)`;
};
return (
<div className="grid gap-4">
{courts.map((court) => {
const bg = slotCountToHue(court.availableSlots.length);
return (
<div
key={court.courtId}
className="rounded-2xl border border-border/70 bg-background p-4 shadow-sm"
>
<div className="flex items-center justify-between mb-2">
<p className="font-semibold text-foreground">{court.courtName}</p>
<span className="text-xs text-muted-foreground">
{court.availableSlots.length} horarios
</span>
</div>
<div className="grid grid-cols-4 gap-2">
{court.availableSlots.map((slot) => {
const isSelected =
selectedSlot?.courtId === court.courtId &&
selectedSlot?.startTime === slot.startTime;
return (
<button
key={slot.startTime}
type="button"
onClick={() =>
onSelectSlot({
courtId: court.courtId,
courtName: court.courtName,
sportId: court.sport.id,
sportName: court.sport.name,
startTime: slot.startTime,
endTime: slot.endTime,
})
}
className={`h-10 rounded-xl border text-sm font-medium transition-all ${
isSelected
? 'border-primary bg-primary text-primary-foreground shadow-sm'
: 'border-border/70 hover:-translate-y-0.5 hover:border-primary/30 hover:shadow-sm'
}`}
style={{
backgroundColor: isSelected ? undefined : bg,
opacity: isSelected ? 1 : 0.8,
}}
>
{slot.startTime}
</button>
);
})}
</div>
</div>
);
})}
</div>
);
}

View File

@@ -5,13 +5,13 @@ import * as React from 'react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
const buttonVariants = cva( const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-xl border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{ {
variants: { variants: {
variant: { variant: {
default: 'bg-primary text-primary-foreground shadow-sm hover:bg-primary/90', default: 'bg-primary text-primary-foreground [a]:hover:bg-primary/80',
outline: outline:
'border-border bg-card shadow-sm hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/20 dark:hover:bg-input/30', 'border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50',
secondary: secondary:
'bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground', 'bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground',
ghost: ghost:
@@ -22,15 +22,16 @@ const buttonVariants = cva(
}, },
size: { size: {
default: default:
'h-9 gap-1.5 px-3 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5', 'h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2',
xs: "h-6 gap-1 rounded-lg px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3", xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1.5 rounded-lg px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 [&_svg:not([class*='size-'])]:size-3.5", sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
lg: 'h-10 gap-1.5 rounded-xl px-3.5 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3', lg: 'h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2',
icon: 'size-9 rounded-xl', icon: 'size-8',
'icon-xs': 'icon-xs':
"size-6 rounded-lg in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3", "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
'icon-sm': 'size-8 rounded-lg in-data-[slot=button-group]:rounded-lg', 'icon-sm':
'icon-lg': 'size-10 rounded-xl', 'size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg',
'icon-lg': 'size-9',
}, },
}, },
defaultVariants: { defaultVariants: {

View File

@@ -4,12 +4,14 @@ import { DayPicker } from 'react-day-picker';
import { buttonVariants } from '@/components/ui/button'; import { buttonVariants } from '@/components/ui/button';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { es } from 'date-fns/locale';
export type CalendarProps = React.ComponentProps<typeof DayPicker>; export type CalendarProps = React.ComponentProps<typeof DayPicker>;
function Calendar({ className, classNames, showOutsideDays = true, ...props }: CalendarProps) { function Calendar({ className, classNames, showOutsideDays = true, ...props }: CalendarProps) {
return ( return (
<DayPicker <DayPicker
locale={es}
showOutsideDays={showOutsideDays} showOutsideDays={showOutsideDays}
className={cn('p-3', className)} className={cn('p-3', className)}
classNames={{ classNames={{

View File

@@ -90,7 +90,7 @@ function DialogFooter({
<div <div
data-slot="dialog-footer" data-slot="dialog-footer"
className={cn( className={cn(
'-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end', '-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-green-50/70 p-4 sm:flex-row sm:justify-end dark:bg-muted/50',
className className
)} )}
{...props} {...props}

View File

@@ -8,7 +8,7 @@ function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
type={type} type={type}
data-slot="input" data-slot="input"
className={cn( className={cn(
'h-10 w-full min-w-0 rounded-xl border border-input bg-card px-3 py-2 text-base shadow-[0_1px_0_rgba(15,23,42,0.02)] transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/20 dark:disabled:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40', 'h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40',
className className
)} )}
{...props} {...props}

View File

@@ -36,7 +36,6 @@ function SelectTrigger({
data-size={size} data-size={size}
className={cn( className={cn(
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"flex w-fit items-center justify-between gap-1.5 rounded-xl border border-input bg-card py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-10 data-[size=sm]:h-9 data-[size=sm]:rounded-lg *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/20 dark:hover:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className className
)} )}
{...props} {...props}
@@ -62,7 +61,7 @@ function SelectContent({
data-slot="select-content" data-slot="select-content"
data-align-trigger={position === 'item-aligned'} data-align-trigger={position === 'item-aligned'}
className={cn( className={cn(
'relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-xl bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95', 'relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
position === 'popper' && position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1', 'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className className
@@ -106,7 +105,7 @@ function SelectItem({
<SelectPrimitive.Item <SelectPrimitive.Item
data-slot="select-item" data-slot="select-item"
className={cn( className={cn(
"relative flex w-full cursor-default items-center gap-1.5 rounded-lg py-2 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2", "relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className className
)} )}
{...props} {...props}

View File

@@ -0,0 +1,128 @@
import { Dialog as SheetPrimitive } from 'radix-ui';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { XIcon } from 'lucide-react';
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
'fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
className
)}
{...props}
/>
);
}
function SheetContent({
className,
children,
side = 'right',
showCloseButton = true,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: 'top' | 'right' | 'bottom' | 'left';
showCloseButton?: boolean;
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
data-side={side}
className={cn(
'fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10',
className
)}
{...props}
>
{children}
{showCloseButton && (
<SheetPrimitive.Close data-slot="sheet-close" asChild>
<Button variant="ghost" className="absolute top-3 right-3" size="icon-sm">
<XIcon />
<span className="sr-only">Close</span>
</Button>
</SheetPrimitive.Close>
)}
</SheetPrimitive.Content>
</SheetPortal>
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-header"
className={cn('flex flex-col gap-0.5 p-4', className)}
{...props}
/>
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-footer"
className={cn('mt-auto flex flex-col gap-2 p-4', className)}
{...props}
/>
);
}
function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn('font-heading text-base font-medium text-foreground', className)}
{...props}
/>
);
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
);
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};

View File

@@ -1,49 +0,0 @@
import { cn } from '@/lib/utils';
import { type LucideIcon } from 'lucide-react';
type StatusType = 'CONFIRMED' | 'PENDING' | 'CANCELLED' | 'NO_SHOW' | 'COMPLETED';
type StatusBadgeProps = {
status: StatusType;
label: string;
icon?: LucideIcon;
className?: string;
};
const statusStyles: Record<StatusType, string> = {
CONFIRMED: 'bg-status-confirmed-bg border-status-confirmed-border text-status-confirmed-text',
PENDING: 'bg-status-pending-bg border-status-pending-border text-status-pending-text',
CANCELLED: 'bg-status-cancelled-bg border-status-cancelled-border text-status-cancelled-text',
NO_SHOW: 'bg-status-noshow-bg border-status-noshow-border text-status-noshow-text',
COMPLETED: 'bg-status-completed-bg border-status-completed-border text-status-completed-text',
};
export function StatusBadge({ status, label, icon: Icon, className }: StatusBadgeProps) {
return (
<span
className={cn(
'inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium',
statusStyles[status],
className
)}
>
{Icon && <Icon className="size-3" />}
{label}
</span>
);
}
export function effectiveStatusClassName(
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW'
): string {
return statusStyles[status];
}
export function effectiveStatusLabel(
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW'
): string {
if (status === 'NO_SHOW') return 'No show';
if (status === 'COMPLETED') return 'Cumplida';
if (status === 'CANCELLED') return 'Cancelada';
return 'Confirmada';
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,4 @@
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { useEffect, useState } from 'react';
type UserAvatarProps = { type UserAvatarProps = {
src?: string | null; src?: string | null;
@@ -22,25 +21,9 @@ export function UserAvatar({
size = 'default', size = 'default',
className, className,
}: UserAvatarProps) { }: UserAvatarProps) {
const [imageError, setImageError] = useState(false);
useEffect(() => {
setImageError(false);
}, [src]);
const canShowImage = Boolean(src) && !imageError;
return ( return (
<Avatar size={size} className={className}> <Avatar size={size} className={className}>
{canShowImage && ( <AvatarImage src={src ?? undefined} alt={alt} />
<AvatarImage
src={src ?? undefined}
alt={alt}
onError={() => {
setImageError(true);
}}
/>
)}
<AvatarFallback>{getInitials(fallbackText)}</AvatarFallback> <AvatarFallback>{getInitials(fallbackText)}</AvatarFallback>
</Avatar> </Avatar>
); );

View File

@@ -1,6 +1,6 @@
export function AboutPage() { export function AboutPage() {
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 min-h-[60vh] w-full max-w-6xl items-center justify-center px-3 sm:px-6">
<section className="w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm"> <section className="w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<h2 className="text-2xl font-semibold">About</h2> <h2 className="text-2xl font-semibold">About</h2>
<p className="mt-2 text-sm text-muted-foreground"> <p className="mt-2 text-sm text-muted-foreground">

View File

@@ -0,0 +1,506 @@
import { ApiClientError, apiClient } from '@/lib/api-client';
import type { AdminBooking, ComplexWithRole, Court } from '@repo/api-contract';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
type ReactNode,
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import type {
BookingCourtSchedule,
BookingSlotDraft,
BookingStatusFilter,
BookingSummary,
BookingTimeRange,
BookingTimelineSegment,
BookingViewMode,
} from './booking.types';
import {
addDaysIso,
formatBookingDate,
getDayOfWeek,
getNowTime,
isTodayIso,
minutesToTime,
timeToMinutes,
toIsoDateLocal,
} from './lib/booking-time';
interface BookingProviderProps {
children: ReactNode;
complex: ComplexWithRole;
}
interface CreateManualBookingPayload {
courtId: string;
date: string;
startTime: string;
customerName: string;
customerPhone: string;
}
interface BookingContextValue {
complex: ComplexWithRole;
courts: Court[];
bookings: AdminBooking[];
schedules: BookingCourtSchedule[];
selectedDate: string;
selectedSportId: string;
selectedStatus: BookingStatusFilter;
viewMode: BookingViewMode;
visibleTimeRange: BookingTimeRange;
timelineHours: string[];
summary: BookingSummary;
currentTime: string | null;
selectedSlot: BookingSlotDraft | null;
selectedSegment: BookingTimelineSegment | null;
isLoading: boolean;
isError: boolean;
errorMessage: string | null;
isCreateBookingOpen: boolean;
createBookingError: string | null;
isCreatingBooking: boolean;
bookingToolsOpen: boolean;
setSelectedDate: (date: string) => void;
moveSelectedDate: (amount: number) => void;
setSelectedSportId: (sportId: string) => void;
setSelectedStatus: (status: BookingStatusFilter) => void;
setViewMode: (mode: BookingViewMode) => void;
setVisibleTimeRange: (range: BookingTimeRange) => void;
openCreateBooking: (draft?: Partial<BookingSlotDraft>) => void;
closeCreateBooking: () => void;
createBooking: (payload: CreateManualBookingPayload) => Promise<void>;
updateBookingStatus: (bookingId: string, status: 'CANCELLED' | 'COMPLETED' | 'NOSHOW') => void;
exportDayReport: () => void;
openBookingTools: (segment?: BookingTimelineSegment) => void;
closeBookingTools: () => void;
}
const BookingContext = createContext<BookingContextValue | null>(null);
const DEFAULT_TIME_RANGE: BookingTimeRange = {
start: '08:00',
end: '22:00',
};
function extractMessage(error: unknown, fallback: string) {
if (error instanceof ApiClientError) {
return error.message || fallback;
}
if (error instanceof Error) {
return error.message || fallback;
}
return fallback;
}
function makeTimelineHours(range: BookingTimeRange) {
const start = timeToMinutes(range.start);
const end = timeToMinutes(range.end);
const hours: string[] = [];
for (let minute = start; minute <= end; minute += 60) {
hours.push(minutesToTime(minute));
}
return hours;
}
function isActiveBooking(booking: AdminBooking) {
return (
booking.status === 'CONFIRMED' || booking.status === 'COMPLETED' || booking.status === 'NOSHOW'
);
}
function getCourtBookings(court: Court, bookings: AdminBooking[], selectedDate: string) {
return bookings
.filter(
(booking) =>
booking.courtId === court.id && booking.date === selectedDate && isActiveBooking(booking)
)
.sort((a, b) => timeToMinutes(a.startTime) - timeToMinutes(b.startTime));
}
function overlapsBooking(start: number, end: number, booking: AdminBooking) {
const bookingStart = timeToMinutes(booking.startTime);
const bookingEnd = timeToMinutes(booking.endTime);
return start < bookingEnd && end > bookingStart;
}
function buildSegmentsForCourt(
court: Court,
bookings: AdminBooking[],
selectedDate: string,
visibleRange: BookingTimeRange
) {
const dayOfWeek = getDayOfWeek(selectedDate);
const rangeStart = timeToMinutes(visibleRange.start);
const rangeEnd = timeToMinutes(visibleRange.end);
const courtBookings = getCourtBookings(court, bookings, selectedDate);
const segments: BookingTimelineSegment[] = [];
const slotDuration = court.slotDurationMinutes;
const availabilityRanges = court.availability
.filter((range) => range.dayOfWeek === dayOfWeek)
.map((range) => ({
start: Math.max(timeToMinutes(range.startTime), rangeStart),
end: Math.min(timeToMinutes(range.endTime), rangeEnd),
}))
.filter((range) => range.start < range.end)
.sort((a, b) => a.start - b.start);
for (const booking of courtBookings) {
const bookingStart = timeToMinutes(booking.startTime);
const bookingEnd = timeToMinutes(booking.endTime);
if (bookingEnd > rangeStart && bookingStart < rangeEnd) {
segments.push({
id: booking.id,
courtId: court.id,
status: 'reserved',
startTime: booking.startTime,
endTime: booking.endTime,
startMinutes: Math.max(bookingStart, rangeStart),
endMinutes: Math.min(bookingEnd, rangeEnd),
booking,
});
}
}
for (const availability of availabilityRanges) {
for (
let slotStart = availability.start;
slotStart + slotDuration <= availability.end;
slotStart += slotDuration
) {
const slotEnd = slotStart + slotDuration;
const isBooked = courtBookings.some((booking) =>
overlapsBooking(slotStart, slotEnd, booking)
);
if (isBooked) continue;
const slotStartTime = minutesToTime(slotStart);
const slotEndTime = minutesToTime(slotEnd);
segments.push({
id: `${court.id}-free-${slotStartTime}-${slotEndTime}`,
courtId: court.id,
status: 'free',
startTime: slotStartTime,
endTime: slotEndTime,
startMinutes: slotStart,
endMinutes: slotEnd,
});
}
}
segments.sort((a, b) => a.startMinutes - b.startMinutes);
return segments;
}
function getSummary(schedules: BookingCourtSchedule[]): BookingSummary {
const freeSlots = schedules.reduce((total, schedule) => total + schedule.metrics.free, 0);
const reservedSlots = schedules.reduce((total, schedule) => total + schedule.metrics.reserved, 0);
const maintenanceSlots = schedules.reduce(
(total, schedule) => total + schedule.metrics.maintenance,
0
);
const totalSegments = freeSlots + reservedSlots + maintenanceSlots || 1;
return {
totalReservations: reservedSlots + maintenanceSlots + freeSlots,
freeSlots,
reservedSlots,
maintenanceSlots,
freePercent: Math.round((freeSlots / totalSegments) * 100),
reservedPercent: Math.round((reservedSlots / totalSegments) * 100),
maintenancePercent: Math.round((maintenanceSlots / totalSegments) * 100),
};
}
export function BookingProvider({ children, complex }: BookingProviderProps) {
const queryClient = useQueryClient();
const todayIso = useMemo(() => toIsoDateLocal(new Date()), []);
const [selectedDate, setSelectedDate] = useState(todayIso);
const [selectedSportId, setSelectedSportId] = useState('all');
const [selectedStatus, setSelectedStatus] = useState<BookingStatusFilter>('all');
const [viewMode, setViewMode] = useState<BookingViewMode>('panel');
const [visibleTimeRange, setVisibleTimeRange] = useState(DEFAULT_TIME_RANGE);
const [selectedSlot, setSelectedSlot] = useState<BookingSlotDraft | null>(null);
const [isCreateBookingOpen, setIsCreateBookingOpen] = useState(false);
const [selectedSegment, setSelectedSegment] = useState<BookingTimelineSegment | null>(null);
const [bookingToolsOpen, setBookingToolsOpen] = useState(false);
const courtsQuery = useQuery({
queryKey: ['courts', complex.id],
queryFn: () => apiClient.courts.listByComplex(complex.id),
});
const bookingsQuery = useQuery({
queryKey: ['admin-bookings', complex.id, selectedDate],
queryFn: () =>
apiClient.adminBookings.listByComplex(complex.id, {
fromDate: selectedDate,
}),
});
const bookings = useMemo(
() => (bookingsQuery.data?.bookings ?? []).filter((booking) => booking.date === selectedDate),
[bookingsQuery.data?.bookings, selectedDate]
);
const courts = useMemo(
() => courtsQuery.data?.sort((a, b) => a.name.localeCompare(b.name)) ?? [],
[courtsQuery.data]
);
const filteredCourts = useMemo(() => {
if (selectedSportId === 'all') return courts;
return courts.filter((court) => court.sportId === selectedSportId);
}, [courts, selectedSportId]);
const schedules = useMemo<BookingCourtSchedule[]>(() => {
return filteredCourts
.map((court) => {
const segments = buildSegmentsForCourt(court, bookings, selectedDate, visibleTimeRange);
const metrics = {
free: segments.filter((segment) => segment.status === 'free').length,
reserved: segments.filter((segment) => segment.status === 'reserved').length,
maintenance: segments.filter((segment) => segment.status === 'maintenance').length,
};
return { court, segments, metrics };
})
.filter((schedule) => {
if (selectedStatus === 'all') return true;
return schedule.segments.some((segment) => segment.status === selectedStatus);
});
}, [bookings, filteredCourts, selectedDate, selectedStatus, visibleTimeRange]);
const summary = useMemo(() => getSummary(schedules), [schedules]);
const timelineHours = useMemo(() => makeTimelineHours(visibleTimeRange), [visibleTimeRange]);
const [now, setNow] = useState(() => getNowTime());
useEffect(() => {
const interval = setInterval(() => {
setNow(getNowTime());
}, 60 * 1000);
return () => clearInterval(interval);
}, []);
const currentTime = useMemo(() => {
if (!isTodayIso(selectedDate)) return null;
const nowMinutes = timeToMinutes(now);
const start = timeToMinutes(visibleTimeRange.start);
const end = timeToMinutes(visibleTimeRange.end);
if (nowMinutes < start || nowMinutes > end) return null;
return now;
}, [selectedDate, visibleTimeRange, now]);
const createBookingMutation = useMutation({
mutationFn: (payload: CreateManualBookingPayload) =>
apiClient.adminBookings.create(complex.id, {
date: payload.date,
courtId: payload.courtId,
startTime: payload.startTime,
customerName: payload.customerName,
customerPhone: payload.customerPhone,
}),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['admin-bookings', complex.id] });
await queryClient.invalidateQueries({ queryKey: ['manual-booking-availability'] });
setIsCreateBookingOpen(false);
setSelectedSlot(null);
},
});
const updateStatusMutation = useMutation({
mutationFn: (payload: { bookingId: string; status: 'CANCELLED' | 'COMPLETED' | 'NOSHOW' }) =>
apiClient.adminBookings.updateStatus(payload.bookingId, { status: payload.status }),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['admin-bookings', complex.id] });
},
});
const openCreateBooking = useCallback(
(draft?: Partial<BookingSlotDraft>) => {
setSelectedSlot({
date: draft?.date ?? selectedDate,
courtId: draft?.courtId,
startTime: draft?.startTime,
sportId: draft?.sportId,
});
setIsCreateBookingOpen(true);
},
[selectedDate]
);
const openBookingTools = useCallback(
(segment?: BookingTimelineSegment) => {
setSelectedSegment(segment ?? null);
setBookingToolsOpen(true);
console.log(JSON.stringify(segment, null, 2));
},
[selectedDate]
);
const closeBookingTools = () => setBookingToolsOpen(false);
useEffect(() => {
const handleOpenCreateBooking = () => {
openCreateBooking();
};
window.addEventListener('playzer:open-booking-create', handleOpenCreateBooking);
return () => {
window.removeEventListener('playzer:open-booking-create', handleOpenCreateBooking);
};
}, [openCreateBooking]);
const closeCreateBooking = useCallback(() => {
setIsCreateBookingOpen(false);
setSelectedSlot(null);
createBookingMutation.reset();
}, [createBookingMutation]);
const createBooking = useCallback(
async (payload: CreateManualBookingPayload) => {
await createBookingMutation.mutateAsync(payload);
},
[createBookingMutation]
);
const updateBookingStatus = useCallback(
(bookingId: string, status: 'CANCELLED' | 'COMPLETED' | 'NOSHOW') => {
updateStatusMutation.mutate({ bookingId, status });
},
[updateStatusMutation]
);
const exportDayReport = useCallback(() => {
const rows = [
['Fecha', 'Cancha', 'Deporte', 'Inicio', 'Fin', 'Cliente', 'Telefono', 'Estado'],
...bookings.map((booking) => [
booking.date,
booking.courtName,
booking.sport.name,
booking.startTime,
booking.endTime,
booking.customerName,
booking.customerPhone,
booking.status,
]),
];
const csv = rows.map((row) => row.map((cell) => `"${cell}"`).join(',')).join('\n');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `reservas-${complex.complexSlug}-${selectedDate}.csv`;
link.click();
URL.revokeObjectURL(url);
}, [bookings, complex.complexSlug, selectedDate]);
const value = useMemo<BookingContextValue>(
() => ({
complex,
courts,
bookings,
schedules,
selectedDate,
selectedSportId,
selectedStatus,
viewMode,
visibleTimeRange,
timelineHours,
summary,
currentTime,
selectedSlot,
isLoading: courtsQuery.isLoading || bookingsQuery.isLoading,
isError: courtsQuery.isError || bookingsQuery.isError,
errorMessage:
courtsQuery.isError || bookingsQuery.isError
? extractMessage(
courtsQuery.error ?? bookingsQuery.error,
'No pudimos cargar el panel de reservas.'
)
: null,
isCreateBookingOpen,
createBookingError: createBookingMutation.isError
? extractMessage(createBookingMutation.error, 'No pudimos crear la reserva.')
: null,
isCreatingBooking: createBookingMutation.isPending,
setSelectedDate,
moveSelectedDate: (amount) => setSelectedDate((date) => addDaysIso(date, amount)),
setSelectedSportId,
setSelectedStatus,
setViewMode,
setVisibleTimeRange,
openCreateBooking,
closeCreateBooking,
createBooking,
updateBookingStatus,
exportDayReport,
bookingToolsOpen,
openBookingTools,
closeBookingTools,
selectedSegment,
}),
[
bookings,
bookingsQuery.error,
bookingsQuery.isError,
bookingsQuery.isLoading,
closeCreateBooking,
complex,
courts,
courtsQuery.error,
courtsQuery.isError,
courtsQuery.isLoading,
createBooking,
createBookingMutation.error,
createBookingMutation.isError,
createBookingMutation.isPending,
currentTime,
exportDayReport,
isCreateBookingOpen,
openCreateBooking,
schedules,
selectedDate,
selectedSlot,
selectedSportId,
selectedStatus,
summary,
timelineHours,
updateBookingStatus,
viewMode,
visibleTimeRange,
bookingToolsOpen,
]
);
return <BookingContext.Provider value={value}>{children}</BookingContext.Provider>;
}
export function useBooking() {
const context = useContext(BookingContext);
if (!context) {
throw new Error('useBooking must be used within BookingProvider');
}
return context;
}
export { formatBookingDate };

View File

@@ -0,0 +1,38 @@
import { useIsMobile } from '@/hooks/use-mobile';
import type { ComplexWithRole } from '@repo/api-contract';
import { BookingProvider } from './booking-provider';
import { BookingCreateDialog } from './components/booking-create-dialog';
import { BookingDaySummary, BookingQuickActions } from './components/booking-day-summary';
import { BookingHeader } from './components/booking-header';
import { BookingMobile } from './components/booking-mobile';
import { BookingTimeline } from './components/booking-timeline';
import { BookingToolbar } from './components/booking-toolbar';
import { BookingToolsDialog } from './components/booking-tools-dialog';
interface BookingProps {
complex: ComplexWithRole;
}
export function Booking({ complex }: BookingProps) {
const isMobile = useIsMobile();
return (
<BookingProvider complex={complex}>
{isMobile ? (
<BookingMobile />
) : (
<div className="flex flex-col gap-5">
<BookingHeader />
<BookingToolbar />
<BookingTimeline />
<div className="grid gap-5 xl:grid-cols-4">
<BookingDaySummary />
<BookingQuickActions />
</div>
</div>
)}
<BookingCreateDialog />
<BookingToolsDialog />
</BookingProvider>
);
}

View File

@@ -0,0 +1,50 @@
import type { AdminBooking, Court } from '@repo/api-contract';
export type BookingViewMode = 'panel' | 'status';
export type BookingStatusFilter = 'all' | 'free' | 'reserved' | 'maintenance';
export type BookingSegmentStatus = 'free' | 'reserved' | 'maintenance';
export interface BookingTimeRange {
start: string;
end: string;
}
export interface BookingSummary {
totalReservations: number;
freeSlots: number;
reservedSlots: number;
maintenanceSlots: number;
freePercent: number;
reservedPercent: number;
maintenancePercent: number;
}
export interface BookingCourtMetrics {
free: number;
reserved: number;
maintenance: number;
}
export interface BookingTimelineSegment {
id: string;
courtId: string;
status: BookingSegmentStatus;
startTime: string;
endTime: string;
startMinutes: number;
endMinutes: number;
booking?: AdminBooking;
}
export interface BookingCourtSchedule {
court: Court;
segments: BookingTimelineSegment[];
metrics: BookingCourtMetrics;
}
export interface BookingSlotDraft {
courtId?: string;
date: string;
startTime?: string;
sportId?: string;
}

View File

@@ -0,0 +1,292 @@
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import { Field, FieldError, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import {
ResponsiveDialog,
ResponsiveDialogClose,
ResponsiveDialogContent,
ResponsiveDialogDescription,
ResponsiveDialogFooter,
ResponsiveDialogHeader,
ResponsiveDialogTitle,
} from '@/components/ui/responsive-dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { zodResolver } from '@hookform/resolvers/zod';
import { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { useBooking } from '../booking-provider';
import {
fromIsoDateLocal,
getDayOfWeek,
minutesToTime,
timeToMinutes,
toIsoDateLocal,
} from '../lib/booking-time';
const bookingFormSchema = z.object({
customerName: z
.string()
.trim()
.min(2, 'Ingresa un nombre válido.')
.max(120, 'El nombre no puede superar los 120 caracteres.'),
customerPhone: z
.string()
.trim()
.min(6, 'Ingresa un telefono válido.')
.max(30, 'El telefono no puede superar los 30 caracteres.'),
});
type BookingForm = z.infer<typeof bookingFormSchema>;
export function BookingCreateDialog() {
const {
courts,
bookings,
selectedDate,
selectedSlot,
isCreateBookingOpen,
createBookingError,
isCreatingBooking,
closeCreateBooking,
createBooking,
} = useBooking();
const [date, setDate] = useState(selectedSlot?.date ?? selectedDate);
const [sportId, setSportId] = useState(selectedSlot?.sportId ?? 'all');
const [courtId, setCourtId] = useState(selectedSlot?.courtId ?? '');
const [startTime, setStartTime] = useState(selectedSlot?.startTime ?? '');
const {
register,
handleSubmit,
reset,
setFocus,
formState: { errors, isValid },
} = useForm<BookingForm>({
resolver: zodResolver(bookingFormSchema),
mode: 'onChange',
defaultValues: {
customerName: '',
customerPhone: '',
},
});
useEffect(() => {
if (!isCreateBookingOpen) return;
setDate(selectedSlot?.date ?? selectedDate);
setSportId(selectedSlot?.sportId ?? 'all');
setCourtId(selectedSlot?.courtId ?? '');
setStartTime(selectedSlot?.startTime ?? '');
reset();
if (selectedSlot?.courtId && selectedSlot?.startTime) {
requestAnimationFrame(() => {
setFocus('customerName');
});
}
}, [isCreateBookingOpen, reset, selectedDate, selectedSlot, setFocus]);
const sports = [...new Map(courts.map((court) => [court.sport.id, court.sport])).values()];
const filteredCourts = useMemo(() => {
if (sportId === 'all') return courts;
return courts.filter((court) => court.sportId === sportId);
}, [courts, sportId]);
const selectedCourt = courts.find((court) => court.id === courtId);
const availableStartTimes = useMemo(() => {
if (!selectedCourt) return [];
const times: string[] = [];
const dayOfWeek = getDayOfWeek(date);
const dayAvailability = selectedCourt.availability
.filter((range) => range.dayOfWeek === dayOfWeek)
.sort((a, b) => timeToMinutes(a.startTime) - timeToMinutes(b.startTime));
const courtBookings = bookings.filter(
(booking) =>
booking.date === date &&
booking.courtId === selectedCourt.id &&
booking.status !== 'CANCELLED'
);
for (const range of dayAvailability) {
const start = timeToMinutes(range.startTime);
const end = timeToMinutes(range.endTime);
for (
let minute = start;
minute + selectedCourt.slotDurationMinutes <= end;
minute += selectedCourt.slotDurationMinutes
) {
const slotEnd = minute + selectedCourt.slotDurationMinutes;
const isBooked = courtBookings.some((booking) => {
const bookingStart = timeToMinutes(booking.startTime);
const bookingEnd = timeToMinutes(booking.endTime);
return minute < bookingEnd && slotEnd > bookingStart;
});
if (!isBooked) {
times.push(minutesToTime(minute));
}
}
}
return times;
}, [bookings, date, selectedCourt]);
useEffect(() => {
if (startTime && !availableStartTimes.includes(startTime)) {
setStartTime('');
}
}, [availableStartTimes, startTime]);
const onSubmit = async (values: BookingForm) => {
await createBooking({
courtId,
date,
startTime,
customerName: values.customerName,
customerPhone: values.customerPhone,
});
};
return (
<ResponsiveDialog
open={isCreateBookingOpen}
onOpenChange={(open) => !open && closeCreateBooking()}
>
<ResponsiveDialogContent
className="data-[variant=dialog]:max-w-lg"
onOpenAutoFocus={(event) => event.preventDefault()}
>
<ResponsiveDialogHeader>
<ResponsiveDialogTitle>Nueva reserva</ResponsiveDialogTitle>
<ResponsiveDialogDescription>
Crea un turno para atención telefónica o mostrador.
</ResponsiveDialogDescription>
</ResponsiveDialogHeader>
<form id="booking-create-form" className="grid gap-4" onSubmit={handleSubmit(onSubmit)}>
<div className="grid gap-3 md:grid-cols-2">
<Field>
<FieldLabel>Fecha</FieldLabel>
<DatePicker
value={fromIsoDateLocal(date)}
onChange={(nextDate) => {
setDate(nextDate ? toIsoDateLocal(nextDate) : selectedDate);
}}
/>
</Field>
<Field>
<FieldLabel>Deporte</FieldLabel>
<Select
value={sportId}
onValueChange={(value) => {
setSportId(value);
setCourtId('');
setStartTime('');
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
{sports.map((sport) => (
<SelectItem key={sport.id} value={sport.id}>
{sport.name}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel>Cancha</FieldLabel>
<Select
value={courtId}
onValueChange={(value) => {
setCourtId(value);
setStartTime('');
}}
>
<SelectTrigger>
<SelectValue placeholder="Selecciona una cancha" />
</SelectTrigger>
<SelectContent>
{filteredCourts.map((court) => (
<SelectItem key={court.id} value={court.id}>
{court.name} · {court.sport.name}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel>Horario</FieldLabel>
<Select value={startTime} onValueChange={setStartTime}>
<SelectTrigger>
<SelectValue placeholder="Selecciona un horario" />
</SelectTrigger>
<SelectContent>
{availableStartTimes.map((time) => (
<SelectItem key={time} value={time}>
{time}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
</div>
<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>
{createBookingError && <p className="text-sm text-destructive">{createBookingError}</p>}
</form>
<ResponsiveDialogFooter>
<ResponsiveDialogClose asChild>
<Button variant="outline">Cancelar</Button>
</ResponsiveDialogClose>
<Button
type="submit"
form="booking-create-form"
disabled={!isValid || isCreatingBooking || !courtId || !startTime}
>
{isCreatingBooking ? 'Guardando...' : 'Crear reserva'}
</Button>
</ResponsiveDialogFooter>
</ResponsiveDialogContent>
</ResponsiveDialog>
);
}

View File

@@ -0,0 +1,118 @@
import { CalendarDays, Download, Drill, ShieldCheck, UsersRound } from 'lucide-react';
import { useBooking } from '../booking-provider';
import { formatBookingDate, toIsoDateLocal } from '../lib/booking-time';
export function BookingDaySummary() {
const { selectedDate, summary } = useBooking();
return (
<section className="rounded-lg border bg-card/85 p-5 shadow-sm xl:col-span-3">
<div className="mb-4">
<h2 className="text-base font-semibold">Resumen del día</h2>
<p className="mt-1 text-sm capitalize text-muted-foreground">
{formatBookingDate(selectedDate, { year: 'numeric' })}
</p>
</div>
<div className="grid gap-3 md:grid-cols-4">
<SummaryCard
label="Total de bloques"
value={summary.totalReservations}
icon={CalendarDays}
className="border-border bg-background/45"
/>
<SummaryCard
label="Libres"
value={summary.freeSlots}
detail={`${summary.freePercent}% del total`}
icon={UsersRound}
className="border-primary/30 bg-primary/10 text-primary"
/>
<SummaryCard
label="Reservados"
value={summary.reservedSlots}
detail={`${summary.reservedPercent}% del total`}
icon={ShieldCheck}
className="border-reserved/35 bg-reserved/10 text-reserved"
/>
<SummaryCard
label="Mantenimiento"
value={summary.maintenanceSlots}
detail={`${summary.maintenancePercent}% del total`}
icon={Drill}
className="border-maintenance/35 bg-maintenance/10 text-maintenance"
/>
</div>
</section>
);
}
interface SummaryCardProps {
label: string;
value: number;
detail?: string;
icon: typeof CalendarDays;
className: string;
}
function SummaryCard({ label, value, detail, icon: Icon, className }: SummaryCardProps) {
return (
<article className={`rounded-lg border p-4 ${className}`}>
<div className="flex items-center gap-3">
<div className="flex size-10 shrink-0 items-center justify-center rounded-md bg-transparent">
<Icon className="size-5" />
</div>
<div className="min-w-0">
<p className="truncate text-sm text-muted-foreground">{label}</p>
<p className="text-2xl font-semibold leading-tight">{value}</p>
{detail && <p className="mt-1 truncate text-xs text-muted-foreground">{detail}</p>}
</div>
</div>
</article>
);
}
export function BookingQuickActions() {
const { selectedDate, selectedStatus, setSelectedDate, setSelectedStatus, exportDayReport } =
useBooking();
const todayIso = toIsoDateLocal(new Date());
const isViewingTodayReservations = selectedDate === todayIso && selectedStatus === 'reserved';
const isViewingMaintenance = selectedStatus === 'maintenance';
return (
<section className="rounded-lg border bg-card/85 p-5 shadow-sm">
<h2 className="text-base font-semibold">Acciones rápidas</h2>
<div className="mt-3 grid gap-2">
<button
type="button"
onClick={() => {
setSelectedDate(todayIso);
setSelectedStatus(isViewingTodayReservations ? 'all' : 'reserved');
}}
aria-pressed={isViewingTodayReservations}
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted aria-pressed:border-reserved/50 aria-pressed:bg-reserved/10"
>
<CalendarDays className="size-4 text-muted-foreground" />
{isViewingTodayReservations ? 'Ver todos los estados' : 'Ver reservas de hoy'}
</button>
<button
type="button"
onClick={() => setSelectedStatus(isViewingMaintenance ? 'all' : 'maintenance')}
aria-pressed={isViewingMaintenance}
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted aria-pressed:border-maintenance/50 aria-pressed:bg-maintenance/10"
>
<Drill className="size-4 text-maintenance" />
{isViewingMaintenance ? 'Ver todos los estados' : 'Ver mantenimiento'}
</button>
<button
type="button"
onClick={exportDayReport}
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted"
>
<Download className="size-4 text-primary" />
Exportar reporte
</button>
</div>
</section>
);
}

View File

@@ -0,0 +1,18 @@
import { useBooking } from '../booking-provider';
export function BookingHeader() {
const { complex } = useBooking();
return (
<section>
<div>
<h1 className="text-3xl font-semibold tracking-normal text-foreground">
Panel de Reservas
</h1>
<p className="mt-2 text-sm text-muted-foreground">
Gestiona las canchas de {complex.complexName}
</p>
</div>
</section>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
const items = [
{ label: 'Libre', className: 'bg-primary' },
{ label: 'Reservado', className: 'bg-reserved' },
{ label: 'Mantenimiento', className: 'bg-maintenance' },
];
export function BookingStatusLegend() {
return (
<div className="flex flex-wrap items-center gap-5 text-sm text-muted-foreground">
{items.map((item) => (
<span key={item.label} className="inline-flex items-center gap-2">
<span className={`size-3 rounded-full ${item.className}`} />
{item.label}
</span>
))}
</div>
);
}

View File

@@ -0,0 +1,336 @@
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { ChevronLeft, ChevronRight, Dumbbell, Plus, UserX, Users } from 'lucide-react';
import { useEffect, useRef } from 'react';
import { useBooking } from '../booking-provider';
import type { BookingCourtSchedule, BookingTimelineSegment } from '../booking.types';
import { timeToMinutes } from '../lib/booking-time';
import { BookingStatusLegend } from './booking-status-legend';
const courtInfoWidth = 220;
const hourWidth = 104;
export function BookingTimeline() {
const {
schedules,
timelineHours,
visibleTimeRange,
currentTime,
isLoading,
isError,
errorMessage,
} = useBooking();
const scrollRef = useRef<HTMLDivElement>(null);
const prevCurrentTimeRef = useRef<string | null>(null);
const rangeStart = timeToMinutes(visibleTimeRange.start);
const rangeEnd = timeToMinutes(visibleTimeRange.end);
const totalMinutes = rangeEnd - rangeStart;
const gridWidth = Math.max((timelineHours.length - 1) * hourWidth, 760);
const timelineMarks = timelineHours.map((hour) => ({
hour,
left: ((timeToMinutes(hour) - rangeStart) / totalMinutes) * 100,
}));
useEffect(() => {
if (!currentTime || !scrollRef.current) return;
if (currentTime === prevCurrentTimeRef.current) return;
prevCurrentTimeRef.current = currentTime;
const container = scrollRef.current;
const indicatorLeft =
courtInfoWidth + ((timeToMinutes(currentTime) - rangeStart) / totalMinutes) * gridWidth;
const targetScroll = indicatorLeft - container.clientWidth / 2;
const clampedScroll = Math.max(
0,
Math.min(targetScroll, container.scrollWidth - container.clientWidth)
);
requestAnimationFrame(() => {
container.scrollTo({ left: clampedScroll, behavior: 'smooth' });
});
}, [currentTime, rangeStart, totalMinutes, gridWidth]);
return (
<section className="overflow-hidden rounded-lg border bg-card/85 shadow-sm">
<div className="flex items-center justify-between gap-4 border-b px-4 py-4">
<BookingStatusLegend />
<div className="hidden items-center gap-2 md:flex">
<Button type="button" size="icon-sm" variant="ghost">
<ChevronLeft className="size-4" />
</Button>
<Button type="button" size="icon-sm" variant="ghost">
<ChevronRight className="size-4" />
</Button>
</div>
</div>
{isLoading && (
<div className="px-4 py-10 text-sm text-muted-foreground">Cargando reservas...</div>
)}
{isError && !isLoading && (
<div className="px-4 py-10 text-sm text-destructive">{errorMessage}</div>
)}
{!isLoading && !isError && schedules.length === 0 && (
<div className="px-4 py-10 text-sm text-muted-foreground">
No hay canchas para los filtros seleccionados.
</div>
)}
{!isLoading && !isError && schedules.length > 0 && (
<div ref={scrollRef} className="booking-scrollbar overflow-x-auto overflow-y-hidden">
<div className="relative min-w-full" style={{ width: courtInfoWidth + gridWidth }}>
<TimelineHeader
timelineMarks={timelineMarks}
courtInfoWidth={courtInfoWidth}
gridWidth={gridWidth}
/>
<div className="divide-y">
{schedules.map((schedule) => (
<BookingCourtRow
key={schedule.court.id}
schedule={schedule}
courtInfoWidth={courtInfoWidth}
gridWidth={gridWidth}
rangeStart={rangeStart}
totalMinutes={totalMinutes}
timelineMarks={timelineMarks}
/>
))}
</div>
{currentTime && (
<CurrentTimeIndicator
time={currentTime}
courtInfoWidth={courtInfoWidth}
gridWidth={gridWidth}
rangeStart={rangeStart}
totalMinutes={totalMinutes}
/>
)}
</div>
</div>
)}
</section>
);
}
interface TimelineHeaderProps {
timelineMarks: Array<{ hour: string; left: number }>;
courtInfoWidth: number;
gridWidth: number;
}
function TimelineHeader({ timelineMarks, courtInfoWidth, gridWidth }: TimelineHeaderProps) {
return (
<div
className="sticky top-0 z-20 grid border-b bg-card/95 z-auto"
style={{ gridTemplateColumns: `${courtInfoWidth}px ${gridWidth}px` }}
>
<div className="sticky left-0 z-30 border-r bg-card/95 px-4 py-3 shadow-[8px_0_18px_-18px_oklch(0_0_0/0.45)]" />
<div className="relative h-12">
{timelineMarks.map((mark) => (
<div
key={mark.hour}
className="absolute top-0 flex h-full items-center border-l px-3 text-sm text-muted-foreground first:border-l-0"
style={{ left: `${mark.left}%` }}
>
{mark.hour}
</div>
))}
</div>
</div>
);
}
interface BookingCourtRowProps {
schedule: BookingCourtSchedule;
courtInfoWidth: number;
gridWidth: number;
rangeStart: number;
totalMinutes: number;
timelineMarks: Array<{ hour: string; left: number }>;
}
function BookingCourtRow({
schedule,
courtInfoWidth,
gridWidth,
rangeStart,
totalMinutes,
timelineMarks,
}: BookingCourtRowProps) {
return (
<div
className="grid min-h-[96px]"
style={{ gridTemplateColumns: `${courtInfoWidth}px ${gridWidth}px` }}
>
<BookingCourtInfo schedule={schedule} />
<div className="relative bg-background/20 py-4">
<div className="absolute inset-y-0 left-0 right-0 opacity-70">
{timelineMarks.map((mark) => (
<span
key={mark.hour}
className="absolute top-0 h-full border-l first:border-l-0"
style={{ left: `${mark.left}%` }}
/>
))}
</div>
<div className="relative h-16">
{schedule.segments.map((segment) => (
<BookingSlotBlock
key={segment.id}
segment={segment}
schedule={schedule}
rangeStart={rangeStart}
totalMinutes={totalMinutes}
/>
))}
</div>
</div>
</div>
);
}
function BookingCourtInfo({ schedule }: { schedule: BookingCourtSchedule }) {
return (
<div className="sticky left-0 z-10 flex items-center gap-3 border-r bg-card/95 px-4 py-4 shadow-[8px_0_18px_-18px_oklch(0_0_0/0.45)]">
<div className="flex size-12 shrink-0 items-center justify-center rounded-lg border border-primary/40 bg-primary/15 text-primary">
<Dumbbell className="size-6" />
</div>
<div className="min-w-0">
<h2 className="truncate text-base font-semibold">{schedule.court.name}</h2>
<p className="truncate text-sm text-muted-foreground">{schedule.court.sport.name}</p>
<div className="mt-1 flex items-center gap-3 text-xs text-muted-foreground">
<span className="inline-flex items-center gap-1">
<span className="size-2 rounded-full bg-primary" />
{schedule.metrics.free}
</span>
<span className="inline-flex items-center gap-1">
<span className="size-2 rounded-full bg-reserved" />
{schedule.metrics.reserved}
</span>
<span className="inline-flex items-center gap-1">
<span className="size-2 rounded-full bg-maintenance" />
{schedule.metrics.maintenance}
</span>
</div>
</div>
</div>
);
}
interface BookingSlotBlockProps {
segment: BookingTimelineSegment;
schedule: BookingCourtSchedule;
rangeStart: number;
totalMinutes: number;
}
function BookingSlotBlock({ segment, schedule, rangeStart, totalMinutes }: BookingSlotBlockProps) {
const { openCreateBooking, updateBookingStatus, openBookingTools } = useBooking();
const left = ((segment.startMinutes - rangeStart) / totalMinutes) * 100;
const width = ((segment.endMinutes - segment.startMinutes) / totalMinutes) * 100;
const isFree = segment.status === 'free';
return (
<button
type="button"
className={cn(
'absolute top-0 flex h-16 min-w-0 flex-col justify-center overflow-hidden rounded-md border px-2 text-left text-xs shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md focus-visible:ring-2 focus-visible:ring-ring',
segment.status === 'free' &&
'border-primary/70 bg-primary/20 text-primary hover:bg-primary/25',
segment.status === 'reserved' &&
'border-reserved/70 bg-reserved/80 text-reserved-foreground',
segment.status === 'maintenance' &&
'border-maintenance/80 bg-maintenance/75 text-maintenance-foreground',
segment.booking?.status === 'COMPLETED' &&
'border-reserved/70 bg-reserved/25 dark:text-reserved-foreground text-gray-600 line-through',
segment.booking?.status === 'NOSHOW' &&
'border-amber-500/60 bg-amber-500/50 text-amber-950 dark:text-amber-200'
)}
style={{
left: `calc(${left}% + 4px)`,
width: `calc(${width}% - 8px)`,
}}
onClick={(event) => {
if (isFree) {
openCreateBooking({
courtId: schedule.court.id,
startTime: segment.startTime,
sportId: schedule.court.sportId,
});
} else if (segment.booking?.status === 'NOSHOW') {
return;
} else {
if (event.shiftKey && segment.booking?.status === 'CONFIRMED') {
updateBookingStatus(segment.booking.id, 'COMPLETED');
} else {
openBookingTools(segment);
}
}
}}
title={
segment.booking
? `${segment.booking.customerName} · ${segment.startTime} - ${segment.endTime}`
: `${segment.startTime} - ${segment.endTime}`
}
>
{isFree ? (
<span className="flex items-center justify-center gap-1 text-sm font-medium">
<Plus className="size-4" />
<span className="hidden sm:inline">Reservar</span>
</span>
) : (
<>
<div className="flex items-center justify-between">
<span className="truncate text-sm font-medium">
{segment.startTime} - {segment.endTime}
</span>
{segment.booking?.status === 'NOSHOW' && (
<span title="No Show - El cliente no se presentó">
<UserX className="size-3 shrink-0" />
</span>
)}
</div>
<span className="mt-1 flex items-center gap-1 truncate opacity-90">
<Users className="size-3" />
{segment.booking?.customerName ?? 'Mantenimiento'}
</span>
</>
)}
</button>
);
}
interface CurrentTimeIndicatorProps {
time: string;
courtInfoWidth: number;
gridWidth: number;
rangeStart: number;
totalMinutes: number;
}
function CurrentTimeIndicator({
time,
courtInfoWidth,
gridWidth,
rangeStart,
totalMinutes,
}: CurrentTimeIndicatorProps) {
const left = courtInfoWidth + ((timeToMinutes(time) - rangeStart) / totalMinutes) * gridWidth;
return (
<div className="pointer-events-none absolute bottom-0 top-12 z-[5]" style={{ left }}>
<div className="absolute left-0 top-0 -translate-x-1/2 -translate-y-1/2 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground shadow-sm">
{time}
</div>
<div className="absolute bottom-0 left-0 top-0 w-px bg-primary" />
</div>
);
}

View File

@@ -0,0 +1,144 @@
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import { Field, FieldLabel } from '@/components/ui/field';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { ChevronLeft, ChevronRight, Clock, SlidersHorizontal } from 'lucide-react';
import { useBooking } from '../booking-provider';
import type { BookingStatusFilter } from '../booking.types';
import { fromIsoDateLocal, toIsoDateLocal } from '../lib/booking-time';
const timeRangeOptions = [
{ label: '08:00 - 22:00', start: '08:00', end: '22:00' },
{ label: '06:00 - 00:00', start: '06:00', end: '23:59' },
{ label: '08:00 - 14:00', start: '08:00', end: '14:00' },
{ label: '14:00 - 22:00', start: '14:00', end: '22:00' },
];
const statusOptions: Array<{ value: BookingStatusFilter; label: string }> = [
{ value: 'all', label: 'Todos' },
{ value: 'free', label: 'Libre' },
{ value: 'reserved', label: 'Reservado' },
{ value: 'maintenance', label: 'Mantenimiento' },
];
export function BookingToolbar() {
const {
courts,
selectedDate,
selectedSportId,
selectedStatus,
visibleTimeRange,
setSelectedDate,
moveSelectedDate,
setSelectedSportId,
setSelectedStatus,
setVisibleTimeRange,
} = useBooking();
const sports = [...new Map(courts.map((court) => [court.sport.id, court.sport])).values()];
const activeRangeValue = `${visibleTimeRange.start}-${visibleTimeRange.end}`;
return (
<section className="rounded-lg border bg-card/85 p-4 shadow-sm">
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-[1fr_1fr_1.6fr_1.1fr_auto] xl:items-end">
<Field>
<FieldLabel>Deporte</FieldLabel>
<Select value={selectedSportId} onValueChange={setSelectedSportId}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
{sports.map((sport) => (
<SelectItem key={sport.id} value={sport.id}>
{sport.name}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel>Estado</FieldLabel>
<Select
value={selectedStatus}
onValueChange={(value) => setSelectedStatus(value as BookingStatusFilter)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{statusOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel>Fecha</FieldLabel>
<div className="grid grid-cols-[auto_1fr_auto] gap-2">
<Button
type="button"
variant="outline"
size="icon"
onClick={() => moveSelectedDate(-1)}
>
<ChevronLeft className="size-4" />
</Button>
<DatePicker
value={fromIsoDateLocal(selectedDate)}
onChange={(date) =>
setSelectedDate(date ? toIsoDateLocal(date) : toIsoDateLocal(new Date()))
}
/>
<Button type="button" variant="outline" size="icon" onClick={() => moveSelectedDate(1)}>
<ChevronRight className="size-4" />
</Button>
</div>
</Field>
<Field>
<FieldLabel>Hora</FieldLabel>
<Select
value={activeRangeValue}
onValueChange={(value) => {
const option = timeRangeOptions.find((item) => `${item.start}-${item.end}` === value);
if (option) {
setVisibleTimeRange({ start: option.start, end: option.end });
}
}}
>
<SelectTrigger>
<Clock className="mr-2 size-4 text-muted-foreground" />
<SelectValue />
</SelectTrigger>
<SelectContent>
{timeRangeOptions.map((option) => (
<SelectItem
key={`${option.start}-${option.end}`}
value={`${option.start}-${option.end}`}
>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Button variant="outline" className="xl:self-end">
<SlidersHorizontal className="size-4" />
Filtros avanzados
</Button>
</div>
</section>
);
}

View File

@@ -0,0 +1,503 @@
import { Button } from '@/components/ui/button';
import {
ResponsiveDialog,
ResponsiveDialogClose,
ResponsiveDialogContent,
ResponsiveDialogDescription,
ResponsiveDialogFooter,
ResponsiveDialogHeader,
ResponsiveDialogTitle,
} from '@/components/ui/responsive-dialog';
import { Separator } from '@/components/ui/separator';
import { useIsMobile } from '@/hooks/use-mobile';
import { cn } from '@/lib/utils';
import {
AlertTriangle,
BadgeCheck,
CalendarDays,
CheckCircle2,
Clock,
MapPin,
MessageCircle,
Phone,
User,
Wrench,
XCircle,
} from 'lucide-react';
import { useBooking } from '../booking-provider';
function formatDate(date: string | undefined) {
if (!date) return '';
const formatted = new Intl.DateTimeFormat('es-AR', {
weekday: 'long',
day: 'numeric',
month: 'long',
}).format(new Date(`${date}T00:00:00`));
return formatted
.split(' ')
.map((word, index) => {
if (index === 0 || index === 3) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
return word;
})
.join(' ');
}
const statusConfig: Record<string, { label: string; className: string }> = {
CONFIRMED: {
label: 'Reservada',
className: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/30',
},
COMPLETED: {
label: 'Completada',
className: 'bg-sky-500/15 text-sky-400 border-sky-500/30',
},
CANCELLED: {
label: 'Cancelada',
className: 'bg-red-500/15 text-red-400 border-red-500/30',
},
NOSHOW: {
label: 'No show',
className: 'bg-amber-500/15 text-amber-400 border-amber-500/30',
},
};
export function BookingToolsDialog() {
const { selectedSegment, bookingToolsOpen, closeBookingTools, updateBookingStatus } =
useBooking();
const isMobile = useIsMobile();
const booking = selectedSegment?.booking;
const status = statusConfig[booking?.status ?? 'CONFIRMED'] ?? {
label: booking?.status,
className: 'bg-slate-500/15 text-slate-300 border-slate-500/30',
};
const sendWhatsappReminder = () => {
const phone = booking?.customerPhone;
if (!phone) return;
const message = `
Hola ${booking?.customerName}. \nTe recordamos que tenés una reserva para el día *${formatDate(booking?.date)} de ${booking?.startTime} a ${booking?.endTime} en la cancha ${booking?.courtName} (${booking?.sport?.name})*. ¡Te esperamos! \nSi no vas a poder asistir, por favor avisanos para que otros clientes puedan reservar. Gracias.\n\n*Equipo de ${booking?.complexName}*`;
const url = `https://wa.me/${phone}?text=${encodeURIComponent(message)}`;
window.open(url, '_blank');
};
const updateStatus = (nextStatus: 'CANCELLED' | 'COMPLETED' | 'NOSHOW') => {
if (!booking?.id) return;
updateBookingStatus(booking.id, nextStatus);
closeBookingTools();
};
if (isMobile) {
return (
<ResponsiveDialog
open={bookingToolsOpen}
onOpenChange={(open) => !open && closeBookingTools()}
>
<ResponsiveDialogContent
className="data-[variant=drawer]:!h-[92dvh] data-[variant=drawer]:!max-h-[92dvh] data-[variant=drawer]:overflow-hidden data-[variant=drawer]:px-0 data-[variant=drawer]:pb-0"
onOpenAutoFocus={(event) => event.preventDefault()}
>
<MobileBookingToolsSheet
status={status}
onComplete={() => updateStatus('COMPLETED')}
onCancel={() => updateStatus('CANCELLED')}
onReminder={sendWhatsappReminder}
onNoShow={() => updateStatus('NOSHOW')}
/>
</ResponsiveDialogContent>
</ResponsiveDialog>
);
}
return (
<ResponsiveDialog open={bookingToolsOpen} onOpenChange={(open) => !open && closeBookingTools()}>
<ResponsiveDialogContent
className="data-[variant=dialog]:max-w-5xl data-[variant=drawer]:max-h-[92dvh] data-[variant=drawer]:overflow-y-auto data-[variant=drawer]:px-4 data-[variant=drawer]:pb-5"
onOpenAutoFocus={(event) => event.preventDefault()}
>
<ResponsiveDialogHeader className="data-[variant=drawer]:px-0 data-[variant=drawer]:text-left">
<ResponsiveDialogTitle>Detalles de la reserva</ResponsiveDialogTitle>
<ResponsiveDialogDescription>
Administra la reserva y su estado.
</ResponsiveDialogDescription>
</ResponsiveDialogHeader>
<section className="mx-0 px-0 pt-3 pb-3 sm:-mx-6 sm:px-6 sm:pb-5">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3 sm:gap-0">
<DetailItem
icon={<MapPin className="h-5 w-5" />}
label="Cancha"
value={selectedSegment?.booking?.courtName ?? '-'}
helper={selectedSegment?.booking?.sport?.name}
withDivider
/>
<DetailItem
icon={<BadgeCheck className="h-5 w-5" />}
label="Estado actual"
value={status.label}
valueClassName="text-emerald-400 uppercase dark:text-emerald-500"
withDivider
/>
<DetailItem
icon={<User className="h-5 w-5" />}
label="Cliente"
value={selectedSegment?.booking?.customerName ?? '-'}
/>
<DetailItem
icon={<Clock className="h-5 w-5" />}
label="Fecha"
value={`${formatDate(selectedSegment?.booking?.date)}`}
withDivider
className="sm:pt-10"
/>
<DetailItem
icon={<Clock className="h-5 w-5" />}
label="Hora"
value={`${selectedSegment?.booking?.startTime} a ${selectedSegment?.booking?.endTime}`}
withDivider
className="sm:pt-10"
/>
<DetailItem
icon={<Phone className="h-5 w-5" />}
label="Teléfono"
value={selectedSegment?.booking?.customerPhone ?? '-'}
className="sm:pt-10"
/>
</div>
</section>
<Separator className="dark:bg-slate-800 bg-slate-300" />
<section className="space-y-3">
<div>
<h3 className="font-medium text-slate-100">Acciones disponibles</h3>
<p className="text-sm text-slate-400">
Elegí qué hacer según lo que ocurrió con el cliente.
</p>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<ActionButton
icon={<CheckCircle2 className="h-5 w-5" />}
title="Completar reserva"
description="El cliente se presentó para usar la cancha."
className="border-emerald-500/40 bg-emerald-500/10 text-lg text-emerald-600 hover:bg-emerald-500/15 hover:text-emerald-800"
onClick={() => {
updateStatus('COMPLETED');
}}
/>
<ActionButton
icon={<XCircle className="h-5 w-5" />}
title="Cancelar reserva"
description="El cliente avisó que no va a venir. La cancha vuelve a estar disponible."
className="border-red-500/40 bg-red-500/10 text-lg text-red-600 hover:bg-red-500/15 hover:text-red-800"
onClick={() => {
updateStatus('CANCELLED');
}}
/>
<ActionButton
icon={<MessageCircle className="h-5 w-5" />}
title="Enviar recordatorio"
description="Enviar un mensaje por WhatsApp al cliente."
className="border-sky-500/40 bg-sky-500/10 text-lg text-sky-600 hover:bg-sky-500/15 hover:text-sky-800"
onClick={sendWhatsappReminder}
/>
<ActionButton
icon={<AlertTriangle className="h-5 w-5" />}
title="Marcar como No Show"
description="El cliente no vino y no canceló."
className="border-amber-500/40 bg-amber-500/10 text-lg text-amber-600 hover:bg-amber-500/15 hover:text-amber-800"
onClick={() => {
updateStatus('NOSHOW');
}}
/>
</div>
</section>
<ResponsiveDialogFooter className="data-[variant=drawer]:px-0">
<ResponsiveDialogClose asChild>
<Button variant="outline" className="data-[variant=drawer]:h-11">
Cerrar
</Button>
</ResponsiveDialogClose>
</ResponsiveDialogFooter>
</ResponsiveDialogContent>
</ResponsiveDialog>
);
}
function MobileBookingToolsSheet({
status,
onComplete,
onCancel,
onReminder,
onNoShow,
}: {
status: { label: string | undefined; className: string };
onComplete: () => void;
onCancel: () => void;
onReminder: () => void;
onNoShow: () => void;
}) {
const { selectedSegment } = useBooking();
const booking = selectedSegment?.booking;
return (
<div className="flex min-h-0 flex-1 flex-col pt-3">
<ResponsiveDialogHeader className="shrink-0 px-4 pb-3 text-left">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<ResponsiveDialogTitle className="text-lg">Reserva</ResponsiveDialogTitle>
<ResponsiveDialogDescription>
{booking?.courtName ?? '-'} · {booking?.startTime ?? '--:--'} a{' '}
{booking?.endTime ?? '--:--'}
</ResponsiveDialogDescription>
</div>
<span
className={cn(
'shrink-0 rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-normal',
status.className
)}
>
{status.label ?? '-'}
</span>
</div>
</ResponsiveDialogHeader>
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4">
<section className="rounded-lg border border-border/70 bg-card/75 p-4">
<div className="flex items-center gap-3">
<div className="flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">
<MapPin className="size-6" />
</div>
<div className="min-w-0">
<p className="text-xs text-muted-foreground">Cancha</p>
<p className="truncate text-xl font-semibold">{booking?.courtName ?? '-'}</p>
<p className="text-sm text-muted-foreground">{booking?.sport?.name ?? '-'}</p>
</div>
</div>
</section>
<section className="mt-3 grid gap-2">
<MobileDetailRow
icon={<User className="size-5" />}
label="Cliente"
value={booking?.customerName ?? '-'}
/>
<MobileDetailRow
icon={<Phone className="size-5" />}
label="Teléfono"
value={booking?.customerPhone ?? '-'}
/>
<MobileDetailRow
icon={<CalendarDays className="size-5" />}
label="Fecha"
value={formatDate(booking?.date) || '-'}
/>
<MobileDetailRow
icon={<Clock className="size-5" />}
label="Horario"
value={`${booking?.startTime ?? '--:--'} a ${booking?.endTime ?? '--:--'}`}
/>
<MobileDetailRow
icon={<Wrench className="size-5" />}
label="Estado"
value={status.label ?? '-'}
valueClassName="uppercase text-primary"
/>
</section>
</div>
<section className="shrink-0 border-t border-border/70 bg-popover/95 px-4 py-3">
<h3 className="text-sm font-medium">Acciones</h3>
<div className="mt-3 grid grid-cols-2 gap-2">
<MobileActionButton
icon={<CheckCircle2 className="size-5" />}
label="Completar"
className="border-primary/45 bg-primary/12 text-primary"
onClick={onComplete}
/>
<MobileActionButton
icon={<MessageCircle className="size-5" />}
label="Recordar"
className="border-reserved/45 bg-reserved/12 text-reserved"
onClick={onReminder}
/>
<MobileActionButton
icon={<XCircle className="size-5" />}
label="Cancelar"
className="border-destructive/45 bg-destructive/12 text-destructive"
onClick={onCancel}
/>
<MobileActionButton
icon={<AlertTriangle className="size-5" />}
label="No show"
className="border-warning/50 bg-warning/12 text-warning"
onClick={onNoShow}
/>
</div>
<ResponsiveDialogFooter className="px-0 pb-0 pt-3">
<ResponsiveDialogClose asChild>
<Button variant="outline" className="h-11 w-full rounded-lg">
Cerrar
</Button>
</ResponsiveDialogClose>
</ResponsiveDialogFooter>
</section>
</div>
);
}
function MobileDetailRow({
icon,
label,
value,
valueClassName,
}: {
icon: React.ReactNode;
label: string;
value: string;
valueClassName?: string;
}) {
return (
<div className="flex items-center gap-3 rounded-lg border border-border/60 bg-secondary/35 p-3">
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-secondary text-muted-foreground">
{icon}
</div>
<div className="min-w-0">
<p className="text-xs text-muted-foreground">{label}</p>
<p className={cn('truncate text-base font-semibold', valueClassName)}>{value}</p>
</div>
</div>
);
}
function MobileActionButton({
icon,
label,
className,
onClick,
}: {
icon: React.ReactNode;
label: string;
className: string;
onClick: () => void;
}) {
return (
<Button
type="button"
variant="outline"
className={cn('h-14 justify-start rounded-lg px-3 text-sm font-semibold', className)}
onClick={onClick}
>
{icon}
{label}
</Button>
);
}
function DetailItem({
icon,
label,
value,
helper,
valueClassName,
withDivider,
className,
}: {
icon: React.ReactNode;
label: string;
value: string;
helper?: string;
valueClassName?: string;
withDivider?: boolean;
className?: string;
}) {
return (
<div
className={cn(
'relative flex items-start gap-4 rounded-lg bg-secondary/45 p-3 sm:bg-transparent sm:px-5 sm:py-1',
className
)}
>
{withDivider && (
<div
className="
absolute
right-0
top-1/2
hidden
h-16
w-px
-translate-y-1/2
dark:bg-slate-800
bg-slate-300
sm:block
"
/>
)}
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-slate-300/80 text-slate-800 dark:bg-slate-800/80 dark:text-slate-300">
{icon}
</div>
<div className="min-w-0">
<p className="text-sm text-slate-400">{label}</p>
<p
className={cn(
'mt-1 text-lg leading-tight font-semibold tracking-normal text-gray-600 sm:text-[22px] dark:text-white',
valueClassName
)}
>
{value}
</p>
{helper && <p className="mt-1 text-sm text-slate-500">{helper}</p>}
</div>
</div>
);
}
function ActionButton({
icon,
title,
description,
className,
onClick,
}: {
icon: React.ReactNode;
title: string;
description: string;
className: string;
onClick?: () => void;
}) {
return (
<Button
type="button"
variant="outline"
className={`h-auto min-h-[76px] justify-start rounded-lg p-4 text-left ${className}`}
onClick={onClick}
>
<div className="flex gap-3">
<div className="mt-0.5">{icon}</div>
<div>
<p className="font-semibold">{title}</p>
<p className="mt-1 whitespace-normal text-sm font-normal leading-relaxed dark:text-slate-200 text-slate-500">
{description}
</p>
</div>
</div>
</Button>
);
}

View File

@@ -0,0 +1,66 @@
import type { DayOfWeek } from '@repo/api-contract';
export 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}`;
}
export function fromIsoDateLocal(dateIso: string): Date | undefined {
const [year, month, day] = dateIso.split('-').map(Number);
if (!year || !month || !day) return undefined;
return new Date(year, month - 1, day);
}
export function timeToMinutes(time: string) {
const [hours, minutes] = time.split(':').map(Number);
return hours * 60 + minutes;
}
export function minutesToTime(minutes: number) {
const hours = Math.floor(minutes / 60);
const remainder = minutes % 60;
return `${String(hours).padStart(2, '0')}:${String(remainder).padStart(2, '0')}`;
}
export function addDaysIso(dateIso: string, amount: number) {
const date = fromIsoDateLocal(dateIso) ?? new Date();
date.setDate(date.getDate() + amount);
return toIsoDateLocal(date);
}
export function isTodayIso(dateIso: string) {
return dateIso === toIsoDateLocal(new Date());
}
export function formatBookingDate(dateIso: string, options?: Intl.DateTimeFormatOptions) {
const date = fromIsoDateLocal(dateIso);
if (!date) return dateIso;
return new Intl.DateTimeFormat('es-AR', {
weekday: 'long',
day: '2-digit',
month: 'long',
year: options?.year,
...options,
}).format(date);
}
export function getDayOfWeek(dateIso: string): DayOfWeek {
const date = fromIsoDateLocal(dateIso) ?? new Date();
const day = date.getDay();
if (day === 0) return 'SUNDAY';
if (day === 1) return 'MONDAY';
if (day === 2) return 'TUESDAY';
if (day === 3) return 'WEDNESDAY';
if (day === 4) return 'THURSDAY';
if (day === 5) return 'FRIDAY';
return 'SATURDAY';
}
export function getNowTime() {
const now = new Date();
return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
}

View File

@@ -32,7 +32,7 @@ export function ComplexCourtsPage({ complexSlug }: ComplexCourtsPageProps) {
}); });
return ( return (
<main className="mx-auto w-full max-w-6xl space-y-6 px-4 py-4 sm:px-6"> <main className="mx-auto w-full max-w-6xl space-y-6 py-4">
<section className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm sm:p-5"> <section className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm sm:p-5">
<h2 className="text-2xl font-semibold"> <h2 className="text-2xl font-semibold">
{complexQuery.data?.complexName ?? 'Configurar canchas'} {complexQuery.data?.complexName ?? 'Configurar canchas'}

View File

@@ -43,30 +43,19 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
]; ];
return ( return (
<div className="mx-auto w-full max-w-7xl px-4 py-4 sm:px-6 lg:px-8 lg:py-6"> <div className="mx-auto w-full max-w-6xl py-4">
<section className="overflow-hidden rounded-2xl border border-border/70 bg-card p-6 text-card-foreground shadow-sm sm:p-8"> <section className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm sm:p-5">
<div className="flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between"> <h2 className="text-2xl font-semibold">
<div className="space-y-3">
<div className="inline-flex items-center gap-2 rounded-full border border-border/70 bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
<span className="size-2 rounded-full bg-primary" />
Administración del complejo
</div>
<h2 className="text-3xl font-semibold tracking-tight">
<Settings className="mb-1 mr-2 inline size-6" /> <Settings className="mb-1 mr-2 inline size-6" />
Configuración del complejo Configuración del complejo
</h2> </h2>
<p className="max-w-2xl text-sm text-muted-foreground"> <p className="mt-2 text-sm text-muted-foreground">
{complexQuery.data?.complexName ?? {complexQuery.data?.complexName ?? 'Configura los datos de tu complejo'}
'Configurá los datos del complejo, las canchas y los usuarios.'}
</p> </p>
</div>
</div>
</section> </section>
<div className="mt-6 grid gap-6 lg:grid-cols-[220px_1fr]"> <div className="mt-6 grid gap-5 lg:grid-cols-[200px_1fr] lg:gap-6">
<nav className="flex flex-row gap-2 overflow-x-auto rounded-2xl border border-border/70 bg-card p-2 shadow-sm lg:flex-col lg:overflow-visible"> <nav className="flex flex-row gap-1 overflow-x-auto lg:flex-col lg:overflow-visible">
{tabs.map((tab) => { {tabs.map((tab) => {
const Icon = tab.icon; const Icon = tab.icon;
const isActive = activeTab === tab.id; const isActive = activeTab === tab.id;
@@ -75,8 +64,9 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
key={tab.id} key={tab.id}
type="button" type="button"
onClick={() => setActiveTab(tab.id)} onClick={() => setActiveTab(tab.id)}
className={`inline-flex items-center gap-2 rounded-2xl px-3 py-3 text-sm font-medium transition-all lg:w-full lg:justify-start ${isActive className={`inline-flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-colors lg:w-full lg:justify-start ${
? 'bg-primary text-primary-foreground shadow-sm' isActive
? 'bg-muted text-foreground'
: 'text-muted-foreground hover:bg-muted hover:text-foreground' : 'text-muted-foreground hover:bg-muted hover:text-foreground'
}`} }`}
> >
@@ -87,7 +77,7 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
})} })}
</nav> </nav>
<div className="min-w-0 rounded-2xl border border-border/70 bg-card p-4 shadow-sm sm:p-6"> <div className="min-w-0">
{activeTab === 'details' && ( {activeTab === 'details' && (
<ComplexDetailsSection <ComplexDetailsSection
complex={complexQuery.data ?? null} complex={complexQuery.data ?? null}

View File

@@ -22,7 +22,7 @@ export function ComplexCourtsSection({ complexId }: ComplexCourtsSectionProps) {
}); });
return ( return (
<section className="mt-6 rounded-xl border bg-card p-5"> <section className="mt-6 rounded-xl border bg-card p-3 sm:p-5">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<MapPin className="size-5 text-muted-foreground" /> <MapPin className="size-5 text-muted-foreground" />
<h3 className="text-lg font-medium">Canchas</h3> <h3 className="text-lg font-medium">Canchas</h3>

View File

@@ -128,7 +128,7 @@ export function CourtFormSection({
const buttonText = editingCourt ? 'Guardar cambios' : 'Agregar cancha'; const buttonText = editingCourt ? 'Guardar cambios' : 'Agregar cancha';
return ( return (
<section className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm sm:p-5 mb-4"> <section className="mb-4 rounded-xl border bg-card p-3 text-card-foreground shadow-sm sm:p-5">
<h3 className="text-lg font-semibold">{title}</h3> <h3 className="text-lg font-semibold">{title}</h3>
<p className="mt-1 text-sm text-muted-foreground"> <p className="mt-1 text-sm text-muted-foreground">
Configura nombre, deporte, duración, precio base y horarios. El backend ya contempla precios Configura nombre, deporte, duración, precio base y horarios. El backend ya contempla precios

View File

@@ -18,7 +18,7 @@ export function CourtListSection({
onEditCourt, onEditCourt,
}: CourtListSectionProps) { }: CourtListSectionProps) {
return ( return (
<section className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm sm:p-5"> <section className="rounded-xl border bg-card p-3 text-card-foreground shadow-sm sm:p-5">
<h3 className="text-lg font-semibold">Canchas configuradas</h3> <h3 className="text-lg font-semibold">Canchas configuradas</h3>
{isLoading && <p className="mt-3 text-sm text-muted-foreground">Cargando canchas...</p>} {isLoading && <p className="mt-3 text-sm text-muted-foreground">Cargando canchas...</p>}
@@ -37,7 +37,7 @@ export function CourtListSection({
<div className="mt-4 space-y-3"> <div className="mt-4 space-y-3">
{courts.map((court) => ( {courts.map((court) => (
<article key={court.id} className="rounded-lg border p-4"> <article key={court.id} className="rounded-lg border p-3 sm:p-4">
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between"> <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
<div> <div>
<p className="font-medium">{court.name}</p> <p className="font-medium">{court.name}</p>

View File

@@ -1,64 +1,9 @@
import AvailabilityHeatMap from '@/components/ui/availability-heatmap'; import { Booking } from '@/features/booking/booking';
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import { Field, FieldError, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import {
ResponsiveDialog,
ResponsiveDialogClose,
ResponsiveDialogContent,
ResponsiveDialogDescription,
ResponsiveDialogFooter,
ResponsiveDialogHeader,
ResponsiveDialogTitle,
ResponsiveDialogTrigger,
} from '@/components/ui/responsive-dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { StatusBadge } from '@/components/ui/status-badge';
import { ApiClientError, apiClient } from '@/lib/api-client'; import { ApiClientError, apiClient } from '@/lib/api-client';
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store'; import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
import { zodResolver } from '@hookform/resolvers/zod'; import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { AdminBooking } from '@repo/api-contract';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router'; import { useNavigate } from '@tanstack/react-router';
import { Check, Copy } from 'lucide-react'; import { useEffect } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
const manualBookingSchema = z.object({
customerName: z
.string()
.trim()
.min(2, 'Ingresa un nombre válido.')
.max(120, 'El nombre no puede superar los 120 caracteres.'),
customerPhone: z
.string()
.trim()
.min(6, 'Ingresa un telefono válido.')
.max(30, 'El telefono no puede superar los 30 caracteres.'),
});
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 fromIsoDateLocal(dateIso: string): Date | undefined {
const [year, month, day] = dateIso.split('-').map(Number);
if (!year || !month || !day) return undefined;
return new Date(year, month - 1, day);
}
function extractMessage(error: unknown, fallback: string) { function extractMessage(error: unknown, fallback: string) {
if (error instanceof ApiClientError) { if (error instanceof ApiClientError) {
@@ -68,72 +13,9 @@ function extractMessage(error: unknown, fallback: string) {
return fallback; return fallback;
} }
function formatDateLabel(dateIso: string, todayIso: string) {
const [year, month, day] = dateIso.split('-').map(Number);
if (!year || !month || !day) return dateIso;
const [tYear, tMonth, tDay] = todayIso.split('-').map(Number);
const isToday = year === tYear && month === tMonth && day === tDay;
const tmrw = new Date(tYear, tMonth - 1, tDay);
tmrw.setDate(tmrw.getDate() + 1);
const isTomorrow =
year === tmrw.getFullYear() && month === tmrw.getMonth() + 1 && day === tmrw.getDate();
if (isToday) return 'Hoy';
if (isTomorrow) return 'Mañana';
const date = new Date(year, month - 1, day);
return new Intl.DateTimeFormat('es-AR', {
weekday: 'long',
day: '2-digit',
month: 'long',
}).format(date);
}
function getEffectiveStatus(
booking: AdminBooking
): 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW' {
if (booking.status !== 'CONFIRMED') {
return booking.status;
}
// Check if booking is past end time and still confirmed
const now = new Date();
const bookingDateTime = new Date(`${booking.date}T${booking.endTime}:00`);
if (now > bookingDateTime) {
return 'NO_SHOW';
}
return 'CONFIRMED';
}
function effectiveStatusLabel(status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW') {
if (status === 'NO_SHOW') return 'No show';
if (status === 'COMPLETED') return 'Cumplida';
if (status === 'CANCELLED') return 'Cancelada';
return 'Confirmada';
}
export function HomePage() { export function HomePage() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const navigate = useNavigate(); const navigate = useNavigate();
const todayIso = useMemo(() => toIsoDateLocal(new Date()), []);
const [fromDate, setFromDate] = useState(todayIso);
const [manualDate, setManualDate] = useState(todayIso);
const [selectedSportId, setSelectedSportId] = useState<string | undefined>();
const [selectedCourtId, setSelectedCourtId] = useState<string>('');
const [selectedStartTime, setSelectedStartTime] = useState<string>('');
const [selectedSlot, setSelectedSlot] = useState<{ courtId: string; startTime: string } | null>(
null
);
const [isManualBookingOpen, setIsManualBookingOpen] = useState(false);
const [urlCopied, setUrlCopied] = useState(false);
const [bookingToCancel, setBookingToCancel] = useState<AdminBooking | null>(null);
const currentComplexQuery = useQuery({ const currentComplexQuery = useQuery({
queryKey: ['current-complex'], queryKey: ['current-complex'],
@@ -155,6 +37,7 @@ export function HomePage() {
queryClient.invalidateQueries({ queryKey: ['admin-bookings'] }); queryClient.invalidateQueries({ queryKey: ['admin-bookings'] });
} }
}); });
return unsubscribe; return unsubscribe;
}, [queryClient]); }, [queryClient]);
@@ -194,7 +77,6 @@ export function HomePage() {
if (!selectedComplex?.id) return; if (!selectedComplex?.id) return;
const channel = `complex-${selectedComplex.id}`; const channel = `complex-${selectedComplex.id}`;
let eventSource: EventSource | null = null; let eventSource: EventSource | null = null;
let reconnectTimeout: ReturnType<typeof setTimeout> | null = null; let reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
let reconnectAttempts = 0; let reconnectAttempts = 0;
@@ -202,27 +84,32 @@ export function HomePage() {
let lastEventId: string | null = null; let lastEventId: string | null = null;
let pollInterval: ReturnType<typeof setInterval> | null = null; let pollInterval: ReturnType<typeof setInterval> | null = null;
const startPolling = () => {
if (pollInterval) return;
pollInterval = setInterval(() => {
void queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex.id] });
}, 10000);
};
const connect = () => { const connect = () => {
if (eventSource) { if (eventSource) {
eventSource.close(); eventSource.close();
} }
if (reconnectAttempts >= maxReconnectAttempts) { if (reconnectAttempts >= maxReconnectAttempts) {
console.log('[SSE] Max reconnect attempts reached, switching to polling');
startPolling(); startPolling();
return; return;
} }
const url = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'}/api/events/${encodeURIComponent(channel)}`; const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
const url = `${baseUrl}/api/events/${encodeURIComponent(channel)}`;
eventSource = new EventSource(url); eventSource = new EventSource(url);
eventSource.onerror = () => { eventSource.onerror = () => {
if (eventSource?.readyState === EventSource.CLOSED) { if (eventSource?.readyState === EventSource.CLOSED) {
reconnectAttempts++; reconnectAttempts++;
console.log(
`[SSE] Connection closed, retry ${reconnectAttempts}/${maxReconnectAttempts}`
);
reconnectTimeout = setTimeout(() => { reconnectTimeout = setTimeout(() => {
connect(); connect();
}, 2000); }, 2000);
@@ -242,15 +129,6 @@ export function HomePage() {
}); });
}; };
const startPolling = () => {
if (pollInterval) return;
console.log('[SSE] Starting polling fallback');
pollInterval = setInterval(() => {
void queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex.id] });
}, 10000);
};
connect(); connect();
return () => { return () => {
@@ -264,652 +142,21 @@ export function HomePage() {
}; };
}, [selectedComplex?.id, queryClient]); }, [selectedComplex?.id, queryClient]);
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('');
setSelectedSlot(null);
}
}, [manualAvailabilityQuery.data, selectedCourtId]);
const selectedCourt = useMemo(() => {
return manualAvailabilityQuery.data?.courts.find((court) => court.courtId === selectedCourtId);
}, [manualAvailabilityQuery.data?.courts, selectedCourtId]);
useEffect(() => {
if (!selectedCourt) {
setSelectedStartTime('');
setSelectedSlot(null);
return;
}
if (!selectedCourt.availableSlots.some((slot) => slot.startTime === selectedStartTime)) {
setSelectedStartTime('');
setSelectedSlot(null);
}
}, [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 dashboardStats = useMemo(() => {
const bookings = bookingsQuery.data?.bookings ?? [];
const todayBookings = bookings.filter((booking) => booking.date === todayIso);
const confirmedBookings = bookings.filter(
(booking) => getEffectiveStatus(booking) === 'CONFIRMED'
);
const completedBookings = bookings.filter(
(booking) => getEffectiveStatus(booking) === 'COMPLETED'
);
return {
total: bookings.length,
today: todayBookings.length,
confirmed: confirmedBookings.length,
completed: completedBookings.length,
};
}, [bookingsQuery.data?.bookings, todayIso]);
const updateStatusMutation = useMutation({
mutationFn: (payload: { bookingId: string; status: 'CANCELLED' | 'COMPLETED' }) =>
apiClient.adminBookings.updateStatus(payload.bookingId, { status: payload.status }),
onSuccess: () => {
setBookingToCancel(null);
void queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex?.id] });
void queryClient.invalidateQueries({
queryKey: ['manual-booking-availability', selectedComplex?.complexSlug],
});
},
});
function handleCancelBooking(booking: AdminBooking) {
setBookingToCancel(booking);
}
function confirmCancelBooking() {
if (!bookingToCancel) return;
updateStatusMutation.mutate({
bookingId: bookingToCancel.id,
status: 'CANCELLED',
});
}
const {
register,
handleSubmit,
reset,
formState: { errors, isValid },
} = useForm<ManualBookingForm>({
resolver: zodResolver(manualBookingSchema),
mode: 'onChange',
defaultValues: {
customerName: '',
customerPhone: '',
},
});
const createManualBookingMutation = useMutation({
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('');
setSelectedSlot(null);
setIsManualBookingOpen(false);
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);
};
const publicBookingUrl = selectedComplex
? `${window.location.origin}/${selectedComplex.complexSlug}/booking`
: '';
const copyToClipboard = async () => {
await navigator.clipboard.writeText(publicBookingUrl);
setUrlCopied(true);
setTimeout(() => {
setUrlCopied(false);
}, 3000);
};
if (myComplexesQuery.isLoading) { if (myComplexesQuery.isLoading) {
return ( return <p className="text-sm text-muted-foreground">Cargando panel...</p>;
<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) { if (myComplexesQuery.isError) {
return ( return (
<main className="mx-auto w-full max-w-6xl px-6 py-8">
<p className="text-sm text-destructive"> <p className="text-sm text-destructive">
{extractMessage(myComplexesQuery.error, 'No pudimos cargar tus complejos.')} {extractMessage(myComplexesQuery.error, 'No pudimos cargar tus complejos.')}
</p> </p>
</main>
); );
} }
if (!selectedComplex) { if (!selectedComplex) {
return ( return <p className="text-sm text-muted-foreground">No tienes complejos asignados todavía.</p>;
<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>
);
} }
const manualBookingDialog = ( return <Booking complex={selectedComplex} />;
<ResponsiveDialog
open={isManualBookingOpen}
onOpenChange={(open) => {
setIsManualBookingOpen(open);
if (!open) {
reset();
setManualDate(todayIso);
setSelectedSportId(undefined);
setSelectedCourtId('');
setSelectedStartTime('');
setSelectedSlot(null);
}
}}
>
<ResponsiveDialogTrigger asChild>
<Button className="w-full">Nueva reserva</Button>
</ResponsiveDialogTrigger>
<ResponsiveDialogContent
className="data-[variant=dialog]:max-w-lg"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<ResponsiveDialogHeader>
<ResponsiveDialogTitle>Reserva manual</ResponsiveDialogTitle>
<ResponsiveDialogDescription>
Crea un turno para atención telefónica o mostrador.
</ResponsiveDialogDescription>
</ResponsiveDialogHeader>
<form
id="manual-booking-form"
className="grid gap-4"
onSubmit={handleSubmit(onSubmitManualBooking)}
>
<div className="grid gap-3">
<Field>
<FieldLabel htmlFor="manualDate">Fecha</FieldLabel>
<DatePicker
value={fromIsoDateLocal(manualDate)}
onChange={(date) => {
const isoDate = date ? toIsoDateLocal(date) : todayIso;
setManualDate(isoDate);
setSelectedCourtId('');
setSelectedStartTime('');
setSelectedSlot(null);
}}
minDate={new Date()}
placeholder="Selecciona una fecha"
/>
</Field>
{manualAvailabilityQuery.data?.sportSelectionRequired && (
<Field>
<FieldLabel>Deporte</FieldLabel>
<Select
value={selectedSportId ?? ''}
onValueChange={(value) => {
setSelectedSportId(value);
setSelectedCourtId('');
setSelectedStartTime('');
setSelectedSlot(null);
}}
>
<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>
)}
{manualAvailabilityQuery.data?.courts && (
<Field>
<FieldLabel>Disponibilidad</FieldLabel>
<AvailabilityHeatMap
courts={manualAvailabilityQuery.data.courts}
selectedSlot={selectedSlot}
onSelectSlot={({ courtId, startTime }) => {
setSelectedCourtId(courtId);
setSelectedStartTime(startTime);
setSelectedSlot({ courtId, startTime });
}}
/>
</Field>
)}
</div>
{manualAvailabilityQuery.isLoading && (
<p className="text-sm text-muted-foreground">Cargando horarios disponibles...</p>
)}
{manualAvailabilityQuery.isError && (
<p className="text-sm text-destructive">
{extractMessage(
manualAvailabilityQuery.error,
'No pudimos cargar disponibilidad para la reserva manual.'
)}
</p>
)}
<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">
{extractMessage(
createManualBookingMutation.error,
'No pudimos crear la reserva manual.'
)}
</p>
)}
</form>
<ResponsiveDialogFooter>
<ResponsiveDialogClose asChild>
<Button variant="outline">Cancelar</Button>
</ResponsiveDialogClose>
<Button
type="submit"
form="manual-booking-form"
disabled={
!isValid ||
createManualBookingMutation.isPending ||
!selectedCourtId ||
!selectedStartTime
}
>
{createManualBookingMutation.isPending ? 'Guardando...' : 'Crear reserva'}
</Button>
</ResponsiveDialogFooter>
</ResponsiveDialogContent>
</ResponsiveDialog>
);
const urlCard = (
<div className="group relative overflow-hidden rounded-2xl border border-blue-200/60 bg-blue-50/50 p-5">
<div className="absolute inset-0 bg-gradient-to-br from-blue-50/80 to-blue-100/30" />
<div className="relative flex items-center justify-between gap-4">
<div className="min-w-0 flex-1">
<p className="text-[11px] font-semibold uppercase tracking-[0.28em] text-blue-600/70">
Reserva online
</p>
<a
href={publicBookingUrl}
target="_blank"
rel="noopener noreferrer"
className="mt-1 block truncate text-sm font-medium text-blue-700 underline-offset-2 hover:underline"
>
{publicBookingUrl}
</a>
</div>
<button
type="button"
onClick={copyToClipboard}
className="relative flex shrink-0 items-center gap-2 rounded-lg bg-blue-500/10 px-3 py-2 text-sm font-medium text-blue-700 transition-colors hover:bg-blue-500/20"
title="Copiar URL"
>
{urlCopied ? (
<>
<Check className="size-4" />
<span>Copiado</span>
</>
) : (
<>
<Copy className="size-4" />
<span>Copiar</span>
</>
)}
</button>
</div>
</div>
);
const headerPills = (
<div className="flex flex-wrap gap-2">
<span className="rounded-full border border-emerald-200/60 bg-emerald-50/60 px-3 py-1 text-xs font-medium text-emerald-700">
{dashboardStats.today} hoy
</span>
<span className="rounded-full border border-border/70 bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
{dashboardStats.confirmed} confirmadas
</span>
<span className="rounded-full border border-border/70 bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
{dashboardStats.completed} cumplidas
</span>
</div>
);
const dateSelector = (
<div className="flex flex-col gap-2 sm:flex-row sm:items-end">
<Field>
<FieldLabel htmlFor="fromDate">Desde</FieldLabel>
<DatePicker
value={fromIsoDateLocal(fromDate)}
onChange={(date) => {
const isoDate = date ? toIsoDateLocal(date) : todayIso;
setFromDate(isoDate);
}}
disabled={(date) => {
const today = new Date();
today.setHours(0, 0, 0, 0);
const checkDate = new Date(date);
checkDate.setHours(0, 0, 0, 0);
return checkDate < today;
}}
placeholder="Selecciona"
/>
</Field>
</div>
);
return (
<main className="mx-auto w-full max-w-7xl px-4 py-4 sm:px-6 lg:px-8 lg:py-6">
<div className="space-y-5">
<div className="grid gap-4 lg:grid-cols-[1fr_1fr]">
<section className="overflow-hidden rounded-2xl border border-border/70 bg-card p-5 sm:p-6">
<div className="space-y-4">
<div className="space-y-2">
<h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">
Panel de reservas
</h1>
<p className="text-sm text-muted-foreground">
Gestioná turnos de {selectedComplex.complexName}
</p>
</div>
{headerPills}
</div>
</section>
<div className="space-y-4">
{urlCard}
{manualBookingDialog}
</div>
</div>
<section className="rounded-2xl border border-border/70 bg-card p-4 sm:p-5">
{dateSelector}
{bookingsQuery.isLoading && (
<p className="mt-4 text-sm text-muted-foreground">Cargando reservas...</p>
)}
{bookingsQuery.isError && (
<p className="mt-4 text-sm text-destructive">
{extractMessage(bookingsQuery.error, 'No pudimos cargar las reservas.')}
</p>
)}
{!bookingsQuery.isLoading && !bookingsQuery.isError && groupedBookings.length === 0 && (
<p className="mt-4 text-sm text-muted-foreground">
No hay reservas para la fecha seleccionada.
</p>
)}
<div className="mt-4 space-y-6">
{groupedBookings.map(([date, bookings]) => (
<article key={date}>
<div className="flex items-center gap-3">
<h2 className="text-sm font-semibold capitalize">
{formatDateLabel(date, todayIso)}
</h2>
<div className="h-px flex-1 border-t border-dashed border-border/40" />
<span className="shrink-0 rounded-full border border-border/70 bg-background px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground">
{bookings.length}
</span>
</div>
<div className="mt-3 space-y-2">
{bookings
.slice()
.sort((a, b) => a.startTime.localeCompare(b.startTime))
.map((booking) => {
const effectiveStatus = getEffectiveStatus(booking);
const canManage =
booking.status === 'CONFIRMED' && effectiveStatus === 'CONFIRMED';
const isMutating = updateStatusMutation.isPending;
const now = new Date();
const bookingStart = new Date(`${date}T${booking.startTime}:00`);
const bookingEnd = new Date(`${date}T${booking.endTime}:00`);
const isPast = bookingEnd < now;
const isNow = date === todayIso && bookingStart <= now && bookingEnd > now;
return (
<div
key={booking.id}
className={[
'group flex items-center justify-between gap-3 rounded-xl border border-border/70 bg-card/60 p-3.5 transition-all hover:bg-muted/50',
isPast && 'opacity-50',
isNow && 'border-l-2 border-l-emerald-500 bg-emerald-50/30',
].join(' ')}
>
<div className="flex min-w-0 flex-1 items-center gap-3">
<div className="flex w-14 flex-col items-center">
<span className="text-sm font-medium tabular-nums">
{booking.startTime}
</span>
<span className="text-[11px] text-muted-foreground">
{booking.endTime}
</span>
</div>
<div className="flex flex-1 min-w-0">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{booking.courtName}</p>
<p className="truncate text-xs text-muted-foreground">
{booking.customerName}{' '}
<span className="text-muted-foreground/60">
· {booking.customerPhone}
</span>
</p>
</div>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<StatusBadge
status={effectiveStatus}
label={effectiveStatusLabel(effectiveStatus)}
/>
<div className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
{canManage && !isMutating && (
<>
<Button
type="button"
size="icon-xs"
variant="ghost"
title="Marcar cumplida"
onClick={() => {
updateStatusMutation.mutate({
bookingId: booking.id,
status: 'COMPLETED',
});
}}
>
<Check className="size-3.5" />
</Button>
<Button
type="button"
size="icon-xs"
variant="ghost"
title="Cancelar"
onClick={() => {
handleCancelBooking(booking);
}}
>
×
</Button>
</>
)}
</div>
</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>
</div>
{bookingToCancel && (
<ResponsiveDialog
open={Boolean(bookingToCancel)}
onOpenChange={() => setBookingToCancel(null)}
>
<ResponsiveDialogContent>
<ResponsiveDialogHeader>
<ResponsiveDialogTitle>Cancelar reserva</ResponsiveDialogTitle>
<ResponsiveDialogDescription>
¿Estás seguro de que quieres cancelar esta reserva? Esta acción no se puede
deshacer.
</ResponsiveDialogDescription>
</ResponsiveDialogHeader>
<div className="mt-4 rounded-2xl border border-border/70 bg-background p-4">
<p className="font-medium">
{bookingToCancel.startTime} - {bookingToCancel.endTime} ·{' '}
{bookingToCancel.courtName}
</p>
<p className="mt-1 text-sm text-muted-foreground">
{bookingToCancel.customerName} ({bookingToCancel.customerPhone})
</p>
</div>
<ResponsiveDialogFooter>
<ResponsiveDialogClose asChild>
<Button variant="outline" disabled={updateStatusMutation.isPending}>
Mantener
</Button>
</ResponsiveDialogClose>
<Button
variant="destructive"
onClick={confirmCancelBooking}
disabled={updateStatusMutation.isPending}
>
{updateStatusMutation.isPending ? 'Cancelando...' : 'Sí, cancelar reserva'}
</Button>
</ResponsiveDialogFooter>
</ResponsiveDialogContent>
</ResponsiveDialog>
)}
</main>
);
} }

View File

@@ -1,314 +0,0 @@
import { FootballIcon } from '@/assets/icons/football';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { UserAvatar } from '@/components/user-avatar';
import { apiClient } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { acceptStoredPendingInvite } from '@/lib/invitations';
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Link, Outlet, useNavigate } from '@tanstack/react-router';
import { LogOut, Menu, UserRound } from 'lucide-react';
import { useEffect, useMemo, useRef } from 'react';
import { ThemeSwitcher } from './theme-switcher';
export function RootLayout() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { user, isAuthenticated, displayName, avatarUrl, signOut } = useAuth();
const { currentComplexSlug, setCurrentComplex } = useCurrentComplexStore();
const processedInviteForUser = useRef<string | null>(null);
const myComplexesQuery = useQuery({
queryKey: ['my-complexes'],
enabled: isAuthenticated,
queryFn: () => apiClient.complexes.listMine(),
});
useEffect(() => {
if (!isAuthenticated) {
processedInviteForUser.current = null;
return;
}
const userKey = user?.email ?? displayName ?? 'authenticated-user';
if (processedInviteForUser.current === userKey) {
return;
}
processedInviteForUser.current = userKey;
void (async () => {
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
await queryClient.invalidateQueries({ queryKey: ['my-complexes'] });
})();
}, [displayName, isAuthenticated, queryClient, user?.email]);
const complexSlug = currentComplexSlug || myComplexesQuery.data?.[0]?.complexSlug;
const currentComplexName = useMemo(() => {
const complexes = myComplexesQuery.data ?? [];
if (complexes.length === 0) return 'Mi complejo';
const selected = complexes.find((complex) => complex.complexSlug === complexSlug);
return selected?.complexName ?? complexes[0]?.complexName ?? 'Mi complejo';
}, [complexSlug, myComplexesQuery.data]);
const handleSignOut = async () => {
await signOut();
await navigate({ to: '/login' });
};
type NavigationItem = {
label: string;
to: '/' | '/profile' | '/complex/$slug/edit';
show: boolean;
params?: { slug: string };
};
const navigationItems: NavigationItem[] = [
{
label: 'Inicio',
to: '/',
show: true,
},
{
label: 'Configuración',
to: '/complex/$slug/edit',
params: currentComplexSlug ? { slug: currentComplexSlug } : undefined,
show: isAuthenticated && Boolean(currentComplexSlug),
},
{
label: 'Perfil',
to: '/profile',
show: isAuthenticated,
},
] as const;
return (
<div className="flex min-h-screen flex-col">
<header className="sticky top-0 z-40 border-b border-border/70 bg-background/80 backdrop-blur-xl">
<div className="mx-auto flex w-full max-w-7xl items-center justify-between gap-4 px-4 py-3 sm:px-6">
<div className="flex min-w-0 items-center gap-4">
<Link to="/" className="flex min-w-0 items-center gap-3">
<span className="relative flex size-10 items-center justify-center rounded-2xl bg-primary text-primary-foreground shadow-sm ring-1 ring-primary/20">
<FootballIcon className="size-5" />
<span className="absolute -right-0.5 -bottom-0.5 size-2 rounded-full border border-background bg-accent" />
</span>
<span className="min-w-0">
<span className="block text-[10px] font-semibold uppercase tracking-[0.32em] text-muted-foreground">
Playzer
</span>
<span className="block truncate text-sm font-semibold text-foreground">
{currentComplexName}
</span>
</span>
</Link>
<nav className="hidden items-center gap-1 lg:flex">
{navigationItems
.filter((item) => item.show)
.map((item) =>
item.params ? (
<Link
key={item.label}
to={item.to}
params={item.params}
className="rounded-full px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
activeProps={{ className: 'bg-muted text-foreground font-medium' }}
>
{item.label}
</Link>
) : (
<Link
key={item.label}
to={item.to}
className="rounded-full px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
activeProps={{ className: 'bg-muted text-foreground font-medium' }}
>
{item.label}
</Link>
)
)}
</nav>
</div>
<div className="flex items-center gap-2">
<ThemeSwitcher />
{!isAuthenticated && (
<Button asChild size="sm" variant="outline" className="hidden md:inline-flex">
<Link to="/login">Ingresar</Link>
</Button>
)}
{isAuthenticated && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="inline-flex items-center gap-2 rounded-full border border-border/70 bg-card px-2 py-1.5 transition-colors hover:bg-muted"
>
<UserAvatar
src={avatarUrl}
alt={displayName}
fallbackText={displayName}
size="sm"
/>
<span className="hidden max-w-32 truncate text-sm text-foreground sm:block">
{displayName}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel>Mi cuenta</DropdownMenuLabel>
<DropdownMenuSeparator />
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
<>
<DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
Cambiar complejo
</DropdownMenuLabel>
{myComplexesQuery.data.map((complex) => (
<DropdownMenuItem
key={complex.id}
onSelect={async () => {
await apiClient.complexes.select({ complexId: complex.id });
setCurrentComplex(complex.complexSlug);
}}
>
{complex.complexSlug === complexSlug && <span className="mr-2"></span>}
{complex.complexName}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
</>
)}
<DropdownMenuItem
onSelect={() => {
void navigate({ to: '/profile' });
}}
>
<UserRound className="size-4" />
Perfil
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onSelect={() => {
void handleSignOut();
}}
>
<LogOut className="size-4" />
Cerrar sesión
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="icon-sm"
className="lg:hidden"
aria-label="Abrir menú"
>
<Menu className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64 lg:hidden">
<DropdownMenuLabel>{currentComplexName}</DropdownMenuLabel>
<DropdownMenuSeparator />
{navigationItems
.filter((item) => item.show)
.map((item) =>
item.params ? (
<DropdownMenuItem
key={item.label}
onSelect={() => {
void navigate({ to: item.to, params: item.params });
}}
>
{item.label}
</DropdownMenuItem>
) : (
<DropdownMenuItem
key={item.label}
onSelect={() => {
void navigate({ to: item.to });
}}
>
{item.label}
</DropdownMenuItem>
)
)}
<DropdownMenuSeparator />
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
<>
<DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
Cambiar complejo
</DropdownMenuLabel>
{myComplexesQuery.data.map((complex) => (
<DropdownMenuItem
key={complex.id}
onSelect={async () => {
await apiClient.complexes.select({ complexId: complex.id });
setCurrentComplex(complex.complexSlug);
}}
>
{complex.complexSlug === complexSlug && <span className="mr-2"></span>}
{complex.complexName}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
</>
)}
{isAuthenticated ? (
<>
<DropdownMenuItem
onSelect={() => {
void navigate({ to: '/profile' });
}}
>
<UserRound className="size-4" />
Perfil
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onSelect={() => {
void handleSignOut();
}}
>
<LogOut className="size-4" />
Cerrar sesión
</DropdownMenuItem>
</>
) : (
<DropdownMenuItem
onSelect={() => {
void navigate({ to: '/login' });
}}
>
Ingresar
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</header>
<div className="flex-1">
<Outlet />
</div>
</div>
);
}

View File

@@ -30,15 +30,15 @@ export function ThemeSwitcher() {
> >
<DropdownMenuRadioItem value="light"> <DropdownMenuRadioItem value="light">
<Sun className="size-4" /> <Sun className="size-4" />
Claro Light
</DropdownMenuRadioItem> </DropdownMenuRadioItem>
<DropdownMenuRadioItem value="dark"> <DropdownMenuRadioItem value="dark">
<Moon className="size-4" /> <Moon className="size-4" />
Oscuro Dark
</DropdownMenuRadioItem> </DropdownMenuRadioItem>
<DropdownMenuRadioItem value="system"> <DropdownMenuRadioItem value="system">
<Laptop className="size-4" /> <Laptop className="size-4" />
Sistema System
</DropdownMenuRadioItem> </DropdownMenuRadioItem>
</DropdownMenuRadioGroup> </DropdownMenuRadioGroup>
</DropdownMenuContent> </DropdownMenuContent>

View File

@@ -78,69 +78,14 @@ export function LoginPage({ redirectTo = '/' }: LoginPageProps) {
}; };
return ( return (
<main className="min-h-screen px-4 py-4 sm:px-6 lg:px-8 lg:py-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<div className="mx-auto grid min-h-[calc(100vh-2rem)] w-full max-w-6xl items-center gap-6 lg:grid-cols-[1.1fr_0.9fr]"> <section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<section className="relative hidden overflow-hidden rounded-2xl border border-border/70 bg-card p-8 text-card-foreground shadow-sm lg:flex lg:min-h-[640px] lg:flex-col lg:justify-between"> <h1 className="mb-2 text-2xl font-semibold">Iniciar sesión</h1>
<div className="absolute inset-0 bg-[radial-gradient(circle_at_top_left,rgba(43,139,82,0.12),transparent_38%),radial-gradient(circle_at_bottom_right,rgba(35,80,128,0.1),transparent_35%)]" /> <p className="mb-4 text-sm text-muted-foreground">
<div className="relative space-y-8"> Ingresá con tu cuenta para acceder a Home.
<div className="inline-flex items-center gap-2 rounded-full border border-border/70 bg-background/70 px-3 py-1 text-xs font-medium text-muted-foreground backdrop-blur">
<span className="size-2 rounded-full bg-emerald-500" />
Gestión de reservas y complejos
</div>
<div className="max-w-xl space-y-5">
<p className="text-[11px] font-semibold uppercase tracking-[0.34em] text-muted-foreground">
Playzer
</p> </p>
<h1 className="text-4xl font-semibold tracking-tight text-foreground xl:text-5xl">
Un panel para operar el club con velocidad, claridad y presencia.
</h1>
<p className="max-w-lg text-base leading-7 text-muted-foreground">
Accedé a reservas, configuración y usuarios desde una interfaz más limpia, pensada
para trabajar rápido en escritorio y también en móvil.
</p>
</div>
</div>
<div className="relative grid gap-3 sm:grid-cols-3"> <Button type="button" variant="outline" className="w-full" onClick={handleGoogleSignIn}>
{[
'Disponibilidad y reservas en un vistazo',
'Cambios de complejo sin perder contexto',
'Estados y acciones con feedback claro',
].map((item) => (
<div
key={item}
className="rounded-2xl border border-border/70 bg-background/70 p-4 text-sm text-muted-foreground backdrop-blur"
>
{item}
</div>
))}
</div>
</section>
<section className="w-full rounded-2xl border border-border/70 bg-card p-6 text-card-foreground shadow-sm sm:p-8">
<div className="mb-8 flex items-start justify-between gap-4">
<div className="space-y-2">
<p className="text-[11px] font-semibold uppercase tracking-[0.34em] text-muted-foreground">
Acceso
</p>
<h1 className="text-3xl font-semibold tracking-tight">Ingresá a tu cuenta</h1>
<p className="max-w-sm text-sm text-muted-foreground">
Entrá con Google o con tu email y contraseña para continuar con tu complejo.
</p>
</div>
<div className="hidden rounded-2xl border border-border/70 bg-background p-3 text-right sm:block">
<p className="text-xs uppercase tracking-[0.24em] text-muted-foreground">Estado</p>
<p className="mt-1 text-sm font-medium">Acceso seguro</p>
</div>
</div>
<Button
type="button"
variant="outline"
className="w-full justify-center"
onClick={handleGoogleSignIn}
>
<svg className="mr-2 h-4 w-4" viewBox="0 0 24 24" aria-hidden="true"> <svg className="mr-2 h-4 w-4" viewBox="0 0 24 24" aria-hidden="true">
<path <path
fill="currentColor" fill="currentColor"
@@ -162,16 +107,16 @@ export function LoginPage({ redirectTo = '/' }: LoginPageProps) {
Continuar con Google Continuar con Google
</Button> </Button>
<div className="relative my-5"> <div className="relative my-4">
<div className="absolute inset-0 flex items-center"> <div className="absolute inset-0 flex items-center">
<span className="w-full border-t border-border/80" /> <span className="w-full border-t" />
</div> </div>
<div className="relative flex justify-center text-xs uppercase"> <div className="relative flex justify-center text-xs uppercase">
<span className="bg-card px-2 text-muted-foreground">O continuá con email</span> <span className="bg-card px-2 text-muted-foreground">O</span>
</div> </div>
</div> </div>
<form className="space-y-4" onSubmit={handleSubmit(onSubmit)}> <form className="space-y-3" onSubmit={handleSubmit(onSubmit)}>
<Field data-invalid={Boolean(errors.email)}> <Field data-invalid={Boolean(errors.email)}>
<FieldLabel htmlFor="email">Email</FieldLabel> <FieldLabel htmlFor="email">Email</FieldLabel>
<Input <Input
@@ -203,14 +148,12 @@ export function LoginPage({ redirectTo = '/' }: LoginPageProps) {
</Button> </Button>
</form> </form>
<div className="mt-5 flex items-center justify-between gap-3 text-sm"> <p className="mt-4 text-center text-sm text-muted-foreground">
<p className="text-muted-foreground">¿Olvidaste tu contraseña?</p> <Link to="/reset-password" className="text-primary hover:underline">
<Link to="/reset-password" className="font-medium text-primary hover:underline"> ¿Olvidaste tu contraseña?
Recuperarla
</Link> </Link>
</div> </p>
</section> </section>
</div>
</main> </main>
); );
} }

View File

@@ -4,7 +4,7 @@ import { Compass, Home, Sparkles } from 'lucide-react';
export function NotFoundPage() { export function NotFoundPage() {
return ( return (
<main className="relative isolate mx-auto flex min-h-screen w-full max-w-5xl items-center justify-center overflow-hidden px-6 py-10"> <main className="relative isolate mx-auto flex min-h-screen w-full max-w-5xl items-center justify-center overflow-hidden px-3 py-10 sm:px-6">
<div className="pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(circle_at_20%_20%,rgba(56,189,248,0.14),transparent_45%),radial-gradient(circle_at_80%_10%,rgba(244,114,182,0.12),transparent_40%),radial-gradient(circle_at_50%_90%,rgba(59,130,246,0.10),transparent_40%)]" /> <div className="pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(circle_at_20%_20%,rgba(56,189,248,0.14),transparent_45%),radial-gradient(circle_at_80%_10%,rgba(244,114,182,0.12),transparent_40%),radial-gradient(circle_at_50%_90%,rgba(59,130,246,0.10),transparent_40%)]" />
<section className="w-full max-w-2xl rounded-2xl border bg-card/80 p-8 text-card-foreground shadow-xl backdrop-blur"> <section className="w-full max-w-2xl rounded-2xl border bg-card/80 p-8 text-card-foreground shadow-xl backdrop-blur">

View File

@@ -1,7 +1,7 @@
export function OnboardingCheckEmailStep() { export function OnboardingCheckEmailStep() {
return ( return (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
Revisa tu correo y abrí el link de verificación para continuar. Revisa tu correo y abre el link de verificacion para continuar.
</p> </p>
); );
} }

View File

@@ -7,55 +7,12 @@ type OnboardingLayoutProps = PropsWithChildren<{
export function OnboardingLayout({ title, description, children }: OnboardingLayoutProps) { export function OnboardingLayout({ title, description, children }: OnboardingLayoutProps) {
return ( return (
<main className="min-h-screen px-4 py-4 sm:px-6 lg:px-8 lg:py-6"> <main className="mx-auto flex min-h-screen w-full max-w-6xl items-center justify-center px-3 sm:px-6">
<div className="mx-auto grid min-h-[calc(100vh-2rem)] w-full max-w-6xl gap-6 lg:grid-cols-[0.95fr_1.05fr]"> <section className="w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<aside className="hidden overflow-hidden rounded-2xl border border-border/70 bg-card p-8 shadow-sm lg:flex lg:flex-col lg:justify-between"> <h1 className="mb-2 text-2xl font-semibold">{title}</h1>
<div className="space-y-6"> <p className="mb-4 text-sm text-muted-foreground">{description}</p>
<div className="inline-flex items-center gap-2 rounded-full border border-border/70 bg-background/70 px-3 py-1 text-xs font-medium text-muted-foreground">
<span className="size-2 rounded-full bg-primary" />
Alta guiada
</div>
<div className="space-y-4">
<p className="text-[11px] font-semibold uppercase tracking-[0.32em] text-muted-foreground">
Onboarding
</p>
<h1 className="max-w-md text-4xl font-semibold tracking-tight">
Un alta que guía, no que interrumpe.
</h1>
<p className="max-w-md text-base leading-7 text-muted-foreground">
Verificá email, completá los datos y dejá el complejo listo para operar sin pasos
confusos ni pantallas iguales entre .
</p>
</div>
</div>
<div className="grid gap-3">
<div className="rounded-2xl border border-border/70 bg-background p-4">
<p className="text-xs uppercase tracking-[0.24em] text-muted-foreground">Paso 1</p>
<p className="mt-2 text-sm text-foreground">Ingresar nombre y correo</p>
</div>
<div className="rounded-2xl border border-border/70 bg-background p-4">
<p className="text-xs uppercase tracking-[0.24em] text-muted-foreground">Paso 2</p>
<p className="mt-2 text-sm text-foreground">Verificar email o código OTP</p>
</div>
<div className="rounded-2xl border border-border/70 bg-background p-4">
<p className="text-xs uppercase tracking-[0.24em] text-muted-foreground">Paso 3</p>
<p className="mt-2 text-sm text-foreground">Crear el complejo y empezar</p>
</div>
</div>
</aside>
<section className="w-full rounded-2xl border border-border/70 bg-card p-6 text-card-foreground shadow-sm sm:p-8">
<div className="mb-6 space-y-2">
<p className="text-[11px] font-semibold uppercase tracking-[0.32em] text-muted-foreground">
Inicio
</p>
<h1 className="text-3xl font-semibold tracking-tight">{title}</h1>
<p className="max-w-lg text-sm text-muted-foreground">{description}</p>
</div>
{children} {children}
</section> </section>
</div>
</main> </main>
); );
} }

View File

@@ -18,7 +18,7 @@ export function OnboardingStartStep({
onSubmit, onSubmit,
}: OnboardingStartStepProps) { }: OnboardingStartStepProps) {
return ( return (
<form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}> <form className="space-y-3" onSubmit={form.handleSubmit(onSubmit)}>
<Field data-invalid={Boolean(form.formState.errors.fullName)}> <Field data-invalid={Boolean(form.formState.errors.fullName)}>
<FieldLabel htmlFor="onboard-fullname">Nombre</FieldLabel> <FieldLabel htmlFor="onboard-fullname">Nombre</FieldLabel>
<Input <Input
@@ -51,7 +51,7 @@ export function OnboardingStartStep({
className="w-full" className="w-full"
disabled={form.formState.isSubmitting || !form.formState.isValid} disabled={form.formState.isSubmitting || !form.formState.isValid}
> >
{form.formState.isSubmitting ? 'Enviando...' : 'Enviar código OTP'} {form.formState.isSubmitting ? 'Enviando...' : 'Enviar codigo OTP'}
</Button> </Button>
</form> </form>
); );

View File

@@ -38,13 +38,13 @@ export function OnboardingVerifyOtpStep({
return ( return (
<form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}> <form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
Ingresa el código de 6 dígitos que enviamos a{' '} Ingresa el codigo de 6 digitos que enviamos a{' '}
<span className="font-medium text-foreground">{email ?? 'tu email'}</span>. <span className="font-medium text-foreground">{email ?? 'tu email'}</span>.
</p> </p>
<Field data-invalid={Boolean(form.formState.errors.otp)}> <Field data-invalid={Boolean(form.formState.errors.otp)}>
<div className="mb-2 flex items-center justify-between gap-3"> <div className="mb-2 flex items-center justify-between gap-3">
<FieldLabel htmlFor="onboard-otp">Código de verificación</FieldLabel> <FieldLabel htmlFor="onboard-otp">Codigo de verificacion</FieldLabel>
<Button <Button
type="button" type="button"
variant="outline" variant="outline"
@@ -59,7 +59,7 @@ export function OnboardingVerifyOtpStep({
? 'Reenviando...' ? 'Reenviando...'
: resendCooldownSeconds > 0 : resendCooldownSeconds > 0
? `Reenviar en ${resendCooldownSeconds}s` ? `Reenviar en ${resendCooldownSeconds}s`
: 'Reenviar código'} : 'Reenviar codigo'}
</Button> </Button>
</div> </div>
@@ -101,7 +101,7 @@ export function OnboardingVerifyOtpStep({
className="w-full" className="w-full"
disabled={form.formState.isSubmitting || !form.formState.isValid} disabled={form.formState.isSubmitting || !form.formState.isValid}
> >
{form.formState.isSubmitting ? 'Verificando...' : 'Verificar código'} {form.formState.isSubmitting ? 'Verificando...' : 'Verificar codigo'}
</Button> </Button>
</form> </form>
); );

View File

@@ -106,7 +106,7 @@ export function CreateComplexPage() {
}; };
return ( return (
<main className="flex min-h-screen w-full items-center justify-center px-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm"> <section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<h1 className="mb-2 text-2xl font-semibold">Crear tu complejo</h1> <h1 className="mb-2 text-2xl font-semibold">Crear tu complejo</h1>
<p className="mb-4 text-sm text-muted-foreground"> <p className="mb-4 text-sm text-muted-foreground">

View File

@@ -142,7 +142,7 @@ export function OnboardLoginPage({
}; };
return ( return (
<main className="flex min-h-screen w-full items-center justify-center px-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm"> <section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<h1 className="mb-2 text-2xl font-semibold"> <h1 className="mb-2 text-2xl font-semibold">
{mode === 'login' ? 'Iniciar sesión' : 'Crear cuenta'} {mode === 'login' ? 'Iniciar sesión' : 'Crear cuenta'}

View File

@@ -24,7 +24,7 @@ export function VerifyEmailPage() {
}; };
return ( return (
<main className="flex min-h-screen w-full items-center justify-center px-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm"> <section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<h1 className="mb-2 text-2xl font-semibold">Verificá tu email</h1> <h1 className="mb-2 text-2xl font-semibold">Verificá tu email</h1>
<p className="mb-4 text-sm text-muted-foreground"> <p className="mb-4 text-sm text-muted-foreground">

View File

@@ -149,7 +149,7 @@ export function ResetPasswordPage() {
if (successMessage) { if (successMessage) {
return ( return (
<main className="flex min-h-screen w-full items-center justify-center px-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm"> <section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<div className="text-center"> <div className="text-center">
<div className="mb-4 text-2xl"></div> <div className="mb-4 text-2xl"></div>
@@ -162,7 +162,7 @@ export function ResetPasswordPage() {
} }
return ( return (
<main className="flex min-h-screen w-full items-center justify-center px-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm"> <section className="w-full max-w-sm rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<h1 className="mb-2 text-2xl font-semibold"> <h1 className="mb-2 text-2xl font-semibold">
{step === 'email' ? 'Restablecer contraseña' : 'Ingresá el código'} {step === 'email' ? 'Restablecer contraseña' : 'Ingresá el código'}

View File

@@ -15,7 +15,6 @@ import { zodResolver } from '@hookform/resolvers/zod';
import type { UserProfileResponse } from '@repo/api-contract'; import type { UserProfileResponse } from '@repo/api-contract';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Link } from '@tanstack/react-router'; import { Link } from '@tanstack/react-router';
import { Mail, ShieldCheck } from 'lucide-react';
import { useEffect } from 'react'; import { useEffect } from 'react';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
@@ -101,16 +100,13 @@ export function ProfilePage() {
if (!isAuthenticated) { if (!isAuthenticated) {
return ( return (
<main className="mx-auto flex min-h-[60vh] w-full max-w-6xl items-center justify-center px-4 py-6"> <main className="mx-auto flex min-h-[60vh] w-full max-w-6xl items-center justify-center px-3 sm:px-6">
<section className="w-full max-w-3xl rounded-2xl border border-border/70 bg-card p-6 text-card-foreground shadow-sm"> <section className="w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<p className="text-[11px] font-semibold uppercase tracking-[0.32em] text-muted-foreground"> <h1 className="text-2xl font-semibold">Perfil</h1>
Perfil
</p>
<h1 className="mt-2 text-3xl font-semibold tracking-tight">Necesitás iniciar sesión</h1>
<p className="mt-2 text-sm text-muted-foreground"> <p className="mt-2 text-sm text-muted-foreground">
Ingresá para editar tu nombre, revisar tu correo y cambiar la contraseña. Necesitás iniciar sesión para ver tu perfil.
</p> </p>
<Button asChild className="mt-5"> <Button asChild className="mt-4">
<Link to="/login">Ir a Login</Link> <Link to="/login">Ir a Login</Link>
</Button> </Button>
</section> </section>
@@ -119,74 +115,42 @@ export function ProfilePage() {
} }
return ( return (
<main className="mx-auto w-full max-w-6xl px-4 py-6 sm:px-6 lg:px-8"> <main className="mx-auto flex min-h-[60vh] w-full max-w-6xl items-center justify-center px-3 py-8 sm:px-6">
<div className="grid gap-6 lg:grid-cols-[0.9fr_1.1fr]"> <div className="w-full max-w-3xl space-y-6">
<section className="relative overflow-hidden rounded-2xl border border-border/70 bg-card p-6 text-card-foreground shadow-sm"> <section className="rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(43,139,82,0.12),transparent_36%)]" /> <div className="flex items-center gap-3">
<div className="relative space-y-6">
<div className="flex items-center gap-4">
<UserAvatar <UserAvatar
src={profileQuery.data?.avatarUrl ?? avatarUrl} src={profileQuery.data?.avatarUrl ?? avatarUrl}
alt={displayName} alt={displayName}
fallbackText={displayName} fallbackText={displayName}
size="lg" size="lg"
/> />
<div className="min-w-0"> <div>
<p className="text-[11px] font-semibold uppercase tracking-[0.32em] text-muted-foreground"> <h1 className="text-2xl font-semibold">{displayName}</h1>
Perfil <p className="text-sm text-muted-foreground">
</p>
<h1 className="mt-2 text-3xl font-semibold tracking-tight">{displayName}</h1>
<div className="mt-3 flex flex-wrap gap-2">
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
<Mail className="size-3.5" />
{profileQuery.data?.email ?? user?.email} {profileQuery.data?.email ?? user?.email}
</span> </p>
{profileQuery.data?.role && ( {profileQuery.data?.role && (
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background px-3 py-1 text-xs font-medium text-muted-foreground"> <p className="text-sm text-muted-foreground">Rol: {profileQuery.data.role}</p>
<ShieldCheck className="size-3.5" />
Rol {profileQuery.data.role}
</span>
)} )}
</div> </div>
</div> </div>
</div>
{profileQuery.isLoading && ( {profileQuery.isLoading && (
<p className="text-sm text-muted-foreground">Cargando perfil...</p> <p className="mt-4 text-sm text-muted-foreground">Cargando perfil...</p>
)} )}
{profileQuery.isError && ( {profileQuery.isError && (
<p className="text-sm text-destructive"> <p className="mt-4 text-sm text-destructive">
No se pudo cargar el perfil desde el backend. No se pudo cargar el perfil desde el backend.
</p> </p>
)} )}
<div className="grid gap-3 sm:grid-cols-2">
<div className="rounded-2xl border border-border/70 bg-background p-4">
<p className="text-xs uppercase tracking-[0.24em] text-muted-foreground">Cuenta</p>
<p className="mt-2 text-sm text-foreground">Actualizá datos personales y acceso.</p>
</div>
<div className="rounded-2xl border border-border/70 bg-background p-4">
<p className="text-xs uppercase tracking-[0.24em] text-muted-foreground">
Seguridad
</p>
<p className="mt-2 text-sm text-foreground">Cambiá tu contraseña cuando quieras.</p>
</div>
</div>
</div>
</section> </section>
<div className="space-y-6"> <section className="rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<section className="rounded-2xl border border-border/70 bg-card p-6 text-card-foreground shadow-sm"> <h2 className="text-xl font-semibold mb-4">Editar Perfil</h2>
<h2 className="text-xl font-semibold">Editar perfil</h2>
<p className="mt-2 text-sm text-muted-foreground">
Mantené tu nombre visible y consistente para el resto del equipo.
</p>
<Form {...updateProfileForm}> <Form {...updateProfileForm}>
<form <form onSubmit={updateProfileForm.handleSubmit(onUpdateProfile)} className="space-y-4">
onSubmit={updateProfileForm.handleSubmit(onUpdateProfile)}
className="mt-5 space-y-4"
>
<FormField <FormField
control={updateProfileForm.control} control={updateProfileForm.control}
name="fullName" name="fullName"
@@ -211,19 +175,16 @@ export function ProfilePage() {
</p> </p>
)} )}
{updateProfileMutation.isSuccess && ( {updateProfileMutation.isSuccess && (
<p className="mt-4 text-sm text-emerald-700">Perfil actualizado exitosamente.</p> <p className="mt-4 text-sm text-green-600">Perfil actualizado exitosamente.</p>
)} )}
</section> </section>
<section className="rounded-2xl border border-border/70 bg-card p-6 text-card-foreground shadow-sm"> <section className="rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
<h2 className="text-xl font-semibold">Cambiar contraseña</h2> <h2 className="text-xl font-semibold mb-4">Cambiar Contraseña</h2>
<p className="mt-2 text-sm text-muted-foreground">
Usá una contraseña fuerte para proteger el acceso al panel.
</p>
<Form {...updatePasswordForm}> <Form {...updatePasswordForm}>
<form <form
onSubmit={updatePasswordForm.handleSubmit(onUpdatePassword)} onSubmit={updatePasswordForm.handleSubmit(onUpdatePassword)}
className="mt-5 space-y-4" className="space-y-4"
> >
<FormField <FormField
control={updatePasswordForm.control} control={updatePasswordForm.control}
@@ -275,11 +236,10 @@ export function ProfilePage() {
</p> </p>
)} )}
{updatePasswordMutation.isSuccess && ( {updatePasswordMutation.isSuccess && (
<p className="mt-4 text-sm text-emerald-700">Contraseña cambiada exitosamente.</p> <p className="mt-4 text-sm text-green-600">Contraseña cambiada exitosamente.</p>
)} )}
</section> </section>
</div> </div>
</div>
</main> </main>
); );
} }

View File

@@ -41,7 +41,7 @@ export function PublicBookingConfirmationPage({
return ( return (
<main className="min-h-screen bg-linear-to-b from-background via-background to-primary/5"> <main className="min-h-screen bg-linear-to-b from-background via-background to-primary/5">
<div className="mx-auto flex min-h-screen w-full max-w-3xl items-center px-4 py-8 sm:px-6"> <div className="mx-auto flex min-h-screen w-full max-w-3xl items-center px-3 py-8 sm:px-6">
<section className="w-full rounded-3xl border bg-card p-5 shadow-lg sm:p-8"> <section className="w-full rounded-3xl border bg-card p-5 shadow-lg sm:p-8">
{confirmationQuery.isLoading && ( {confirmationQuery.isLoading && (
<p className="text-sm text-muted-foreground">Cargando confirmacion...</p> <p className="text-sm text-muted-foreground">Cargando confirmacion...</p>
@@ -89,15 +89,6 @@ export function PublicBookingConfirmationPage({
<p className="mt-1 text-base font-medium sm:text-lg"> <p className="mt-1 text-base font-medium sm:text-lg">
{confirmationQuery.data.courtName} · {confirmationQuery.data.sport.name} {confirmationQuery.data.courtName} · {confirmationQuery.data.sport.name}
</p> </p>
{confirmationQuery.data.price > 0 && (
<>
<p className="mt-4 text-sm text-muted-foreground">Precio</p>
<p className="mt-1 text-xl font-bold sm:text-2xl">
${confirmationQuery.data.price.toLocaleString('es-AR')}
</p>
</>
)}
</div> </div>
<div className="grid gap-3 sm:grid-cols-2"> <div className="grid gap-3 sm:grid-cols-2">

View File

@@ -3,7 +3,7 @@ import { apiClient } from '@/lib/api-client';
import type { ComplexWithRole } from '@repo/api-contract'; import type { ComplexWithRole } from '@repo/api-contract';
import { useMutation, useQuery } from '@tanstack/react-query'; import { useMutation, useQuery } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router'; import { useNavigate } from '@tanstack/react-router';
import { ArrowRight, Building2, Loader2 } from 'lucide-react'; import { Building2, Loader2 } from 'lucide-react';
export function SelectComplexPage() { export function SelectComplexPage() {
const navigate = useNavigate(); const navigate = useNavigate();
@@ -29,15 +29,15 @@ export function SelectComplexPage() {
if (complexesQuery.isLoading) { if (complexesQuery.isLoading) {
return ( return (
<main className="flex min-h-screen w-full items-center justify-center px-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<Loader2 className="h-9 w-9 animate-spin text-muted-foreground" /> <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</main> </main>
); );
} }
if (complexesQuery.isError) { if (complexesQuery.isError) {
return ( return (
<main className="flex min-h-screen w-full items-center justify-center px-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<div className="text-center"> <div className="text-center">
<p className="text-destructive">Error al cargar tus complejos.</p> <p className="text-destructive">Error al cargar tus complejos.</p>
<Button variant="link" className="mt-2" onClick={() => complexesQuery.refetch()}> <Button variant="link" className="mt-2" onClick={() => complexesQuery.refetch()}>
@@ -52,7 +52,7 @@ export function SelectComplexPage() {
if (complexes.length === 0) { if (complexes.length === 0) {
return ( return (
<main className="flex min-h-screen w-full items-center justify-center px-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<div className="text-center"> <div className="text-center">
<p className="text-muted-foreground">No tenés complejos asociados.</p> <p className="text-muted-foreground">No tenés complejos asociados.</p>
</div> </div>
@@ -61,93 +61,38 @@ export function SelectComplexPage() {
} }
return ( return (
<main className="min-h-screen px-4 py-4 sm:px-6 lg:px-8 lg:py-6"> <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
<div className="mx-auto grid min-h-[calc(100vh-2rem)] w-full max-w-6xl gap-6 lg:grid-cols-[0.9fr_1.1fr]"> <section className="w-full max-w-md space-y-6">
<section className="hidden overflow-hidden rounded-2xl border border-border/70 bg-card p-8 shadow-sm lg:flex lg:flex-col lg:justify-between">
<div className="space-y-6">
<div className="inline-flex items-center gap-2 rounded-full border border-border/70 bg-background/70 px-3 py-1 text-xs font-medium text-muted-foreground">
<span className="size-2 rounded-full bg-primary" />
Cambio de contexto
</div>
<div className="space-y-4">
<p className="text-[11px] font-semibold uppercase tracking-[0.32em] text-muted-foreground">
Playzer
</p>
<h1 className="max-w-md text-4xl font-semibold tracking-tight">
Elegí el complejo con el que vas a operar.
</h1>
<p className="max-w-md text-base leading-7 text-muted-foreground">
Cada complejo tiene su propio estado, su lista de canchas y su panel de reservas.
Seleccioná uno para entrar con todo el contexto listo.
</p>
</div>
</div>
<div className="grid gap-3">
<div className="rounded-2xl border border-border/70 bg-background p-4">
<p className="text-xs uppercase tracking-[0.24em] text-muted-foreground">
Qué cambia
</p>
<p className="mt-2 text-sm text-foreground">
Reservas, usuarios, configuración y disponibilidad se actualizan según el complejo
seleccionado.
</p>
</div>
<div className="rounded-2xl border border-border/70 bg-background p-4">
<p className="text-xs uppercase tracking-[0.24em] text-muted-foreground">Tip</p>
<p className="mt-2 text-sm text-foreground">
Si administrás varios complejos, el menú superior te deja cambiar sin perder el
hilo.
</p>
</div>
</div>
</section>
<section className="w-full rounded-2xl border border-border/70 bg-card p-6 shadow-sm sm:p-8">
<div className="space-y-2"> <div className="space-y-2">
<p className="text-[11px] font-semibold uppercase tracking-[0.32em] text-muted-foreground"> <h1 className="text-2xl font-semibold">Seleccioná un complejo</h1>
Selección <p className="text-sm text-muted-foreground">
</p> Elegí el complejo con el que vas a trabajar.
<h1 className="text-3xl font-semibold tracking-tight">Seleccioná un complejo</h1>
<p className="max-w-md text-sm text-muted-foreground">
Elegí el espacio con el que vas a trabajar ahora mismo.
</p> </p>
</div> </div>
<div className="mt-6 space-y-3"> <div className="space-y-2">
{complexes.map((complex) => ( {complexes.map((complex) => (
<button <button
key={complex.id} key={complex.id}
type="button" type="button"
className="flex w-full items-center gap-4 rounded-2xl border border-border/70 bg-background p-4 text-left transition-all hover:-translate-y-0.5 hover:border-primary/30 hover:shadow-sm" className="flex w-full items-center gap-3 rounded-lg border p-4 text-left transition-colors hover:bg-accent"
onClick={() => handleSelect(complex)} onClick={() => handleSelect(complex)}
disabled={selectMutation.isPending} disabled={selectMutation.isPending}
> >
<div className="flex size-11 items-center justify-center rounded-2xl bg-primary/10 text-primary"> <Building2 className="h-5 w-5 text-muted-foreground" />
<Building2 className="h-5 w-5" />
</div>
<div className="flex-1"> <div className="flex-1">
<div className="flex items-center gap-2"> <p className="font-medium">{complex.complexName}</p>
<p className="font-medium text-foreground">{complex.complexName}</p> <p className="text-sm text-muted-foreground">
<span className="rounded-full border border-border/70 bg-card px-2 py-0.5 text-[11px] font-medium text-muted-foreground"> {complex.city ?? 'Sin ciudad'} · {complex.role}
{complex.role}
</span>
</div>
<p className="mt-1 text-sm text-muted-foreground">
{complex.city ?? 'Sin ciudad'} · {complex.complexSlug}
</p> </p>
</div> </div>
{selectMutation.isPending && selectMutation.variables === complex.id && ( {selectMutation.isPending && selectMutation.variables === complex.id && (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" /> <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
)} )}
{!selectMutation.isPending && (
<ArrowRight className="h-4 w-4 text-muted-foreground" />
)}
</button> </button>
))} ))}
</div> </div>
</section> </section>
</div>
</main> </main>
); );
} }

View File

@@ -4,7 +4,7 @@ import { AlertTriangle, Home, RefreshCw, Route } from 'lucide-react';
export function ServerErrorPage({ error, reset }: ErrorComponentProps) { export function ServerErrorPage({ error, reset }: ErrorComponentProps) {
return ( return (
<main className="relative isolate mx-auto flex min-h-screen w-full max-w-5xl items-center justify-center overflow-hidden px-6 py-10"> <main className="relative isolate mx-auto flex min-h-screen w-full max-w-5xl items-center justify-center overflow-hidden px-3 py-10 sm:px-6">
<div className="pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(circle_at_15%_10%,rgba(248,113,113,0.14),transparent_42%),radial-gradient(circle_at_80%_20%,rgba(251,191,36,0.12),transparent_38%),radial-gradient(circle_at_60%_90%,rgba(59,130,246,0.10),transparent_42%)]" /> <div className="pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(circle_at_15%_10%,rgba(248,113,113,0.14),transparent_42%),radial-gradient(circle_at_80%_20%,rgba(251,191,36,0.12),transparent_38%),radial-gradient(circle_at_60%_90%,rgba(59,130,246,0.10),transparent_42%)]" />
<section className="w-full max-w-2xl rounded-2xl border bg-card/80 p-8 text-card-foreground shadow-xl backdrop-blur"> <section className="w-full max-w-2xl rounded-2xl border bg-card/80 p-8 text-card-foreground shadow-xl backdrop-blur">

View File

@@ -1,227 +1,289 @@
@import "tailwindcss"; @import "tailwindcss";
@import "tw-animate-css"; @import "tw-animate-css";
@import "shadcn/tailwind.css"; @import "shadcn/tailwind.css";
@import "@fontsource-variable/geist"; /* @import "@fontsource-variable/inter"; */
@custom-variant dark (&:is(.dark *)); @custom-variant dark (&:is(.dark *));
@source "../../../apps/**/*.{ts,tsx}";
@source "../../../components/**/*.{ts,tsx}";
@source "../**/*.{ts,tsx}";
html,
body,
#root {
width: 100%;
min-height: 100%;
margin: 0;
}
@theme inline { @theme inline {
--font-heading: var(--font-sans); --font-heading: var(--font-sans);
--font-sans: "Geist Variable", sans-serif;
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background); --color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-success: var(--success);
--color-success-foreground: var(--success-foreground);
--color-reserved: var(--reserved);
--color-reserved-foreground: var(--reserved-foreground);
--color-maintenance: var(--maintenance);
--color-maintenance-foreground: var(--maintenance-foreground);
--color-warning: var(--warning);
--color-warning-foreground: var(--warning-foreground);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--radius-sm: calc(var(--radius) * 0.6); --radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8); --radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius); --radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.2); --radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.5); --radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 1.8); --radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.1); --radius-4xl: calc(var(--radius) * 2.6);
--font-sans: "Inter Variable", sans-serif;
} }
:root { :root {
/* Base colors (retaining the shadcn structure, but with a sports-club identity) */ --background: oklch(0.985 0.004 240);
--background: oklch(0.94 0.01 145); --foreground: oklch(0.18 0.012 245);
--foreground: oklch(0.16 0.02 145);
--card: oklch(0.995 0.005 145);
--card-foreground: oklch(0.16 0.02 145);
--popover: oklch(0.995 0.005 145);
--popover-foreground: oklch(0.16 0.02 145);
--primary: oklch(0.42 0.11 145);
--primary-foreground: oklch(0.985 0.01 145);
--secondary: oklch(0.95 0.015 145);
--secondary-foreground: oklch(0.24 0.02 145);
--muted: oklch(0.95 0.01 145);
--muted-foreground: oklch(0.49 0.02 145);
--accent: oklch(0.93 0.05 82);
--accent-foreground: oklch(0.28 0.05 82);
--destructive: oklch(0.58 0.22 27);
--border: oklch(0.9 0.01 145);
--input: oklch(0.89 0.01 145);
--ring: oklch(0.55 0.12 145);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.5rem;
--sidebar: oklch(0.99 0.005 145);
--sidebar-foreground: oklch(0.16 0.02 145);
--sidebar-primary: oklch(0.42 0.11 145);
--sidebar-primary-foreground: oklch(0.985 0.01 145);
--sidebar-accent: oklch(0.93 0.05 82);
--sidebar-accent-foreground: oklch(0.28 0.05 82);
--sidebar-border: oklch(0.9 0.01 145);
--sidebar-ring: oklch(0.55 0.12 145);
/* Surface elevation (light mode: higher = lighter) */ --card: oklch(1 0 0);
--surface-base: oklch(1 0 0); --card-foreground: oklch(0.18 0.012 245);
--surface-raised: oklch(0.99 0 0);
--surface-overlay: oklch(0.98 0 0);
/* Semantic status - Light mode (subtle, not overwhelming) */ --popover: oklch(1 0 0);
--status-confirmed-bg: oklch(0.97 0.02 145); --popover-foreground: oklch(0.18 0.012 245);
--status-confirmed-border: oklch(0.88 0.03 145);
--status-confirmed-text: oklch(0.38 0.12 145);
--status-pending-bg: oklch(0.97 0.02 75); --primary: oklch(0.63 0.19 158);
--status-pending-border: oklch(0.88 0.03 75); --primary-foreground: oklch(0.985 0.004 160);
--status-pending-text: oklch(0.48 0.15 75);
--status-cancelled-bg: oklch(0.97 0.02 25); --secondary: oklch(0.94 0.01 240);
--status-cancelled-border: oklch(0.88 0.03 25); --secondary-foreground: oklch(0.28 0.018 245);
--status-cancelled-text: oklch(0.45 0.15 25);
--status-noshow-bg: oklch(0.97 0.02 50); --muted: oklch(0.95 0.008 240);
--status-noshow-border: oklch(0.88 0.03 50); --muted-foreground: oklch(0.52 0.018 245);
--status-noshow-text: oklch(0.45 0.12 50);
--status-completed-bg: oklch(0.97 0.02 220); --accent: oklch(0.93 0.035 158);
--status-completed-border: oklch(0.88 0.03 220); --accent-foreground: oklch(0.34 0.12 158);
--status-completed-text: oklch(0.38 0.1 220);
/* Borders */ --destructive: oklch(0.62 0.22 25);
--border-subtle: oklch(1 0 0 / 8%); --destructive-foreground: oklch(0.98 0.01 25);
--border-default: oklch(1 0 0 / 12%);
--border-emphasis: oklch(1 0 0 / 20%);
/* Input */ --success: oklch(0.63 0.19 158);
--input-bg: oklch(0.97 0 0); --success-foreground: oklch(0.985 0.004 160);
--input-border: oklch(0.89 0 0);
--reserved: oklch(0.58 0.19 255);
--reserved-foreground: oklch(0.985 0.01 255);
--maintenance: oklch(0.64 0.22 25);
--maintenance-foreground: oklch(0.985 0.01 25);
--warning: oklch(0.78 0.16 75);
--warning-foreground: oklch(0.18 0.04 75);
--border: oklch(0.86 0.01 245 / 65%);
--input: oklch(0.86 0.01 245 / 75%);
--ring: oklch(0.63 0.19 158);
--chart-1: oklch(0.63 0.19 158);
--chart-2: oklch(0.58 0.19 255);
--chart-3: oklch(0.64 0.22 25);
--chart-4: oklch(0.78 0.16 75);
--chart-5: oklch(0.68 0.16 205);
--radius: 0.875rem;
--sidebar: oklch(0.98 0.004 240);
--sidebar-foreground: oklch(0.18 0.012 245);
--sidebar-primary: oklch(0.63 0.19 158);
--sidebar-primary-foreground: oklch(0.985 0.004 160);
--sidebar-accent: oklch(0.94 0.01 240);
--sidebar-accent-foreground: oklch(0.28 0.018 245);
--sidebar-border: oklch(0.86 0.01 245 / 65%);
--sidebar-ring: oklch(0.63 0.19 158);
} }
.dark { .dark {
--background: oklch(0.14 0.015 145); --background: #081118;
--foreground: oklch(0.98 0.01 145); --foreground: oklch(0.96 0.006 245);
--card: oklch(0.19 0.02 145);
--card-foreground: oklch(0.98 0.01 145);
--popover: oklch(0.2 0.02 145);
--popover-foreground: oklch(0.98 0.01 145);
--primary: oklch(0.76 0.11 145);
--primary-foreground: oklch(0.15 0.02 145);
--secondary: oklch(0.24 0.02 145);
--secondary-foreground: oklch(0.98 0.01 145);
--muted: oklch(0.24 0.02 145);
--muted-foreground: oklch(0.72 0.02 145);
--accent: oklch(0.28 0.05 82);
--accent-foreground: oklch(0.98 0.01 82);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 12%);
--ring: oklch(0.72 0.08 145);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.18 0.02 145);
--sidebar-foreground: oklch(0.98 0.01 145);
--sidebar-primary: oklch(0.76 0.11 145);
--sidebar-primary-foreground: oklch(0.15 0.02 145);
--sidebar-accent: oklch(0.28 0.05 82);
--sidebar-accent-foreground: oklch(0.98 0.01 82);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.72 0.08 145);
/* Surface elevation (dark mode: higher = lighter) */ --card: oklch(0.19 0.022 240);
--surface-base: oklch(0.145 0 0); --card-foreground: oklch(0.96 0.006 245);
--surface-raised: oklch(0.18 0 0);
--surface-overlay: oklch(0.22 0 0);
/* Semantic status - Dark mode (desaturated, lower contrast) */ --popover: oklch(0.18 0.022 240);
--status-confirmed-bg: oklch(0.25 0.06 145 / 40%); --popover-foreground: oklch(0.96 0.006 245);
--status-confirmed-border: oklch(0.35 0.06 145 / 60%);
--status-confirmed-text: oklch(0.7 0.08 145);
--status-pending-bg: oklch(0.25 0.06 75 / 40%); --primary: oklch(0.67 0.21 158);
--status-pending-border: oklch(0.35 0.06 75 / 60%); --primary-foreground: oklch(0.12 0.02 158);
--status-pending-text: oklch(0.75 0.08 75);
--status-cancelled-bg: oklch(0.25 0.06 25 / 40%); --secondary: oklch(0.235 0.024 240);
--status-cancelled-border: oklch(0.35 0.06 25 / 60%); --secondary-foreground: oklch(0.9 0.008 245);
--status-cancelled-text: oklch(0.75 0.08 25);
--status-noshow-bg: oklch(0.25 0.06 50 / 40%); --muted: oklch(0.24 0.022 240);
--status-noshow-border: oklch(0.35 0.06 50 / 60%); --muted-foreground: oklch(0.68 0.018 245);
--status-noshow-text: oklch(0.75 0.08 50);
--status-completed-bg: oklch(0.25 0.06 220 / 40%); --accent: oklch(0.28 0.06 158);
--status-completed-border: oklch(0.35 0.06 220 / 60%); --accent-foreground: oklch(0.9 0.04 158);
--status-completed-text: oklch(0.7 0.08 220);
/* Borders */ --destructive: oklch(0.66 0.23 25);
--border-subtle: oklch(1 0 0 / 6%); --destructive-foreground: oklch(0.98 0.01 25);
--border-default: oklch(1 0 0 / 10%);
--border-emphasis: oklch(1 0 0 / 18%);
/* Input */ --success: oklch(0.67 0.21 158);
--input-bg: oklch(1 0 0 / 10%); --success-foreground: oklch(0.12 0.02 158);
--input-border: oklch(1 0 0 / 15%);
--reserved: oklch(0.61 0.2 255);
--reserved-foreground: oklch(0.97 0.012 255);
--maintenance: oklch(0.66 0.23 25);
--maintenance-foreground: oklch(0.98 0.01 25);
--warning: oklch(0.78 0.17 75);
--warning-foreground: oklch(0.18 0.04 75);
--border: oklch(1 0 0 / 11%);
--input: oklch(1 0 0 / 14%);
--ring: oklch(0.67 0.21 158);
--chart-1: oklch(0.67 0.21 158);
--chart-2: oklch(0.61 0.2 255);
--chart-3: oklch(0.66 0.23 25);
--chart-4: oklch(0.78 0.17 75);
--chart-5: oklch(0.7 0.16 205);
--sidebar: oklch(0.165 0.02 240);
--sidebar-foreground: oklch(0.96 0.006 245);
--sidebar-primary: oklch(0.67 0.21 158);
--sidebar-primary-foreground: oklch(0.12 0.02 158);
--sidebar-accent: oklch(0.235 0.024 240);
--sidebar-accent-foreground: oklch(0.9 0.008 245);
--sidebar-border: oklch(1 0 0 / 11%);
--sidebar-ring: oklch(0.67 0.21 158);
} }
@layer base { @layer base {
* { * {
@apply border-border outline-ring/50; @apply border-border outline-ring/50;
} }
html {
@apply font-sans;
font-synthesis-weight: none;
text-rendering: optimizeLegibility;
}
body { body {
@apply bg-background text-foreground antialiased; @apply bg-background text-foreground antialiased;
background-image: radial-gradient(
circle at top left,
oklch(0.94 0.04 145 / 0.55),
transparent 32%
), radial-gradient(circle at top right, oklch(0.96 0.03 220 / 0.45), transparent 28%),
linear-gradient(
to bottom,
oklch(0.99 0.005 145),
oklch(0.985 0.01 145) 28%,
oklch(0.97 0.01 145)
);
background-attachment: fixed;
} }
.dark body {
background-image: radial-gradient( button:not(:disabled),
circle at top left, [role="button"]:not(:disabled) {
oklch(0.32 0.08 145 / 0.35), cursor: pointer;
transparent 32% }
), radial-gradient(circle at top right, oklch(0.26 0.05 220 / 0.2), transparent 28%), }
linear-gradient(to bottom, oklch(0.15 0.015 145), oklch(0.14 0.015 145));
} @layer utilities {
::selection { .booking-scrollbar {
background: color-mix(in oklab, var(--primary) 28%, transparent); scrollbar-color: oklch(0.67 0.21 158 / 62%) oklch(1 0 0 / 8%);
color: var(--foreground); scrollbar-width: thin;
}
.booking-scrollbar::-webkit-scrollbar {
height: 12px;
}
.booking-scrollbar::-webkit-scrollbar-track {
background: oklch(1 0 0 / 6%);
border-radius: 999px;
}
.booking-scrollbar::-webkit-scrollbar-thumb {
background: linear-gradient(90deg, oklch(0.67 0.21 158 / 72%), oklch(0.61 0.2 255 / 58%));
border: 3px solid transparent;
border-radius: 999px;
background-clip: padding-box;
}
.booking-scrollbar::-webkit-scrollbar-thumb:hover {
background: linear-gradient(90deg, oklch(0.67 0.21 158 / 88%), oklch(0.61 0.2 255 / 72%));
border: 3px solid transparent;
background-clip: padding-box;
}
.public-booking-light {
background: #eaf2f4;
color: #0f172a;
}
.public-booking-light .public-booking-frame {
background: radial-gradient(circle at 18% 10%, rgba(16, 185, 129, 0.18), transparent 28%),
radial-gradient(circle at 82% 18%, rgba(59, 130, 246, 0.14), transparent 30%),
linear-gradient(180deg, #f8fbfc 0%, #edf5f7 52%, #e5eef2 100%);
}
.public-booking-light .public-booking-panel {
background: rgba(255, 255, 255, 0.78);
border-color: rgba(15, 23, 42, 0.13);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.72), 0 18px 48px rgba(15, 23, 42, 0.09);
}
.public-booking-light [class*="border-white"] {
border-color: rgba(15, 23, 42, 0.13);
}
.public-booking-light [class*="bg-white"] {
background-color: rgba(15, 23, 42, 0.045);
}
.public-booking-light [class*="text-white"] {
color: rgba(15, 23, 42, 0.72);
}
.public-booking-light .text-emerald-400,
.public-booking-light .text-cyan-300 {
color: #059669;
}
.public-booking-light .bg-emerald-500 {
background-color: #10b981;
}
.public-booking-light .text-red-300 {
color: #dc2626;
} }
} }

View File

@@ -0,0 +1,61 @@
import * as React from 'react';
type PossibleRef<T> = React.Ref<T> | undefined;
/**
* Set a given ref to a given value
* This utility takes care of different types of refs: callback refs and RefObject(s)
*/
function setRef<T>(ref: PossibleRef<T>, value: T) {
if (typeof ref === 'function') {
return ref(value);
}
if (ref !== null && ref !== undefined) {
ref.current = value;
}
}
/**
* A utility to compose multiple refs together
* Accepts callback refs and RefObject(s)
*/
function composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
return (node) => {
let hasCleanup = false;
const cleanups = refs.map((ref) => {
const cleanup = setRef(ref, node);
if (!hasCleanup && typeof cleanup === 'function') {
hasCleanup = true;
}
return cleanup;
});
// React <19 will log an error to the console if a callback ref returns a
// value. We don't use ref cleanups internally so this will only happen if a
// user's ref callback returns a value, which we only expect if they are
// using the cleanup functionality added in React 19.
if (hasCleanup) {
return () => {
for (let i = 0; i < cleanups.length; i++) {
const cleanup = cleanups[i];
if (typeof cleanup === 'function') {
cleanup();
} else {
setRef(refs[i], null);
}
}
};
}
};
}
/**
* A custom hook that composes multiple refs
* Accepts callback refs and RefObject(s)
*/
function useComposedRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
return React.useCallback(composeRefs(...refs), refs);
}
export { composeRefs, useComposedRefs };

View File

@@ -1,6 +1,7 @@
import { import {
type PropsWithChildren, type PropsWithChildren,
createContext, createContext,
useCallback,
useContext, useContext,
useEffect, useEffect,
useMemo, useMemo,
@@ -14,6 +15,7 @@ type ThemeContextValue = {
theme: Theme; theme: Theme;
resolvedTheme: ResolvedTheme; resolvedTheme: ResolvedTheme;
setTheme: (theme: Theme) => void; setTheme: (theme: Theme) => void;
toggleTheme: () => void;
}; };
const THEME_STORAGE_KEY = 'theme'; const THEME_STORAGE_KEY = 'theme';
@@ -27,6 +29,18 @@ function applyResolvedTheme(theme: ResolvedTheme) {
document.documentElement.classList.toggle('dark', theme === 'dark'); document.documentElement.classList.toggle('dark', theme === 'dark');
} }
function isEditableElement(target: EventTarget | null) {
if (!(target instanceof HTMLElement)) return false;
const tagName = target.tagName.toLowerCase();
return (
tagName === 'input' ||
tagName === 'textarea' ||
tagName === 'select' ||
target.isContentEditable
);
}
export function ThemeProvider({ children }: PropsWithChildren) { export function ThemeProvider({ children }: PropsWithChildren) {
const [theme, setThemeState] = useState<Theme>('system'); const [theme, setThemeState] = useState<Theme>('system');
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>('light'); const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>('light');
@@ -54,18 +68,37 @@ export function ThemeProvider({ children }: PropsWithChildren) {
return () => mediaQuery.removeEventListener('change', updateTheme); return () => mediaQuery.removeEventListener('change', updateTheme);
}, [theme]); }, [theme]);
const setTheme = (nextTheme: Theme) => { const setTheme = useCallback((nextTheme: Theme) => {
setThemeState(nextTheme); setThemeState(nextTheme);
localStorage.setItem(THEME_STORAGE_KEY, nextTheme); localStorage.setItem(THEME_STORAGE_KEY, nextTheme);
}, []);
const toggleTheme = useCallback(() => {
setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');
}, [resolvedTheme, setTheme]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (isEditableElement(event.target)) return;
if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
if (event.key.toLowerCase() !== 'd') return;
event.preventDefault();
toggleTheme();
}; };
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [toggleTheme]);
const value = useMemo<ThemeContextValue>( const value = useMemo<ThemeContextValue>(
() => ({ () => ({
theme, theme,
resolvedTheme, resolvedTheme,
setTheme, setTheme,
toggleTheme,
}), }),
[theme, resolvedTheme] [theme, resolvedTheme, setTheme, toggleTheme]
); );
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>; return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;

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