summaryrefslogtreecommitdiffstats
path: root/src/features
diff options
context:
space:
mode:
Diffstat (limited to 'src/features')
-rw-r--r--src/features/profile/services/profileService.ts12
-rw-r--r--src/features/reservations/domain/hasReservationConflict.ts4
-rw-r--r--src/features/reservations/hooks/useCreateReservation.ts27
-rw-r--r--src/features/reservations/hooks/useReservations.ts17
-rw-r--r--src/features/reservations/services/reservationsService.ts115
-rw-r--r--src/features/reservations/types.ts3
6 files changed, 150 insertions, 28 deletions
diff --git a/src/features/profile/services/profileService.ts b/src/features/profile/services/profileService.ts
index 566c3fa..f7e89b4 100644
--- a/src/features/profile/services/profileService.ts
+++ b/src/features/profile/services/profileService.ts
@@ -1,6 +1,6 @@
// src/features/profile/services/profileService.ts
-import { doc, getDoc, updateDoc } from 'firebase/firestore';
+import { doc, getDoc, setDoc } from 'firebase/firestore';
import { updateProfile } from 'firebase/auth';
import { db, auth } from '@/shared/lib/firebase/config';
import { UserProfile } from '@/features/profile/types';
@@ -29,14 +29,16 @@ export const profileService = {
photoURL?: string;
}): Promise<void> {
const { uid, displayName, photoURL } = params;
+ const currentUser = auth.currentUser;
- await updateDoc(doc(db, 'users', uid), {
+ await setDoc(doc(db, 'users', uid), {
+ email: currentUser?.email ?? '',
displayName,
...(photoURL !== undefined ? { photoURL } : {}),
- });
+ }, { merge: true });
- if (auth.currentUser) {
- await updateProfile(auth.currentUser, {
+ if (currentUser) {
+ await updateProfile(currentUser, {
displayName,
...(photoURL !== undefined ? { photoURL } : {}),
});
diff --git a/src/features/reservations/domain/hasReservationConflict.ts b/src/features/reservations/domain/hasReservationConflict.ts
index e246c00..c2348de 100644
--- a/src/features/reservations/domain/hasReservationConflict.ts
+++ b/src/features/reservations/domain/hasReservationConflict.ts
@@ -16,6 +16,10 @@ export function hasReservationConflict({
endTime,
}: ConflictParams): boolean {
return existingReservations.some((reservation) => {
+ if (reservation.status !== 'active') {
+ return false;
+ }
+
if (reservation.officeId !== officeId) {
return false;
}
diff --git a/src/features/reservations/hooks/useCreateReservation.ts b/src/features/reservations/hooks/useCreateReservation.ts
index 5361894..2b6830c 100644
--- a/src/features/reservations/hooks/useCreateReservation.ts
+++ b/src/features/reservations/hooks/useCreateReservation.ts
@@ -1,8 +1,10 @@
import { useState } from 'react';
import { router } from 'expo-router';
-import { reservationsService } from '@/features/reservations/services/reservationsService';
+import {
+ isReservationConflictError,
+ reservationsService,
+} from '@/features/reservations/services/reservationsService';
import { validateReservation } from '@/features/reservations/domain/validateReservation';
-import { hasReservationConflict } from '@/features/reservations/domain/hasReservationConflict';
import { CreateReservationInput } from '@/features/reservations/types';
import { useAuthSession } from '@/providers/AuthProvider';
@@ -47,22 +49,6 @@ export function useCreateReservation({
return;
}
- const existingReservations =
- await reservationsService.getByOfficeAndDate(input.officeId, input.date);
-
- const hasConflict = hasReservationConflict({
- existingReservations,
- officeId: input.officeId,
- date: input.date,
- startTime: input.startTime,
- endTime: input.endTime,
- });
-
- if (hasConflict) {
- setError('Ya existe una reserva que se solapa con ese horario');
- return;
- }
-
await reservationsService.create(input);
setSuccessMessage('Reserva creada correctamente');
@@ -72,6 +58,11 @@ export function useCreateReservation({
router.replace('/(protected)/(tabs)/reservations');
} catch (err: any) {
+ if (isReservationConflictError(err)) {
+ setError('Ya existe una reserva que se solapa con ese horario');
+ return;
+ }
+
setError(err?.message ?? 'No se pudo crear la reserva');
} finally {
setIsSubmitting(false);
diff --git a/src/features/reservations/hooks/useReservations.ts b/src/features/reservations/hooks/useReservations.ts
index c993c89..abeecf5 100644
--- a/src/features/reservations/hooks/useReservations.ts
+++ b/src/features/reservations/hooks/useReservations.ts
@@ -9,6 +9,7 @@ export function useReservations() {
const [reservations, setReservations] = useState<Reservation[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
+ const [cancelingReservationId, setCancelingReservationId] = useState<string | null>(null);
const loadReservations = async () => {
if (!user?.uid) {
@@ -34,10 +35,26 @@ export function useReservations() {
loadReservations();
}, [user?.uid]);
+ const cancelReservation = async (reservationId: string) => {
+ try {
+ setError(null);
+ setCancelingReservationId(reservationId);
+
+ await reservationsService.cancel(reservationId);
+ await loadReservations();
+ } catch (err: any) {
+ setError(err?.message ?? 'No se pudo cancelar la reserva');
+ } finally {
+ setCancelingReservationId(null);
+ }
+ };
+
return {
reservations,
loading,
error,
+ cancelingReservationId,
+ cancelReservation,
reload: loadReservations,
};
}
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;
+}
diff --git a/src/features/reservations/types.ts b/src/features/reservations/types.ts
index b04b980..5900ac7 100644
--- a/src/features/reservations/types.ts
+++ b/src/features/reservations/types.ts
@@ -1,3 +1,5 @@
+export type ReservationStatus = 'active' | 'cancelled';
+
export type Reservation = {
id: string;
officeId: string;
@@ -7,6 +9,7 @@ export type Reservation = {
date: string;
startTime: string;
endTime: string;
+ status: ReservationStatus;
createdAt?: unknown;
};