summaryrefslogtreecommitdiffstats
path: root/src/features/reservations/services/reservationsService.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/features/reservations/services/reservationsService.ts')
-rw-r--r--src/features/reservations/services/reservationsService.ts391
1 files changed, 323 insertions, 68 deletions
diff --git a/src/features/reservations/services/reservationsService.ts b/src/features/reservations/services/reservationsService.ts
index 176bbce..ac67001 100644
--- a/src/features/reservations/services/reservationsService.ts
+++ b/src/features/reservations/services/reservationsService.ts
@@ -1,4 +1,15 @@
import {
+ CreateReservationInput,
+ Reservation,
+ ReservationStatus,
+} from "@/features/reservations/types";
+import { db } from "@/shared/lib/firebase/config";
+import {
+ mockDelay,
+ mockReservationLocks,
+ mockReservations,
+} from "@/shared/lib/mockData";
+import {
collection,
doc,
getDocs,
@@ -6,44 +17,40 @@ import {
query,
runTransaction,
serverTimestamp,
- writeBatch,
where,
-} from 'firebase/firestore';
-import { db } from '@/shared/lib/firebase/config';
-import {
- CreateReservationInput,
- Reservation,
- ReservationStatus,
-} from '@/features/reservations/types';
+ writeBatch,
+} from "firebase/firestore";
+
+const USE_MOCK = process.env.EXPO_PUBLIC_USE_MOCK_DATA === "true";
function mapReservationStatus(value: unknown): ReservationStatus {
- if (value === 'completed') {
- return 'completed';
+ if (value === "completed") {
+ return "completed";
}
- return value === 'cancelled' ? 'cancelled' : 'active';
+ return value === "cancelled" ? "cancelled" : "active";
}
function mapReservation(id: string, data: any): Reservation {
return {
id,
- officeId: data.officeId ?? '',
- officeName: data.officeName ?? '',
- userId: data.userId ?? '',
- userEmail: data.userEmail ?? '',
- date: data.date ?? '',
- startTime: data.startTime ?? '',
- endTime: data.endTime ?? '',
+ officeId: data.officeId ?? "",
+ officeName: data.officeName ?? "",
+ userId: data.userId ?? "",
+ userEmail: data.userEmail ?? "",
+ date: data.date ?? "",
+ startTime: data.startTime ?? "",
+ endTime: data.endTime ?? "",
status: mapReservationStatus(data.status),
checkInAt: data.checkInAt,
createdAt: data.createdAt,
};
}
-const RESERVATION_CONFLICT_ERROR = 'RESERVATION_CONFLICT';
+const RESERVATION_CONFLICT_ERROR = "RESERVATION_CONFLICT";
function parseTimeToMinutes(value: string): number {
- const [hours, minutes] = value.split(':').map(Number);
+ const [hours, minutes] = value.split(":").map(Number);
return hours * 60 + minutes;
}
@@ -51,7 +58,7 @@ 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')}`;
+ return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
}
function buildReservationLockIds(input: {
@@ -66,19 +73,26 @@ function buildReservationLockIds(input: {
for (let minute = startMinutes; minute < endMinutes; minute += 1) {
lockIds.push(
- `${input.officeId}__${input.date}__${formatMinuteSlot(minute)}`
+ `${input.officeId}__${input.date}__${formatMinuteSlot(minute)}`,
);
}
return lockIds;
}
-function getReservationEndDate(reservation: Pick<Reservation, 'date' | 'endTime'>): Date {
+function getReservationEndDate(
+ reservation: Pick<Reservation, "date" | "endTime">,
+): Date {
return new Date(`${reservation.date}T${reservation.endTime}:00`);
}
-function isPastActiveReservation(reservation: Reservation, now = new Date()): boolean {
- return reservation.status === 'active' && getReservationEndDate(reservation) < now;
+function isPastActiveReservation(
+ reservation: Reservation,
+ now = new Date(),
+): boolean {
+ return (
+ reservation.status === "active" && getReservationEndDate(reservation) < now
+ );
}
type ReservationRecord = {
@@ -88,15 +102,52 @@ type ReservationRecord = {
export const reservationsService = {
async create(input: CreateReservationInput): Promise<void> {
- const reservationsCollection = collection(db, 'reservations');
- const reservationLocksCollection = collection(db, 'reservationLocks');
+ if (USE_MOCK) {
+ await mockDelay();
+ const lockId = `${input.officeId}__${input.date}__${input.startTime}`;
+ const newLockIds = buildReservationLockIds(input);
+
+ // Simular conflicto si hay locks existentes
+ for (const lockId of newLockIds) {
+ if (mockReservationLocks[lockId]) {
+ throw new Error(RESERVATION_CONFLICT_ERROR);
+ }
+ }
+
+ // Crear locks simulados
+ for (const lockId of newLockIds) {
+ mockReservationLocks[lockId] = {
+ reservationId: `res-mock-${Date.now()}`,
+ userId: input.userId,
+ officeId: input.officeId,
+ date: input.date,
+ time: lockId.split("__")[2],
+ };
+ }
+
+ // Agregar reserva al array simulado
+ mockReservations.push({
+ id: `res-mock-${Date.now()}`,
+ ...input,
+ lockIds: newLockIds,
+ status: "active",
+ createdAt: new Date(),
+ checkInAt: null,
+ });
+ return;
+ }
+
+ const reservationsCollection = collection(db, "reservations");
+ const reservationLocksCollection = collection(db, "reservationLocks");
const reservationRef = doc(reservationsCollection);
const lockIds = buildReservationLockIds(input);
await runTransaction(db, async (transaction) => {
- const lockRefs = lockIds.map((lockId) => doc(reservationLocksCollection, lockId));
+ const lockRefs = lockIds.map((lockId) =>
+ doc(reservationLocksCollection, lockId),
+ );
const lockSnapshots = await Promise.all(
- lockRefs.map((lockRef) => transaction.get(lockRef))
+ lockRefs.map((lockRef) => transaction.get(lockRef)),
);
for (const lockSnapshot of lockSnapshots) {
@@ -111,39 +162,63 @@ export const reservationsService = {
userId: input.userId,
officeId: input.officeId,
date: input.date,
- time: lockIds[index].split('__')[2],
+ time: lockIds[index].split("__")[2],
});
}
transaction.set(reservationRef, {
...input,
lockIds,
- status: 'active',
+ status: "active",
createdAt: serverTimestamp(),
});
});
},
async cancel(reservationId: string): Promise<void> {
- const reservationRef = doc(db, 'reservations', reservationId);
- const reservationLocksCollection = collection(db, 'reservationLocks');
+ if (USE_MOCK) {
+ await mockDelay();
+ const reservation = mockReservations.find((r) => r.id === reservationId);
+ if (!reservation) {
+ throw new Error("La reserva no existe");
+ }
+ if (reservation.status === "cancelled") {
+ return;
+ }
+ reservation.status = "cancelled";
+
+ // Limpiar locks simulados
+ const lockIds =
+ reservation.lockIds || buildReservationLockIds(reservation);
+ for (const lockId of lockIds) {
+ delete mockReservationLocks[lockId];
+ }
+ return;
+ }
+
+ 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');
+ throw new Error("La reserva no existe");
}
- const reservation = mapReservation(reservationSnapshot.id, reservationSnapshot.data());
+ const reservation = mapReservation(
+ reservationSnapshot.id,
+ reservationSnapshot.data(),
+ );
- if (reservation.status === 'cancelled') {
+ if (reservation.status === "cancelled") {
return;
}
const storedLockIds = reservationSnapshot.data().lockIds;
const lockIds =
- Array.isArray(storedLockIds) && storedLockIds.every((value) => typeof value === 'string')
+ Array.isArray(storedLockIds) &&
+ storedLockIds.every((value) => typeof value === "string")
? storedLockIds
: buildReservationLockIds(reservation);
@@ -152,25 +227,44 @@ export const reservationsService = {
}
transaction.update(reservationRef, {
- status: 'cancelled',
+ status: "cancelled",
});
});
},
async checkIn(reservationId: string): Promise<void> {
- const reservationRef = doc(db, 'reservations', reservationId);
+ if (USE_MOCK) {
+ await mockDelay();
+ const reservation = mockReservations.find((r) => r.id === reservationId);
+ if (!reservation) {
+ throw new Error("La reserva no existe");
+ }
+ if (reservation.status !== "active") {
+ throw new Error("Solo puedes hacer check-in en reservas activas");
+ }
+ if (reservation.checkInAt) {
+ return;
+ }
+ reservation.checkInAt = new Date();
+ return;
+ }
+
+ const reservationRef = doc(db, "reservations", reservationId);
await runTransaction(db, async (transaction) => {
const reservationSnapshot = await transaction.get(reservationRef);
if (!reservationSnapshot.exists()) {
- throw new Error('La reserva no existe');
+ throw new Error("La reserva no existe");
}
- const reservation = mapReservation(reservationSnapshot.id, reservationSnapshot.data());
+ const reservation = mapReservation(
+ reservationSnapshot.id,
+ reservationSnapshot.data(),
+ );
- if (reservation.status !== 'active') {
- throw new Error('Solo puedes hacer check-in en reservas activas');
+ if (reservation.status !== "active") {
+ throw new Error("Solo puedes hacer check-in en reservas activas");
}
if (reservation.checkInAt) {
@@ -184,35 +278,49 @@ export const reservationsService = {
},
async getByUserId(userId: string): Promise<Reservation[]> {
+ if (USE_MOCK) {
+ await mockDelay();
+ return mockReservations
+ .filter((r) => r.userId === userId)
+ .sort((a, b) => {
+ const dateCompare = a.date.localeCompare(b.date);
+ if (dateCompare !== 0) return dateCompare;
+ return a.startTime.localeCompare(b.startTime);
+ });
+ }
+
const q = query(
- collection(db, 'reservations'),
- where('userId', '==', userId),
- orderBy('date', 'asc'),
- orderBy('startTime', 'asc')
+ collection(db, "reservations"),
+ where("userId", "==", userId),
+ orderBy("date", "asc"),
+ orderBy("startTime", "asc"),
);
const snapshot = await getDocs(q);
- const reservationRecords: ReservationRecord[] = snapshot.docs.map((snapshotDoc) => {
- const rawData = snapshotDoc.data() as Record<string, unknown>;
-
- return {
- reservation: mapReservation(snapshotDoc.id, rawData),
- rawData,
- };
- });
+ const reservationRecords: ReservationRecord[] = snapshot.docs.map(
+ (snapshotDoc) => {
+ const rawData = snapshotDoc.data() as Record<string, unknown>;
+
+ return {
+ reservation: mapReservation(snapshotDoc.id, rawData),
+ rawData,
+ };
+ },
+ );
const reservations = reservationRecords.map((record) => record.reservation);
const reservationsToComplete = reservationRecords.filter((record) =>
- isPastActiveReservation(record.reservation)
+ isPastActiveReservation(record.reservation),
);
if (reservationsToComplete.length > 0) {
const batch = writeBatch(db);
- const reservationLocksCollection = collection(db, 'reservationLocks');
+ const reservationLocksCollection = collection(db, "reservationLocks");
for (const { reservation, rawData } of reservationsToComplete) {
const storedLockIds = rawData.lockIds;
const lockIds =
- Array.isArray(storedLockIds) && storedLockIds.every((value) => typeof value === 'string')
+ Array.isArray(storedLockIds) &&
+ storedLockIds.every((value) => typeof value === "string")
? storedLockIds
: buildReservationLockIds(reservation);
@@ -220,8 +328,8 @@ export const reservationsService = {
batch.delete(doc(reservationLocksCollection, lockId));
}
- batch.update(doc(db, 'reservations', reservation.id), {
- status: 'completed',
+ batch.update(doc(db, "reservations", reservation.id), {
+ status: "completed",
});
}
@@ -229,27 +337,174 @@ export const reservationsService = {
return reservations.map((reservation) =>
isPastActiveReservation(reservation)
- ? { ...reservation, status: 'completed' }
- : reservation
+ ? { ...reservation, status: "completed" }
+ : reservation,
);
}
return reservations;
},
- async getByOfficeAndDate(officeId: string, date: string): Promise<Reservation[]> {
+ async getByOfficeAndDate(
+ officeId: string,
+ date: string,
+ ): Promise<Reservation[]> {
+ if (USE_MOCK) {
+ await mockDelay();
+ return mockReservations
+ .filter(
+ (r) =>
+ r.officeId === officeId && r.date === date && r.status === "active",
+ )
+ .sort((a, b) => a.startTime.localeCompare(b.startTime));
+ }
+
const q = query(
- collection(db, 'reservations'),
- where('officeId', '==', officeId),
- where('date', '==', date),
- where('status', '==', 'active'),
- orderBy('startTime', 'asc')
+ collection(db, "reservations"),
+ where("officeId", "==", officeId),
+ where("date", "==", date),
+ where("status", "==", "active"),
+ orderBy("startTime", "asc"),
);
const snapshot = await getDocs(q);
return snapshot.docs.map((item) => mapReservation(item.id, item.data()));
},
+
+ async update(input: {
+ reservationId: string;
+ userId: string;
+ officeId: string;
+ date: string;
+ startTime: string;
+ endTime: string;
+ oldDate: string;
+ oldStartTime: string;
+ oldEndTime: string;
+ }): Promise<void> {
+ if (USE_MOCK) {
+ await mockDelay();
+ const reservation = mockReservations.find(
+ (r) => r.id === input.reservationId,
+ );
+
+ if (!reservation) {
+ throw new Error("La reserva no existe");
+ }
+
+ // Generar nuevos bloqueos
+ const newLockIds = buildReservationLockIds({
+ officeId: input.officeId,
+ date: input.date,
+ startTime: input.startTime,
+ endTime: input.endTime,
+ });
+
+ // Verificar conflictos
+ for (const lockId of newLockIds) {
+ if (mockReservationLocks[lockId]) {
+ throw new Error(RESERVATION_CONFLICT_ERROR);
+ }
+ }
+
+ // Limpiar locks antiguos
+ const oldLockIds = buildReservationLockIds({
+ officeId: input.officeId,
+ date: input.oldDate,
+ startTime: input.oldStartTime,
+ endTime: input.oldEndTime,
+ });
+
+ for (const lockId of oldLockIds) {
+ delete mockReservationLocks[lockId];
+ }
+
+ // Crear nuevos locks
+ for (const lockId of newLockIds) {
+ mockReservationLocks[lockId] = {
+ reservationId: input.reservationId,
+ userId: input.userId,
+ officeId: input.officeId,
+ date: input.date,
+ time: lockId.split("__")[2],
+ };
+ }
+
+ // Actualizar reserva
+ reservation.date = input.date;
+ reservation.startTime = input.startTime;
+ reservation.endTime = input.endTime;
+ reservation.lockIds = newLockIds;
+ return;
+ }
+
+ const reservationRef = doc(db, "reservations", input.reservationId);
+ const reservationLocksCollection = collection(db, "reservationLocks");
+
+ // generar los bloqueos antiguos que necesitan ser eliminados
+ const oldLockIds = buildReservationLockIds({
+ officeId: input.officeId,
+ date: input.oldDate,
+ startTime: input.oldStartTime,
+ endTime: input.oldEndTime,
+ });
+
+ // generar los nuevos bloqueos que se van a crear
+ const newLockIds = buildReservationLockIds({
+ officeId: input.officeId,
+ date: input.date,
+ startTime: input.startTime,
+ endTime: input.endTime,
+ });
+
+ await runTransaction(db, async (transaction) => {
+ // verificar que la reserva existe
+ const reservationSnapshot = await transaction.get(reservationRef);
+
+ if (!reservationSnapshot.exists()) {
+ throw new Error("La reserva no existe");
+ }
+
+ // verificar que todos los nuevos bloqueos estan disponibles
+ const newLockRefs = newLockIds.map((lockId) =>
+ doc(reservationLocksCollection, lockId),
+ );
+ const newLockSnapshots = await Promise.all(
+ newLockRefs.map((lockRef) => transaction.get(lockRef)),
+ );
+
+ for (const lockSnapshot of newLockSnapshots) {
+ if (lockSnapshot.exists()) {
+ throw new Error(RESERVATION_CONFLICT_ERROR);
+ }
+ }
+
+ // eliminar los bloqueos antiguos
+ for (const lockId of oldLockIds) {
+ transaction.delete(doc(reservationLocksCollection, lockId));
+ }
+
+ // crear los nuevos bloqueos
+ for (const [index, lockRef] of newLockRefs.entries()) {
+ transaction.set(lockRef, {
+ reservationId: input.reservationId,
+ userId: input.userId,
+ officeId: input.officeId,
+ date: input.date,
+ time: newLockIds[index].split("__")[2],
+ });
+ }
+
+ // actualizar la reserva con los nuevos datos y bloqueos
+ transaction.update(reservationRef, {
+ date: input.date,
+ startTime: input.startTime,
+ endTime: input.endTime,
+ lockIds: newLockIds,
+ });
+ });
+ },
};
export function isReservationConflictError(error: unknown): boolean {