feat: add complex user invitation and management features
- Implemented complex member and invitation schemas using Zod for validation. - Created new API endpoints for inviting, accepting, revoking, and canceling complex user invitations. - Developed handlers for managing complex users, including listing, inviting, revoking, and canceling invitations. - Added frontend components for displaying and managing complex users and invitations. - Introduced session storage management for pending invitations. - Integrated Gravatar for user avatars based on email. - Created database migration for complex invitations table.
This commit is contained in:
47
apps/frontend/src/components/user-avatar.tsx
Normal file
47
apps/frontend/src/components/user-avatar.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
type UserAvatarProps = {
|
||||
src?: string | null;
|
||||
alt: string;
|
||||
fallbackText: string;
|
||||
size?: 'default' | 'sm' | 'lg';
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function getInitials(text: string) {
|
||||
const words = text.trim().split(/\s+/).filter(Boolean).slice(0, 2);
|
||||
const initials = words.map((word) => word[0]?.toUpperCase() ?? '').join('');
|
||||
return initials || 'U';
|
||||
}
|
||||
|
||||
export function UserAvatar({
|
||||
src,
|
||||
alt,
|
||||
fallbackText,
|
||||
size = 'default',
|
||||
className,
|
||||
}: UserAvatarProps) {
|
||||
const [imageError, setImageError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setImageError(false);
|
||||
}, [src]);
|
||||
|
||||
const canShowImage = Boolean(src) && !imageError;
|
||||
|
||||
return (
|
||||
<Avatar size={size} className={className}>
|
||||
{canShowImage && (
|
||||
<AvatarImage
|
||||
src={src ?? undefined}
|
||||
alt={alt}
|
||||
onError={() => {
|
||||
setImageError(true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<AvatarFallback>{getInitials(fallbackText)}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { setCurrentComplexSlug } from '@/lib/current-complex';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Building2, MapPin, Settings } from 'lucide-react';
|
||||
import { Building2, MapPin, Settings, Users } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ComplexCourtsSection } from './components/complex-courts-section';
|
||||
import { ComplexDetailsSection } from './components/complex-details-section';
|
||||
import { ComplexUsersSection } from './components/complex-users-section';
|
||||
|
||||
type ComplexSettingsPageProps = {
|
||||
complexSlug: string;
|
||||
};
|
||||
|
||||
type TabOption = 'details' | 'courts';
|
||||
type TabOption = 'details' | 'courts' | 'users';
|
||||
|
||||
export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
|
||||
const [activeTab, setActiveTab] = useState<TabOption>('details');
|
||||
@@ -24,11 +25,21 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
|
||||
queryFn: () => apiClient.complexes.getBySlug(complexSlug),
|
||||
});
|
||||
|
||||
const myComplexesQuery = useQuery({
|
||||
queryKey: ['my-complexes'],
|
||||
queryFn: () => apiClient.complexes.listMine(),
|
||||
});
|
||||
|
||||
const complexId = complexQuery.data?.id ?? null;
|
||||
const currentMembership = myComplexesQuery.data?.find(
|
||||
(complex) => complex.complexSlug === complexSlug
|
||||
);
|
||||
const canManageUsers = currentMembership?.role === 'ADMIN';
|
||||
|
||||
const tabs = [
|
||||
{ id: 'details' as const, label: 'Datos del complejo', icon: Building2 },
|
||||
{ id: 'courts' as const, label: 'Canchas', icon: MapPin },
|
||||
{ id: 'users' as const, label: 'Usuarios', icon: Users },
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -76,6 +87,10 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
|
||||
)}
|
||||
|
||||
{activeTab === 'courts' && <ComplexCourtsSection complexId={complexId} />}
|
||||
|
||||
{activeTab === 'users' && (
|
||||
<ComplexUsersSection complexId={complexId} canManageUsers={canManageUsers} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Field, FieldLabel } from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
ResponsiveDialog,
|
||||
ResponsiveDialogClose,
|
||||
ResponsiveDialogContent,
|
||||
ResponsiveDialogDescription,
|
||||
ResponsiveDialogFooter,
|
||||
ResponsiveDialogHeader,
|
||||
ResponsiveDialogTitle,
|
||||
} from '@/components/ui/responsive-dialog';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import type { ComplexUsersOverview } from '@repo/api-contract';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AlertCircle, Loader2, Mail, RotateCw, Trash2, UserPlus, UserX, Users } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
type ComplexUsersSectionProps = {
|
||||
complexId: string | null;
|
||||
canManageUsers: boolean;
|
||||
};
|
||||
|
||||
function formatDate(value: string) {
|
||||
return new Intl.DateTimeFormat('es-AR', {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function UsersSkeleton() {
|
||||
return (
|
||||
<section className="rounded-xl border bg-card p-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">Usuarios</h3>
|
||||
</div>
|
||||
<Separator className="my-4" />
|
||||
<p className="text-sm text-muted-foreground">Cargando usuarios...</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComplexUsersSection({ complexId, canManageUsers }: ComplexUsersSectionProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [email, setEmail] = useState('');
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [invitationToCancel, setInvitationToCancel] = useState<
|
||||
ComplexUsersOverview['invitations'][number] | null
|
||||
>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setEmail('');
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage(null);
|
||||
setInvitationToCancel(null);
|
||||
}, [complexId]);
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ['complex-users', complexId],
|
||||
enabled: Boolean(complexId),
|
||||
queryFn: () => apiClient.complexes.listUsers(complexId!),
|
||||
});
|
||||
|
||||
const inviteMutation = useMutation({
|
||||
mutationFn: (payload: { email: string }) => apiClient.complexes.inviteUser(complexId!, payload),
|
||||
onSuccess: async () => {
|
||||
setEmail('');
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage('Invitación enviada correctamente.');
|
||||
await queryClient.invalidateQueries({ queryKey: ['complex-users', complexId] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || 'No pudimos enviar la invitación.');
|
||||
setSuccessMessage(null);
|
||||
},
|
||||
});
|
||||
|
||||
const revokeMutation = useMutation({
|
||||
mutationFn: (userId: string) => apiClient.complexes.revokeUser(complexId!, { userId }),
|
||||
onSuccess: async () => {
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage('El usuario fue desvinculado del complejo.');
|
||||
await queryClient.invalidateQueries({ queryKey: ['complex-users', complexId] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || 'No pudimos revocar el permiso.');
|
||||
setSuccessMessage(null);
|
||||
},
|
||||
});
|
||||
|
||||
const resendInvitationMutation = useMutation({
|
||||
mutationFn: (invitationId: string) =>
|
||||
apiClient.complexes.resendInvitation(complexId!, invitationId),
|
||||
onSuccess: async () => {
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage('La invitación se reenvió correctamente.');
|
||||
await queryClient.invalidateQueries({ queryKey: ['complex-users', complexId] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || 'No pudimos reenviar la invitación.');
|
||||
setSuccessMessage(null);
|
||||
},
|
||||
});
|
||||
|
||||
const cancelInvitationMutation = useMutation({
|
||||
mutationFn: (invitationId: string) =>
|
||||
apiClient.complexes.cancelInvitation(complexId!, invitationId),
|
||||
onSuccess: async () => {
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage('La invitación fue cancelada.');
|
||||
setInvitationToCancel(null);
|
||||
await queryClient.invalidateQueries({ queryKey: ['complex-users', complexId] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || 'No pudimos cancelar la invitación.');
|
||||
setSuccessMessage(null);
|
||||
},
|
||||
});
|
||||
|
||||
const handleInvite = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage(null);
|
||||
|
||||
const trimmedEmail = email.trim();
|
||||
|
||||
if (!trimmedEmail) {
|
||||
setErrorMessage('Ingresá un email.');
|
||||
return;
|
||||
}
|
||||
|
||||
inviteMutation.mutate({ email: trimmedEmail });
|
||||
};
|
||||
|
||||
if (!complexId) {
|
||||
return (
|
||||
<section className="rounded-xl border bg-card p-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">Usuarios</h3>
|
||||
</div>
|
||||
<Separator className="my-4" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Seleccioná un complejo para ver sus usuarios.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
if (usersQuery.isLoading) {
|
||||
return <UsersSkeleton />;
|
||||
}
|
||||
|
||||
if (usersQuery.isError || !usersQuery.data) {
|
||||
return (
|
||||
<section className="rounded-xl border bg-card p-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">Usuarios</h3>
|
||||
</div>
|
||||
<Separator className="my-4" />
|
||||
<p className="text-sm text-destructive">No se pudieron cargar los usuarios del complejo.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const data: ComplexUsersOverview = usersQuery.data;
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border bg-card p-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">Usuarios</h3>
|
||||
</div>
|
||||
<Separator className="my-4" />
|
||||
|
||||
{canManageUsers ? (
|
||||
<form className="mb-6 rounded-lg border bg-muted/30 p-4" onSubmit={handleInvite}>
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<UserPlus className="size-4 text-muted-foreground" />
|
||||
<h4 className="text-sm font-medium">Invitar un usuario</h4>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<Field className="flex-1">
|
||||
<FieldLabel htmlFor="invite-email">Email</FieldLabel>
|
||||
<Input
|
||||
id="invite-email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
placeholder="empleado@correo.com"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className="flex items-end">
|
||||
<Button type="submit" disabled={inviteMutation.isPending}>
|
||||
{inviteMutation.isPending && <Loader2 className="mr-2 size-4 animate-spin" />}
|
||||
Enviar invitación
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
La invitación se envía por email y el usuario quedará vinculado como EMPLOYEE al
|
||||
aceptar.
|
||||
</p>
|
||||
</form>
|
||||
) : (
|
||||
<div className="mb-6 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
Solo un ADMIN puede invitar o desvincular usuarios.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{successMessage && (
|
||||
<p className="mb-4 text-sm text-green-600 dark:text-green-400">{successMessage}</p>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<p className="mb-4 flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="size-4" />
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h4 className="mb-3 text-sm font-medium">Miembros</h4>
|
||||
<div className="space-y-2">
|
||||
{data.members.map((member) => (
|
||||
<div
|
||||
key={member.userId}
|
||||
className="flex flex-col gap-3 rounded-lg border px-4 py-3 sm:flex-row sm:items-center sm:justify-between"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{member.fullName}</p>
|
||||
<p className="text-sm text-muted-foreground">{member.email}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Rol: {member.role} · Desde {formatDate(member.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<UserAvatar
|
||||
src={member.avatarUrl}
|
||||
alt={member.fullName}
|
||||
fallbackText={member.fullName}
|
||||
size="default"
|
||||
className="border"
|
||||
/>
|
||||
|
||||
{canManageUsers && member.role === 'EMPLOYEE' && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => revokeMutation.mutate(member.userId)}
|
||||
disabled={revokeMutation.isPending}
|
||||
>
|
||||
<UserX className="mr-2 size-4" />
|
||||
Revocar
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="mb-3 text-sm font-medium">Invitaciones pendientes</h4>
|
||||
{data.invitations.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No hay invitaciones pendientes.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{data.invitations.map((invitation) => (
|
||||
<div
|
||||
key={invitation.id}
|
||||
className="flex flex-col gap-2 rounded-lg border px-4 py-3 sm:flex-row sm:items-center sm:justify-between"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{invitation.email}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Vence {formatDate(invitation.expiresAt)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col items-start gap-2 sm:items-end">
|
||||
<span className="inline-flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground">
|
||||
<Mail className="size-3.5" />
|
||||
Pendiente
|
||||
</span>
|
||||
|
||||
{canManageUsers && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => resendInvitationMutation.mutate(invitation.id)}
|
||||
disabled={resendInvitationMutation.isPending}
|
||||
>
|
||||
<RotateCw className="mr-2 size-4" />
|
||||
Reenviar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => setInvitationToCancel(invitation)}
|
||||
disabled={cancelInvitationMutation.isPending}
|
||||
>
|
||||
<Trash2 className="mr-2 size-4" />
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={Boolean(invitationToCancel)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setInvitationToCancel(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ResponsiveDialogContent className="data-[variant=dialog]:max-w-md">
|
||||
<ResponsiveDialogHeader>
|
||||
<ResponsiveDialogTitle>Cancelar invitación</ResponsiveDialogTitle>
|
||||
<ResponsiveDialogDescription>
|
||||
Esta acción va a invalidar el link de invitación y la persona ya no podrá aceptar la
|
||||
invitación.
|
||||
</ResponsiveDialogDescription>
|
||||
</ResponsiveDialogHeader>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{invitationToCancel
|
||||
? `Se cancelará la invitación enviada a ${invitationToCancel.email}.`
|
||||
: 'Se cancelará la invitación seleccionada.'}
|
||||
</p>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Si querés volver a invitarlo, vas a poder generar una nueva invitación después.
|
||||
</p>
|
||||
|
||||
<ResponsiveDialogFooter>
|
||||
<ResponsiveDialogClose asChild>
|
||||
<Button variant="outline">Volver</Button>
|
||||
</ResponsiveDialogClose>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
if (!invitationToCancel) return;
|
||||
cancelInvitationMutation.mutate(invitationToCancel.id);
|
||||
}}
|
||||
disabled={cancelInvitationMutation.isPending}
|
||||
>
|
||||
{cancelInvitationMutation.isPending ? 'Cancelando...' : 'Cancelar invitación'}
|
||||
</Button>
|
||||
</ResponsiveDialogFooter>
|
||||
</ResponsiveDialogContent>
|
||||
</ResponsiveDialog>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -8,25 +7,49 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Link, Outlet, useNavigate } from '@tanstack/react-router';
|
||||
import { LogOut, Menu, UserRound } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { ThemeSwitcher } from './theme-switcher';
|
||||
|
||||
export function RootLayout() {
|
||||
const navigate = useNavigate();
|
||||
const { isAuthenticated, displayName, initials, avatarUrl, signOut } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const { user, isAuthenticated, displayName, avatarUrl, signOut } = useAuth();
|
||||
const { currentComplexSlug, setCurrentComplex } = useCurrentComplexStore();
|
||||
const processedInviteForUser = useRef<string | null>(null);
|
||||
const myComplexesQuery = useQuery({
|
||||
queryKey: ['my-complexes'],
|
||||
enabled: isAuthenticated,
|
||||
queryFn: () => apiClient.complexes.listMine(),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
processedInviteForUser.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const userKey = user?.email ?? displayName ?? 'authenticated-user';
|
||||
|
||||
if (processedInviteForUser.current === userKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
processedInviteForUser.current = userKey;
|
||||
|
||||
void (async () => {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
await queryClient.invalidateQueries({ queryKey: ['my-complexes'] });
|
||||
})();
|
||||
}, [displayName, isAuthenticated, queryClient, user?.email]);
|
||||
|
||||
const complexSlug = currentComplexSlug || myComplexesQuery.data?.[0]?.complexSlug;
|
||||
|
||||
const currentComplexName = useMemo(() => {
|
||||
@@ -85,10 +108,12 @@ export function RootLayout() {
|
||||
type="button"
|
||||
className="hidden items-center gap-2 rounded-md px-2 py-1.5 transition-colors hover:bg-muted md:inline-flex"
|
||||
>
|
||||
<Avatar size="sm">
|
||||
<AvatarImage src={avatarUrl ?? undefined} alt={displayName} />
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<UserAvatar
|
||||
src={avatarUrl}
|
||||
alt={displayName}
|
||||
fallbackText={displayName}
|
||||
size="sm"
|
||||
/>
|
||||
<span className="max-w-32 truncate text-sm text-foreground">{displayName}</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Field, FieldError, FieldLabel } from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { apiClient, authClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Link, useNavigate } from '@tanstack/react-router';
|
||||
import { useState } from 'react';
|
||||
@@ -39,6 +40,7 @@ export function LoginPage({ redirectTo = '/' }: LoginPageProps) {
|
||||
});
|
||||
|
||||
async function handlePostLogin() {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
const complexes = await apiClient.complexes.listMine();
|
||||
|
||||
if (complexes.length === 0) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Field, FieldError, FieldLabel } from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { apiClient, authClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { useState } from 'react';
|
||||
@@ -29,26 +30,46 @@ const signupSchema = z
|
||||
type LoginForm = z.infer<typeof loginSchema>;
|
||||
type SignupForm = z.infer<typeof signupSchema>;
|
||||
|
||||
export function OnboardLoginPage() {
|
||||
type OnboardLoginPageProps = {
|
||||
variant?: 'onboard' | 'invite';
|
||||
inviteEmail?: string | null;
|
||||
};
|
||||
|
||||
export function OnboardLoginPage({
|
||||
variant = 'onboard',
|
||||
inviteEmail = null,
|
||||
}: OnboardLoginPageProps) {
|
||||
const navigate = useNavigate();
|
||||
const { signInWithPassword, signUp } = useAuth();
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login');
|
||||
const [mode, setMode] = useState<'login' | 'signup'>(variant === 'invite' ? 'signup' : 'login');
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const loginForm = useForm<LoginForm>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
mode: 'onChange',
|
||||
defaultValues: { email: '', password: '' },
|
||||
defaultValues: { email: inviteEmail ?? '', password: '' },
|
||||
});
|
||||
|
||||
const signupForm = useForm<SignupForm>({
|
||||
resolver: zodResolver(signupSchema),
|
||||
mode: 'onChange',
|
||||
defaultValues: { fullName: '', email: '', password: '', confirmPassword: '' },
|
||||
defaultValues: {
|
||||
fullName: '',
|
||||
email: inviteEmail ?? '',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
},
|
||||
});
|
||||
|
||||
async function handlePostLogin() {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
|
||||
if (variant === 'invite') {
|
||||
await navigate({ to: '/' });
|
||||
return;
|
||||
}
|
||||
|
||||
const complexes = await apiClient.complexes.listMine();
|
||||
|
||||
if (complexes.length === 0) {
|
||||
@@ -93,7 +114,12 @@ export function OnboardLoginPage() {
|
||||
search: { email: values.email },
|
||||
});
|
||||
} else {
|
||||
navigate({ to: '/onboard/create-complex' });
|
||||
if (variant === 'invite') {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
await navigate({ to: '/' });
|
||||
} else {
|
||||
await handlePostLogin();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
setSubmitError('No pudimos crear la cuenta. Intenta nuevamente.');
|
||||
@@ -108,7 +134,7 @@ export function OnboardLoginPage() {
|
||||
try {
|
||||
await authClient.signIn.social({
|
||||
provider: 'google',
|
||||
callbackURL: `${window.location.origin}/onboard/create-complex`,
|
||||
callbackURL: `${window.location.origin}/auth-callback`,
|
||||
});
|
||||
} catch {
|
||||
setSubmitError('No pudimos iniciar sesión con Google.');
|
||||
@@ -123,8 +149,12 @@ export function OnboardLoginPage() {
|
||||
</h1>
|
||||
<p className="mb-4 text-sm text-muted-foreground">
|
||||
{mode === 'login'
|
||||
? 'Ingresá con tu cuenta para continuar.'
|
||||
: 'Creá tu cuenta para comenzar.'}
|
||||
? variant === 'invite'
|
||||
? 'Ingresá con tu cuenta para aceptar la invitación.'
|
||||
: 'Ingresá con tu cuenta para continuar.'
|
||||
: variant === 'invite'
|
||||
? 'Creá tu cuenta para aceptar la invitación.'
|
||||
: 'Creá tu cuenta para comenzar.'}
|
||||
</p>
|
||||
|
||||
<Button type="button" variant="outline" className="w-full" onClick={handleGoogleSignIn}>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { getPendingInvite } from '@/lib/invitations';
|
||||
import { Route } from '@/routes/onboard/verify-email';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { useEffect, useState } from 'react';
|
||||
@@ -6,6 +7,7 @@ import { useEffect, useState } from 'react';
|
||||
export function VerifyEmailPage() {
|
||||
const search = Route.useSearch();
|
||||
const email = search.email || sessionStorage.getItem('pending-signup-email') || '';
|
||||
const pendingInvite = getPendingInvite();
|
||||
const [resendCooldown, setResendCooldown] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -42,9 +44,22 @@ export function VerifyEmailPage() {
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
¿Ya verificaste tu email?{' '}
|
||||
<Link to="/onboard/create-complex" className="text-primary hover:underline">
|
||||
Continuar
|
||||
</Link>
|
||||
{pendingInvite.token ? (
|
||||
<Link
|
||||
to="/invite"
|
||||
search={{
|
||||
email: pendingInvite.email ?? email,
|
||||
inviteToken: pendingInvite.token,
|
||||
}}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
Continuar con la invitación
|
||||
</Link>
|
||||
) : (
|
||||
<Link to="/onboard/create-complex" className="text-primary hover:underline">
|
||||
Continuar
|
||||
</Link>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Form,
|
||||
@@ -9,6 +8,7 @@ import {
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
@@ -38,7 +38,7 @@ type UpdateProfileForm = z.infer<typeof updateProfileSchema>;
|
||||
type UpdatePasswordForm = z.infer<typeof updatePasswordSchema>;
|
||||
|
||||
export function ProfilePage() {
|
||||
const { user, displayName, initials, avatarUrl, isAuthenticated, updateProfile, updatePassword } =
|
||||
const { user, displayName, avatarUrl, isAuthenticated, updateProfile, updatePassword } =
|
||||
useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const profileQuery = useQuery({
|
||||
@@ -119,13 +119,12 @@ export function ProfilePage() {
|
||||
<div className="w-full max-w-3xl space-y-6">
|
||||
<section className="rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar size="lg">
|
||||
<AvatarImage
|
||||
src={profileQuery.data?.avatarUrl ?? avatarUrl ?? undefined}
|
||||
alt={displayName}
|
||||
/>
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<UserAvatar
|
||||
src={profileQuery.data?.avatarUrl ?? avatarUrl}
|
||||
alt={displayName}
|
||||
fallbackText={displayName}
|
||||
size="lg"
|
||||
/>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">{displayName}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { sentinelClient } from '@better-auth/infra/client';
|
||||
import { createAuthClient } from 'better-auth/react';
|
||||
import * as api from './api';
|
||||
import { sentinelClient } from "@better-auth/infra/client";
|
||||
|
||||
const apiBaseUrl = api.apiBaseUrl;
|
||||
|
||||
const plugins = [
|
||||
sentinelClient()
|
||||
]
|
||||
const plugins = [sentinelClient()];
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: apiBaseUrl,
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import type {
|
||||
AcceptComplexInvitationsInput,
|
||||
AcceptComplexInvitationsResponse,
|
||||
CancelComplexInvitationResponse,
|
||||
Complex,
|
||||
ComplexUsersOverview,
|
||||
ComplexWithRole,
|
||||
CreateComplexPayload,
|
||||
CreateComplexResponse,
|
||||
InviteComplexUserInput,
|
||||
InviteComplexUserResponse,
|
||||
RevokeComplexUserInput,
|
||||
SelectComplexInput,
|
||||
UpdateComplexPayload,
|
||||
UpdateComplexResponse,
|
||||
@@ -49,3 +56,47 @@ export async function select(payload: SelectComplexInput) {
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function listUsers(id: string) {
|
||||
const response = await http.get<ComplexUsersOverview>(`/api/complexes/${id}/users`);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function inviteUser(id: string, payload: InviteComplexUserInput) {
|
||||
const response = await http.post<InviteComplexUserResponse>(
|
||||
`/api/complexes/${id}/users`,
|
||||
JSON.stringify(payload),
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function revokeUser(id: string, payload: RevokeComplexUserInput) {
|
||||
const response = await http.delete<{ ok: boolean }>(
|
||||
`/api/complexes/${id}/users/${payload.userId}`
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function acceptPendingInvitations(payload: AcceptComplexInvitationsInput = {}) {
|
||||
const response = await http.post<AcceptComplexInvitationsResponse>(
|
||||
'/api/complexes/accept-pending',
|
||||
JSON.stringify(payload),
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function resendInvitation(id: string, invitationId: string) {
|
||||
const response = await http.post<InviteComplexUserResponse>(
|
||||
`/api/complexes/${id}/invitations/${invitationId}/resend`
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function cancelInvitation(id: string, invitationId: string) {
|
||||
const response = await http.delete<CancelComplexInvitationResponse>(
|
||||
`/api/complexes/${id}/invitations/${invitationId}`
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
71
apps/frontend/src/lib/invitations.ts
Normal file
71
apps/frontend/src/lib/invitations.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
const PENDING_INVITE_EMAIL_KEY = 'pending-invite-email';
|
||||
const PENDING_INVITE_TOKEN_KEY = 'pending-invite-token';
|
||||
|
||||
export type PendingInvite = {
|
||||
email: string | null;
|
||||
token: string | null;
|
||||
};
|
||||
|
||||
function getSessionStorage(): Storage | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return window.sessionStorage;
|
||||
}
|
||||
|
||||
export function setPendingInvite(invite: PendingInvite) {
|
||||
const storage = getSessionStorage();
|
||||
|
||||
if (!storage) return;
|
||||
|
||||
clearPendingInvite();
|
||||
|
||||
if (invite.email) {
|
||||
storage.setItem(PENDING_INVITE_EMAIL_KEY, invite.email);
|
||||
}
|
||||
|
||||
if (invite.token) {
|
||||
storage.setItem(PENDING_INVITE_TOKEN_KEY, invite.token);
|
||||
}
|
||||
}
|
||||
|
||||
export function getPendingInvite(): PendingInvite {
|
||||
const storage = getSessionStorage();
|
||||
|
||||
if (!storage) {
|
||||
return {
|
||||
email: null,
|
||||
token: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
email: storage.getItem(PENDING_INVITE_EMAIL_KEY),
|
||||
token: storage.getItem(PENDING_INVITE_TOKEN_KEY),
|
||||
};
|
||||
}
|
||||
|
||||
export function clearPendingInvite() {
|
||||
const storage = getSessionStorage();
|
||||
|
||||
if (!storage) return;
|
||||
|
||||
storage.removeItem(PENDING_INVITE_EMAIL_KEY);
|
||||
storage.removeItem(PENDING_INVITE_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export async function acceptStoredPendingInvite(
|
||||
acceptPendingInvitations: (payload: { inviteToken?: string }) => Promise<unknown>
|
||||
) {
|
||||
const pendingInvite = getPendingInvite();
|
||||
|
||||
if (!pendingInvite.token) {
|
||||
await acceptPendingInvitations({});
|
||||
clearPendingInvite();
|
||||
return;
|
||||
}
|
||||
|
||||
await acceptPendingInvitations({ inviteToken: pendingInvite.token });
|
||||
clearPendingInvite();
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { Route as SelectComplexRouteImport } from './routes/select-complex'
|
||||
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
|
||||
import { Route as OnboardRouteImport } from './routes/onboard'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as InviteRouteImport } from './routes/invite'
|
||||
import { Route as AuthCallbackRouteImport } from './routes/auth-callback'
|
||||
import { Route as AppRouteRouteImport } from './routes/_app/route'
|
||||
import { Route as OnboardIndexRouteImport } from './routes/onboard/index'
|
||||
@@ -49,6 +50,11 @@ const LoginRoute = LoginRouteImport.update({
|
||||
path: '/login',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const InviteRoute = InviteRouteImport.update({
|
||||
id: '/invite',
|
||||
path: '/invite',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AuthCallbackRoute = AuthCallbackRouteImport.update({
|
||||
id: '/auth-callback',
|
||||
path: '/auth-callback',
|
||||
@@ -128,6 +134,7 @@ const AppAuthenticatedComplexSlugEditRoute =
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof AppAuthenticatedIndexRoute
|
||||
'/auth-callback': typeof AuthCallbackRoute
|
||||
'/invite': typeof InviteRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/onboard': typeof OnboardRouteWithChildren
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
@@ -147,6 +154,7 @@ export interface FileRoutesByFullPath {
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof AppAuthenticatedIndexRoute
|
||||
'/auth-callback': typeof AuthCallbackRoute
|
||||
'/invite': typeof InviteRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/select-complex': typeof SelectComplexRoute
|
||||
@@ -165,6 +173,7 @@ export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/_app': typeof AppRouteRouteWithChildren
|
||||
'/auth-callback': typeof AuthCallbackRoute
|
||||
'/invite': typeof InviteRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/onboard': typeof OnboardRouteWithChildren
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
@@ -188,6 +197,7 @@ export interface FileRouteTypes {
|
||||
fullPaths:
|
||||
| '/'
|
||||
| '/auth-callback'
|
||||
| '/invite'
|
||||
| '/login'
|
||||
| '/onboard'
|
||||
| '/reset-password'
|
||||
@@ -207,6 +217,7 @@ export interface FileRouteTypes {
|
||||
to:
|
||||
| '/'
|
||||
| '/auth-callback'
|
||||
| '/invite'
|
||||
| '/login'
|
||||
| '/reset-password'
|
||||
| '/select-complex'
|
||||
@@ -224,6 +235,7 @@ export interface FileRouteTypes {
|
||||
| '__root__'
|
||||
| '/_app'
|
||||
| '/auth-callback'
|
||||
| '/invite'
|
||||
| '/login'
|
||||
| '/onboard'
|
||||
| '/reset-password'
|
||||
@@ -246,6 +258,7 @@ export interface FileRouteTypes {
|
||||
export interface RootRouteChildren {
|
||||
AppRouteRoute: typeof AppRouteRouteWithChildren
|
||||
AuthCallbackRoute: typeof AuthCallbackRoute
|
||||
InviteRoute: typeof InviteRoute
|
||||
LoginRoute: typeof LoginRoute
|
||||
OnboardRoute: typeof OnboardRouteWithChildren
|
||||
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||
@@ -283,6 +296,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof LoginRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/invite': {
|
||||
id: '/invite'
|
||||
path: '/invite'
|
||||
fullPath: '/invite'
|
||||
preLoaderRoute: typeof InviteRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/auth-callback': {
|
||||
id: '/auth-callback'
|
||||
path: '/auth-callback'
|
||||
@@ -458,6 +478,7 @@ const ComplexSlugBookingRouteWithChildren =
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
AppRouteRoute: AppRouteRouteWithChildren,
|
||||
AuthCallbackRoute: AuthCallbackRoute,
|
||||
InviteRoute: InviteRoute,
|
||||
LoginRoute: LoginRoute,
|
||||
OnboardRoute: OnboardRouteWithChildren,
|
||||
ResetPasswordRoute: ResetPasswordRoute,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
@@ -15,6 +16,7 @@ function AuthCallbackPage() {
|
||||
}
|
||||
|
||||
try {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
const complexes = await apiClient.complexes.listMine();
|
||||
|
||||
if (complexes.length === 1) {
|
||||
|
||||
51
apps/frontend/src/routes/invite.tsx
Normal file
51
apps/frontend/src/routes/invite.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { OnboardLoginPage } from '@/features/onboard/onboard-login-page';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite, setPendingInvite } from '@/lib/invitations';
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { useEffect } from 'react';
|
||||
import { z } from 'zod';
|
||||
|
||||
const inviteSearchSchema = z.object({
|
||||
email: z.string().email().optional(),
|
||||
inviteToken: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
function InvitePage() {
|
||||
const navigate = useNavigate();
|
||||
const { isAuthenticated } = useAuth();
|
||||
const search = Route.useSearch();
|
||||
|
||||
useEffect(() => {
|
||||
setPendingInvite({
|
||||
email: search.email ?? null,
|
||||
token: search.inviteToken ?? null,
|
||||
});
|
||||
}, [search.email, search.inviteToken]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
return;
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
await navigate({ to: '/' });
|
||||
})();
|
||||
}, [isAuthenticated, navigate]);
|
||||
|
||||
if (isAuthenticated) {
|
||||
return (
|
||||
<main className="flex min-h-screen w-full items-center justify-center px-6">
|
||||
<p className="text-sm text-muted-foreground">Aceptando invitación...</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return <OnboardLoginPage variant="invite" inviteEmail={search.email ?? null} />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/invite')({
|
||||
validateSearch: inviteSearchSchema,
|
||||
component: InvitePage,
|
||||
});
|
||||
Reference in New Issue
Block a user