diff options
| author | Alberto Duarte Delgado <alberto@albertoduarte.com> | 2026-04-01 00:56:41 +0100 |
|---|---|---|
| committer | Alberto Duarte Delgado <alberto@albertoduarte.com> | 2026-04-01 00:56:41 +0100 |
| commit | bd4a70dab890153617cad4e0be1364941993d51d (patch) | |
| tree | 5242c256c3e96f8768b29907716fb1274eb9c1fb /src/features/reservations/services/reservationsService.ts | |
| parent | dac9dc1ae6b3531c93801360147100950a103692 (diff) | |
firestore rules y logica de cancelación de reservas
Diffstat (limited to 'src/features/reservations/services/reservationsService.ts')
| -rw-r--r-- | src/features/reservations/services/reservationsService.ts | 115 |
1 files changed, 110 insertions, 5 deletions
diff --git a/src/features/reservations/services/reservationsService.ts b/src/features/reservations/services/reservationsService.ts index e56a302..e58308d 100644 --- a/src/features/reservations/services/reservationsService.ts +++ b/src/features/reservations/services/reservationsService.ts @@ -1,9 +1,10 @@ import { - addDoc, collection, + doc, getDocs, orderBy, query, + runTransaction, serverTimestamp, where, } from 'firebase/firestore'; @@ -11,8 +12,13 @@ import { db } from '@/shared/lib/firebase/config'; import { CreateReservationInput, Reservation, + ReservationStatus, } from '@/features/reservations/types'; +function mapReservationStatus(value: unknown): ReservationStatus { + return value === 'cancelled' ? 'cancelled' : 'active'; +} + function mapReservation(id: string, data: any): Reservation { return { id, @@ -23,15 +29,108 @@ function mapReservation(id: string, data: any): Reservation { date: data.date ?? '', startTime: data.startTime ?? '', endTime: data.endTime ?? '', + status: mapReservationStatus(data.status), createdAt: data.createdAt, }; } +const RESERVATION_CONFLICT_ERROR = 'RESERVATION_CONFLICT'; + +function parseTimeToMinutes(value: string): number { + const [hours, minutes] = value.split(':').map(Number); + return hours * 60 + minutes; +} + +function formatMinuteSlot(totalMinutes: number): string { + const hours = Math.floor(totalMinutes / 60); + const minutes = totalMinutes % 60; + + return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`; +} + +function buildReservationLockIds(input: { + officeId: string; + date: string; + startTime: string; + endTime: string; +}): string[] { + const startMinutes = parseTimeToMinutes(input.startTime); + const endMinutes = parseTimeToMinutes(input.endTime); + const lockIds: string[] = []; + + for (let minute = startMinutes; minute < endMinutes; minute += 1) { + lockIds.push( + `${input.officeId}__${input.date}__${formatMinuteSlot(minute)}` + ); + } + + return lockIds; +} + export const reservationsService = { async create(input: CreateReservationInput): Promise<void> { - await addDoc(collection(db, 'reservations'), { - ...input, - createdAt: serverTimestamp(), + const reservationsCollection = collection(db, 'reservations'); + const reservationLocksCollection = collection(db, 'reservationLocks'); + const reservationRef = doc(reservationsCollection); + const lockIds = buildReservationLockIds(input); + + await runTransaction(db, async (transaction) => { + for (const lockId of lockIds) { + const lockRef = doc(reservationLocksCollection, lockId); + const lockSnapshot = await transaction.get(lockRef); + + if (lockSnapshot.exists()) { + throw new Error(RESERVATION_CONFLICT_ERROR); + } + + transaction.set(lockRef, { + reservationId: reservationRef.id, + userId: input.userId, + officeId: input.officeId, + date: input.date, + time: lockId.split('__')[2], + }); + } + + transaction.set(reservationRef, { + ...input, + lockIds, + status: 'active', + createdAt: serverTimestamp(), + }); + }); + }, + + async cancel(reservationId: string): Promise<void> { + const reservationRef = doc(db, 'reservations', reservationId); + const reservationLocksCollection = collection(db, 'reservationLocks'); + + await runTransaction(db, async (transaction) => { + const reservationSnapshot = await transaction.get(reservationRef); + + if (!reservationSnapshot.exists()) { + throw new Error('La reserva no existe'); + } + + const reservation = mapReservation(reservationSnapshot.id, reservationSnapshot.data()); + + if (reservation.status === 'cancelled') { + return; + } + + const storedLockIds = reservationSnapshot.data().lockIds; + const lockIds = + Array.isArray(storedLockIds) && storedLockIds.every((value) => typeof value === 'string') + ? storedLockIds + : buildReservationLockIds(reservation); + + for (const lockId of lockIds) { + transaction.delete(doc(reservationLocksCollection, lockId)); + } + + transaction.update(reservationRef, { + status: 'cancelled', + }); }); }, @@ -58,6 +157,12 @@ export const reservationsService = { const snapshot = await getDocs(q); - return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data())); + return snapshot.docs + .map((item) => mapReservation(item.id, item.data())) + .filter((reservation) => reservation.status === 'active'); }, }; + +export function isReservationConflictError(error: unknown): boolean { + return error instanceof Error && error.message === RESERVATION_CONFLICT_ERROR; +} |