diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/app/(protected)/(tabs)/reservations/index.tsx | 85 | ||||
| -rw-r--r-- | src/db/schema.ts | 73 | ||||
| -rw-r--r-- | src/features/profile/services/profileService.ts | 12 | ||||
| -rw-r--r-- | src/features/reservations/domain/hasReservationConflict.ts | 4 | ||||
| -rw-r--r-- | src/features/reservations/hooks/useCreateReservation.ts | 27 | ||||
| -rw-r--r-- | src/features/reservations/hooks/useReservations.ts | 17 | ||||
| -rw-r--r-- | src/features/reservations/services/reservationsService.ts | 115 | ||||
| -rw-r--r-- | src/features/reservations/types.ts | 3 |
8 files changed, 274 insertions, 62 deletions
diff --git a/src/app/(protected)/(tabs)/reservations/index.tsx b/src/app/(protected)/(tabs)/reservations/index.tsx index 56f7832..a2a0d9d 100644 --- a/src/app/(protected)/(tabs)/reservations/index.tsx +++ b/src/app/(protected)/(tabs)/reservations/index.tsx @@ -1,5 +1,6 @@ import { ActivityIndicator, + Alert, FlatList, Pressable, StyleSheet, @@ -9,7 +10,31 @@ import { import { useReservations } from '@/features/reservations/hooks/useReservations'; export default function ReservationsScreen() { - const { reservations, loading, error, reload } = useReservations(); + const { + reservations, + loading, + error, + reload, + cancelReservation, + cancelingReservationId, + } = useReservations(); + + const handleCancelReservation = (reservationId: string) => { + Alert.alert( + 'Cancelar reserva', + 'Esta acción marcará la reserva como cancelada.', + [ + { text: 'Volver', style: 'cancel' }, + { + text: 'Cancelar reserva', + style: 'destructive', + onPress: () => { + void cancelReservation(reservationId); + }, + }, + ] + ); + }; if (loading) { return ( @@ -43,10 +68,36 @@ export default function ReservationsScreen() { } renderItem={({ item }) => ( <View style={styles.card}> - <Text style={styles.cardTitle}>{item.officeName}</Text> + <View style={styles.cardHeader}> + <Text style={styles.cardTitle}>{item.officeName}</Text> + <View + style={[ + styles.statusBadge, + item.status === 'active' ? styles.statusActive : styles.statusCancelled, + ]} + > + <Text style={styles.statusText}> + {item.status === 'active' ? 'Activa' : 'Cancelada'} + </Text> + </View> + </View> <Text>Fecha: {item.date}</Text> <Text>Inicio: {item.startTime}</Text> <Text>Fin: {item.endTime}</Text> + + {item.status === 'active' ? ( + <Pressable + style={styles.cancelButton} + onPress={() => handleCancelReservation(item.id)} + disabled={cancelingReservationId === item.id} + > + <Text style={styles.buttonText}> + {cancelingReservationId === item.id + ? 'Cancelando...' + : 'Cancelar reserva'} + </Text> + </Pressable> + ) : null} </View> )} /> @@ -80,9 +131,32 @@ const styles = StyleSheet.create({ padding: 16, gap: 6, }, + cardHeader: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + gap: 12, + }, cardTitle: { fontSize: 18, fontWeight: '600', + flex: 1, + }, + statusBadge: { + borderRadius: 999, + paddingHorizontal: 10, + paddingVertical: 4, + }, + statusActive: { + backgroundColor: '#d7f5df', + }, + statusCancelled: { + backgroundColor: '#f3d8d8', + }, + statusText: { + fontSize: 12, + fontWeight: '700', + color: '#333', }, error: { color: 'red', @@ -98,6 +172,13 @@ const styles = StyleSheet.create({ color: '#fff', fontWeight: '600', }, + cancelButton: { + backgroundColor: '#c62828', + paddingVertical: 12, + borderRadius: 10, + alignItems: 'center', + marginTop: 8, + }, empty: { color: '#666', }, diff --git a/src/db/schema.ts b/src/db/schema.ts index 322d78d..d15bea8 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -1,43 +1,52 @@ -; import { relations } from 'drizzle-orm'; -import { integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core'; -export const personas = sqliteTable('personas', { - id: integer('id').primaryKey({ autoIncrement: true }), - nombre: text('nombre').notNull(), - edad: integer('edad'), -}); - - - - -/* -export const categorias = sqliteTable('categorias', { - id: integer('id').primaryKey({ autoIncrement: true }), - nombre: text('nombre').unique().notNull(), - +import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'; +export const users = sqliteTable('users', { + uid: text('uid').primaryKey(), + email: text('email').notNull(), + displayName: text('display_name').notNull(), + photoURL: text('photo_url'), }); - -export const productos = sqliteTable('productos', { - id: integer('id').primaryKey({ autoIncrement: true }), - nombre: text('nombre').unique().notNull(), - stock: integer('stock'), - precio: real('precio'), - categoriaId: integer('categoria_id').references(() => categorias.id), +export const offices = sqliteTable('offices', { + id: text('id').primaryKey(), + name: text('name').notNull(), + location: text('location').notNull(), + capacity: integer('capacity').notNull(), + description: text('description'), }); +export const reservations = sqliteTable('reservations', { + id: text('id').primaryKey(), + officeId: text('office_id') + .notNull() + .references(() => offices.id), + userId: text('user_id') + .notNull() + .references(() => users.uid), + officeName: text('office_name').notNull(), + userEmail: text('user_email').notNull(), + date: text('date').notNull(), + startTime: text('start_time').notNull(), + endTime: text('end_time').notNull(), + createdAt: integer('created_at'), +}); - -export const categoriasRelations = relations(categorias, ({ many }) => ({ - productos: many(productos), +export const usersRelations = relations(users, ({ many }) => ({ + reservations: many(reservations), })); -export const productosRelations = relations(productos, ({ one }) => ({ - pais: one(categorias, { - fields: [productos.categoriaId], - references: [categorias.id], - }), +export const officesRelations = relations(offices, ({ many }) => ({ + reservations: many(reservations), })); -*/
\ No newline at end of file +export const reservationsRelations = relations(reservations, ({ one }) => ({ + office: one(offices, { + fields: [reservations.officeId], + references: [offices.id], + }), + user: one(users, { + fields: [reservations.userId], + references: [users.uid], + }), +})); 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; }; |