summaryrefslogtreecommitdiffstats
path: root/src/features
diff options
context:
space:
mode:
authorAlberto Duarte Delgado <alberto@albertoduarte.com>2026-04-01 13:03:25 +0100
committerAlberto Duarte Delgado <alberto@albertoduarte.com>2026-04-01 13:03:25 +0100
commit08ce78dbd97ad792e163482f454f285557c7cdd0 (patch)
tree998ce8d7d48f8344d9ec34691809f2482cde5136 /src/features
parentc927739f8f221feabb6e19af2c2667eda905a2eb (diff)
Mejoras de UX y feedback de errores; y, manejo de status de reserva
Diffstat (limited to 'src/features')
-rw-r--r--src/features/auth/hooks/useLogin.ts5
-rw-r--r--src/features/auth/hooks/useRegister.ts5
-rw-r--r--src/features/offices/hooks/useOffice.ts5
-rw-r--r--src/features/offices/hooks/useOffices.ts5
-rw-r--r--src/features/profile/hooks/useProfile.ts5
-rw-r--r--src/features/profile/hooks/useUpdateProfile.ts5
-rw-r--r--src/features/reservations/domain/validateReservation.ts67
-rw-r--r--src/features/reservations/hooks/useCreateReservation.ts56
-rw-r--r--src/features/reservations/hooks/useReservations.ts11
-rw-r--r--src/features/reservations/services/reservationsService.ts61
-rw-r--r--src/features/reservations/types.ts2
11 files changed, 200 insertions, 27 deletions
diff --git a/src/features/auth/hooks/useLogin.ts b/src/features/auth/hooks/useLogin.ts
index 5e4c881..6af76c5 100644
--- a/src/features/auth/hooks/useLogin.ts
+++ b/src/features/auth/hooks/useLogin.ts
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { router } from 'expo-router';
import { authService } from '@/features/auth/services/authService';
+import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
export function useLogin() {
const [email, setEmail] = useState('');
@@ -19,8 +20,8 @@ export function useLogin() {
});
router.replace('/(protected)/home');
- } catch (err: any) {
- setError(err?.message ?? 'No se pudo iniciar sesión');
+ } catch (err) {
+ setError(getErrorMessage(err, 'No se pudo iniciar sesión'));
} finally {
setIsSubmitting(false);
}
diff --git a/src/features/auth/hooks/useRegister.ts b/src/features/auth/hooks/useRegister.ts
index 7b93e92..fe83d85 100644
--- a/src/features/auth/hooks/useRegister.ts
+++ b/src/features/auth/hooks/useRegister.ts
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { router } from 'expo-router';
import { authService } from '@/features/auth/services/authService';
+import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
export function useRegister() {
const [displayName, setDisplayName] = useState('');
@@ -21,8 +22,8 @@ export function useRegister() {
});
router.replace('/(protected)/home');
- } catch (err: any) {
- setError(err?.message ?? 'No se pudo registrar el usuario');
+ } catch (err) {
+ setError(getErrorMessage(err, 'No se pudo registrar el usuario'));
} finally {
setIsSubmitting(false);
}
diff --git a/src/features/offices/hooks/useOffice.ts b/src/features/offices/hooks/useOffice.ts
index 87d47b5..c737719 100644
--- a/src/features/offices/hooks/useOffice.ts
+++ b/src/features/offices/hooks/useOffice.ts
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { officesService } from '@/features/offices/services/officesService';
import { Office } from '@/features/offices/types';
+import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
export function useOffice(officeId?: string) {
const [office, setOffice] = useState<Office | null>(null);
@@ -27,8 +28,8 @@ export function useOffice(officeId?: string) {
}
setOffice(data);
- } catch (err: any) {
- setError(err?.message ?? 'No se pudo cargar la oficina');
+ } catch (err) {
+ setError(getErrorMessage(err, 'No se pudo cargar la oficina'));
} finally {
setLoading(false);
}
diff --git a/src/features/offices/hooks/useOffices.ts b/src/features/offices/hooks/useOffices.ts
index ff08f6c..99f8f8e 100644
--- a/src/features/offices/hooks/useOffices.ts
+++ b/src/features/offices/hooks/useOffices.ts
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { officesService } from '@/features/offices/services/officesService';
import { Office } from '@/features/offices/types';
+import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
export function useOffices() {
const [offices, setOffices] = useState<Office[]>([]);
@@ -14,8 +15,8 @@ export function useOffices() {
const data = await officesService.getAll();
setOffices(data);
- } catch (err: any) {
- setError(err?.message ?? 'No se pudieron cargar los espacios');
+ } catch (err) {
+ setError(getErrorMessage(err, 'No se pudieron cargar los espacios'));
} finally {
setLoading(false);
}
diff --git a/src/features/profile/hooks/useProfile.ts b/src/features/profile/hooks/useProfile.ts
index 82068f4..2f5278d 100644
--- a/src/features/profile/hooks/useProfile.ts
+++ b/src/features/profile/hooks/useProfile.ts
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import { useAuthSession } from '@/providers/AuthProvider';
import { profileService } from '@/features/profile/services/profileService';
import { UserProfile } from '@/features/profile/types';
+import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
export function useProfile() {
const { user } = useAuthSession();
@@ -25,8 +26,8 @@ export function useProfile() {
const data = await profileService.getMyProfile(user.uid);
setProfile(data);
- } catch (err: any) {
- setError(err?.message ?? 'No se pudo cargar el perfil');
+ } catch (err) {
+ setError(getErrorMessage(err, 'No se pudo cargar el perfil'));
} finally {
setLoading(false);
}
diff --git a/src/features/profile/hooks/useUpdateProfile.ts b/src/features/profile/hooks/useUpdateProfile.ts
index bc069dc..cd4a39a 100644
--- a/src/features/profile/hooks/useUpdateProfile.ts
+++ b/src/features/profile/hooks/useUpdateProfile.ts
@@ -3,6 +3,7 @@
import { useState } from 'react';
import { profileService } from '@/features/profile/services/profileService';
import { useAuthSession } from '@/providers/AuthProvider';
+import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
export function useUpdateProfile(initialDisplayName = '', initialPhotoURL = '') {
const { user } = useAuthSession();
@@ -37,8 +38,8 @@ export function useUpdateProfile(initialDisplayName = '', initialPhotoURL = '')
setPhotoURL(photoURL.trim());
setSuccessMessage('Perfil actualizado correctamente');
- } catch (err: any) {
- setError(err?.message ?? 'No se pudo actualizar el perfil');
+ } catch (err) {
+ setError(getErrorMessage(err, 'No se pudo actualizar el perfil'));
} finally {
setIsSubmitting(false);
}
diff --git a/src/features/reservations/domain/validateReservation.ts b/src/features/reservations/domain/validateReservation.ts
index 40055c0..93df375 100644
--- a/src/features/reservations/domain/validateReservation.ts
+++ b/src/features/reservations/domain/validateReservation.ts
@@ -1,5 +1,43 @@
import { CreateReservationInput } from '@/features/reservations/types';
+const ALLOWED_START_MINUTES = 8 * 60;
+const ALLOWED_END_MINUTES = 20 * 60;
+const MIN_DURATION_MINUTES = 30;
+const MAX_DURATION_MINUTES = 8 * 60;
+
+function isValidDate(value: string): boolean {
+ const [year, month, day] = value.split('-').map(Number);
+ const date = new Date(`${value}T00:00:00`);
+
+ return (
+ Number.isInteger(year) &&
+ Number.isInteger(month) &&
+ Number.isInteger(day) &&
+ !Number.isNaN(date.getTime()) &&
+ date.getFullYear() === year &&
+ date.getMonth() + 1 === month &&
+ date.getDate() === day
+ );
+}
+
+function isValidTime(value: string): boolean {
+ const [hours, minutes] = value.split(':').map(Number);
+
+ return (
+ Number.isInteger(hours) &&
+ Number.isInteger(minutes) &&
+ hours >= 0 &&
+ hours <= 23 &&
+ minutes >= 0 &&
+ minutes <= 59
+ );
+}
+
+function parseTimeToMinutes(value: string): number {
+ const [hours, minutes] = value.split(':').map(Number);
+ return hours * 60 + minutes;
+}
+
export function validateReservation(input: CreateReservationInput): string | null {
if (!input.officeId.trim()) {
return 'No se indicó una oficina válida';
@@ -34,14 +72,43 @@ export function validateReservation(input: CreateReservationInput): string | nul
return 'La fecha debe tener formato YYYY-MM-DD';
}
+ if (!isValidDate(input.date)) {
+ return 'La fecha indicada no es válida';
+ }
+
const timePattern = /^\d{2}:\d{2}$/;
if (!timePattern.test(input.startTime) || !timePattern.test(input.endTime)) {
return 'Las horas deben tener formato HH:MM';
}
+ if (!isValidTime(input.startTime) || !isValidTime(input.endTime)) {
+ return 'Indica horas válidas en formato 24h';
+ }
+
if (input.endTime <= input.startTime) {
return 'La hora de fin debe ser posterior a la de inicio';
}
+ const startMinutes = parseTimeToMinutes(input.startTime);
+ const endMinutes = parseTimeToMinutes(input.endTime);
+ const durationMinutes = endMinutes - startMinutes;
+
+ const reservationStart = new Date(`${input.date}T${input.startTime}:00`);
+ if (reservationStart.getTime() < Date.now()) {
+ return 'No puedes crear una reserva en una fecha u hora pasada';
+ }
+
+ if (startMinutes < ALLOWED_START_MINUTES || endMinutes > ALLOWED_END_MINUTES) {
+ return 'Las reservas solo están permitidas entre las 08:00 y las 20:00';
+ }
+
+ if (durationMinutes < MIN_DURATION_MINUTES) {
+ return 'La reserva debe durar al menos 30 minutos';
+ }
+
+ if (durationMinutes > MAX_DURATION_MINUTES) {
+ return 'La reserva no puede superar las 8 horas';
+ }
+
return null;
}
diff --git a/src/features/reservations/hooks/useCreateReservation.ts b/src/features/reservations/hooks/useCreateReservation.ts
index 2b6830c..00faa7c 100644
--- a/src/features/reservations/hooks/useCreateReservation.ts
+++ b/src/features/reservations/hooks/useCreateReservation.ts
@@ -7,12 +7,37 @@ import {
import { validateReservation } from '@/features/reservations/domain/validateReservation';
import { CreateReservationInput } from '@/features/reservations/types';
import { useAuthSession } from '@/providers/AuthProvider';
+import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
type UseCreateReservationParams = {
officeId?: string;
officeName?: string;
};
+function normalizeDateInput(value: string): string {
+ const digits = value.replace(/\D/g, '').slice(0, 8);
+
+ if (digits.length <= 4) {
+ return digits;
+ }
+
+ if (digits.length <= 6) {
+ return `${digits.slice(0, 4)}-${digits.slice(4)}`;
+ }
+
+ return `${digits.slice(0, 4)}-${digits.slice(4, 6)}-${digits.slice(6)}`;
+}
+
+function normalizeTimeInput(value: string): string {
+ const digits = value.replace(/\D/g, '').slice(0, 4);
+
+ if (digits.length <= 2) {
+ return digits;
+ }
+
+ return `${digits.slice(0, 2)}:${digits.slice(2)}`;
+}
+
export function useCreateReservation({
officeId,
officeName,
@@ -26,6 +51,26 @@ export function useCreateReservation({
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
+ const handleDateChange = (value: string) => {
+ setError(null);
+ setDate(normalizeDateInput(value));
+ };
+
+ const handleStartTimeChange = (value: string) => {
+ setError(null);
+ setStartTime(normalizeTimeInput(value));
+ };
+
+ const handleEndTimeChange = (value: string) => {
+ setError(null);
+ setEndTime(normalizeTimeInput(value));
+ };
+
+ const isFormComplete =
+ date.trim().length === 10 &&
+ startTime.trim().length === 5 &&
+ endTime.trim().length === 5;
+
const submit = async () => {
try {
setError(null);
@@ -57,13 +102,13 @@ export function useCreateReservation({
setEndTime('');
router.replace('/(protected)/(tabs)/reservations');
- } catch (err: any) {
+ } catch (err) {
if (isReservationConflictError(err)) {
setError('Ya existe una reserva que se solapa con ese horario');
return;
}
- setError(err?.message ?? 'No se pudo crear la reserva');
+ setError(getErrorMessage(err, 'No se pudo crear la reserva'));
} finally {
setIsSubmitting(false);
}
@@ -73,12 +118,13 @@ export function useCreateReservation({
date,
startTime,
endTime,
+ isFormComplete,
isSubmitting,
error,
successMessage,
- setDate,
- setStartTime,
- setEndTime,
+ setDate: handleDateChange,
+ setStartTime: handleStartTimeChange,
+ setEndTime: handleEndTimeChange,
submit,
};
}
diff --git a/src/features/reservations/hooks/useReservations.ts b/src/features/reservations/hooks/useReservations.ts
index abeecf5..cf58811 100644
--- a/src/features/reservations/hooks/useReservations.ts
+++ b/src/features/reservations/hooks/useReservations.ts
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
import { reservationsService } from '@/features/reservations/services/reservationsService';
import { Reservation } from '@/features/reservations/types';
import { useAuthSession } from '@/providers/AuthProvider';
+import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
export function useReservations() {
const { user } = useAuthSession();
@@ -24,8 +25,8 @@ export function useReservations() {
const data = await reservationsService.getByUserId(user.uid);
setReservations(data);
- } catch (err: any) {
- setError(err?.message ?? 'No se pudieron cargar las reservas');
+ } catch (err) {
+ setError(getErrorMessage(err, 'No se pudieron cargar las reservas'));
} finally {
setLoading(false);
}
@@ -42,8 +43,8 @@ export function useReservations() {
await reservationsService.cancel(reservationId);
await loadReservations();
- } catch (err: any) {
- setError(err?.message ?? 'No se pudo cancelar la reserva');
+ } catch (err) {
+ setError(getErrorMessage(err, 'No se pudo cancelar la reserva'));
} finally {
setCancelingReservationId(null);
}
@@ -51,6 +52,8 @@ export function useReservations() {
return {
reservations,
+ activeReservations: reservations.filter((reservation) => reservation.status === 'active'),
+ historyReservations: reservations.filter((reservation) => reservation.status !== 'active'),
loading,
error,
cancelingReservationId,
diff --git a/src/features/reservations/services/reservationsService.ts b/src/features/reservations/services/reservationsService.ts
index e58308d..4ddf436 100644
--- a/src/features/reservations/services/reservationsService.ts
+++ b/src/features/reservations/services/reservationsService.ts
@@ -6,6 +6,7 @@ import {
query,
runTransaction,
serverTimestamp,
+ writeBatch,
where,
} from 'firebase/firestore';
import { db } from '@/shared/lib/firebase/config';
@@ -16,6 +17,10 @@ import {
} from '@/features/reservations/types';
function mapReservationStatus(value: unknown): ReservationStatus {
+ if (value === 'completed') {
+ return 'completed';
+ }
+
return value === 'cancelled' ? 'cancelled' : 'active';
}
@@ -67,6 +72,14 @@ function buildReservationLockIds(input: {
return lockIds;
}
+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;
+}
+
export const reservationsService = {
async create(input: CreateReservationInput): Promise<void> {
const reservationsCollection = collection(db, 'reservations');
@@ -75,20 +88,24 @@ export const reservationsService = {
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);
+ const lockRefs = lockIds.map((lockId) => doc(reservationLocksCollection, lockId));
+ const lockSnapshots = await Promise.all(
+ lockRefs.map((lockRef) => transaction.get(lockRef))
+ );
+ for (const lockSnapshot of lockSnapshots) {
if (lockSnapshot.exists()) {
throw new Error(RESERVATION_CONFLICT_ERROR);
}
+ }
+ for (const [index, lockRef] of lockRefs.entries()) {
transaction.set(lockRef, {
reservationId: reservationRef.id,
userId: input.userId,
officeId: input.officeId,
date: input.date,
- time: lockId.split('__')[2],
+ time: lockIds[index].split('__')[2],
});
}
@@ -143,8 +160,42 @@ export const reservationsService = {
);
const snapshot = await getDocs(q);
+ const reservations = snapshot.docs.map((doc) => mapReservation(doc.id, doc.data()));
+ const reservationsToComplete = reservations.filter((reservation) =>
+ isPastActiveReservation(reservation)
+ );
+
+ if (reservationsToComplete.length > 0) {
+ const batch = writeBatch(db);
+ const reservationLocksCollection = collection(db, 'reservationLocks');
+
+ for (const reservation of reservationsToComplete) {
+ const snapshotData = snapshot.docs.find((doc) => doc.id === reservation.id)?.data();
+ const storedLockIds = snapshotData?.lockIds;
+ const lockIds =
+ Array.isArray(storedLockIds) && storedLockIds.every((value) => typeof value === 'string')
+ ? storedLockIds
+ : buildReservationLockIds(reservation);
+
+ for (const lockId of lockIds) {
+ batch.delete(doc(reservationLocksCollection, lockId));
+ }
+
+ batch.update(doc(db, 'reservations', reservation.id), {
+ status: 'completed',
+ });
+ }
+
+ await batch.commit();
+
+ return reservations.map((reservation) =>
+ isPastActiveReservation(reservation)
+ ? { ...reservation, status: 'completed' }
+ : reservation
+ );
+ }
- return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data()));
+ return reservations;
},
async getByOfficeAndDate(officeId: string, date: string): Promise<Reservation[]> {
diff --git a/src/features/reservations/types.ts b/src/features/reservations/types.ts
index 5900ac7..9a5fe73 100644
--- a/src/features/reservations/types.ts
+++ b/src/features/reservations/types.ts
@@ -1,4 +1,4 @@
-export type ReservationStatus = 'active' | 'cancelled';
+export type ReservationStatus = 'active' | 'completed' | 'cancelled';
export type Reservation = {
id: string;