feat: implement StepEngine architecture for assistant onboarding and configuration flows

This commit is contained in:
2026-07-28 20:01:59 -03:00
parent 0a285776c7
commit c77d479344
27 changed files with 4036 additions and 3867 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,38 @@
import React from "react";
import QuestionCard from "../../QuestionCard/QuestionCard";
type Props = any;
export default function OrganizationPicker({ allOrganizations, loadOrganizationContext }: Props) {
return (
<QuestionCard
isActive={true}
title="Selecciona la Organización"
description="¿A qué negocio deseas aplicar estos cambios?"
onNext={() => {}}
disableNext={true}
nextLabel=""
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
{allOrganizations.map((org: any) => (
<div
key={org.id || org._id}
onClick={() => loadOrganizationContext(org)}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: 'rgba(255,255,255,0.05)',
border: '2px solid transparent',
color: 'white', transition: 'all 0.2s ease',
display: 'flex', flexDirection: 'column', alignItems: 'center'
}}
onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--wine-red)'}
onMouseLeave={(e) => e.currentTarget.style.borderColor = 'transparent'}
>
<h4 style={{ margin: '0 0 5px 0' }}>{org.name}</h4>
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>{org.street} {org.streetNumber}, {org.city}</p>
</div>
))}
</div>
</QuestionCard>
);
}
@@ -0,0 +1,79 @@
import React from "react";
type Props = any;
export default function SuccessScreen(props: Props) {
const { action, flowId, isStandaloneAction, router } = props;
const getSuccessMessage = () => {
if (action === "new-service") return "Has agregado tu nuevo servicio exitosamente.";
if (action === "edit-schedule") return "Tus horarios se han actualizado exitosamente.";
if (action === "edit-location") return "La ubicación de tu negocio ha sido actualizada.";
if (action === "edit-contact") return "Tus datos de contacto han sido actualizados.";
if (action === "edit-appearance") return "La apariencia de tu negocio ha sido actualizada.";
if (flowId === "override-schedule" || flowId === "disable-schedule") return "El horario especial ha sido guardado exitosamente.";
if (flowId === "new-collaborator") return "El colaborador fue invitado exitosamente.";
if (flowId === "setup-collaborator") return "El colaborador ha sido configurado exitosamente y ya puede comenzar a recibir reservas.";
if (flowId === "notifications") return "La configuración de notificaciones se ha guardado exitosamente.";
if (flowId === "whatsapp-bot") return "Tu bot de WhatsApp está configurado y funcionando. Tus clientes recibirán notificaciones automáticas por WhatsApp.";
if (flowId === "open-reservation-periods") return "El período de reservas fue extendido exitosamente.";
if (isStandaloneAction) return "Tus cambios se han guardado exitosamente.";
return "Has configurado exitosamente tu negocio. Todo está listo para que empieces a recibir reservas y gestionar tu agenda como un profesional.";
};
const successButtonStyle: React.CSSProperties = {
padding: '16px 40px', fontSize: '18px', fontWeight: 'bold',
background: 'white', color: 'var(--wine-red)', border: 'none',
borderRadius: '30px', cursor: 'pointer',
boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
transition: 'transform 0.2s, box-shadow 0.2s'
};
return (
<div style={{
position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh',
background: 'linear-gradient(135deg, #1a0515 0%, #300018 100%)',
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
zIndex: 9999, overflow: 'hidden', padding: '20px', boxSizing: 'border-box'
}}>
<div style={{
width: '120px', height: '120px', borderRadius: '50%', background: 'rgba(255,255,255,0.1)',
display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '30px',
boxShadow: '0 0 50px rgba(255, 255, 255, 0.2)',
animation: 'pulse 2s infinite ease-in-out'
}}>
<span style={{ fontSize: '60px' }}>🎉</span>
</div>
<h1 style={{ color: 'white', fontSize: '32px', marginBottom: '15px', textAlign: 'center', textShadow: '0 2px 10px rgba(0,0,0,0.5)' }}>
¡Felicitaciones!
</h1>
<p style={{ color: 'rgba(255,255,255,0.8)', fontSize: '18px', maxWidth: '500px', textAlign: 'center', marginBottom: '40px', lineHeight: '1.5' }}>
{getSuccessMessage()}
</p>
<button
onClick={() => {
if (isStandaloneAction) router.push("/admin/assistant");
else window.location.href = "/landing/dashboard";
}}
style={successButtonStyle}
onMouseOver={(e) => {
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 6px 20px rgba(255,255,255,0.3)';
}}
onMouseOut={(e) => {
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = '0 4px 15px rgba(0,0,0,0.3)';
}}
>
{isStandaloneAction ? "Volver al Menú Principal" : "Ir a mi Panel de Control"}
</button>
<style>{`
@keyframes pulse {
0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.4); }
70% { transform: scale(1.05); box-shadow: 0 0 0 30px rgba(255, 255, 255, 0); }
100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0); }
}
`}</style>
</div>
);
}
@@ -0,0 +1,18 @@
import { NotificationChannel } from "@models/NotificationPreferences.model";
export const NOTIF_CHANNELS: { key: NotificationChannel; label: string; description: string }[] = [
{ key: "whatsapp", label: "WhatsApp", description: "Mensajes automáticos por WhatsApp." },
{ key: "email", label: "Email", description: "Correos electrónicos al cliente." },
{ key: "system", label: "Sistema", description: "Notificaciones dentro de la plataforma." }
];
export const NOTIF_REMINDER_PRESETS: { minutes: number; label: string }[] = [
{ minutes: 60, label: "1 hora antes" },
{ minutes: 180, label: "3 horas antes" },
{ minutes: 360, label: "6 horas antes" },
{ minutes: 720, label: "12 horas antes" },
{ minutes: 1440, label: "1 día antes" },
{ minutes: 2880, label: "2 días antes" }
];
export const ALL_NOTIF_CHANNELS: NotificationChannel[] = ["whatsapp", "email", "system"];
@@ -0,0 +1,9 @@
import { ReservationPeriodDuration } from "@models/SchedulesEnabled.type";
export const reservationPeriodOptions: Array<ReservationPeriodDuration & { label: string }> = [
{ unit: "week", value: 1, label: "1 semana" },
{ unit: "week", value: 2, label: "2 semanas" },
{ unit: "week", value: 3, label: "3 semanas" },
{ unit: "month", value: 1, label: "1 mes" },
{ unit: "month", value: 2, label: "2 meses" },
];
@@ -0,0 +1,292 @@
import React from "react";
import QuestionCard from "../../QuestionCard/QuestionCard";
type Props = any;
export default function DisableScheduleFlow(props: Props) {
const { currentStepIndex, scheduleScope, setScheduleScope, targetEmployeeId, setTargetEmployeeId, allEmployees, handleNext, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleUpdateScheduleSubmit, handleOverrideScheduleSubmit, disableDuration, setDisableDuration, disableStartDate, setDisableStartDate, disableEndDate, setDisableEndDate, isFullDayDisabled, setIsFullDayDisabled, disableStartTime, setDisableStartTime, disableEndTime, setDisableEndTime, handleDisableScheduleSubmit } = props;
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Cerrar Agenda"
description="¿A quiénes quieres aplicar esta inhabilitación de agenda?"
onNext={() => {
if (scheduleScope === "specific" && !targetEmployeeId) {
alert("Por favor selecciona un colaborador.");
return;
}
handleNext();
}}
disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
<div
onClick={() => setScheduleScope("me")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>Solo a </h4>
</div>
<div
onClick={() => setScheduleScope("specific")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
</div>
<div
onClick={() => setScheduleScope("all")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
</div>
{scheduleScope === "specific" && (
<div style={{ marginTop: '15px', width: '100%' }}>
<select
value={targetEmployeeId || ""}
onChange={(e) => setTargetEmployeeId(e.target.value)}
style={{
width: '100%', padding: '12px', borderRadius: '8px',
background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
outline: 'none', fontSize: '16px'
}}
>
<option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
{allEmployees.map((emp: any) => (
<option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
{emp.firstName} {emp.lastName}
</option>
))}
</select>
</div>
)}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1}
title="Duración del Cierre"
description="¿Por cuánto tiempo se cerrará la agenda?"
onNext={handleNext}
disableNext={!disableDuration}
>
<div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
<div
onClick={() => setDisableDuration("one-day")}
style={{
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: disableDuration === "one-day" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${disableDuration === "one-day" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center'
}}
>
Solo por un día
</div>
<div
onClick={() => setDisableDuration("multi-day")}
style={{
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: disableDuration === "multi-day" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${disableDuration === "multi-day" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center'
}}
>
Por varios días
</div>
</div>
</QuestionCard>
{disableDuration === "one-day" && (
<>
<QuestionCard
isActive={currentStepIndex === 2}
title="Fecha del Cierre"
description="Selecciona la fecha en la que no se recibirán turnos."
onNext={handleNext}
disableNext={!disableStartDate}
>
<div style={{ display: 'flex', width: '100%', justifyContent: 'center' }}>
<input
type="date"
value={disableStartDate}
onChange={(e) => setDisableStartDate(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '16px', fontFamily: 'sans-serif'
}}
/>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="Rango Horario"
description="¿Esta inhabilitación aplica para todo el día o solo en una franja horaria?"
onNext={() => {
if (isFullDayDisabled) {
handleDisableScheduleSubmit();
} else if (disableStartTime && disableEndTime) {
handleDisableScheduleSubmit();
}
}}
nextLabel={isCreating ? "Guardando..." : "Cerrar Agenda"}
disableNext={(!isFullDayDisabled && (!disableStartTime || !disableEndTime)) || isCreating}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
<div style={{ display: 'flex', gap: '15px', width: '100%' }}>
<div
onClick={() => setIsFullDayDisabled(true)}
style={{
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: isFullDayDisabled === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${isFullDayDisabled === true ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center'
}}
>
Todo el día
</div>
<div
onClick={() => setIsFullDayDisabled(false)}
style={{
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: isFullDayDisabled === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${isFullDayDisabled === false ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center'
}}
>
Franja Específica
</div>
</div>
{!isFullDayDisabled && (
<div style={{ display: 'flex', gap: '20px' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Desde (Hora)</label>
<input
type="time"
value={disableStartTime}
onChange={(e) => setDisableStartTime(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hasta (Hora)</label>
<input
type="time"
value={disableEndTime}
onChange={(e) => setDisableEndTime(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
</div>
)}
</div>
</QuestionCard>
</>
)}
{disableDuration === "multi-day" && (
<>
<QuestionCard
isActive={currentStepIndex === 2}
title="¿Cuándo inicia?"
description="Selecciona la fecha y hora de inicio de la inhabilitación."
onNext={handleNext}
disableNext={!disableStartDate || !disableStartTime}
>
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fecha de Inicio</label>
<input
type="date"
value={disableStartDate}
onChange={(e) => setDisableStartDate(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '16px', fontFamily: 'sans-serif'
}}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hora de Inicio</label>
<input
type="time"
value={disableStartTime}
onChange={(e) => setDisableStartTime(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="¿Cuándo termina?"
description="Selecciona la fecha y hora en la que finaliza el cierre."
onNext={handleDisableScheduleSubmit}
nextLabel={isCreating ? "Guardando..." : "Cerrar Agenda"}
disableNext={!disableEndDate || !disableEndTime || isCreating}
>
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fecha de Fin</label>
<input
type="date"
value={disableEndDate}
onChange={(e) => setDisableEndDate(e.target.value)}
min={disableStartDate}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '16px', fontFamily: 'sans-serif'
}}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hora de Fin</label>
<input
type="time"
value={disableEndTime}
onChange={(e) => setDisableEndTime(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
</div>
</QuestionCard>
</>
)}
</>
);
}
@@ -0,0 +1,100 @@
import React from "react";
import ReactAvatar from "react-avatar";
import QuestionCard from "../../QuestionCard/QuestionCard";
import QuestionInput from "../../QuestionCard/QuestionInput";
type Props = any;
export default function NewCollaboratorFlow(props: Props) {
const { currentStepIndex, inviteEmail, setInviteEmail, inviteEmailError, setInviteEmailError, isSearchingEmail, handleSearchCollaboratorEmail, handleKeyDown, inviteCollaborator, inviteRole, setInviteRole, handleNext, handleCreateCollaborator, isCreating, createdCompanyId, router, resetInviteFlow, inviteFlowNotice, isUpgradeRequired } = props;
return (
<>
<QuestionCard isActive={currentStepIndex === 1} title="Buscar Colaborador" description="Ingresa el e-mail del usuario. Importante: debe estar registrado previamente en TurnosXpress." onNext={handleSearchCollaboratorEmail} disableNext={!inviteEmail || !inviteEmail.includes("@") || isSearchingEmail} nextLabel={isSearchingEmail ? "Buscando..." : "Buscar"}>
<QuestionInput
placeholder="ejemplo@correo.com"
value={inviteEmail}
onChange={(e) => { setInviteEmail(e.target.value); setInviteEmailError(""); }}
onKeyDown={(e) => {
if (inviteEmail.includes("@") && !isSearchingEmail) handleKeyDown(e, handleSearchCollaboratorEmail);
}}
autoFocus
/>
{inviteEmailError && (
<div style={{ marginTop: '15px', padding: '15px', background: 'rgba(255,0,0,0.1)', border: '1px solid rgba(255,0,0,0.3)', borderRadius: '8px', color: '#ff9999', fontSize: '13px' }}>
<b>No encontramos este e-mail.</b><br />
Asegúrate de que la persona ya haya creado una cuenta en TurnosXpress con este correo. Pídele que se registre primero y vuelve a intentarlo.
</div>
)}
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 2} title="Configurar Rol" description={`¿Qué permisos quieres darle a ${inviteCollaborator?.firstName || inviteCollaborator?.fullName}?`} onNext={handleNext}>
{inviteCollaborator && (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: '20px' }}>
{inviteCollaborator.avatar ? (
<img src={inviteCollaborator.avatar} alt="Avatar" style={{ width: 60, height: 60, borderRadius: '50%', marginBottom: '10px', objectFit: 'cover' }} />
) : (
<ReactAvatar name={inviteCollaborator.fullName} size="60" round color="#600018" style={{ marginBottom: '10px' }} />
)}
<div style={{ color: 'white', fontWeight: 'bold' }}>{inviteCollaborator.fullName}</div>
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
<div onClick={() => setInviteRole("colaborador")} style={{ padding: '15px', borderRadius: '12px', background: inviteRole === "colaborador" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)', border: `1px solid ${inviteRole === "colaborador" ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`, cursor: 'pointer', color: 'white', transition: 'all 0.2s' }}>
<div style={{ fontWeight: 'bold' }}>Colaborador</div>
<div style={{ fontSize: '12px', opacity: 0.8, marginTop: '5px' }}>Solo podrá ver y gestionar su propia agenda de turnos.</div>
</div>
<div onClick={() => setInviteRole("admin")} style={{ padding: '15px', borderRadius: '12px', background: inviteRole === "admin" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)', border: `1px solid ${inviteRole === "admin" ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`, cursor: 'pointer', color: 'white', transition: 'all 0.2s' }}>
<div style={{ fontWeight: 'bold' }}>Administrador</div>
<div style={{ fontSize: '12px', opacity: 0.8, marginTop: '5px' }}>Tendrá acceso total para modificar horarios, servicios y otros colaboradores de esta organización.</div>
</div>
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 3 && !isUpgradeRequired} title="Confirmar Invitación" description={`Se enviará una invitación a ${inviteCollaborator?.email}. El usuario deberá aceptarla para comenzar.`} onNext={handleCreateCollaborator} disableNext={isCreating} nextLabel={isCreating ? "Enviando..." : "Enviar Invitación"}>{null}</QuestionCard>
<QuestionCard isActive={currentStepIndex === 4} title="Invitación Enviada" description="¿Cómo quieres continuar?">
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
<ActionCard onClick={resetInviteFlow} title="Invitar otro colaborador" description="Agrega otra persona a tu equipo." />
<ActionCard onClick={() => router.push(`/admin/assistant?flow=update-schedule${createdCompanyId ? `&companyId=${createdCompanyId}` : ""}`)} title="Configurar mis horarios" description="Define tus horarios personales de atención." />
<ActionCard onClick={() => router.push("/admin/assistant")} title="Terminar" description="Volver a la home del asistente." />
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 5} title="Invitación Pendiente" description={inviteFlowNotice || "No pudimos enviar la invitación en este momento."}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
<ActionCard onClick={resetInviteFlow} title="Invitar otro colaborador" description="Busca otra persona para sumar al equipo." />
<ActionCard onClick={() => router.push("/admin/assistant")} title="Volver al asistente" description="Regresar a la home del asistente." />
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 6} title="El usuario ya pertenece" description={inviteFlowNotice || "Este usuario ya pertenece a la compañía."}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
<ActionCard onClick={resetInviteFlow} title="Invitar otro colaborador" description="Busca otra persona para sumar al equipo." />
<ActionCard onClick={() => router.push("/admin/assistant")} title="Volver al asistente" description="Regresar a la home del asistente." />
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 3 && isUpgradeRequired} title="¡Haz crecer tu equipo!" description="Parece que has alcanzado el límite de colaboradores de tu plan actual. Actualiza tu suscripción para seguir sumando profesionales a tu negocio." onNext={() => window.location.href = "/landing/pricing"} nextLabel="Ver Planes y Mejorar">
<div style={{ padding: '20px', background: 'linear-gradient(135deg, rgba(255, 65, 108, 0.1) 0%, rgba(255, 75, 43, 0.1) 100%)', border: '1px solid var(--wine-red)', borderRadius: '15px', color: 'white', textAlign: 'center', margin: '15px 0' }}>
<div style={{ fontSize: '40px', marginBottom: '10px' }}>🚀</div>
<h4 style={{ margin: '0 0 10px 0', fontSize: '18px' }}>Beneficios de expandirte</h4>
<ul style={{ textAlign: 'left', margin: '0', padding: '0 0 0 20px', opacity: 0.9, fontSize: '14px', lineHeight: '1.6' }}>
<li>Agendas ilimitadas para todo tu equipo.</li>
<li>Aumento exponencial de tus reservas diarias.</li>
<li>Control total sobre los permisos de cada integrante.</li>
</ul>
</div>
</QuestionCard>
</>
);
}
function ActionCard({ onClick, title, description }: Props) {
return (
<div onClick={onClick} style={{ padding: '15px', borderRadius: '12px', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.2)', cursor: 'pointer', color: 'white', transition: 'all 0.2s' }}>
<div style={{ fontWeight: 'bold' }}>{title}</div>
<div style={{ fontSize: '12px', opacity: 0.8, marginTop: '5px' }}>{description}</div>
</div>
);
}
@@ -0,0 +1,366 @@
// @ts-nocheck
import React from "react";
import SearchIcon from '@mui/icons-material/Search';
import QuestionCard from "../../QuestionCard/QuestionCard";
import ClientPicker from "../../ClientPicker/ClientPicker";
import Switch from "@components/Switch/Switch";
import TextTime from "@components/TextTime/TextTime";
type Props = any;
export default function NotificationsFlow(props: Props) {
const { currentStepIndex, notificationsScope, setNotificationsScope, handleNext, notifLoading, NOTIF_CHANNELS, NOTIF_REMINDER_PRESETS, notifChannels, notifReminderRules, toggleNotifReminder, notifQuietHoursActive, setNotifQuietHoursActive, dayjsFromHHmm, notifQuietHoursFrom, setNotifQuietHoursFrom, notifQuietHoursTo, setNotifQuietHoursTo, handleSaveNotifications, isCreating, notifSelectedClientId, setNotifSelectedClientId, notifClients, notifClientPickerOpen, setNotifClientPickerOpen, setNotifChannels, toggleNotifChannel, handleSelectNotifScope } = props;
const renderNotificationsChannelToggle = (channel: NotificationChannel) => (
<div
key={channel}
style={{
display: "flex", justifyContent: "space-between", alignItems: "center",
padding: "14px 16px", borderRadius: "12px",
background: "rgba(255,255,255,0.05)",
border: `1px solid ${notifChannels.includes(channel) ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
color: "white", transition: "all 0.2s ease"
}}
>
<div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
<span style={{ fontWeight: 700 }}>{NOTIF_CHANNELS.find(c => c.key === channel)?.label}</span>
<span style={{ fontSize: "13px", color: "rgba(255,255,255,0.65)" }}>
{NOTIF_CHANNELS.find(c => c.key === channel)?.description}
</span>
</div>
<Switch
checked={notifChannels.includes(channel)}
onChange={() => toggleNotifChannel(channel)}
disabled={notifLoading}
/>
</div>
);
return (() => {
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Configurar Notificaciones"
description="Te ayudamos a definir cómo y cuándo reciben notificaciones tus clientes. Primero elegí a qué querés aplicarle esta configuración."
onNext={() => {
if (!notificationsScope) return;
handleNext();
}}
disableNext={!notificationsScope}
nextLabel="Siguiente"
>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
<div
onClick={() => handleSelectNotifScope("org")}
style={{
padding: "18px", borderRadius: "12px", cursor: "pointer",
background: notificationsScope === "org" ? "var(--wine-red)" : "rgba(255,255,255,0.05)",
border: `2px solid ${notificationsScope === "org" ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
color: "white", textAlign: "center", transition: "all 0.2s ease"
}}
>
<h4 style={{ margin: "0 0 5px 0", fontSize: "16px", fontWeight: notificationsScope === "org" ? "bold" : "normal" }}>
A la organización en general
</h4>
<p style={{ margin: 0, fontSize: "13px", color: "rgba(255,255,255,0.75)" }}>
Configura canales, recordatorios y horario silencioso para todos los clientes.
</p>
</div>
<div
onClick={() => handleSelectNotifScope("client")}
style={{
padding: "18px", borderRadius: "12px", cursor: "pointer",
background: notificationsScope === "client" ? "var(--wine-red)" : "rgba(255,255,255,0.05)",
border: `2px solid ${notificationsScope === "client" ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
color: "white", textAlign: "center", transition: "all 0.2s ease"
}}
>
<h4 style={{ margin: "0 0 5px 0", fontSize: "16px", fontWeight: notificationsScope === "client" ? "bold" : "normal" }}>
A un cliente específico
</h4>
<p style={{ margin: 0, fontSize: "13px", color: "rgba(255,255,255,0.75)" }}>
Elige un cliente y define qué canales de notificación recibe.
</p>
</div>
</div>
<div style={{ marginTop: "18px", padding: "14px", borderRadius: "12px", background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)", color: "rgba(255,255,255,0.7)", fontSize: "13px", lineHeight: 1.5 }}>
Estos ajustes se sincronizan con la página de notificaciones de tu organización, así que después podés seguir ajustándolos desde ahí.
</div>
</QuestionCard>
{notificationsScope === "org" && (
<>
<QuestionCard
isActive={currentStepIndex === 1}
title="1. Canales de notificación"
description="Elige los canales por los cuales se enviarán las notificaciones automáticas a tus clientes."
onNext={handleNext}
disableNext={notifLoading}
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
>
<div style={{ display: "flex", flexDirection: "column", gap: "10px", width: "100%" }}>
{NOTIF_CHANNELS.map(c => renderNotificationsChannelToggle(c.key))}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 2}
title="2. Reglas de recordatorio"
description="Activá los momentos en los que se enviará un recordatorio antes del turno. Podés elegir varios."
onNext={handleNext}
disableNext={notifLoading}
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
>
<div style={{ display: "flex", flexWrap: "wrap", gap: "10px", justifyContent: "center", width: "100%" }}>
{NOTIF_REMINDER_PRESETS.map(preset => {
const isActive = notifReminderRules.some(r => r.offset === preset.minutes);
return (
<div
key={preset.minutes}
onClick={() => toggleNotifReminder(preset.minutes)}
style={{
padding: "10px 18px", borderRadius: "999px", cursor: "pointer",
background: isActive ? "var(--wine-red)" : "rgba(255,255,255,0.05)",
border: `1px solid ${isActive ? "var(--wine-red)" : "rgba(255,255,255,0.15)"}`,
color: "white",
fontWeight: isActive ? "bold" : "normal",
transition: "all 0.2s ease",
fontSize: "14px"
}}
>
{preset.label}
</div>
);
})}
</div>
<div style={{ marginTop: "18px", color: "rgba(255,255,255,0.55)", fontSize: "13px", textAlign: "center" }}>
{notifReminderRules.length === 0
? "No hay recordatorios activos todavía."
: `Recordatorios activos: ${notifReminderRules.length}.`}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="3. Horario silencioso"
description="Durante este rango horario no se enviarán notificaciones. Activá la opción solo si querés definirlo."
onNext={handleNext}
disableNext={notifLoading}
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
>
<div style={{ display: "flex", flexDirection: "column", gap: "20px", width: "100%", alignItems: "center" }}>
<div
style={{
display: "flex", justifyContent: "space-between", alignItems: "center",
padding: "14px 16px", borderRadius: "12px", width: "100%", maxWidth: "400px",
background: "rgba(255,255,255,0.05)",
border: `1px solid ${notifQuietHoursActive ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`,
color: "white", transition: "all 0.2s ease"
}}
>
<span style={{ fontWeight: 700 }}>Activar horario silencioso</span>
<Switch
checked={notifQuietHoursActive}
onChange={(checked) => setNotifQuietHoursActive(checked)}
disabled={notifLoading}
/>
</div>
{notifQuietHoursActive && (
<div style={{ display: "flex", gap: "16px", width: "100%", maxWidth: "500px" }}>
<div style={{ flex: 1 }}>
<TextTime
placeholder="Desde"
width="100%"
value={dayjsFromHHmm(notifQuietHoursFrom)}
onChange={(v) => setNotifQuietHoursFrom(v.format("HH:mm"))}
/>
</div>
<div style={{ flex: 1 }}>
<TextTime
placeholder="Hasta"
width="100%"
value={dayjsFromHHmm(notifQuietHoursTo)}
onChange={(v) => setNotifQuietHoursTo(v.format("HH:mm"))}
/>
</div>
</div>
)}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 4}
title="Resumen"
description="Revisá la configuración antes de guardarla."
onNext={handleSaveNotifications}
disableNext={isCreating || notifLoading}
nextLabel={isCreating ? "Guardando..." : "Guardar configuración"}
>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%", maxWidth: "500px", margin: "0 auto", background: "rgba(255,255,255,0.05)", borderRadius: "12px", padding: "18px", border: "1px solid rgba(255,255,255,0.1)" }}>
<div>
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Canales activos</div>
<div style={{ color: "white", fontWeight: 700 }}>
{notifChannels.length > 0
? notifChannels.map(c => NOTIF_CHANNELS.find(nc => nc.key === c)?.label).join(", ")
: "Ninguno"}
</div>
</div>
<div>
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Recordatorios</div>
<div style={{ color: "white", fontWeight: 700 }}>
{notifReminderRules.length > 0
? notifReminderRules.map(r => NOTIF_REMINDER_PRESETS.find(p => p.minutes === r.offset)?.label || `${r.offset} min`).join(", ")
: "Ninguno"}
</div>
</div>
<div>
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Horario silencioso</div>
<div style={{ color: "white", fontWeight: 700 }}>
{notifQuietHoursActive ? `De ${notifQuietHoursFrom} a ${notifQuietHoursTo}` : "Desactivado"}
</div>
</div>
</div>
</QuestionCard>
</>
)}
{notificationsScope === "client" && (
<>
<QuestionCard
isActive={currentStepIndex === 1}
title="1. Selecciona el cliente"
description="Elegí a qué cliente de la organización querés aplicarle esta configuración de canales."
onNext={() => {
if (!notifSelectedClientId) return;
handleNext();
}}
disableNext={!notifSelectedClientId || notifLoading}
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
>
<div style={{ width: "100%", display: "flex", flexDirection: "column", gap: "12px" }}>
{notifClients.length === 0 ? (
<div style={{ color: "rgba(255,255,255,0.7)", textAlign: "center", padding: "24px", borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)" }}>
No hay clientes para esta organización todavía. Cuando alguien reserve un turno, aparecerá acá.
</div>
) : notifSelectedClientId ? (() => {
const sc = notifClients.find(c => c.id === notifSelectedClientId);
const sub = sc ? ((sc.email && sc.email.trim() !== "") ? sc.email : [sc.phoneCountryCode, sc.phoneAreaCode, sc.phoneNumber].filter(p => p && String(p).trim() !== "").map(p => String(p).trim()).join(" ")).replace(/^(?!\+)/, "+") : "";
return (
<button
type="button"
onClick={() => setNotifClientPickerOpen(true)}
style={{
display: "flex", alignItems: "center", gap: "12px", width: "100%",
padding: "12px", borderRadius: "14px",
background: "rgba(255,42,127,0.08)",
border: "1px solid var(--wine-red)",
boxShadow: "0 0 24px rgba(255,42,127,0.18)",
cursor: "pointer", color: "white", textAlign: "left",
fontFamily: "inherit",
transition: "background 0.2s, box-shadow 0.2s",
}}
>
<div style={{ position: "relative", width: "44px", height: "44px", borderRadius: "50%", overflow: "hidden", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: "14px", fontWeight: 700, color: "white", background: "linear-gradient(135deg, var(--wine-red) 0%, var(--wine-dark) 100%)" }}>
{(sc?.avatar && sc.avatar.trim() !== "") ? (
<img
src={sc.avatar}
alt={sc?.fullName || ""}
style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}
onError={(e) => { (e.currentTarget as HTMLImageElement).style.opacity = "0"; }}
/>
) : null}
{sc ? `${(sc.firstName?.[0] || "").toUpperCase()}${(sc.lastName?.[0] || "").toUpperCase()}` : "?"}
</div>
<div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: "2px" }}>
<span style={{ color: "white", fontWeight: 700, fontSize: "15px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
{sc?.fullName || "—"}
</span>
{sub && (
<span style={{ color: "rgba(255,255,255,0.55)", fontSize: "12px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
{sub}
</span>
)}
</div>
<span style={{ color: "var(--wine-red)", fontSize: "13px", fontWeight: 600, flexShrink: 0 }}>Cambiar</span>
</button>
);
})() : (
<button
type="button"
onClick={() => setNotifClientPickerOpen(true)}
style={{
display: "flex", alignItems: "center", justifyContent: "center", gap: "10px", width: "100%",
padding: "14px", borderRadius: "14px",
background: "rgba(255,255,255,0.05)",
border: "1px solid rgba(255,255,255,0.14)",
cursor: "pointer", color: "white",
fontFamily: "inherit", fontSize: "15px", fontWeight: 600,
transition: "border-color 0.2s, background 0.2s, box-shadow 0.2s",
}}
>
<SearchIcon style={{ fontSize: 20, color: "var(--wine-red)" }} />
Buscar y seleccionar cliente
</button>
)}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 2}
title="2. Canales de notificación"
description="Activá los canales por los que este cliente recibirá notificaciones de la organización. Los desactivados se silencian."
onNext={handleNext}
disableNext={!notifSelectedClientId || notifLoading}
nextLabel={notifLoading ? "Cargando..." : "Siguiente"}
>
<div style={{ display: "flex", flexDirection: "column", gap: "10px", width: "100%" }}>
{NOTIF_CHANNELS.map(c => renderNotificationsChannelToggle(c.key))}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="Resumen"
description="Revisá la configuración antes de guardarla."
onNext={handleSaveNotifications}
disableNext={isCreating || notifLoading}
nextLabel={isCreating ? "Guardando..." : "Guardar configuración"}
>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%", maxWidth: "500px", margin: "0 auto", background: "rgba(255,255,255,0.05)", borderRadius: "12px", padding: "18px", border: "1px solid rgba(255,255,255,0.1)" }}>
<div>
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Cliente</div>
<div style={{ color: "white", fontWeight: 700 }}>
{notifClients.find(c => c.id === notifSelectedClientId)?.fullName || "—"}
</div>
</div>
<div>
<div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>Canales activos</div>
<div style={{ color: "white", fontWeight: 700 }}>
{notifChannels.length > 0
? notifChannels.map(c => NOTIF_CHANNELS.find(nc => nc.key === c)?.label).join(", ")
: "Ninguno"}
</div>
</div>
</div>
</QuestionCard>
<ClientPicker
open={notifClientPickerOpen}
clients={notifClients}
selectedId={notifSelectedClientId}
loading={notifLoading}
onSelect={(id) => {
setNotifChannels([]);
setNotifSelectedClientId(id);
setNotifClientPickerOpen(false);
}}
onClose={() => setNotifClientPickerOpen(false)}
/>
</>
)}
</>
);
})();
}
@@ -0,0 +1,478 @@
import React from "react";
import ReactAvatar from "react-avatar";
import QuestionCard from "../../QuestionCard/QuestionCard";
import QuestionInput from "../../QuestionCard/QuestionInput";
import OnboardingPhone from "../../OnboardingPhone/OnboardingPhone";
import OnboardingLocation from "../../OnboardingLocation/OnboardingLocation";
import SelectLocationMap from "@core/app/components/SelectLocationMap/SelectLocationMap";
import { validatePhone } from "@core/helpers/validatePhone";
import categories from "@models/Categories.type";
import style from "../StepEngine.module.css";
type OnboardingOrgFlowProps = {
currentStepIndex: any;
SessionInfo: any;
imageError: any;
setImageError: any;
handleNext: any;
handleNextName: any;
orgName: any;
setOrgName: any;
nameError: any;
setNameError: any;
isCheckingName: any;
categoryId: any;
setCategoryId: any;
handleCreateCompany: any;
isCreating: any;
orgDescription: any;
setOrgDescription: any;
handleKeyDown: any;
handleUpdateLocation: any;
isStandaloneAction: any;
street: any;
streetNumber: any;
builingFloor: any;
buildingApartament: any;
state: any;
city: any;
block: any;
zipCode: any;
latitude: any;
longitude: any;
setStreet: any;
setStreetNumber: any;
setBuilingFloor: any;
setBuildingApartament: any;
setState: any;
setCity: any;
setBlock: any;
setZipCode: any;
setLatitude: any;
setLongitude: any;
handleUpdateContact: any;
phoneAreaCode: any;
phoneNumber: any;
setPhoneAreaCode: any;
setPhoneNumber: any;
handleUpdateRules: any;
heatMapFraction: any;
setHeatMapFraction: any;
appointmentTime: any;
setAppointmentTime: any;
cancellationTime: any;
setCancellationTime: any;
handleUploadHeader: any;
headerColor: any;
setHeaderColor: any;
headerFontColor: any;
setHeaderFontColor: any;
headerImage: any;
setHeaderImage: any;
};
export default function OnboardingOrgFlow(props: OnboardingOrgFlowProps) {
const { currentStepIndex, SessionInfo, imageError, setImageError, handleNext, handleNextName, orgName, setOrgName, nameError, setNameError, isCheckingName, categoryId, setCategoryId, handleCreateCompany, isCreating, orgDescription, setOrgDescription, handleKeyDown, handleUpdateLocation, isStandaloneAction, street, streetNumber, builingFloor, buildingApartament, state, city, block, zipCode, latitude, longitude, setStreet, setStreetNumber, setBuilingFloor, setBuildingApartament, setState, setCity, setBlock, setZipCode, setLatitude, setLongitude, handleUpdateContact, phoneAreaCode, phoneNumber, setPhoneAreaCode, setPhoneNumber, handleUpdateRules, heatMapFraction, setHeatMapFraction, appointmentTime, setAppointmentTime, cancellationTime, setCancellationTime, handleUploadHeader, headerColor, setHeaderColor, headerFontColor, setHeaderFontColor, headerImage, setHeaderImage } = props;
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title={`¡Bienvenido a TurnosXpress, ${SessionInfo.userFullName.split(" ")[0]}!`}
description="Vamos a configurar tu negocio en solo unos minutos. Relájate, yo te guiaré paso a paso para que todo quede perfecto."
onNext={handleNext}
nextLabel="Empezar ahora"
topAccessory={
SessionInfo.avatar && !imageError ? (
<img
src={SessionInfo.avatar}
alt="Avatar"
style={{ width: 90, height: 90, borderRadius: '50%', objectFit: 'cover' }}
onError={() => setImageError(true)}
/>
) : (
<ReactAvatar
name={SessionInfo.userFullName || "Usuario"}
size="90"
round={true}
textSizeRatio={2.5}
maxInitials={2}
color="#600018"
/>
)
}
>
{null}
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1}
title="1. Identidad de tu Negocio"
description="Para empezar, ¿cuál es el nombre de tu organización o emprendimiento?"
onNext={handleNextName}
disableNext={orgName.trim().length < 3 || isCheckingName}
nextLabel={isCheckingName ? "Validando..." : "Siguiente"}
>
<QuestionInput
placeholder="Ej. Salón de Belleza VIP"
value={orgName}
onChange={(e) => {
setOrgName(e.target.value);
if (nameError) setNameError("");
}}
onKeyDown={(e) => {
if (orgName.trim().length >= 3) {
handleKeyDown(e, handleNextName);
}
}}
autoFocus
error={nameError}
/>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 2}
title="2. ¿A qué te dedicas?"
description="Elige la categoría que mejor describa los servicios que ofreces."
onNext={handleNext}
disableNext={categoryId === null}
>
<div className={style.categoryGrid}>
{categories.filter(c => c.id !== 0).map(cat => (
<div
key={cat.id}
className={`${style.categoryItem} ${categoryId === cat.id ? style.categorySelected : ''}`}
onClick={() => {
setCategoryId(cat.id);
setTimeout(handleNext, 400);
}}
>
<div className={style.categoryIcon}></div>
<div className={style.categoryName}>{cat.name}</div>
</div>
))}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="3. Una breve descripción"
description={`Cuentanos un poco sobre "${orgName}". Esta descripción la verán tus clientes.`}
onNext={handleCreateCompany}
disableNext={isCreating}
nextLabel={isCreating ? "Creando..." : "Guardar Organización"}
>
<QuestionInput
placeholder="Ej. Ofrecemos los mejores cortes..."
value={orgDescription}
onChange={(e) => setOrgDescription(e.target.value)}
onKeyDown={(e) => {
if (orgDescription.trim().length >= 10) {
handleKeyDown(e, handleCreateCompany);
}
}}
autoFocus
/>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 4}
title="4. Ubicación de tu Negocio"
description={`¿Dónde queda "${orgName}"? Esto es crucial para que tus clientes te encuentren.`}
onNext={handleUpdateLocation}
disableNext={isCreating}
nextLabel={isCreating ? "Guardando..." : (isStandaloneAction ? "Guardar Cambios" : "Siguiente")}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
<OnboardingLocation
data={{
street, streetNumber, builingFloor, buildingApartament, state, city, block, zipCode, latitude, longitude
}}
onChange={(newData) => {
if (newData.street !== undefined) setStreet(newData.street);
if (newData.streetNumber !== undefined) setStreetNumber(newData.streetNumber);
if (newData.builingFloor !== undefined) setBuilingFloor(newData.builingFloor);
if (newData.buildingApartament !== undefined) setBuildingApartament(newData.buildingApartament);
if (newData.state !== undefined) setState(newData.state);
if (newData.city !== undefined) setCity(newData.city);
if (newData.block !== undefined) setBlock(newData.block);
if (newData.zipCode !== undefined) setZipCode(newData.zipCode);
if (newData.latitude !== undefined) setLatitude(newData.latitude);
if (newData.longitude !== undefined) setLongitude(newData.longitude);
}}
/>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 5}
title="5. Ubica tu local en el mapa (Opcional)"
description={`Para que los clientes encuentren "${orgName}" con exactitud. Por favor, haz el máximo zoom posible y arrastra el marcador a tu ubicación exacta.`}
onNext={handleUpdateLocation}
disableNext={isCreating}
nextLabel={isCreating ? "Guardando..." : "Guardar Ubicación"}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%', alignItems: 'center' }}>
<div style={{ width: '100%', borderRadius: '8px', overflow: 'hidden' }}>
<SelectLocationMap
initialCoordinates={{ latitude, longitude }}
height="350px"
onChange={(loc) => {
setLatitude(loc.latitude);
setLongitude(loc.longitude);
}}
/>
</div>
<div
style={{
marginTop: '10px',
fontSize: '13px',
color: 'rgba(255,255,255,0.6)',
cursor: 'pointer',
textDecoration: 'underline'
}}
onClick={() => {
if (!isCreating) handleUpdateLocation();
}}
>
Omitir este paso
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 6}
title="6. Contacto"
description="¿Cómo pueden contactarte tus clientes? Ingresa el número de teléfono (preferiblemente WhatsApp)."
onNext={handleUpdateContact}
disableNext={!validatePhone(phoneAreaCode, phoneNumber).isValid || isCreating}
nextLabel={isCreating ? "Guardando..." : (isStandaloneAction ? "Guardar Cambios" : "Siguiente")}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%', alignItems: 'center' }}>
<OnboardingPhone
value={phoneAreaCode + phoneNumber}
onChange={(area, num, full) => {
setPhoneAreaCode(area);
setPhoneNumber(num);
}}
onKeyDown={(e) => {
if (validatePhone(phoneAreaCode, phoneNumber).isValid) {
handleKeyDown(e, handleUpdateContact);
}
}}
/>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 7}
title="7. Reglas de Negocio"
description="Configura los tiempos de tu agenda. Esto determinará cómo se muestran los turnos a tus clientes."
onNext={handleUpdateRules}
disableNext={isCreating}
nextLabel={isCreating ? "Guardando..." : "Siguiente: Crear Servicio"}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%' }}>
<div>
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Fracción de la Agenda (Minutos)</div>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
{[15, 30, 45, 60, 120].map(val => (
<div
key={val}
onClick={() => setHeatMapFraction(val)}
style={{
padding: '8px 16px',
borderRadius: '8px',
cursor: 'pointer',
background: heatMapFraction === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
border: `1px solid ${heatMapFraction === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
color: 'white',
fontWeight: heatMapFraction === val ? 'bold' : 'normal',
transition: 'all 0.2s ease'
}}
>
{val}m
</div>
))}
</div>
</div>
<div>
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Anticipación mínima para reservar (Horas)</div>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
{[1, 2, 12, 24, 48].map(val => (
<div
key={val}
onClick={() => setAppointmentTime(val)}
style={{
padding: '8px 16px',
borderRadius: '8px',
cursor: 'pointer',
background: appointmentTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
border: `1px solid ${appointmentTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
color: 'white',
fontWeight: appointmentTime === val ? 'bold' : 'normal',
transition: 'all 0.2s ease'
}}
>
{val}h
</div>
))}
</div>
</div>
<div>
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Anticipación mínima para cancelar (Horas)</div>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
{[1, 2, 12, 24, 48].map(val => (
<div
key={val}
onClick={() => setCancellationTime(val)}
style={{
padding: '8px 16px',
borderRadius: '8px',
cursor: 'pointer',
background: cancellationTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
border: `1px solid ${cancellationTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
color: 'white',
fontWeight: cancellationTime === val ? 'bold' : 'normal',
transition: 'all 0.2s ease'
}}
>
{val}h
</div>
))}
</div>
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 8}
title="8. Apariencia"
description="Sube una foto de portada para tu negocio y elige tus colores corporativos. Esto es lo primero que verán tus clientes."
onNext={handleUploadHeader}
disableNext={isCreating}
nextLabel={isCreating ? "Guardando..." : (isStandaloneAction ? "Guardar Cambios" : "Siguiente")}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
<div style={{
display: 'flex', gap: '20px', width: '100%', maxWidth: '500px',
justifyContent: 'center', background: 'rgba(255,255,255,0.05)',
padding: '15px', borderRadius: '12px'
}}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px', flex: 1 }}>
<label style={{ color: 'white', fontSize: '13px' }}>Color de Fondo</label>
<input
type="color"
value={headerColor}
onChange={(e) => setHeaderColor(e.target.value)}
style={{ width: '100%', height: '40px', border: 'none', borderRadius: '8px', cursor: 'pointer' }}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px', flex: 1 }}>
<label style={{ color: 'white', fontSize: '13px' }}>Color del Texto</label>
<input
type="color"
value={headerFontColor}
onChange={(e) => setHeaderFontColor(e.target.value)}
style={{ width: '100%', height: '40px', border: 'none', borderRadius: '8px', cursor: 'pointer' }}
/>
</div>
</div>
{/* PREVIEW BOX */}
<div style={{ width: '100%', maxWidth: '500px', marginTop: '10px' }}>
<div style={{ color: 'rgba(255,255,255,0.7)', fontSize: '13px', marginBottom: '8px', textAlign: 'left' }}>
Vista previa:
</div>
<div style={{
width: '100%',
height: '120px',
backgroundColor: headerColor,
borderRadius: '12px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
position: 'relative',
overflow: 'hidden'
}}>
{headerImage && (
<img
src={URL.createObjectURL(headerImage)}
style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.4 }}
alt="Preview"
/>
)}
<div style={{
color: headerFontColor,
fontSize: '24px',
fontWeight: 'bold',
position: 'relative',
zIndex: 1,
textShadow: '0 2px 4px rgba(0,0,0,0.5)'
}}>
{orgName || "Tu Negocio"}
</div>
<div style={{
color: headerFontColor,
fontSize: '14px',
position: 'relative',
zIndex: 1,
opacity: 0.9,
marginTop: '5px'
}}>
Categoría seleccionada
</div>
</div>
</div>
<label style={{
position: 'relative',
width: '100%',
maxWidth: '500px',
height: '200px',
border: '2px dashed rgba(255, 255, 255, 0.3)',
borderRadius: '12px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
cursor: 'pointer',
background: headerImage ? 'transparent' : 'rgba(255,255,255,0.05)'
}}>
{headerImage ? (
<img
src={URL.createObjectURL(headerImage)}
alt="Preview"
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
/>
) : (
<span style={{ color: 'rgba(255,255,255,0.6)' }}>Toca para seleccionar imagen</span>
)}
<input
type="file"
accept="image/*"
onChange={(e) => {
if (e.target.files && e.target.files.length > 0) {
setHeaderImage(e.target.files[0]);
}
}}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
opacity: 0,
cursor: 'pointer'
}}
/>
</label>
</div>
</QuestionCard>
</>
);
}
@@ -0,0 +1,381 @@
import React from "react";
import QuestionCard from "../../QuestionCard/QuestionCard";
type OnboardingScheduleFlowProps = {
currentStepIndex: any;
handleNext: any;
doesProvideServices: any;
setDoesProvideServices: any;
createdCompanyId: any;
router: any;
workingDaysMode: any;
setWorkingDaysMode: any;
openTime: any;
setOpenTime: any;
closeTime: any;
setCloseTime: any;
hasBreak: any;
setHasBreak: any;
breakStart: any;
setBreakStart: any;
breakEnd: any;
setBreakEnd: any;
handleCreateSchedule: any;
isCreating: any;
headerColor: any;
headerImage: any;
headerFontColor: any;
orgName: any;
previewServices: any;
setServiceName: any;
setServiceDescription: any;
setServiceLength: any;
setServicePrice: any;
setServiceLimit: any;
setServiceImage: any;
setCreatedServiceId: any;
setIsAddingAnotherService: any;
setCurrentStepIndex: any;
};
export default function OnboardingScheduleFlow(props: OnboardingScheduleFlowProps) {
const { currentStepIndex, handleNext, doesProvideServices, setDoesProvideServices, createdCompanyId, router, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, handleCreateSchedule, isCreating, headerColor, headerImage, headerFontColor, orgName, previewServices, setServiceName, setServiceDescription, setServiceLength, setServicePrice, setServiceLimit, setServiceImage, setCreatedServiceId, setIsAddingAnotherService, setCurrentStepIndex } = props;
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Configura tus Horarios"
description="El último paso. Vamos a definir cuándo estás disponible para recibir clientes."
onNext={handleNext}
nextLabel="Comenzar"
>
<div style={{ color: "rgba(255, 255, 255, 0.7)", textAlign: "center", padding: "10px" }}>
Con esta información, tu agenda online comenzará a aceptar reservas automáticamente.
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1}
title="Atención al Cliente"
description="¿Brindas tú mismo los servicios que configuraste?"
onNext={() => {
if (doesProvideServices === null) return;
if (!doesProvideServices) {
const query = createdCompanyId ? `&companyId=${createdCompanyId}` : "";
router.push(`/admin/assistant?flow=new-collaborator${query}`);
} else {
handleNext();
}
}}
disableNext={doesProvideServices === null}
nextLabel={doesProvideServices === false ? "Invitar colaborador" : "Siguiente"}
>
<div style={{ display: 'flex', gap: '15px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
<div
onClick={() => setDoesProvideServices(true)}
style={{
padding: '20px 24px',
borderRadius: '12px',
cursor: 'pointer',
background: doesProvideServices === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${doesProvideServices === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
color: 'white',
transition: 'all 0.2s ease',
textAlign: 'center',
flex: '1',
minWidth: '200px'
}}
>
<h4 style={{ margin: '0 0 5px 0', fontSize: '18px', fontWeight: doesProvideServices === true ? 'bold' : 'normal' }}>, yo atiendo a los clientes</h4>
<p style={{ margin: 0, fontSize: '13px', color: 'rgba(255,255,255,0.7)' }}>Asignaremos los servicios a tu nombre.</p>
</div>
<div
onClick={() => setDoesProvideServices(false)}
style={{
padding: '20px 24px',
borderRadius: '12px',
cursor: 'pointer',
background: doesProvideServices === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${doesProvideServices === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
color: 'white',
transition: 'all 0.2s ease',
textAlign: 'center',
flex: '1',
minWidth: '200px'
}}
>
<h4 style={{ margin: '0 0 5px 0', fontSize: '18px', fontWeight: doesProvideServices === false ? 'bold' : 'normal' }}>No, tengo un equipo</h4>
<p style={{ margin: 0, fontSize: '13px', color: 'rgba(255,255,255,0.7)' }}>Te guiaremos para invitar al primer colaborador.</p>
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 2}
title="1. Días Laborables"
description="¿Qué días de la semana atiendes?"
onNext={handleNext}
disableNext={!workingDaysMode}
>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
{[
{ value: "mon-fri", label: "Lunes a Viernes" },
{ value: "mon-sat", label: "Lunes a Sábado" },
{ value: "mon-sun", label: "Lunes a Domingo" },
].map(opt => (
<div
key={opt.value}
onClick={() => setWorkingDaysMode(opt.value)}
style={{
padding: '12px 24px',
borderRadius: '12px',
cursor: 'pointer',
background: workingDaysMode === opt.value ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${workingDaysMode === opt.value ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
color: 'white',
fontWeight: workingDaysMode === opt.value ? 'bold' : 'normal',
transition: 'all 0.2s ease',
fontSize: '16px'
}}
>
{opt.label}
</div>
))}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="2. Horario General"
description="¿A qué hora abres y cierras tu negocio?"
onNext={handleNext}
disableNext={!openTime || !closeTime}
>
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center', alignItems: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<span style={{ color: 'white', fontSize: '14px' }}>Apertura</span>
<input
type="time"
value={openTime}
onChange={(e) => setOpenTime(e.target.value)}
style={{
padding: '12px',
borderRadius: '8px',
border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.05)',
color: 'white',
fontSize: '16px'
}}
/>
</div>
<span style={{ color: 'white', fontSize: '18px' }}>a</span>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<span style={{ color: 'white', fontSize: '14px' }}>Cierre</span>
<input
type="time"
value={closeTime}
onChange={(e) => setCloseTime(e.target.value)}
style={{
padding: '12px',
borderRadius: '8px',
border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.05)',
color: 'white',
fontSize: '16px'
}}
/>
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 4}
title="3. Horario Cortado"
description="¿Cierras tu negocio al mediodía para descansar?"
onNext={handleNext}
disableNext={hasBreak === null}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
<div style={{ display: 'flex', gap: '10px' }}>
<div
onClick={() => setHasBreak(true)}
style={{
padding: '10px 20px',
borderRadius: '8px',
cursor: 'pointer',
background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
border: `1px solid ${hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
color: 'white',
transition: 'all 0.2s ease'
}}
>
, tengo descanso
</div>
<div
onClick={() => setHasBreak(false)}
style={{
padding: '10px 20px',
borderRadius: '8px',
cursor: 'pointer',
background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
border: `1px solid ${hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
color: 'white',
transition: 'all 0.2s ease'
}}
>
No, horario corrido
</div>
</div>
{hasBreak && (
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center', alignItems: 'center', marginTop: '10px' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<span style={{ color: 'white', fontSize: '14px' }}>Inicia el descanso</span>
<input
type="time"
value={breakStart}
onChange={(e) => setBreakStart(e.target.value)}
style={{
padding: '12px',
borderRadius: '8px',
border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.05)',
color: 'white',
fontSize: '16px'
}}
/>
</div>
<span style={{ color: 'white', fontSize: '18px' }}>a</span>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<span style={{ color: 'white', fontSize: '14px' }}>Termina</span>
<input
type="time"
value={breakEnd}
onChange={(e) => setBreakEnd(e.target.value)}
style={{
padding: '12px',
borderRadius: '8px',
border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.05)',
color: 'white',
fontSize: '16px'
}}
/>
</div>
</div>
)}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 5}
title="Resumen Final y Vista Previa"
description="Revisa cómo se verá tu negocio. Al finalizar, será publicado automáticamente."
onNext={handleCreateSchedule}
disableNext={isCreating}
nextLabel={isCreating ? "Publicando..." : "Publicar y Activar Agenda"}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
{/* Mockup visual */}
<div style={{
width: '100%', maxWidth: '500px', borderRadius: '12px', overflow: 'hidden',
boxShadow: '0 4px 20px rgba(0,0,0,0.5)', background: '#1e1e1e', border: '1px solid rgba(255,255,255,0.1)'
}}>
{/* Cabecera Mockup */}
<div style={{
background: headerColor,
height: '120px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position: 'relative'
}}>
{/* Simular imagen de cabecera si hay Archivo */}
{headerImage && (
<img src={URL.createObjectURL(headerImage)} style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.6 }} />
)}
<h2 style={{ color: headerFontColor, margin: 0, zIndex: 1, textShadow: '0 2px 4px rgba(0,0,0,0.5)' }}>{orgName || "Tu Negocio"}</h2>
</div>
{/* Cuerpo Mockup (Servicios y Horarios) */}
<div style={{ padding: '20px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
<h4 style={{ margin: 0, color: 'white' }}>Servicios ({previewServices.length})</h4>
<button
onClick={() => {
setServiceName("");
setServiceDescription("");
setServiceLength(null);
setServicePrice("");
setServiceLimit(1);
setServiceImage(null);
setCreatedServiceId(null);
setIsAddingAnotherService(true);
setCurrentStepIndex(1); // Service creation starts at step 1
}}
style={{
background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)',
color: 'white', borderRadius: '15px', padding: '4px 12px', fontSize: '12px',
cursor: 'pointer', transition: 'background 0.2s'
}}
onMouseOver={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.2)'}
onMouseOut={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
>
+ Agregar otro
</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginBottom: '20px' }}>
{previewServices.map((s: any, idx: number) => (
<div key={idx} style={{ background: 'rgba(255,255,255,0.05)', padding: '10px', borderRadius: '8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<span style={{ color: 'white', fontWeight: 'bold', fontSize: '14px' }}>{s.name}</span>
<span style={{ color: 'rgba(255,255,255,0.6)', fontSize: '12px' }}>{s.length} min</span>
</div>
<span style={{ color: 'var(--wine-red)', fontWeight: 'bold' }}>${s.originalPrice}</span>
</div>
))}
{previewServices.length === 0 && (
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: '14px' }}>Sin servicios configurados aún.</span>
)}
</div>
<h4 style={{ margin: '0 0 10px 0', color: 'white' }}>Horario Laboral</h4>
<div style={{ background: 'rgba(255,255,255,0.05)', padding: '15px', borderRadius: '8px' }}>
<div style={{ color: 'white', fontSize: '14px', marginBottom: '5px' }}>
<strong>Días:</strong> {workingDaysMode === "mon-fri" ? "Lunes a Viernes" : (workingDaysMode === "mon-sat" ? "Lunes a Sábado" : "Lunes a Domingo")}
</div>
<div style={{ color: 'white', fontSize: '14px', marginBottom: '5px' }}>
<strong>Horario:</strong> {openTime} a {closeTime}
</div>
{hasBreak && (
<div style={{ color: 'white', fontSize: '14px' }}>
<strong>Descanso:</strong> {breakStart} a {breakEnd}
</div>
)}
</div>
</div>
</div>
{/* Advertencia Explícita */}
<div style={{
background: 'rgba(255, 60, 60, 0.1)',
borderLeft: '4px solid #ff3c3c',
padding: '15px',
borderRadius: '0 8px 8px 0',
width: '100%',
maxWidth: '500px'
}}>
<h4 style={{ margin: '0 0 5px 0', color: '#ff3c3c', fontSize: '16px' }}>🚨 Aviso de Publicación</h4>
<p style={{ margin: 0, color: 'rgba(255,255,255,0.8)', fontSize: '13px', lineHeight: '1.4' }}>
Al hacer clic en <strong>Publicar y Activar Agenda</strong>, tu organización, servicios y esta primera jornada laboral serán publicados en TurnosXpress.
<br/><br/>
¡Tus clientes podrán empezar a reservar turnos de inmediato! Podrás editar todo más tarde desde tu panel.
</p>
</div>
</div>
</QuestionCard>
</>
);
}
@@ -0,0 +1,224 @@
import React from "react";
import QuestionCard from "../../QuestionCard/QuestionCard";
import QuestionInput from "../../QuestionCard/QuestionInput";
type OnboardingServiceFlowProps = {
heatMapFraction: any;
currentStepIndex: any;
handleNext: any;
serviceName: any;
setServiceName: any;
serviceDescription: any;
setServiceDescription: any;
handleKeyDown: any;
serviceLength: any;
setServiceLength: any;
handleCreateService: any;
isCreating: any;
servicePrice: any;
setServicePrice: any;
serviceLimit: any;
setServiceLimit: any;
handleUploadServiceImage: any;
serviceImage: any;
setServiceImage: any;
};
export default function OnboardingServiceFlow(props: OnboardingServiceFlowProps) {
const { heatMapFraction, currentStepIndex, handleNext, serviceName, setServiceName, serviceDescription, setServiceDescription, handleKeyDown, serviceLength, setServiceLength, handleCreateService, isCreating, servicePrice, setServicePrice, serviceLimit, setServiceLimit, handleUploadServiceImage, serviceImage, setServiceImage } = props;
const fraction = heatMapFraction || 60;
const durationOptions = [fraction, fraction * 2, fraction * 3, fraction * 4];
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Configura tus Servicios"
description="Ya creaste tu negocio. Ahora necesitas configurar al menos un servicio para que tus clientes puedan empezar a reservar."
onNext={handleNext}
nextLabel="Comenzar"
>
<div style={{ color: "rgba(255, 255, 255, 0.7)", textAlign: "center", padding: "10px" }}>
Vamos a crear el primer servicio de tu negocio. ¡Es muy fácil!
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1}
title="1. Nombre y Descripción"
description="Elige un nombre atractivo y describe de qué trata el servicio."
onNext={handleNext}
disableNext={serviceName.trim().length < 3 || serviceDescription.trim().length < 5}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
<QuestionInput
placeholder="Ej. Corte clásico con lavado"
value={serviceName}
onChange={(e) => setServiceName(e.target.value)}
autoFocus
/>
<QuestionInput
placeholder="Breve descripción del servicio..."
value={serviceDescription}
onChange={(e) => setServiceDescription(e.target.value)}
onKeyDown={(e) => {
if (serviceName.trim().length >= 3 && serviceDescription.trim().length >= 5) {
handleKeyDown(e, handleNext);
}
}}
/>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 2}
title="2. Duración del Servicio"
description={`Elige cuánto tiempo tomará. Las opciones están basadas en tu fracción de agenda (${fraction} min).`}
onNext={handleNext}
disableNext={!serviceLength}
>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
{durationOptions.map(val => {
const hours = Math.floor(val / 60);
const minutes = val % 60;
const label = hours > 0
? `${hours}h ${minutes > 0 ? minutes + 'm' : ''}`.trim()
: `${minutes} min`;
return (
<div
key={val}
onClick={() => setServiceLength(val)}
style={{
padding: '12px 24px',
borderRadius: '12px',
cursor: 'pointer',
background: serviceLength === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${serviceLength === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
color: 'white',
fontWeight: serviceLength === val ? 'bold' : 'normal',
transition: 'all 0.2s ease',
fontSize: '16px'
}}
>
{label}
</div>
);
})}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="3. Precio y Cupos"
description="¿Cuánto cuesta y a cuántas personas puedes atender a la vez en este servicio?"
onNext={handleCreateService}
disableNext={isCreating || !servicePrice}
nextLabel={isCreating ? "Guardando..." : "Crear Servicio"}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%' }}>
<div>
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Precio Original</div>
<div style={{ position: 'relative' }}>
<span style={{ position: 'absolute', left: '15px', top: '50%', transform: 'translateY(-50%)', color: 'white', fontSize: '18px' }}>$</span>
<input
type="number"
placeholder="0.00"
value={servicePrice}
onChange={(e) => setServicePrice(e.target.value)}
style={{
width: '100%',
padding: '15px 15px 15px 35px',
borderRadius: '12px',
border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.05)',
color: 'white',
fontSize: '18px',
outline: 'none'
}}
/>
</div>
</div>
<div>
<div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Cupos Simultáneos (Por defecto 1)</div>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
{[1, 2, 3, 5, 10].map(val => (
<div
key={val}
onClick={() => setServiceLimit(val)}
style={{
padding: '8px 16px',
borderRadius: '8px',
cursor: 'pointer',
background: serviceLimit === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
border: `1px solid ${serviceLimit === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
color: 'white',
fontWeight: serviceLimit === val ? 'bold' : 'normal',
transition: 'all 0.2s ease'
}}
>
{val}
</div>
))}
</div>
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 4}
title="4. Imagen del Servicio"
description="Sube una foto representativa para que los clientes sepan qué ofreces. (Opcional)"
onNext={handleUploadServiceImage}
disableNext={isCreating}
nextLabel={isCreating ? "Subiendo..." : (serviceImage ? "Subir y Finalizar" : "Omitir por ahora")}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
<div style={{
width: '100%',
height: '150px',
border: '2px dashed rgba(255,255,255,0.3)',
borderRadius: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position: 'relative',
overflow: 'hidden',
cursor: 'pointer',
background: serviceImage ? 'transparent' : 'rgba(255,255,255,0.05)'
}}>
{serviceImage ? (
<img
src={URL.createObjectURL(serviceImage)}
alt="Preview"
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
/>
) : (
<span style={{ color: 'rgba(255,255,255,0.6)' }}>Toca para seleccionar imagen</span>
)}
<input
type="file"
accept="image/*"
onChange={(e) => {
if (e.target.files && e.target.files.length > 0) {
setServiceImage(e.target.files[0]);
}
}}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
opacity: 0,
cursor: 'pointer'
}}
/>
</div>
</div>
</QuestionCard>
</>
);
}
@@ -0,0 +1,218 @@
import React from "react";
import QuestionCard from "../../QuestionCard/QuestionCard";
type Props = any;
export default function OverrideScheduleFlow(props: Props) {
const { currentStepIndex, scheduleScope, setScheduleScope, targetEmployeeId, setTargetEmployeeId, allEmployees, handleNext, overrideDate, setOverrideDate, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleUpdateScheduleSubmit, handleOverrideScheduleSubmit, disableDuration, setDisableDuration, disableStartDate, setDisableStartDate, disableEndDate, setDisableEndDate, isFullDayDisabled, setIsFullDayDisabled, disableStartTime, setDisableStartTime, disableEndTime, setDisableEndTime, handleDisableScheduleSubmit } = props;
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Horario Especial"
description="¿A quiénes quieres aplicar este horario especial?"
onNext={() => {
if (scheduleScope === "specific" && !targetEmployeeId) {
alert("Por favor selecciona un colaborador.");
return;
}
handleNext();
}}
disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
<div
onClick={() => setScheduleScope("me")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>Solo a </h4>
</div>
<div
onClick={() => setScheduleScope("specific")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
</div>
<div
onClick={() => setScheduleScope("all")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
</div>
{scheduleScope === "specific" && (
<div style={{ marginTop: '15px', width: '100%' }}>
<select
value={targetEmployeeId || ""}
onChange={(e) => setTargetEmployeeId(e.target.value)}
style={{
width: '100%', padding: '12px', borderRadius: '8px',
background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
outline: 'none', fontSize: '16px'
}}
>
<option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
{allEmployees.map((emp: any) => (
<option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
{emp.firstName} {emp.lastName}
</option>
))}
</select>
</div>
)}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1}
title="Fecha de la Excepción"
description="¿En qué fecha deseas aplicar este horario distinto?"
onNext={handleNext}
disableNext={!overrideDate}
>
<div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
<input
type="date"
value={overrideDate}
onChange={(e) => setOverrideDate(e.target.value)}
style={{
padding: '12px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'sans-serif'
}}
/>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 2}
title="Horario Especial"
description="¿A qué hora empieza y termina la jornada para este día en particular?"
onNext={handleNext}
disableNext={!openTime || !closeTime}
>
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Apertura</label>
<input
type="time"
value={openTime}
onChange={(e) => setOpenTime(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Cierre</label>
<input
type="time"
value={closeTime}
onChange={(e) => setCloseTime(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="Descansos"
description="¿Habrá algún horario de descanso en este día especial?"
onNext={() => {
if (hasBreak) {
handleNext();
} else {
handleOverrideScheduleSubmit();
}
}}
disableNext={hasBreak === null}
nextLabel={hasBreak ? "Siguiente" : (isCreating ? "Guardando..." : "Guardar Excepción")}
>
<div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
<div
onClick={() => setHasBreak(true)}
style={{
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${hasBreak === true ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center'
}}
>
, hay descanso
</div>
<div
onClick={() => setHasBreak(false)}
style={{
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${hasBreak === false ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center'
}}
>
No, de corrido
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 4}
title="Horario de Descanso"
description="¿De qué hora a qué hora no estarán disponibles en este día?"
onNext={handleOverrideScheduleSubmit}
disableNext={!breakStart || !breakEnd || isCreating}
nextLabel={isCreating ? "Guardando..." : "Guardar Excepción"}
>
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Inicio descanso</label>
<input
type="time"
value={breakStart}
onChange={(e) => setBreakStart(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fin descanso</label>
<input
type="time"
value={breakEnd}
onChange={(e) => setBreakEnd(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
</div>
</QuestionCard>
</>
);
}
@@ -0,0 +1,92 @@
import React from "react";
import QrCode2Icon from "@mui/icons-material/QrCode2";
import QuestionCard from "../../QuestionCard/QuestionCard";
type PublicLinkFlowProps = {
options: any;
getPublicLink: any;
getPublicLinkQrUrl: any;
getSelectedOrganizationSlug: any;
setShowOnboardingPublicLink: any;
setIsSuccess: any;
router: any;
selectedOrganization: any;
orgName: any;
handleCopyPublicLink: any;
publicLinkCopied: any;
};
export default function PublicLinkFlow(props: PublicLinkFlowProps) {
const { options, getPublicLink, getPublicLinkQrUrl, getSelectedOrganizationSlug, setShowOnboardingPublicLink, setIsSuccess, router, selectedOrganization, orgName, handleCopyPublicLink, publicLinkCopied } = props;
const isOnboardingCompletion = options?.onboardingCompletion === true;
const publicLink = getPublicLink();
const publicLinkQrUrl = getPublicLinkQrUrl();
const orgSlug = getSelectedOrganizationSlug();
return (
<QuestionCard
isActive={true}
title="Link público y código QR"
description="Compartí este enlace para que tus clientes entren directo a la página pública de reservas de la organización. También podés usar el código QR en redes, vidriera o piezas impresas."
onNext={() => {
if (isOnboardingCompletion) {
setShowOnboardingPublicLink(false);
setIsSuccess(true);
return;
}
router.push("/admin/assistant");
}}
nextLabel={isOnboardingCompletion ? "Finalizar" : "Volver al asistente"}
topAccessory={<QrCode2Icon style={{ fontSize: 52, color: "var(--wine-red)" }} />}
>
<div style={{ display: "flex", flexDirection: "column", gap: "18px", width: "100%", maxWidth: "560px", margin: "0 auto" }}>
<div style={{ padding: "16px", borderRadius: "14px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.75)", lineHeight: 1.5, fontSize: "14px" }}>
Organización: <strong style={{ color: "white" }}>{selectedOrganization?.name || orgName || "Sin organización seleccionada"}</strong>
{orgSlug && (
<div style={{ marginTop: "6px", color: "rgba(255,255,255,0.62)", fontSize: "13px" }}>
Slug público: <strong style={{ color: "white" }}>{orgSlug}</strong>
</div>
)}
</div>
{publicLink ? (
<>
<div style={{ display: "flex", flexDirection: "column", gap: "10px", padding: "16px", borderRadius: "14px", background: "rgba(255,42,127,0.08)", border: "1px solid rgba(255,42,127,0.32)", boxShadow: "0 0 24px rgba(255,42,127,0.12)" }}>
<span style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px", fontWeight: 600 }}>Link público</span>
<a href={publicLink} target="_blank" rel="noopener noreferrer" style={{ color: "white", fontWeight: 700, wordBreak: "break-all", textDecoration: "none", fontSize: "16px" }}>
{publicLink}
</a>
</div>
<div style={{ display: "flex", gap: "10px", flexWrap: "wrap" }}>
<button type="button" onClick={handleCopyPublicLink} style={{ flex: 1, minWidth: "140px", padding: "12px 16px", borderRadius: "10px", background: "var(--wine-red)", border: "1px solid var(--wine-red)", color: "white", cursor: "pointer", fontWeight: 700, fontFamily: "inherit" }}>
{publicLinkCopied ? "Link copiado" : "Copiar link"}
</button>
<button type="button" onClick={() => window.open(publicLink, "_blank", "noopener,noreferrer")} style={{ flex: 1, minWidth: "140px", padding: "12px 16px", borderRadius: "10px", background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.16)", color: "white", cursor: "pointer", fontWeight: 700, fontFamily: "inherit" }}>
Abrir link
</button>
<a href={`${publicLinkQrUrl}&download=1`} download={`turnosxpress-${orgSlug}-qr.png`} style={{ flex: 1, minWidth: "140px", padding: "12px 16px", borderRadius: "10px", background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.16)", color: "white", cursor: "pointer", fontWeight: 700, fontFamily: "inherit", textAlign: "center", textDecoration: "none", boxSizing: "border-box" }}>
Descargar QR
</a>
</div>
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "12px", padding: "18px", borderRadius: "16px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)" }}>
<div style={{ padding: "14px", borderRadius: "12px", background: "white", boxShadow: "0 4px 20px rgba(0,0,0,0.3)" }}>
<img src={publicLinkQrUrl} width={260} height={260} alt={`Código QR para ${publicLink}`} style={{ display: "block", maxWidth: "100%", height: "auto" }} />
</div>
<span style={{ color: "rgba(255,255,255,0.62)", fontSize: "13px", textAlign: "center", lineHeight: 1.45 }}>
Este QR apunta al mismo link público. Si cambiás el nombre o slug de la organización, generá y compartí el QR actualizado.
</span>
</div>
</>
) : (
<div style={{ padding: "18px", borderRadius: "14px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.72)", textAlign: "center", lineHeight: 1.5 }}>
No encontramos un slug para esta organización. Revisá el nombre de la organización en la configuración del perfil y volvé a intentar.
</div>
)}
</div>
</QuestionCard>
);
}
@@ -0,0 +1,74 @@
import React from "react";
import QuestionCard from "../../QuestionCard/QuestionCard";
type Props = any;
export default function PublicVisibilityFlow(props: Props) {
const { isSelectedOrganizationPaidPlan, router, createdCompanyId, selectedOrganization, handleSavePublicVisibility, isCreating, orgShowPublicScores, setOrgShowPublicScores, orgShowPublicOpinions, setOrgShowPublicOpinions, orgShowPublicProfessionals, setOrgShowPublicProfessionals, servicesShowPublicScores, setServicesShowPublicScores, servicesShowPublicOpinions, setServicesShowPublicOpinions } = props;
const renderVisibilityCheckbox = (label: string, description: string, checked: boolean, onChange: (checked: boolean) => void) => (
<label style={{
display: 'flex', gap: '12px', alignItems: 'flex-start', padding: '14px', borderRadius: '12px',
background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', cursor: 'pointer'
}}>
<input
type="checkbox"
checked={checked}
onChange={(e) => onChange(e.target.checked)}
style={{ width: '18px', height: '18px', marginTop: '2px', accentColor: 'var(--wine-red)', cursor: 'pointer' }}
/>
<span style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
<span style={{ color: 'white', fontWeight: 700 }}>{label}</span>
<span style={{ color: 'rgba(255,255,255,0.65)', fontSize: '13px', lineHeight: 1.4 }}>{description}</span>
</span>
</label>
);
return (() => {
if (!isSelectedOrganizationPaidPlan()) {
return (
<QuestionCard
isActive={true}
title="Esta configuración requiere un plan pago"
description="La visibilidad pública de opiniones, puntuaciones y profesionales está disponible para organizaciones con plan pago activo. El flujo seguirá visible para que puedas volver cuando actualices tu plan."
onNext={() => router.push(createdCompanyId ? `/landing/upgrade-plan?org=${createdCompanyId}` : "/landing/pricing")}
nextLabel="Ver planes"
>
<div style={{
color: 'rgba(255,255,255,0.75)', textAlign: 'center', padding: '18px', borderRadius: '16px',
background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', lineHeight: 1.5
}}>
Estás configurando {selectedOrganization?.name ? <strong>{selectedOrganization.name}</strong> : "esta organización"}. Para cambiar qué opiniones, puntuaciones y profesionales se muestran públicamente, el dueño de esta organización necesita un plan pago.
</div>
</QuestionCard>
);
}
return (
<QuestionCard
isActive={true}
title="Configura la visibilidad pública"
description="Elige qué información verán tus clientes en la página pública de la organización y sus servicios. Si un valor nunca fue configurado, se considera visible por defecto."
onNext={handleSavePublicVisibility}
disableNext={isCreating}
nextLabel={isCreating ? "Guardando..." : "Guardar configuración"}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '18px', width: '100%' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<h3 style={{ color: 'white', margin: 0, fontSize: '16px' }}>Organización</h3>
{renderVisibilityCheckbox("Mostrar puntuación pública", "Permite que los clientes vean la puntuación promedio de la organización.", orgShowPublicScores, setOrgShowPublicScores)}
{renderVisibilityCheckbox("Mostrar opiniones públicas", "Permite que los clientes vean las opiniones recibidas por la organización.", orgShowPublicOpinions, setOrgShowPublicOpinions)}
{renderVisibilityCheckbox("Mostrar profesionales públicos", "Permite que los clientes vean la lista de profesionales de la organización.", orgShowPublicProfessionals, setOrgShowPublicProfessionals)}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<h3 style={{ color: 'white', margin: 0, fontSize: '16px' }}>Servicios</h3>
{renderVisibilityCheckbox("Mostrar puntuación pública de servicios", "Aplica este valor a todos los servicios de la organización.", servicesShowPublicScores, setServicesShowPublicScores)}
{renderVisibilityCheckbox("Mostrar opiniones públicas de servicios", "Aplica este valor a todos los servicios de la organización.", servicesShowPublicOpinions, setServicesShowPublicOpinions)}
</div>
</div>
</QuestionCard>
);
})();
}
@@ -0,0 +1,112 @@
import React from "react";
import dayjs from "dayjs";
import QuestionCard from "../../QuestionCard/QuestionCard";
type Props = any;
export default function ReservationPeriodFlow(props: Props) {
const { reservationPeriodEmployeesLoading, currentStepIndex, reservationPeriodEmployeesError, allEmployees, reservationPeriodScope, setReservationPeriodScope, targetEmployeeId, setTargetEmployeeId, reservationPeriodSummary, handleNext, reservationPeriodDuration, setReservationPeriodDuration, reservationPeriodOptions, handleExtendReservationPeriods, isCreating, selectedOrganization, orgName } = props;
if (reservationPeriodEmployeesLoading) {
return <QuestionCard isActive={currentStepIndex === 0} title="Cargando colaboradores" description="Estamos buscando los colaboradores disponibles para extender el período de reservas." disableNext nextLabel="Cargando..."><div /></QuestionCard>;
}
if (reservationPeriodEmployeesError || allEmployees.length === 0) {
return <QuestionCard isActive={currentStepIndex === 0} title="No pudimos preparar la extensión" description={reservationPeriodEmployeesError || "No encontramos colaboradores activos para extender el período de reservas."} disableNext nextLabel="Extensión bloqueada"><div /></QuestionCard>;
}
const needsEmployeeSelection = allEmployees.length > 1 && reservationPeriodScope === "employee";
const selectedEmployee = allEmployees.find((employee: any) => String(employee.id || employee._id || employee.employeeId) === String(targetEmployeeId));
const reservationPeriodEmployees = reservationPeriodSummary?.employees || [];
const getReservationPeriodEmployeeSummary = (employee: any) => {
const employeeKey = employee.id || employee._id || employee.employeeId;
return reservationPeriodEmployees.find((summary: any) => String(summary.employeeId) === String(employeeKey));
};
const getReservationPeriodStatus = (employee: any) => {
const summary = getReservationPeriodEmployeeSummary(employee);
const daysRemaining = summary?.daysRemaining;
const safeDaysRemaining = typeof daysRemaining === "number" ? Math.max(daysRemaining, 0) : 0;
const progress = Math.min(Math.round((safeDaysRemaining / 30) * 100), 100);
const color = !summary?.isOpen || safeDaysRemaining === 0 ? "#ef4444" : safeDaysRemaining <= 7 ? "#f59e0b" : "#22c55e";
let label = "Sin período abierto";
if (summary?.isOpen && typeof daysRemaining === "number") {
if (daysRemaining < 0) label = "Vencido";
else if (daysRemaining === 1) label = "1 día restante";
else label = `${daysRemaining} días restantes`;
} else if (typeof daysRemaining === "number" && daysRemaining < 0) {
label = "Vencido";
}
return {
label,
color,
progress,
openUntilLabel: summary?.currentOpenUntil ? `Abierto hasta ${dayjs(summary.currentOpenUntil).format("D [de] MMMM")}` : null
};
};
return (
<>
{allEmployees.length > 1 && (
<QuestionCard isActive={currentStepIndex === 0} title="Elegí a quién extenderle el período" description="Podés abrir reservas para todos los colaboradores o para uno específico." onNext={handleNext} disableNext={!reservationPeriodScope || (needsEmployeeSelection && !targetEmployeeId)} nextLabel="Siguiente">
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
<SelectionCard selected={reservationPeriodScope === "all"} onClick={() => { setReservationPeriodScope("all"); setTargetEmployeeId(null); }} title="Todos los colaboradores" description="Extiende el período de reservas para todo el equipo." />
<SelectionCard selected={reservationPeriodScope === "employee"} onClick={() => setReservationPeriodScope("employee")} title="Un colaborador específico" description="Elige una persona del equipo." />
{needsEmployeeSelection && (
<div style={{ display: "flex", flexDirection: "column", gap: "8px", marginTop: "8px" }}>
{allEmployees.map((employee: any) => {
const employeeKey = employee.id || employee._id || employee.employeeId;
const isSelected = String(targetEmployeeId) === String(employeeKey);
const periodStatus = getReservationPeriodStatus(employee);
return (
<div key={employeeKey} onClick={() => setTargetEmployeeId(employeeKey)} style={{ padding: "12px 14px", borderRadius: "10px", cursor: "pointer", background: isSelected ? "rgba(255,42,127,0.18)" : "rgba(255,255,255,0.04)", border: `1px solid ${isSelected ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`, color: "white" }}>
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
<div style={{ display: "flex", justifyContent: "space-between", gap: "12px", alignItems: "flex-start" }}>
<span style={{ fontWeight: 600 }}>{employee.fullName || `${employee.firstName || ""} ${employee.lastName || ""}`.trim() || employee.email || "Colaborador"}</span>
<span style={{ color: periodStatus.color, fontSize: "12px", fontWeight: 700, whiteSpace: "nowrap" }}>{periodStatus.label}</span>
</div>
<div style={{ height: "7px", borderRadius: "999px", background: "rgba(255,255,255,0.12)", overflow: "hidden" }}>
<div style={{ width: `${periodStatus.progress}%`, minWidth: periodStatus.progress > 0 ? "8px" : 0, height: "100%", borderRadius: "999px", background: periodStatus.color, transition: "width 0.2s ease" }} />
</div>
{periodStatus.openUntilLabel && <span style={{ color: "rgba(255,255,255,0.62)", fontSize: "12px" }}>{periodStatus.openUntilLabel}</span>}
</div>
</div>
);
})}
</div>
)}
</div>
</QuestionCard>
)}
<QuestionCard isActive={currentStepIndex === (allEmployees.length > 1 ? 1 : 0)} title="Elegí cuánto extender" description="Abriremos un nuevo bloque continuo desde el último día actualmente disponible." onNext={handleNext} disableNext={!reservationPeriodDuration} nextLabel="Siguiente">
<div style={{ display: "flex", gap: "10px", flexWrap: "wrap", width: "100%", justifyContent: "center" }}>
{reservationPeriodOptions.map((option: any) => {
const isSelected = reservationPeriodDuration?.unit === option.unit && reservationPeriodDuration.value === option.value;
return <div key={`${option.unit}-${option.value}`} onClick={() => setReservationPeriodDuration({ unit: option.unit, value: option.value })} style={{ padding: "12px 24px", borderRadius: "12px", cursor: "pointer", background: isSelected ? "var(--wine-red)" : "rgba(255,255,255,0.05)", border: `2px solid ${isSelected ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`, color: "white", fontWeight: isSelected ? "bold" : "normal", transition: "all 0.2s ease", fontSize: "16px" }}>{option.label}</div>;
})}
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === (allEmployees.length > 1 ? 2 : 1)} title="Confirmar extensión" description="Revisá la selección antes de abrir el nuevo período de reservas." onNext={handleExtendReservationPeriods} disableNext={isCreating || reservationPeriodEmployeesLoading || Boolean(reservationPeriodEmployeesError) || allEmployees.length === 0 || !reservationPeriodScope || !reservationPeriodDuration || (reservationPeriodScope === "employee" && !targetEmployeeId)} nextLabel={isCreating ? "Extendiendo..." : "Extender período"}>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%", maxWidth: "500px", margin: "0 auto", background: "rgba(255,255,255,0.05)", borderRadius: "12px", padding: "18px", border: "1px solid rgba(255,255,255,0.1)", color: "white" }}>
<SummaryLine label="Organización" value={selectedOrganization?.name || orgName} />
<SummaryLine label="Aplicar a" value={reservationPeriodScope === "all" ? "Todos los colaboradores" : (selectedEmployee?.fullName || selectedEmployee?.email || "Colaborador seleccionado")} />
<SummaryLine label="Duración" value={reservationPeriodOptions.find((option: any) => option.unit === reservationPeriodDuration?.unit && option.value === reservationPeriodDuration.value)?.label} />
{reservationPeriodSummary?.worstDaysRemaining !== null && reservationPeriodSummary?.worstDaysRemaining !== undefined && (
<div style={{ color: "rgba(255,255,255,0.7)", fontSize: "13px" }}>Menor disponibilidad actual: {reservationPeriodSummary.worstDaysRemaining} días restantes.</div>
)}
</div>
</QuestionCard>
</>
);
}
function SelectionCard({ selected, onClick, title, description }: Props) {
return <div onClick={onClick} style={{ padding: "18px", borderRadius: "12px", cursor: "pointer", background: selected ? "var(--wine-red)" : "rgba(255,255,255,0.05)", border: `2px solid ${selected ? "var(--wine-red)" : "rgba(255,255,255,0.1)"}`, color: "white", textAlign: "center", transition: "all 0.2s ease" }}><h4 style={{ margin: "0 0 5px 0", fontSize: "16px", fontWeight: selected ? "bold" : "normal" }}>{title}</h4><p style={{ margin: 0, fontSize: "13px", color: "rgba(255,255,255,0.75)" }}>{description}</p></div>;
}
function SummaryLine({ label, value }: Props) {
return <div><div style={{ color: "rgba(255,255,255,0.65)", fontSize: "13px" }}>{label}</div><div style={{ fontWeight: 700 }}>{value}</div></div>;
}
@@ -0,0 +1,155 @@
import React from "react";
import QuestionCard from "../../QuestionCard/QuestionCard";
import QuestionInput from "../../QuestionCard/QuestionInput";
import style from "../StepEngine.module.css";
type Props = any;
const DAY_LABELS = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
const getDayLabel = (day: number) => DAY_LABELS[day];
export default function SetupCollaboratorFlow(props: Props) {
const { currentStepIndex, collaboratorToSetup, setupMissingServices, setupMissingSchedules, setupSelectedServices, setSetupSelectedServices, setupAvailableServices, workingDaysMode, setWorkingDaysMode, customDays, setCustomDays, unifiedCustomSchedule, setUnifiedCustomSchedule, customSchedulesMap, setCustomSchedulesMap, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleSetupIntroNext, handleSetupServicesNext, handleSetupSchedulesNext } = props;
const canProceed = () => {
if (!workingDaysMode) return false;
if (workingDaysMode === "custom") {
if (customDays.length === 0) return false;
if (unifiedCustomSchedule === null) return false;
}
return true;
};
if (currentStepIndex === 0) {
return (
<QuestionCard isActive={true} title="Configuración de Colaborador" description={`El colaborador ${collaboratorToSetup?.name || ""} requiere tu atención para comenzar a recibir reservas.`} step={1} totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2} onNext={handleSetupIntroNext} nextLabel="Comenzar Configuración">
<div style={{ padding: "30px", background: 'linear-gradient(135deg, rgba(255, 65, 108, 0.1) 0%, rgba(255, 75, 43, 0.1) 100%)', border: '1px solid var(--wine-red)', borderRadius: '15px', color: 'white', textAlign: 'center', margin: '15px 0' }}>
<div style={{ fontSize: '40px', marginBottom: '10px' }}></div>
<p style={{ fontSize: '18px', fontWeight: 'bold', marginBottom: '15px' }}>Hemos detectado que a este colaborador le falta:</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', alignItems: 'center', marginBottom: '20px' }}>
{setupMissingServices && <MissingBadge icon="✂️" label="Servicios asignados" />}
{setupMissingSchedules && <MissingBadge icon="🕒" label="Horarios de atención" />}
</div>
<p style={{ opacity: 0.8, fontSize: '14px' }}>Te guiaremos paso a paso para configurarlo rápidamente.</p>
</div>
</QuestionCard>
);
}
if (currentStepIndex === 1) {
return (
<QuestionCard isActive={true} title="Asignación de Servicios" description="Selecciona los servicios que este colaborador podrá realizar." step={2} totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2} onNext={handleSetupServicesNext} nextLabel="Guardar y Continuar" disableNext={isCreating}>
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
{setupAvailableServices.map((service: any) => {
const serviceId = service.id || service._id;
const selected = setupSelectedServices.includes(serviceId);
return (
<div key={serviceId} onClick={() => setSetupSelectedServices((prev: string[]) => prev.includes(serviceId) ? prev.filter(i => i !== serviceId) : [...prev, serviceId])} style={{ padding: "15px", borderRadius: "10px", background: selected ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)", border: `1px solid ${selected ? "#fff" : "rgba(255,255,255,0.1)"}`, cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<div>
<div style={{ color: "#fff", fontWeight: "bold" }}>{service.name}</div>
<div style={{ color: "rgba(255,255,255,0.6)", fontSize: "13px" }}>{service.duration} min - ${service.price}</div>
</div>
{selected && <div style={{ color: "#fff" }}></div>}
</div>
);
})}
{setupAvailableServices.length === 0 && <div style={{ color: "rgba(255,255,255,0.6)" }}>No hay servicios creados en la organización.</div>}
</div>
</QuestionCard>
);
}
if (currentStepIndex === 2) {
return (
<QuestionCard isActive={true} title="Horarios de Atención" description="¿En qué días y horarios trabajará este colaborador?" step={setupMissingServices ? 3 : 2} totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2} onNext={() => handleSetupSchedulesNext(canProceed)} nextLabel="Guardar Horarios" disableNext={isCreating || !canProceed()}>
<div style={{ display: "flex", flexDirection: "column", gap: "10px", marginBottom: "20px" }}>
<ModeCard active={workingDaysMode === "mon-fri"} onClick={() => setWorkingDaysMode("mon-fri")} title="Lunes a Viernes" description="Horario comercial estándar" />
<ModeCard active={workingDaysMode === "mon-sat"} onClick={() => setWorkingDaysMode("mon-sat")} title="Lunes a Sábado" description="Jornada extendida" />
<ModeCard active={workingDaysMode === "mon-sun"} onClick={() => setWorkingDaysMode("mon-sun")} title="Todos los días" description="Lunes a Domingo" />
<ModeCard active={workingDaysMode === "custom"} onClick={() => setWorkingDaysMode("custom")} title="Otros / Personalizado" description="Selecciona días específicos y horarios variables" />
</div>
{workingDaysMode === "custom" && (
<div style={{ marginBottom: "25px", padding: "20px", background: "rgba(0,0,0,0.2)", borderRadius: "15px" }}>
<h4 style={{ color: "white", marginBottom: "15px" }}>Selecciona los días:</h4>
<div style={{ display: "flex", flexWrap: "wrap", gap: "10px", marginBottom: "20px" }}>
{[1,2,3,4,5,6,0].map(day => (
<div key={day} onClick={() => setCustomDays((prev: number[]) => prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day].sort())} style={{ padding: "8px 16px", borderRadius: "20px", cursor: "pointer", background: customDays.includes(day) ? "var(--wine-red)" : "rgba(255,255,255,0.1)", color: "white", fontWeight: customDays.includes(day) ? "bold" : "normal", transition: "all 0.2s", border: `1px solid ${customDays.includes(day) ? "var(--wine-red)" : "transparent"}` }}>
{getDayLabel(day)}
</div>
))}
</div>
{customDays.length > 0 && (
<div style={{ marginTop: "20px" }}>
<h4 style={{ color: "white", marginBottom: "15px", fontSize: "15px" }}>¿Utiliza el mismo horario para todos estos días?</h4>
<div style={{ display: "flex", gap: "10px" }}>
<button className={style.primaryButton} style={{ flex: 1, background: unifiedCustomSchedule === true ? "var(--wine-red)" : "rgba(255,255,255,0.1)", color: "white" }} onClick={() => setUnifiedCustomSchedule(true)}>, el mismo</button>
<button className={style.primaryButton} style={{ flex: 1, background: unifiedCustomSchedule === false ? "var(--wine-red)" : "rgba(255,255,255,0.1)", color: "white" }} onClick={() => setUnifiedCustomSchedule(false)}>No, personalizar por día</button>
</div>
</div>
)}
</div>
)}
{((workingDaysMode && workingDaysMode !== "custom") || (workingDaysMode === "custom" && unifiedCustomSchedule === true && customDays.length > 0)) && (
<TimeSettings openTime={openTime} setOpenTime={setOpenTime} closeTime={closeTime} setCloseTime={setCloseTime} hasBreak={hasBreak} setHasBreak={setHasBreak} breakStart={breakStart} setBreakStart={setBreakStart} breakEnd={breakEnd} setBreakEnd={setBreakEnd} />
)}
{workingDaysMode === "custom" && unifiedCustomSchedule === false && customDays.length > 0 && (
<div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
{customDays.map((day: number) => {
const ds = customSchedulesMap[day] || { openTime: "09:00", closeTime: "18:00", hasBreak: false, breakStart: "13:00", breakEnd: "14:00" };
const updateDS = (updates: any) => setCustomSchedulesMap((prev: any) => ({...prev, [day]: { ...ds, ...updates } }));
return <CustomDaySettings key={day} day={day} ds={ds} updateDS={updateDS} />;
})}
</div>
)}
</QuestionCard>
);
}
return null;
}
function MissingBadge({ icon, label }: Props) {
return <div style={{ background: 'rgba(0,0,0,0.3)', padding: '10px 20px', borderRadius: '20px', display: 'flex', alignItems: 'center', gap: '10px' }}><span>{icon}</span> {label}</div>;
}
function ModeCard({ active, onClick, title, description }: Props) {
return <div style={{ padding: "15px", borderRadius: "10px", background: active ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)", border: `1px solid ${active ? "#fff" : "rgba(255,255,255,0.1)"}`, cursor: "pointer", transition: "all 0.2s" }} onClick={onClick}><h4 style={{ color: "#fff", margin: "0 0 5px 0", fontSize: "16px" }}>{title}</h4><p style={{ color: "rgba(255,255,255,0.6)", margin: 0, fontSize: "13px" }}>{description}</p></div>;
}
function TimeSettings(props: Props) {
const { openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd } = props;
return (
<div className={style.timeSettingsContainer}>
<h4 style={{ color: "rgba(255,255,255,0.9)", marginBottom: "15px" }}>Horario de apertura y cierre</h4>
<div style={{ display: "flex", gap: "20px", marginBottom: "20px" }}>
<QuestionInput label="Hora de Apertura" type="time" value={openTime} onChange={(e) => setOpenTime(e.target.value)} />
<QuestionInput label="Hora de Cierre" type="time" value={closeTime} onChange={(e) => setCloseTime(e.target.value)} />
</div>
<div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "20px" }}>
<input type="checkbox" id="hasBreak" checked={hasBreak === true} onChange={(e) => setHasBreak(e.target.checked)} style={{ width: "18px", height: "18px" }} />
<label htmlFor="hasBreak" style={{ color: "rgba(255,255,255,0.8)", cursor: "pointer" }}>Tiene horario de descanso (almuerzo)</label>
</div>
{hasBreak && <div style={{ display: "flex", gap: "20px", marginBottom: "20px", padding: "15px", background: "rgba(0,0,0,0.2)", borderRadius: "10px" }}><QuestionInput label="Inicio de Descanso" type="time" value={breakStart} onChange={(e) => setBreakStart(e.target.value)} /><QuestionInput label="Fin de Descanso" type="time" value={breakEnd} onChange={(e) => setBreakEnd(e.target.value)} /></div>}
</div>
);
}
function CustomDaySettings({ day, ds, updateDS }: Props) {
return (
<div style={{ padding: "15px", background: "rgba(0,0,0,0.2)", borderRadius: "15px", border: "1px solid rgba(255,255,255,0.1)" }}>
<h4 style={{ color: "white", marginBottom: "15px", borderBottom: "1px solid rgba(255,255,255,0.1)", paddingBottom: "10px" }}>Configuración para {getDayLabel(day)}</h4>
<div style={{ display: "flex", gap: "20px", marginBottom: "15px" }}>
<QuestionInput label="Apertura" type="time" value={ds.openTime} onChange={(e) => updateDS({ openTime: e.target.value })} />
<QuestionInput label="Cierre" type="time" value={ds.closeTime} onChange={(e) => updateDS({ closeTime: e.target.value })} />
</div>
<div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "15px" }}>
<input type="checkbox" id={`hasBreak_${day}`} checked={ds.hasBreak === true} onChange={(e) => updateDS({ hasBreak: e.target.checked })} style={{ width: "18px", height: "18px" }} />
<label htmlFor={`hasBreak_${day}`} style={{ color: "rgba(255,255,255,0.8)", cursor: "pointer", fontSize: "14px" }}>Descanso</label>
</div>
{ds.hasBreak && <div style={{ display: "flex", gap: "20px", padding: "10px", background: "rgba(0,0,0,0.3)", borderRadius: "10px" }}><QuestionInput label="Inicio" type="time" value={ds.breakStart} onChange={(e) => updateDS({ breakStart: e.target.value })} /><QuestionInput label="Fin" type="time" value={ds.breakEnd} onChange={(e) => updateDS({ breakEnd: e.target.value })} /></div>}
</div>
);
}
@@ -0,0 +1,234 @@
import React from "react";
import QuestionCard from "../../QuestionCard/QuestionCard";
type Props = any;
export default function UpdateScheduleFlow(props: Props) {
const { currentStepIndex, scheduleScope, setScheduleScope, targetEmployeeId, setTargetEmployeeId, allEmployees, handleNext, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleUpdateScheduleSubmit, handleOverrideScheduleSubmit, disableDuration, setDisableDuration, disableStartDate, setDisableStartDate, disableEndDate, setDisableEndDate, isFullDayDisabled, setIsFullDayDisabled, disableStartTime, setDisableStartTime, disableEndTime, setDisableEndTime, handleDisableScheduleSubmit } = props;
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Actualizar Horarios"
description="¿A quiénes quieres aplicar esta nueva rutina de horarios?"
onNext={() => {
if (scheduleScope === "specific" && !targetEmployeeId) {
alert("Por favor selecciona un colaborador.");
return;
}
handleNext();
}}
disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
<div
onClick={() => setScheduleScope("me")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>Solo a </h4>
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Aplica esta rutina únicamente a tus horarios.</p>
</div>
<div
onClick={() => setScheduleScope("specific")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Aplica esta rutina a un integrante específico de tu equipo.</p>
</div>
<div
onClick={() => setScheduleScope("all")}
style={{
padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
}}
>
<h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Sobrescribe masivamente los horarios de todo tu equipo.</p>
</div>
{scheduleScope === "specific" && (
<div style={{ marginTop: '15px', width: '100%' }}>
<label style={{ color: 'white', display: 'block', marginBottom: '8px', fontSize: '14px' }}>Selecciona el colaborador:</label>
<select
value={targetEmployeeId || ""}
onChange={(e) => setTargetEmployeeId(e.target.value)}
style={{
width: '100%', padding: '12px', borderRadius: '8px',
background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
outline: 'none', fontSize: '16px'
}}
>
<option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
{allEmployees.map((emp: any) => (
<option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
{emp.firstName} {emp.lastName}
</option>
))}
</select>
</div>
)}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1}
title="Días de Trabajo"
description="¿Qué días aplicará esta rutina?"
onNext={handleNext}
disableNext={!workingDaysMode}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
{[
{ id: 'mon-fri', label: 'Lunes a Viernes' },
{ id: 'mon-sat', label: 'Lunes a Sábado' },
{ id: 'mon-sun', label: 'Todos los días' }
].map(mode => (
<div
key={mode.id}
onClick={() => setWorkingDaysMode(mode.id)}
style={{
padding: '15px',
borderRadius: '12px',
cursor: 'pointer',
background: workingDaysMode === mode.id ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${workingDaysMode === mode.id ? 'var(--wine-red)' : 'transparent'}`,
color: 'white',
textAlign: 'center',
transition: 'all 0.2s ease'
}}
>
{mode.label}
</div>
))}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 2}
title="Horario Comercial"
description="¿A qué hora empieza y termina la jornada laboral?"
onNext={handleNext}
disableNext={!openTime || !closeTime}
>
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Apertura</label>
<input
type="time"
value={openTime}
onChange={(e) => setOpenTime(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Cierre</label>
<input
type="time"
value={closeTime}
onChange={(e) => setCloseTime(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 3}
title="Descansos"
description="¿Tienen un horario de corte al mediodía o descanso?"
onNext={() => {
if (hasBreak) {
handleNext();
} else {
handleUpdateScheduleSubmit();
}
}}
disableNext={hasBreak === null}
nextLabel={hasBreak ? "Siguiente" : (isCreating ? "Guardando..." : "Guardar Horarios")}
>
<div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
<div
onClick={() => setHasBreak(true)}
style={{
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${hasBreak === true ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center'
}}
>
, hay descanso
</div>
<div
onClick={() => setHasBreak(false)}
style={{
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
border: `2px solid ${hasBreak === false ? 'var(--wine-red)' : 'transparent'}`,
color: 'white', textAlign: 'center'
}}
>
No, horario corrido
</div>
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 4}
title="Horario de Descanso"
description="¿De qué hora a qué hora no estarán disponibles?"
onNext={handleUpdateScheduleSubmit}
disableNext={!breakStart || !breakEnd || isCreating}
nextLabel={isCreating ? "Guardando..." : "Guardar Horarios"}
>
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Inicio descanso</label>
<input
type="time"
value={breakStart}
onChange={(e) => setBreakStart(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fin descanso</label>
<input
type="time"
value={breakEnd}
onChange={(e) => setBreakEnd(e.target.value)}
style={{
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
fontSize: '18px', fontFamily: 'monospace'
}}
/>
</div>
</div>
</QuestionCard>
</>
);
}
@@ -0,0 +1,116 @@
import React from "react";
import WhatsAppIcon from "@mui/icons-material/WhatsApp";
import QuestionCard from "../../QuestionCard/QuestionCard";
type WhatsAppBotFlowProps = {
wapPhase: any;
wapAction: any;
wapView: any;
wapQr: any;
wapError: any;
createdCompanyId: any;
router: any;
loadWapView: any;
handleWapAssignServer: any;
handleWapCreateBot: any;
handleWapQuitServer: any;
handleWapStartBot: any;
handleWapDeleteBot: any;
handleWapVerifyQr: any;
handleWapStopBot: any;
getImageFromBase64: any;
setIsSuccess: any;
setWapPhase: any;
setWapError: any;
};
export default function WhatsAppBotFlow(props: WhatsAppBotFlowProps) {
const { wapPhase, wapAction, wapView, wapQr, wapError, createdCompanyId, router, loadWapView, handleWapAssignServer, handleWapCreateBot, handleWapQuitServer, handleWapStartBot, handleWapDeleteBot, handleWapVerifyQr, handleWapStopBot, getImageFromBase64, setIsSuccess, setWapPhase, setWapError } = props;
return (
<>
<QuestionCard isActive={wapPhase === "intro"} title="Bot de WhatsApp" description="Vamos a configurar tu bot de WhatsApp. Esto te permitirá enviar notificaciones automáticas a tus clientes. Primero verificamos el estado actual de tu organización." onNext={loadWapView} nextLabel="Verificar estado" topAccessory={<WhatsAppIcon style={{ fontSize: 48, color: "#25D366" }} />}>
{null}
</QuestionCard>
<QuestionCard isActive={wapPhase === "plan-required"} title="Plan no compatible" description="Tu plan actual no incluye notificaciones por WhatsApp. Necesitás un plan que incluya esta funcionalidad para configurar el bot." onNext={() => router.push(`/landing/upgrade-plan?org=${createdCompanyId}`)} nextLabel="Ver planes" topAccessory={<div style={{ fontSize: 48 }}>📦</div>}>
<div style={{ padding: "14px", borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)", color: "rgba(255,255,255,0.7)", fontSize: "13px", lineHeight: 1.5 }}>
Actualizá tu plan para desbloquear notificaciones por WhatsApp y mejorar la comunicación con tus clientes.
</div>
</QuestionCard>
<QuestionCard isActive={wapPhase === "assign-server"} title="Asignar servidor" description="Tu organización necesita un servidor de WhatsApp. Vamos a asignar uno automáticamente." onNext={handleWapAssignServer} disableNext={wapAction !== null} nextLabel={wapAction === "assign" ? "Asignando servidor..." : "Asignar servidor"} topAccessory={<div style={{ fontSize: 48 }}>🖥</div>}>
{wapAction === "assign" && <LoadingMessage label="Asignando servidor..." />}
</QuestionCard>
<QuestionCard isActive={wapPhase === "create-bot"} title="Crear bot de WhatsApp" description={`Servidor asignado: ${wapView?.serverName || "disponible"}. Ahora vamos a crear tu bot de WhatsApp.`} onNext={handleWapCreateBot} disableNext={wapAction !== null} nextLabel={wapAction === "create" ? "Creando bot..." : "Crear bot de WhatsApp"} topAccessory={<div style={{ fontSize: 48 }}>🤖</div>}>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
{wapAction === "create" && <LoadingMessage label="Creando bot..." />}
<SecondaryButton onClick={handleWapQuitServer} disabled={wapAction !== null} loading={wapAction === "quit"} loadingLabel="Desasignando servidor..." label="Desasignar servidor" />
</div>
</QuestionCard>
<QuestionCard isActive={wapPhase === "start-bot"} title="Iniciar bot" description="Tu bot de WhatsApp está creado pero detenido. Vamos a iniciarlo." onNext={handleWapStartBot} disableNext={wapAction !== null} nextLabel={wapAction === "start" ? "Iniciando bot..." : "Iniciar bot"} topAccessory={<div style={{ fontSize: 48 }}></div>}>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
{wapAction === "start" && <LoadingMessage label="Iniciando bot..." />}
<SecondaryButton onClick={handleWapDeleteBot} disabled={wapAction !== null} loading={wapAction === "delete"} loadingLabel="Eliminando bot..." label="Eliminar bot" />
</div>
</QuestionCard>
<QuestionCard isActive={wapPhase === "scan-qr"} title="Escanear código QR" description="Tu bot está funcionando. Ahora necesitás vincular tu número de WhatsApp escaneando este código QR con tu teléfono." onNext={handleWapVerifyQr} disableNext={wapAction !== null} nextLabel={wapAction === "verify" ? "Verificando..." : "Ya escaneé el código"} topAccessory={<div style={{ fontSize: 48 }}>📱</div>}>
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "16px", width: "100%" }}>
{wapQr ? (
<div style={{ padding: "16px", borderRadius: "12px", background: "white", boxShadow: "0 4px 20px rgba(0,0,0,0.3)" }}>
<img src={getImageFromBase64(wapQr)} width={250} height={250} alt="Escaneá el código QR" style={{ display: "block" }} />
</div>
) : (
<div style={{ width: 250, height: 250, borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "2px dashed rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center", color: "rgba(255,255,255,0.5)", fontSize: "14px" }}>Cargando QR...</div>
)}
<div style={{ padding: "12px 16px", borderRadius: "10px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)", color: "rgba(255,255,255,0.7)", fontSize: "13px", lineHeight: 1.5, textAlign: "center", maxWidth: "350px" }}>
Abrí WhatsApp en tu teléfono <strong style={{ color: "white" }}>Configuración</strong> <strong style={{ color: "white" }}>Dispositivos vinculados</strong> <strong style={{ color: "white" }}>Vincular dispositivo</strong>
</div>
{wapError && <div style={{ padding: "12px 16px", borderRadius: "10px", background: "rgba(255,60,60,0.1)", border: "1px solid rgba(255,60,60,0.3)", color: "#ff9999", fontSize: "13px", textAlign: "center", maxWidth: "350px" }}>{wapError}</div>}
<SecondaryButton onClick={handleWapStopBot} disabled={wapAction !== null} loading={wapAction === "stop"} loadingLabel="Deteniendo bot..." label="Detener bot" />
</div>
</QuestionCard>
<QuestionCard isActive={wapPhase === "bot-ready"} title="¡Bot funcionando!" description="Tu bot de WhatsApp está conectado y funcionando correctamente. Ya puede enviar notificaciones a tus clientes." onNext={() => setIsSuccess(true)} nextLabel="Finalizar" topAccessory={<div style={{ fontSize: 48 }}></div>}>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
<div style={{ padding: "14px", borderRadius: "12px", background: "rgba(74,222,128,0.08)", border: "1px solid rgba(74,222,128,0.2)", color: "#4ade80", fontSize: "13px", textAlign: "center", fontWeight: 600 }}>
Sesión de WhatsApp activa Bot operativo
</div>
<SecondaryButton onClick={handleWapStopBot} disabled={wapAction !== null} loading={wapAction === "stop"} loadingLabel="Deteniendo bot..." label="Detener bot" />
</div>
</QuestionCard>
<QuestionCard isActive={wapPhase === "error"} title="Error" description={wapError || "Ocurrió un error inesperado. Por favor, intentá nuevamente."} onNext={() => { setWapPhase("intro"); setWapError(null); }} nextLabel="Reintentar" topAccessory={<div style={{ fontSize: 48 }}></div>}>
<div style={{ padding: "14px", borderRadius: "12px", background: "rgba(255,60,60,0.1)", border: "1px solid rgba(255,60,60,0.3)", color: "#ff9999", fontSize: "13px", lineHeight: 1.5 }}>
Si el problema persiste, contactá al soporte de TurnosXpress.
</div>
</QuestionCard>
<style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
</>
);
}
function LoadingMessage({ label }: { label: string }) {
return (
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "12px", padding: "20px 0" }}>
<Spinner size={36} borderWidth={3} />
<span style={{ color: "rgba(255,255,255,0.7)", fontSize: "14px" }}>{label}</span>
</div>
);
}
function SecondaryButton({ onClick, disabled, loading, loadingLabel, label }: any) {
return (
<button type="button" onClick={onClick} disabled={disabled} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "8px", padding: "12px 20px", borderRadius: "10px", width: "100%", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.15)", color: "rgba(255,255,255,0.7)", cursor: "pointer", fontSize: "14px", fontWeight: 600, fontFamily: "inherit", transition: "all 0.2s ease", marginTop: "4px" }}>
{loading ? <><Spinner size={18} borderWidth={2} />{loadingLabel}</> : label}
</button>
);
}
function Spinner({ size, borderWidth }: { size: number; borderWidth: number }) {
return <div style={{ width: size, height: size, border: `${borderWidth}px solid rgba(255,255,255,0.2)`, borderTopColor: "var(--wine-red)", borderRadius: "50%", animation: "spin 1s linear infinite" }} />;
}
@@ -0,0 +1,26 @@
export const getEmployeeId = (employee: any) => employee.id || employee._id || employee.employeeId;
export const getEmployeeUserId = (employee: any) => employee.userId?._id || employee.userId?.id || employee.userId;
export const getTargetEmployees = (
allEmployees: any[],
scheduleScope: "me" | "specific" | "all" | null,
targetEmployeeId: string | null,
sessionUserId: string
) => {
if (scheduleScope === "me") {
const me = allEmployees.find((employee: any) => String(getEmployeeUserId(employee)) === String(sessionUserId));
return me ? [me] : [];
}
if (scheduleScope === "specific") {
const specific = allEmployees.find((employee: any) => String(getEmployeeId(employee)) === String(targetEmployeeId));
return specific ? [specific] : [];
}
if (scheduleScope === "all") {
return [...allEmployees];
}
return [];
};
@@ -0,0 +1,10 @@
export const getImageFromBase64 = (base64: string): string => {
const base64Data = base64.includes("base64,") ? base64.split(",")[1] : base64;
const byteCharacters = atob(base64Data);
const byteArray = new Uint8Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteArray[i] = byteCharacters.charCodeAt(i);
}
const blob = new Blob([byteArray], { type: "image/png" });
return URL.createObjectURL(blob);
};
@@ -0,0 +1,16 @@
import { getSlug } from "@core/app/helpers/Slug";
export const getSelectedOrganizationSlug = (selectedOrganization: any, orgName: string) => {
return selectedOrganization?.slug || getSlug(selectedOrganization?.name || orgName || "");
};
export const getPublicLink = (selectedOrganization: any, orgName: string) => {
const slug = getSelectedOrganizationSlug(selectedOrganization, orgName);
const publicBaseUrl = process.env.NEXT_PUBLIC_BASE_URL || "https://turnosxpress.com.ar";
return slug ? `${publicBaseUrl.replace(/\/$/, "")}/${slug}` : "";
};
export const getPublicLinkQrUrl = (selectedOrganization: any, orgName: string) => {
const publicLink = getPublicLink(selectedOrganization, orgName);
return publicLink ? `https://api.qrserver.com/v1/create-qr-code/?size=260x260&format=png&data=${encodeURIComponent(publicLink)}` : "";
};
@@ -0,0 +1,26 @@
type ScheduleBlock = { from: string; to: string; disabled: boolean };
export const getWorkingDays = (workingDaysMode: string, customDays: number[] = []) => {
if (workingDaysMode === "mon-fri") return [1, 2, 3, 4, 5];
if (workingDaysMode === "mon-sat") return [1, 2, 3, 4, 5, 6];
if (workingDaysMode === "mon-sun") return [1, 2, 3, 4, 5, 6, 0];
if (workingDaysMode === "custom") return customDays;
return [];
};
export const buildScheduleBlocks = (
openTime: string,
closeTime: string,
hasBreak: boolean | null,
breakStart: string,
breakEnd: string
): ScheduleBlock[] => {
if (hasBreak) {
return [
{ from: openTime, to: breakStart, disabled: false },
{ from: breakEnd, to: closeTime, disabled: false }
];
}
return [{ from: openTime, to: closeTime, disabled: false }];
};
@@ -0,0 +1,6 @@
import dayjs from "dayjs";
export const dayjsFromHHmm = (hhmm: string) => {
const [h, m] = (hhmm || "00:00").split(":").map(Number);
return dayjs().hour(h || 0).minute(m || 0).second(0).millisecond(0);
};
@@ -0,0 +1,111 @@
import API from "@services/Api.Service";
type UseNewCollaboratorHandlersDeps = {
inviteEmail: string;
inviteCollaborator: any | null;
inviteRole: "admin" | "colaborador";
createdCompanyId: string | null;
sessionUserId: string;
setInviteEmail: (value: string) => void;
setInviteCollaborator: (value: any | null) => void;
setInviteEmailError: (value: string) => void;
setInviteRole: (value: "admin" | "colaborador") => void;
setIsSearchingEmail: (value: boolean) => void;
setIsCreating: (value: boolean) => void;
setIsUpgradeRequired: (value: boolean) => void;
setInviteFlowNotice: (value: string) => void;
setCurrentStepIndex: (value: number) => void;
handleNext: () => void;
};
export function useNewCollaboratorHandlers({
inviteEmail,
inviteCollaborator,
inviteRole,
createdCompanyId,
sessionUserId,
setInviteEmail,
setInviteCollaborator,
setInviteEmailError,
setInviteRole,
setIsSearchingEmail,
setIsCreating,
setIsUpgradeRequired,
setInviteFlowNotice,
setCurrentStepIndex,
handleNext
}: UseNewCollaboratorHandlersDeps) {
const handleSearchCollaboratorEmail = async () => {
if (!inviteEmail || !inviteEmail.includes("@")) return;
setIsSearchingEmail(true);
setInviteEmailError("");
setInviteCollaborator(null);
try {
const data = await API.post<any>("users/get-by-email", { email: inviteEmail.trim().toLowerCase() });
if (data && (data.id || data._id)) {
if ((data.id || data._id) === sessionUserId) {
setInviteEmailError("No puedes invitarte a ti mismo.");
setIsSearchingEmail(false);
return;
}
setInviteCollaborator(data);
handleNext();
} else {
setInviteEmailError("Usuario no registrado");
}
} catch (error: any) {
setInviteEmailError("Usuario no registrado");
} finally {
setIsSearchingEmail(false);
}
};
const handleCreateCollaborator = async () => {
if (!inviteCollaborator || !createdCompanyId) return;
setIsCreating(true);
setInviteFlowNotice("");
try {
await API.post<any>("employees/create", {
companyId: createdCompanyId,
userId: inviteCollaborator.id || inviteCollaborator._id,
roles: inviteRole === "admin" ? ["admin"] : [],
hostOk: true,
sessionUser: sessionUserId
});
handleNext();
} catch (error: any) {
const errorMessage = error.desc || error.message || "Error al invitar al colaborador";
const normalizedErrorMessage = errorMessage.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
if (normalizedErrorMessage.includes("limite")) {
setIsUpgradeRequired(true);
} else if (normalizedErrorMessage.includes("invitacion") && normalizedErrorMessage.includes("pendiente")) {
setInviteFlowNotice("Ya se envió una invitación para que este usuario forme parte de la compañía y todavía no respondió.");
setCurrentStepIndex(5);
} else if (normalizedErrorMessage.includes("ya pertenece")) {
setInviteFlowNotice("Este usuario ya pertenece a la compañía.");
setCurrentStepIndex(6);
} else {
setInviteFlowNotice(errorMessage);
setCurrentStepIndex(5);
}
} finally {
setIsCreating(false);
}
};
const resetInviteFlow = () => {
setInviteEmail("");
setInviteCollaborator(null);
setInviteEmailError("");
setInviteRole("colaborador");
setIsUpgradeRequired(false);
setInviteFlowNotice("");
setCurrentStepIndex(1);
};
return {
handleSearchCollaboratorEmail,
handleCreateCollaborator,
resetInviteFlow
};
}
@@ -0,0 +1,117 @@
import API from "@services/Api.Service";
import type React from "react";
import { NotificationChannel, ReminderRule } from "@models/NotificationPreferences.model";
import { ALL_NOTIF_CHANNELS } from "../constants/notifications";
type UseNotificationsHandlersDeps = {
createdCompanyId: string | null;
sessionUserId: string;
isCreating: boolean;
notificationsScope: "org" | "client" | null;
notifChannels: NotificationChannel[];
notifQuietHoursActive: boolean;
notifQuietHoursFrom: string;
notifQuietHoursTo: string;
notifReminderRules: ReminderRule[];
notifSelectedClientId: string | null;
setNotificationsScope: (value: "org" | "client") => void;
setNotifChannels: React.Dispatch<React.SetStateAction<NotificationChannel[]>>;
setNotifQuietHoursActive: (value: boolean) => void;
setNotifQuietHoursFrom: (value: string) => void;
setNotifQuietHoursTo: (value: string) => void;
setNotifReminderRules: React.Dispatch<React.SetStateAction<ReminderRule[]>>;
setNotifSelectedClientId: (value: string | null) => void;
setIsCreating: (value: boolean) => void;
handleActionSuccess: () => void;
};
export function useNotificationsHandlers({
createdCompanyId,
sessionUserId,
isCreating,
notificationsScope,
notifChannels,
notifQuietHoursActive,
notifQuietHoursFrom,
notifQuietHoursTo,
notifReminderRules,
notifSelectedClientId,
setNotificationsScope,
setNotifChannels,
setNotifQuietHoursActive,
setNotifQuietHoursFrom,
setNotifQuietHoursTo,
setNotifReminderRules,
setNotifSelectedClientId,
setIsCreating,
handleActionSuccess
}: UseNotificationsHandlersDeps) {
const toggleNotifChannel = (channel: NotificationChannel) => {
setNotifChannels(prev =>
prev.includes(channel) ? prev.filter(c => c !== channel) : [...prev, channel]
);
};
const toggleNotifReminder = (minutes: number) => {
const exists = notifReminderRules.some(r => r.offset === minutes);
if (exists) {
setNotifReminderRules(prev => prev.filter(r => r.offset !== minutes));
} else {
setNotifReminderRules(prev => [...prev, { offset: minutes, enabled: true }]);
}
};
const handleSelectNotifScope = (scope: "org" | "client") => {
setNotificationsScope(scope);
setNotifChannels([]);
setNotifQuietHoursActive(false);
setNotifQuietHoursFrom("22:00");
setNotifQuietHoursTo("08:00");
setNotifReminderRules([]);
setNotifSelectedClientId(null);
};
const handleSaveNotifications = async () => {
if (!createdCompanyId || isCreating) return;
if (notificationsScope === "client" && !notifSelectedClientId) return;
setIsCreating(true);
try {
if (notificationsScope === "org") {
const quietHours = notifQuietHoursActive
? { from: notifQuietHoursFrom, to: notifQuietHoursTo }
: null;
await API.post<any>("notifications/policy/save", {
companyId: createdCompanyId,
sessionUser: sessionUserId,
defaultChannels: notifChannels,
timezone: "America/Argentina/Buenos_Aires",
quietHours: quietHours || undefined,
reminderRules: notifReminderRules
});
} else if (notificationsScope === "client") {
const preferredChannels = notifChannels as NotificationChannel[];
const mutedChannels = ALL_NOTIF_CHANNELS.filter(c => !preferredChannels.includes(c));
await API.post<any>("notifications/override/save", {
clientId: notifSelectedClientId,
companyId: createdCompanyId,
sessionUser: sessionUserId,
preferredChannels,
mutedChannels
});
}
handleActionSuccess();
} catch (error: any) {
console.error("Error guardando notificaciones:", error);
alert(error?.message || "Hubo un error al guardar las notificaciones.");
} finally {
setIsCreating(false);
}
};
return {
toggleNotifChannel,
toggleNotifReminder,
handleSelectNotifScope,
handleSaveNotifications
};
}
@@ -0,0 +1,55 @@
import API from "@services/Api.Service";
import { ReservationPeriodDuration, ReservationPeriodsSummary } from "@models/SchedulesEnabled.type";
type UseReservationPeriodHandlersDeps = {
createdCompanyId: string | null;
sessionUserId: string;
isCreating: boolean;
reservationPeriodScope: "employee" | "all" | null;
reservationPeriodDuration: ReservationPeriodDuration | null;
reservationPeriodEmployeesLoading: boolean;
reservationPeriodEmployeesError: string | null;
allEmployees: any[];
targetEmployeeId: string | null;
setIsCreating: (value: boolean) => void;
setIsSuccess: (value: boolean) => void;
};
export function useReservationPeriodHandlers({
createdCompanyId,
sessionUserId,
isCreating,
reservationPeriodScope,
reservationPeriodDuration,
reservationPeriodEmployeesLoading,
reservationPeriodEmployeesError,
allEmployees,
targetEmployeeId,
setIsCreating,
setIsSuccess
}: UseReservationPeriodHandlersDeps) {
const handleExtendReservationPeriods = async () => {
if (!createdCompanyId || !reservationPeriodScope || !reservationPeriodDuration || isCreating) return;
if (reservationPeriodEmployeesLoading || reservationPeriodEmployeesError || allEmployees.length === 0) return;
if (reservationPeriodScope === "employee" && !targetEmployeeId) return;
setIsCreating(true);
try {
await API.post<ReservationPeriodsSummary>("schedules-enabled/reservation-periods/extend", {
companyId: createdCompanyId,
scope: reservationPeriodScope,
employeeId: reservationPeriodScope === "employee" ? targetEmployeeId : undefined,
duration: reservationPeriodDuration,
sessionUser: sessionUserId
});
setIsSuccess(true);
} catch (error: any) {
console.error("Error extendiendo período de reservas:", error);
alert(error?.message || "Hubo un error al extender el período de reservas.");
} finally {
setIsCreating(false);
}
};
return { handleExtendReservationPeriods };
}
@@ -0,0 +1,124 @@
import API from "@services/Api.Service";
type UseWhatsAppBotHandlersDeps = {
createdCompanyId: string | null;
sessionUserId: string;
organizationSubscriptions: any;
wapAction: string | null;
setWapAction: (value: string | null) => void;
setWapError: (value: string | null) => void;
setWapPhase: (value: string) => void;
setWapQr: (value: string | null) => void;
setWapView: (value: any) => void;
setIsSuccess: (value: boolean) => void;
};
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
export function useWhatsAppBotHandlers({
createdCompanyId,
sessionUserId,
organizationSubscriptions,
wapAction,
setWapAction,
setWapError,
setWapPhase,
setWapQr,
setWapView,
setIsSuccess
}: UseWhatsAppBotHandlersDeps) {
const loadWapView = async () => {
if (!createdCompanyId) return;
setWapAction("load");
setWapError(null);
try {
const view = await API.post<any>("views/wap-server-view", {
companyId: createdCompanyId,
sessionUser: sessionUserId
});
setWapView(view);
const hasPlan = organizationSubscriptions?.[createdCompanyId]?.plan?.wapNotifications;
if (!hasPlan) {
setWapPhase("plan-required");
} else if (!view?.serverId) {
setWapPhase("assign-server");
} else if (!view?.exists) {
setWapPhase("create-bot");
} else if (view?.runningState && !String(view.runningState).includes("Up")) {
setWapPhase("start-bot");
} else if (view?.runningState && String(view.runningState).includes("Up") && view?.botSession !== "ok") {
setWapPhase("scan-qr");
try {
const qrData = await API.post<string>("wapserver/qr", {
companyId: createdCompanyId,
sessionUser: sessionUserId
});
setWapQr(qrData);
} catch {
setWapQr(null);
}
} else if (view?.runningState && String(view.runningState).includes("Up") && view?.botSession === "ok") {
setWapPhase("bot-ready");
}
} catch (err: any) {
console.error("Error loading WAP view:", err);
setWapError(err?.message || "Error al verificar el estado del bot.");
setWapPhase("error");
} finally {
setWapAction(null);
}
};
const runWapAction = async (actionName: string, endpoint: string, delayMs: number, errorMessage: string) => {
if (!createdCompanyId || wapAction) return;
setWapAction(actionName);
setWapError(null);
try {
await API.post<any>(endpoint, {
companyId: createdCompanyId,
sessionUser: sessionUserId
});
await wait(delayMs);
await loadWapView();
} catch (err: any) {
console.error(`Error ${actionName} WAP bot:`, err);
setWapError(err?.message || errorMessage);
setWapPhase("error");
} finally {
setWapAction(null);
}
};
const handleWapVerifyQr = async () => {
if (!createdCompanyId) return;
setWapAction("verify");
try {
const view = await API.post<any>("views/wap-server-view", {
companyId: createdCompanyId,
sessionUser: sessionUserId
});
setWapView(view);
if (view?.botSession === "ok") {
setIsSuccess(true);
} else {
setWapError("Aún no se detectó la conexión. Asegurate de haber escaneado el QR y volvé a intentar.");
}
} catch (err: any) {
setWapError(err?.message || "Error al verificar la conexión.");
} finally {
setWapAction(null);
}
};
return {
loadWapView,
handleWapAssignServer: () => runWapAction("assign", "wapserver/assign", 2000, "Error al asignar el servidor."),
handleWapCreateBot: () => runWapAction("create", "wapserver/create", 5000, "Error al crear el bot."),
handleWapStartBot: () => runWapAction("start", "wapserver/start", 3000, "Error al iniciar el bot."),
handleWapStopBot: () => runWapAction("stop", "wapserver/stop", 2000, "Error al detener el bot."),
handleWapDeleteBot: () => runWapAction("delete", "wapserver/delete", 3000, "Error al eliminar el bot."),
handleWapQuitServer: () => runWapAction("quit", "wapserver/quit", 2000, "Error al desasignar el servidor."),
handleWapVerifyQr
};
}