diff options
| -rw-r--r-- | drizzle/0000_high_night_nurse.sql | 5 | ||||
| -rw-r--r-- | drizzle/0001_brief_mandrill.sql | 16 | ||||
| -rw-r--r-- | drizzle/0002_sleepy_ink.sql | 2 | ||||
| -rw-r--r-- | drizzle/meta/0000_snapshot.json | 49 | ||||
| -rw-r--r-- | drizzle/meta/0001_snapshot.json | 148 | ||||
| -rw-r--r-- | drizzle/meta/0002_snapshot.json | 49 | ||||
| -rw-r--r-- | drizzle/meta/_journal.json | 26 | ||||
| -rw-r--r-- | drizzle/migrations.js | 16 | ||||
| -rw-r--r-- | firebase.json | 5 | ||||
| -rw-r--r-- | firestore.rules | 69 | ||||
| -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 |
18 files changed, 354 insertions, 367 deletions
diff --git a/drizzle/0000_high_night_nurse.sql b/drizzle/0000_high_night_nurse.sql deleted file mode 100644 index 9afda09..0000000 --- a/drizzle/0000_high_night_nurse.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TABLE `personas` ( - `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, - `nombre` text NOT NULL, - `edad` integer -); diff --git a/drizzle/0001_brief_mandrill.sql b/drizzle/0001_brief_mandrill.sql deleted file mode 100644 index 0866313..0000000 --- a/drizzle/0001_brief_mandrill.sql +++ /dev/null @@ -1,16 +0,0 @@ -CREATE TABLE `categorias` ( - `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, - `nombre` text NOT NULL -); ---> statement-breakpoint -CREATE UNIQUE INDEX `categorias_nombre_unique` ON `categorias` (`nombre`);--> statement-breakpoint -CREATE TABLE `productos` ( - `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, - `nombre` text NOT NULL, - `stock` integer, - `precio` real, - `categoria_id` integer, - FOREIGN KEY (`categoria_id`) REFERENCES `categorias`(`id`) ON UPDATE no action ON DELETE no action -); ---> statement-breakpoint -CREATE UNIQUE INDEX `productos_nombre_unique` ON `productos` (`nombre`);
\ No newline at end of file diff --git a/drizzle/0002_sleepy_ink.sql b/drizzle/0002_sleepy_ink.sql deleted file mode 100644 index a8f70e0..0000000 --- a/drizzle/0002_sleepy_ink.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE `categorias`;--> statement-breakpoint -DROP TABLE `productos`;
\ No newline at end of file diff --git a/drizzle/meta/0000_snapshot.json b/drizzle/meta/0000_snapshot.json deleted file mode 100644 index b1a67a1..0000000 --- a/drizzle/meta/0000_snapshot.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "d8e12abb-238e-41bb-9928-c817d6d92575", - "prevId": "00000000-0000-0000-0000-000000000000", - "tables": { - "personas": { - "name": "personas", - "columns": { - "id": { - "name": "id", - "type": "integer", - "primaryKey": true, - "notNull": true, - "autoincrement": true - }, - "nombre": { - "name": "nombre", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "edad": { - "name": "edad", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - } - }, - "views": {}, - "enums": {}, - "_meta": { - "schemas": {}, - "tables": {}, - "columns": {} - }, - "internal": { - "indexes": {} - } -}
\ No newline at end of file diff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.json deleted file mode 100644 index db0cea6..0000000 --- a/drizzle/meta/0001_snapshot.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "5ae3a6d7-6e57-40ba-846c-1f66fceb7e00", - "prevId": "d8e12abb-238e-41bb-9928-c817d6d92575", - "tables": { - "categorias": { - "name": "categorias", - "columns": { - "id": { - "name": "id", - "type": "integer", - "primaryKey": true, - "notNull": true, - "autoincrement": true - }, - "nombre": { - "name": "nombre", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "categorias_nombre_unique": { - "name": "categorias_nombre_unique", - "columns": [ - "nombre" - ], - "isUnique": true - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "personas": { - "name": "personas", - "columns": { - "id": { - "name": "id", - "type": "integer", - "primaryKey": true, - "notNull": true, - "autoincrement": true - }, - "nombre": { - "name": "nombre", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "edad": { - "name": "edad", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "productos": { - "name": "productos", - "columns": { - "id": { - "name": "id", - "type": "integer", - "primaryKey": true, - "notNull": true, - "autoincrement": true - }, - "nombre": { - "name": "nombre", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "stock": { - "name": "stock", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "precio": { - "name": "precio", - "type": "real", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "categoria_id": { - "name": "categoria_id", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": { - "productos_nombre_unique": { - "name": "productos_nombre_unique", - "columns": [ - "nombre" - ], - "isUnique": true - } - }, - "foreignKeys": { - "productos_categoria_id_categorias_id_fk": { - "name": "productos_categoria_id_categorias_id_fk", - "tableFrom": "productos", - "tableTo": "categorias", - "columnsFrom": [ - "categoria_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - } - }, - "views": {}, - "enums": {}, - "_meta": { - "schemas": {}, - "tables": {}, - "columns": {} - }, - "internal": { - "indexes": {} - } -}
\ No newline at end of file diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json deleted file mode 100644 index ae0b584..0000000 --- a/drizzle/meta/0002_snapshot.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "abb95522-5cc0-48db-8649-e1aeee626edc", - "prevId": "5ae3a6d7-6e57-40ba-846c-1f66fceb7e00", - "tables": { - "personas": { - "name": "personas", - "columns": { - "id": { - "name": "id", - "type": "integer", - "primaryKey": true, - "notNull": true, - "autoincrement": true - }, - "nombre": { - "name": "nombre", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "edad": { - "name": "edad", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - } - }, - "views": {}, - "enums": {}, - "_meta": { - "schemas": {}, - "tables": {}, - "columns": {} - }, - "internal": { - "indexes": {} - } -}
\ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index c913af9..4377507 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -1,27 +1,5 @@ { "version": "7", "dialect": "sqlite", - "entries": [ - { - "idx": 0, - "version": "6", - "when": 1768914263303, - "tag": "0000_high_night_nurse", - "breakpoints": true - }, - { - "idx": 1, - "version": "6", - "when": 1774354496154, - "tag": "0001_brief_mandrill", - "breakpoints": true - }, - { - "idx": 2, - "version": "6", - "when": 1774356468737, - "tag": "0002_sleepy_ink", - "breakpoints": true - } - ] -}
\ No newline at end of file + "entries": [] +} diff --git a/drizzle/migrations.js b/drizzle/migrations.js index 7a10df8..f5d641f 100644 --- a/drizzle/migrations.js +++ b/drizzle/migrations.js @@ -1,16 +1,8 @@ // This file is required for Expo/React Native SQLite migrations - https://orm.drizzle.team/quick-sqlite/expo import journal from './meta/_journal.json'; -import m0000 from './0000_high_night_nurse.sql'; -import m0001 from './0001_brief_mandrill.sql'; -import m0002 from './0002_sleepy_ink.sql'; - export default { - journal, - migrations: { - m0000, -m0001, -m0002 - } - } -
\ No newline at end of file +export default { + journal, + migrations: {}, +}; diff --git a/firebase.json b/firebase.json new file mode 100644 index 0000000..0207c3f --- /dev/null +++ b/firebase.json @@ -0,0 +1,5 @@ +{ + "firestore": { + "rules": "firestore.rules" + } +} diff --git a/firestore.rules b/firestore.rules new file mode 100644 index 0000000..49dad7c --- /dev/null +++ b/firestore.rules @@ -0,0 +1,69 @@ +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + function isSignedIn() { + return request.auth != null; + } + + function isOwner(userId) { + return isSignedIn() && request.auth.uid == userId; + } + + function reservationCreateIsValid() { + return request.resource.data.userId == request.auth.uid + && request.resource.data.userEmail is string + && request.resource.data.officeId is string + && request.resource.data.officeName is string + && request.resource.data.date is string + && request.resource.data.startTime is string + && request.resource.data.endTime is string + && request.resource.data.status == 'active'; + } + + function reservationUpdateIsValid() { + return request.resource.data.userId == resource.data.userId + && request.resource.data.officeId == resource.data.officeId + && request.resource.data.officeName == resource.data.officeName + && request.resource.data.userEmail == resource.data.userEmail + && request.resource.data.date == resource.data.date + && request.resource.data.startTime == resource.data.startTime + && request.resource.data.endTime == resource.data.endTime + && request.resource.data.status in ['active', 'cancelled']; + } + + match /users/{userId} { + allow create: if isOwner(userId); + allow read: if isOwner(userId); + allow update: if isOwner(userId); + allow delete: if false; + } + + match /offices/{officeId} { + allow read: if isSignedIn(); + allow write: if false; + } + + match /reservations/{reservationId} { + allow create: if isSignedIn() && reservationCreateIsValid(); + allow read: if isOwner(resource.data.userId); + allow update: if isOwner(resource.data.userId) && reservationUpdateIsValid(); + allow delete: if false; + } + + match /reservationLocks/{lockId} { + allow read: if isSignedIn(); + allow create: if isSignedIn() + && request.resource.data.userId == request.auth.uid + && request.resource.data.officeId is string + && request.resource.data.date is string + && request.resource.data.time is string + && request.resource.data.reservationId is string; + allow delete: if isOwner(resource.data.userId); + allow update: if false; + } + + match /{document=**} { + allow read, write: if false; + } + } +} 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; }; |