1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
|
import {
collection,
doc,
getDocs,
orderBy,
query,
runTransaction,
serverTimestamp,
where,
} from 'firebase/firestore';
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,
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),
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> {
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',
});
});
},
async getByUserId(userId: string): Promise<Reservation[]> {
const q = query(
collection(db, 'reservations'),
where('userId', '==', userId),
orderBy('date', 'asc'),
orderBy('startTime', 'asc')
);
const snapshot = await getDocs(q);
return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data()));
},
async getByOfficeAndDate(officeId: string, date: string): Promise<Reservation[]> {
const q = query(
collection(db, 'reservations'),
where('officeId', '==', officeId),
where('date', '==', date),
orderBy('startTime', 'asc')
);
const snapshot = await getDocs(q);
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;
}
|