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 {
formatAvailableSlots,
getAvailableTimeSlots,
} from "@/features/reservations/domain/getAvailableTimeSlots";
import { validateReservation } from "@/features/reservations/domain/validateReservation";
import {
isReservationConflictError,
reservationsService,
} from "@/features/reservations/services/reservationsService";
import { CreateReservationInput } from "@/features/reservations/types";
import { useAuthSession } from "@/providers/AuthProvider";
import { getErrorMessage } from "@/shared/lib/errors/getErrorMessage";
import { router } from "expo-router";
import { useState } from "react";
import { Alert, Platform } from "react-native";
type UseCreateReservationParams = {
officeId?: string;
officeName?: string;
};
// obtiene la fecha de hoy en formato YYYY-MM-DD
function getTodayDate(): string {
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, "0");
const day = String(today.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
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,
}: UseCreateReservationParams) {
const { user } = useAuthSession();
const [date, setDate] = useState(getTodayDate());
const [startTime, setStartTime] = useState("");
const [endTime, setEndTime] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = 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);
setIsSubmitting(true);
const input: CreateReservationInput = {
officeId: officeId ?? "",
officeName: officeName ?? "",
userId: user?.uid ?? "",
userEmail: user?.email ?? "",
date: date.trim(),
startTime: startTime.trim(),
endTime: endTime.trim(),
};
const validationError = validateReservation(input);
if (validationError) {
setError(validationError);
return;
}
await reservationsService.create(input);
// mostrar popup de confirmacion
if (Platform.OS === "web") {
const confirmed = window.confirm("Reserva creada correctamente");
if (confirmed) {
router.replace("/(protected)/(tabs)/reservations");
}
} else {
Alert.alert("¡Éxito!", "Reserva creada correctamente", [
{
text: "OK",
onPress: () => router.replace("/(protected)/(tabs)/reservations"),
},
]);
}
} catch (err) {
if (isReservationConflictError(err)) {
// cuando hay conflicto, obtener las reservas de ese dia
const reservasDelDia = await reservationsService.getByOfficeAndDate(
officeId ?? "",
date.trim(),
);
// calcular las franjas disponibles considerando las reservas existentes
const availableSlots = getAvailableTimeSlots(
date.trim(),
reservasDelDia,
);
// formatear las franjas como mensaje legible
const slotsMessage = formatAvailableSlots(availableSlots);
// mostrar error con las franjas disponibles
setError(
`Ya existe una reserva que se solapa con ese horario.\n\n${slotsMessage}`,
);
return;
}
setError(getErrorMessage(err, "No se pudo crear la reserva"));
} finally {
setIsSubmitting(false);
}
};
return {
date,
startTime,
endTime,
isFormComplete,
isSubmitting,
error,
setDate: handleDateChange,
setStartTime: handleStartTimeChange,
setEndTime: handleEndTimeChange,
submit,
};
}
|