From ed52756173468bfe98cdb62d95483b4949b27351 Mon Sep 17 00:00:00 2001 From: Anita Date: Sun, 19 Apr 2026 19:20:09 +0100 Subject: feat(reservations): edición de reservas + validación de disponibilidad + mejoras de flujo refs #7 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/(protected)/(tabs)/reservations/index.tsx | 220 +++++++++++-------- src/app/(protected)/reservations/create.tsx | 250 ++++++++++++++-------- 2 files changed, 294 insertions(+), 176 deletions(-) (limited to 'src/app') diff --git a/src/app/(protected)/(tabs)/reservations/index.tsx b/src/app/(protected)/(tabs)/reservations/index.tsx index 8eaa80e..e790cb4 100644 --- a/src/app/(protected)/(tabs)/reservations/index.tsx +++ b/src/app/(protected)/(tabs)/reservations/index.tsx @@ -1,4 +1,8 @@ -import { useState } from 'react'; +import { useReservations } from "@/features/reservations/hooks/useReservations"; +import theme from "@/theme"; +import { MaterialIcons } from "@expo/vector-icons"; +import { useRouter } from "expo-router"; +import { useState } from "react"; import { ActivityIndicator, Alert, @@ -8,12 +12,10 @@ import { StyleSheet, Text, View, -} from 'react-native'; -import { MaterialIcons } from '@expo/vector-icons'; -import theme from '@/theme'; -import { useReservations } from '@/features/reservations/hooks/useReservations'; +} from "react-native"; -const { colors, spacing, radius, typography, fontWeight, layout, shadows } = theme; +const { colors, spacing, radius, typography, fontWeight, layout, shadows } = + theme; function getReservationWindowStart(date: string, startTime: string): Date { return new Date(`${date}T${startTime}:00`); @@ -27,7 +29,8 @@ function canCheckIn(date: string, startTime: string, endTime: string): boolean { const now = new Date(); const reservationStart = getReservationWindowStart(date, startTime); const reservationEnd = getReservationWindowEnd(date, endTime); - const checkInOpensAt = new Date(reservationStart.getTime() - 15 * 60 * 1000); + // permitir check-in desde 30 minutos antes de la hora de la reserva + const checkInOpensAt = new Date(reservationStart.getTime() - 30 * 60 * 1000); return now >= checkInOpensAt && now <= reservationEnd; } @@ -35,30 +38,33 @@ function canCheckIn(date: string, startTime: string, endTime: string): boolean { function hasToDate(value: unknown): value is { toDate: () => Date } { return ( !!value && - typeof value === 'object' && - 'toDate' in value && - typeof value.toDate === 'function' + typeof value === "object" && + "toDate" in value && + typeof value.toDate === "function" ); } function formatCheckInAt(value: unknown): string { if (!hasToDate(value)) { - return 'Registrada'; + return "Registrada"; } const date = value.toDate(); if (!(date instanceof Date) || Number.isNaN(date.getTime())) { - return 'Registrada'; + return "Registrada"; } - return new Intl.DateTimeFormat('es-ES', { - dateStyle: 'short', - timeStyle: 'short', + return new Intl.DateTimeFormat("es-ES", { + dateStyle: "short", + timeStyle: "short", }).format(date); } export default function ReservationsScreen() { + // router para navegar a otras pantallas + const router = useRouter(); + // hook principal de reservas const { activeReservations, @@ -73,14 +79,14 @@ export default function ReservationsScreen() { } = useReservations(); // controla la pestaña visible de reservas - const [activeTab, setActiveTab] = useState<'active' | 'history'>('active'); + const [activeTab, setActiveTab] = useState<"active" | "history">("active"); // confirmacion antes de cancelar una reserva // en web usamos window.confirm porque Alert puede no comportarse bien const handleCancelReservation = (reservationId: string) => { - if (Platform.OS === 'web') { + if (Platform.OS === "web") { const confirmed = window.confirm( - 'Esta acción marcará la reserva como cancelada.' + "Esta acción marcará la reserva como cancelada.", ); if (confirmed) { @@ -91,18 +97,18 @@ export default function ReservationsScreen() { } // en movil sigue usando el Alert Alert.alert( - 'Cancelar reserva', - 'Esta acción marcará la reserva como cancelada.', + "Cancelar reserva", + "Esta acción marcará la reserva como cancelada.", [ - { text: 'Volver', style: 'cancel' }, + { text: "Volver", style: "cancel" }, { - text: 'Cancelar reserva', - style: 'destructive', + text: "Cancelar reserva", + style: "destructive", onPress: () => { void cancelReservation(reservationId); }, }, - ] + ], ); }; @@ -145,14 +151,14 @@ export default function ReservationsScreen() { setActiveTab('active')} + onPress={() => setActiveTab("active")} > Activas ({activeReservations.length}) @@ -162,14 +168,14 @@ export default function ReservationsScreen() { setActiveTab('history')} + onPress={() => setActiveTab("history")} > Historial ({historyReservations.length}) @@ -178,7 +184,7 @@ export default function ReservationsScreen() { {/* seccion de reservas activas */} - {activeTab === 'active' ? ( + {activeTab === "active" ? ( Activas @@ -186,7 +192,9 @@ export default function ReservationsScreen() { {activeReservations.length === 0 ? ( - No tienes reservas activas + + No tienes reservas activas + Cuando realices una nueva reserva, aparecerá aquí. @@ -212,7 +220,9 @@ export default function ReservationsScreen() { - + Activa @@ -249,7 +259,7 @@ export default function ReservationsScreen() { {item.checkInAt ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}` - : 'Llegada pendiente'} + : "Llegada pendiente"} @@ -257,8 +267,9 @@ export default function ReservationsScreen() { {/* linea separadora antes de acciones */} - {/* boton de check-in visible siempre de forma temporal para ajustar diseño */} - {!item.checkInAt ? ( + {/* boton de check-in solo visible cuando se puede hacer check-in */} + {!item.checkInAt && + canCheckIn(item.date, item.startTime, item.endTime) ? ( { @@ -268,8 +279,8 @@ export default function ReservationsScreen() { > {checkingInReservationId === item.id - ? 'Registrando llegada...' - : 'He llegado'} + ? "Registrando llegada..." + : "He llegado"} ) : null} @@ -282,6 +293,21 @@ export default function ReservationsScreen() { styles.editButton, pressed && styles.editButtonPressed, ]} + onPress={() => { + // navegar a create en modo edicion, pasando los parametros necesarios + router.push({ + pathname: "/(protected)/reservations/create", + params: { + mode: "edit", + reservationId: item.id, + officeId: item.officeId, + officeName: item.officeName, + oldDate: item.date, + oldStartTime: item.startTime, + oldEndTime: item.endTime, + }, + }); + }} > Editar @@ -296,9 +322,15 @@ export default function ReservationsScreen() { disabled={cancelingReservationId === item.id} > - + - {cancelingReservationId === item.id ? 'Cancelando...' : 'Cancelar'} + {cancelingReservationId === item.id + ? "Cancelando..." + : "Cancelar"} @@ -310,7 +342,7 @@ export default function ReservationsScreen() { ) : null} {/* seccion historial */} - {activeTab === 'history' ? ( + {activeTab === "history" ? ( Historial @@ -339,14 +371,16 @@ export default function ReservationsScreen() { {item.officeName} - Reserva finalizada + + Reserva finalizada + - {item.status === 'completed' ? 'Completada' : 'Cancelada'} + {item.status === "completed" + ? "Completada" + : "Cancelada"} @@ -395,7 +431,7 @@ export default function ReservationsScreen() { {item.checkInAt ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}` - : 'Llegada no registrada'} + : "Llegada no registrada"} @@ -431,10 +467,10 @@ const styles = StyleSheet.create({ fontSize: typography.xxl, fontWeight: fontWeight.semibold, color: colors.text, - textAlign: 'left', + textAlign: "left", maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", }, // scroll principal @@ -450,15 +486,15 @@ const styles = StyleSheet.create({ paddingBottom: spacing.xxxl, gap: spacing.xl, maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", }, // estado de carga / error center: { flex: 1, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", padding: spacing.xxxl, gap: spacing.md, backgroundColor: colors.background, @@ -471,9 +507,9 @@ const styles = StyleSheet.create({ // cabecera de seccion sectionHeader: { - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", }, // titulo de seccion @@ -485,9 +521,9 @@ const styles = StyleSheet.create({ // fila de pestañas superiores tabsRow: { - flexDirection: 'row', + flexDirection: "row", gap: spacing.sm, - backgroundColor: '#E9EEF5', + backgroundColor: "#E9EEF5", borderRadius: radius.xxl, padding: spacing.xs, }, @@ -497,7 +533,7 @@ const styles = StyleSheet.create({ flex: 1, paddingVertical: spacing.md, borderRadius: radius.xl, - alignItems: 'center', + alignItems: "center", }, // boton activo @@ -531,16 +567,16 @@ const styles = StyleSheet.create({ // cabecera de la tarjeta cardHeader: { - flexDirection: 'row', - alignItems: 'flex-start', - justifyContent: 'space-between', + flexDirection: "row", + alignItems: "flex-start", + justifyContent: "space-between", gap: spacing.md, }, // bloque izquierdo de la cabecera de la card cardHeaderLeft: { - flexDirection: 'row', - alignItems: 'flex-start', + flexDirection: "row", + alignItems: "flex-start", gap: spacing.md, flex: 1, }, @@ -551,8 +587,8 @@ const styles = StyleSheet.create({ height: 40, borderRadius: radius.md, backgroundColor: colors.primarySoft, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, // bloque de titulo de tarjeta @@ -583,17 +619,17 @@ const styles = StyleSheet.create({ // estado activa statusActive: { - backgroundColor: '#DCFCE7', + backgroundColor: "#DCFCE7", }, // estado completada statusCompleted: { - backgroundColor: '#DBEAFE', + backgroundColor: "#DBEAFE", }, // estado cancelada statusCancelled: { - backgroundColor: '#FEE2E2', + backgroundColor: "#FEE2E2", }, // texto base del estado @@ -604,17 +640,17 @@ const styles = StyleSheet.create({ // color texto activa statusTextActive: { - color: '#166534', + color: "#166534", }, // color texto completada statusTextCompleted: { - color: '#1D4ED8', + color: "#1D4ED8", }, // color texto cancelada statusTextCancelled: { - color: '#B91C1C', + color: "#B91C1C", }, // lista de detalles @@ -624,8 +660,8 @@ const styles = StyleSheet.create({ // fila individual de detalle detailRow: { - flexDirection: 'row', - alignItems: 'center', + flexDirection: "row", + alignItems: "center", gap: spacing.sm, }, @@ -649,7 +685,7 @@ const styles = StyleSheet.create({ paddingHorizontal: spacing.xl, paddingVertical: spacing.md, borderRadius: radius.md, - alignItems: 'center', + alignItems: "center", }, // texto del boton principal @@ -663,7 +699,7 @@ const styles = StyleSheet.create({ backgroundColor: colors.successBg, paddingVertical: spacing.md, borderRadius: radius.md, - alignItems: 'center', + alignItems: "center", marginTop: spacing.xs, }, @@ -676,28 +712,28 @@ const styles = StyleSheet.create({ // fila de acciones secundarias // coloca editar a la izquierda y cancelar a la derecha actionsRow: { - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', + flexDirection: "row", + justifyContent: "space-between", + alignItems: "center", marginTop: spacing.xs, }, - // boton editar reserva + // boton editar reserva editButton: { paddingVertical: spacing.sm, paddingHorizontal: spacing.md, borderRadius: radius.md, backgroundColor: colors.surface, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, // estado pulsado del boton editar editButtonPressed: { - backgroundColor: '#EAF2FF', + backgroundColor: "#EAF2FF", }, - // texto del boton editar + // texto del boton editar editButtonText: { color: colors.primary, fontWeight: fontWeight.medium, @@ -710,26 +746,26 @@ const styles = StyleSheet.create({ paddingHorizontal: spacing.md, borderRadius: radius.md, backgroundColor: colors.surface, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, // estado pulsado del boton cancelar cancelButtonPressed: { - backgroundColor: '#FEECEC', + backgroundColor: "#FEECEC", }, // texto del boton cancelar cancelButtonText: { - color: '#DC2626', + color: "#DC2626", fontWeight: fontWeight.medium, fontSize: typography.sm, }, // contenido interno del boton cancelar cancelContent: { - flexDirection: 'row', - alignItems: 'center', + flexDirection: "row", + alignItems: "center", gap: spacing.xs, }, @@ -760,6 +796,6 @@ const styles = StyleSheet.create({ // error general error: { color: colors.error, - textAlign: 'center', + textAlign: "center", }, -}); \ No newline at end of file +}); diff --git a/src/app/(protected)/reservations/create.tsx b/src/app/(protected)/reservations/create.tsx index 8d03275..4cddd33 100644 --- a/src/app/(protected)/reservations/create.tsx +++ b/src/app/(protected)/reservations/create.tsx @@ -1,4 +1,9 @@ -import { Link, useLocalSearchParams } from 'expo-router'; +import { useCreateReservation } from "@/features/reservations/hooks/useCreateReservation"; +import { useUpdateReservation } from "@/features/reservations/hooks/useUpdateReservation"; +import { StatusMessage } from "@/shared/ui/StatusMessage"; +import theme from "@/theme"; +import { MaterialIcons } from "@expo/vector-icons"; +import { Link, useLocalSearchParams, useRouter } from "expo-router"; import { KeyboardAvoidingView, Platform, @@ -8,27 +13,61 @@ import { Text, TextInput, View, -} from 'react-native'; -import { MaterialIcons } from '@expo/vector-icons'; -import theme from '@/theme'; -import { useCreateReservation } from '@/features/reservations/hooks/useCreateReservation'; -import { StatusMessage } from '@/shared/ui/StatusMessage'; +} from "react-native"; -const { colors, spacing, radius, typography, fontWeight, layout, shadows } = theme; +const { colors, spacing, radius, typography, fontWeight, layout, shadows } = + theme; export default function CreateReservationScreen() { + // router para navegar + const router = useRouter(); + // parametros recibidos al entrar desde otra pantalla const params = useLocalSearchParams<{ + mode?: string; + reservationId?: string; officeId?: string; officeName?: string; + date?: string; + startTime?: string; + endTime?: string; + oldDate?: string; + oldStartTime?: string; + oldEndTime?: string; }>(); + // determinar si estamos en modo crear o editar + const isEditMode = params.mode === "edit"; + + // extraer parametros de creacion const officeId = - typeof params.officeId === 'string' ? params.officeId : undefined; + typeof params.officeId === "string" ? params.officeId : undefined; const officeName = - typeof params.officeName === 'string' ? params.officeName : undefined; + typeof params.officeName === "string" ? params.officeName : undefined; + + // extraer parametros de edicion + const reservationId = + typeof params.reservationId === "string" ? params.reservationId : ""; + const oldDate = typeof params.oldDate === "string" ? params.oldDate : ""; + const oldStartTime = + typeof params.oldStartTime === "string" ? params.oldStartTime : ""; + const oldEndTime = + typeof params.oldEndTime === "string" ? params.oldEndTime : ""; + + // usar el hook correspondiente segun el modo + const createReservation = useCreateReservation({ officeId, officeName }); + const updateReservation = useUpdateReservation({ + reservationId, + officeId: officeId || params.officeId || "", + officeName: officeName || params.officeName || "", + oldDate, + oldStartTime, + oldEndTime, + }); + + // seleccionar el hook activo segun el modo + const hook = isEditMode ? updateReservation : createReservation; - // hook de creacion de reserva const { date, startTime, @@ -36,21 +75,22 @@ export default function CreateReservationScreen() { isFormComplete, isSubmitting, error, - successMessage, setDate, setStartTime, setEndTime, submit, - } = useCreateReservation({ officeId, officeName }); + } = hook; return ( {/* cabecera superior */} - Crear reserva + + {isEditMode ? "Editar reserva" : "Crear reserva"} + {/* texto introductorio */} - Nueva reserva + + {isEditMode ? "Editar reserva" : "Nueva reserva"} + - Selecciona el espacio, la fecha y el horario de tu reserva. + {isEditMode + ? "Actualiza el horario de tu reserva." + : "Selecciona el espacio, la fecha y el horario de tu reserva."} @@ -81,27 +125,29 @@ export default function CreateReservationScreen() { Espacio - {officeName ?? 'No indicado'} + {officeName ?? "No indicado"} {/* enlace para volver a oficinas */} - - - [ - styles.changeOfficeButton, - pressed && styles.changeOfficeButtonPressed, - ]} - > - - Cambiar oficina - - - - + {!isEditMode && ( + + + [ + styles.changeOfficeButton, + pressed && styles.changeOfficeButtonPressed, + ]} + > + + Cambiar oficina + + + + + )} {/* tarjeta de condiciones de reserva */} @@ -110,25 +156,15 @@ export default function CreateReservationScreen() { - + Horario permitido: de 08:00 a 20:00 - - - Duración mínima: 30 minutos - + + Duración mínima: 30 minutos @@ -137,9 +173,7 @@ export default function CreateReservationScreen() { size={16} color={colors.primary} /> - - Duración máxima: 8 horas - + Duración máxima: 8 horas @@ -153,21 +187,21 @@ export default function CreateReservationScreen() { Fecha {/* en web usamos calendario nativo */} - {Platform.OS === 'web' ? ( + {Platform.OS === "web" ? ( setDate(e.target.value)} - min={new Date().toISOString().split('T')[0]} + min={new Date().toISOString().split("T")[0]} style={{ height: 46, border: `1px solid ${colors.border}`, borderRadius: radius.md, - padding: '0 14px', + padding: "0 14px", fontSize: 14, color: colors.text, backgroundColor: colors.background, - outline: 'none', + outline: "none", }} /> ) : ( @@ -183,9 +217,9 @@ export default function CreateReservationScreen() { )} - {Platform.OS === 'web' - ? 'Selecciona una fecha en el calendario' - : 'Formato: YYYY-MM-DD'} + {Platform.OS === "web" + ? "Selecciona una fecha en el calendario" + : "Formato: YYYY-MM-DD"} @@ -222,11 +256,8 @@ export default function CreateReservationScreen() { {/* mensajes de error / exito */} {error ? : null} - {successMessage ? ( - - ) : null} - {/* boton principal de guardar */} + {/* boton principal de guardar / actualizar */} [ styles.primaryButton, @@ -240,10 +271,32 @@ export default function CreateReservationScreen() { disabled={!isFormComplete || isSubmitting} > - {isSubmitting ? 'Guardando...' : 'Guardar reserva'} + {isSubmitting + ? isEditMode + ? "Actualizando..." + : "Guardando..." + : isEditMode + ? "Actualizar reserva" + : "Guardar reserva"} + + {/* boton cancelar fuera de la tarjeta */} + {isEditMode && ( + [ + styles.cancelButton, + pressed && styles.cancelButtonPressed, + ]} + onPress={() => router.back()} + > + + + Cancelar + + + )} ); @@ -271,10 +324,10 @@ const styles = StyleSheet.create({ fontSize: typography.xxl, fontWeight: fontWeight.semibold, color: colors.text, - textAlign: 'left', + textAlign: "left", maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", }, // scroll principal @@ -290,8 +343,8 @@ const styles = StyleSheet.create({ paddingBottom: spacing.xxxl, gap: spacing.xl, maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", }, // bloque introductorio @@ -326,26 +379,26 @@ const styles = StyleSheet.create({ // tarjeta de condiciones con tono azul suave rulesCard: { - backgroundColor: '#F4F8FF', + backgroundColor: "#F4F8FF", borderRadius: radius.xxl, padding: spacing.lg, borderWidth: 1, - borderColor: '#D7E3F7', + borderColor: "#D7E3F7", gap: spacing.md, }, // cabecera de tarjeta cardHeader: { - flexDirection: 'row', - alignItems: 'flex-start', - justifyContent: 'space-between', + flexDirection: "row", + alignItems: "flex-start", + justifyContent: "space-between", gap: spacing.md, }, // bloque izquierdo de cabecera cardHeaderLeft: { - flexDirection: 'row', - alignItems: 'flex-start', + flexDirection: "row", + alignItems: "flex-start", gap: spacing.md, flex: 1, }, @@ -356,8 +409,8 @@ const styles = StyleSheet.create({ height: 40, borderRadius: radius.md, backgroundColor: colors.primarySoft, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, // bloque de textos de la tarjeta @@ -382,8 +435,8 @@ const styles = StyleSheet.create({ // boton secundario para cambiar oficina changeOfficeRow: { - width: '100%', - alignItems: 'flex-end', + width: "100%", + alignItems: "flex-end", }, changeOfficeButton: { paddingVertical: spacing.xs, @@ -393,7 +446,7 @@ const styles = StyleSheet.create({ // estado pulsado del boton cambiar oficina changeOfficeButtonPressed: { - backgroundColor: '#EAF2FF', + backgroundColor: "#EAF2FF", }, // texto del boton cambiar oficina @@ -424,8 +477,8 @@ const styles = StyleSheet.create({ // fila de una regla ruleRow: { - flexDirection: 'row', - alignItems: 'center', + flexDirection: "row", + alignItems: "center", gap: spacing.sm, }, @@ -443,7 +496,7 @@ const styles = StyleSheet.create({ // fila de campos de hora timeRow: { - flexDirection: 'row', + flexDirection: "row", gap: spacing.lg, }, @@ -481,19 +534,19 @@ const styles = StyleSheet.create({ backgroundColor: colors.primary, paddingVertical: spacing.lg, borderRadius: radius.md, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", marginTop: spacing.sm, }, // estado pulsado del boton principal primaryButtonPressed: { - backgroundColor: '#185DCB', + backgroundColor: "#185DCB", }, // boton deshabilitado primaryButtonDisabled: { - backgroundColor: '#8FB5EC', + backgroundColor: "#8FB5EC", }, // texto del boton principal @@ -502,4 +555,33 @@ const styles = StyleSheet.create({ fontWeight: fontWeight.semibold, fontSize: typography.md, }, -}); \ No newline at end of file + + // boton cancelar reserva + cancelButton: { + paddingVertical: spacing.sm, + paddingHorizontal: spacing.md, + borderRadius: radius.md, + backgroundColor: colors.surface, + alignItems: "center", + justifyContent: "center", + }, + + // estado pulsado del boton cancelar + cancelButtonPressed: { + backgroundColor: "#FEECEC", + }, + + // texto del boton cancelar + cancelButtonText: { + color: "#DC2626", + fontWeight: fontWeight.medium, + fontSize: typography.sm, + }, + + // contenido interno del boton cancelar + cancelContent: { + flexDirection: "row", + alignItems: "center", + gap: spacing.xs, + }, +}); -- cgit v1.2.3-54-g00ecf