Adiciona o frontend Next.js em frontend/ (setup, design system, autenticação/tema, layout/navegação, área master, área tenant completa: clientes, produtos, vendas, recebimentos, whatsapp, e-mail, alertas, equipe e perfil). Estende o backend de forma aditiva e autorizada: cookie httpOnly para refresh token (Etapa 13) e CRUD de equipe + edição de perfil do tenant (Etapa 18, módulo src/modules/equipe/ novo e PUT /tenant/perfil). Detalhes completos em Etapas/V2/*. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
154 lines
5.5 KiB
TypeScript
154 lines
5.5 KiB
TypeScript
'use client';
|
|
|
|
import * as React from 'react';
|
|
import { useRouter, useSearchParams } from 'next/navigation';
|
|
import { useForm } from 'react-hook-form';
|
|
import { zodResolver } from '@hookform/resolvers/zod';
|
|
import Image from 'next/image';
|
|
import { useAuth } from '@/lib/auth/auth-context';
|
|
import { useTenantTheme, TenantThemeProvider } from '@/lib/theme/theme-provider';
|
|
import { ApiError } from '@/lib/api/client';
|
|
import { loginSchema, type LoginFormValues } from '@/lib/validators/auth';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { FormField } from '@/components/ui/form-field';
|
|
import Link from 'next/link';
|
|
|
|
type LoginArea = 'tenant' | 'master';
|
|
|
|
function GenericInvalidCredentialsMessage(): string {
|
|
return 'E-mail ou senha inválidos.';
|
|
}
|
|
|
|
function LoginFormInner() {
|
|
const router = useRouter();
|
|
const searchParams = useSearchParams();
|
|
const { loginMaster, loginTenant } = useAuth();
|
|
const { theme } = useTenantTheme();
|
|
|
|
// Estratégia de detecção de tipo de login (Etapa 13): o backend expõe
|
|
// dois endpoints separados (`/auth/master/login` e `/auth/tenant/login`,
|
|
// sem detecção automática por e-mail — ver observações da Etapa 13 no
|
|
// controle de progresso). Escolhido um toggle explícito em vez de dois
|
|
// formulários separados por ser a opção mais simples de implementar e
|
|
// mais clara para o usuário; "tenant" é o padrão porque é o público
|
|
// majoritário (clientes), master é uso interno raro.
|
|
const [area, setArea] = React.useState<LoginArea>('tenant');
|
|
const [submitError, setSubmitError] = React.useState<string | null>(null);
|
|
|
|
const {
|
|
register,
|
|
handleSubmit,
|
|
formState: { errors, isSubmitting },
|
|
} = useForm<LoginFormValues>({ resolver: zodResolver(loginSchema) });
|
|
|
|
const onSubmit = async (values: LoginFormValues) => {
|
|
setSubmitError(null);
|
|
try {
|
|
if (area === 'master') {
|
|
await loginMaster(values.email, values.senha);
|
|
} else {
|
|
await loginTenant(values.email, values.senha);
|
|
}
|
|
|
|
const redirectParam = searchParams.get('redirect');
|
|
const fallback = area === 'master' ? '/master/dashboard' : '/app/dashboard';
|
|
router.push(redirectParam && redirectParam.startsWith('/') ? redirectParam : fallback);
|
|
} catch (err) {
|
|
if (err instanceof ApiError && err.statusCode === 401) {
|
|
setSubmitError(GenericInvalidCredentialsMessage());
|
|
} else if (err instanceof ApiError) {
|
|
setSubmitError(err.message);
|
|
} else {
|
|
setSubmitError('Não foi possível conectar. Tente novamente.');
|
|
}
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="flex w-full max-w-[420px] flex-col gap-6 rounded-xl border border-border bg-surface p-6 shadow-sm sm:p-8">
|
|
<div className="flex flex-col items-center gap-2 text-center">
|
|
{theme?.logoUrl ? (
|
|
<Image
|
|
src={theme.logoUrl}
|
|
alt={theme.nome}
|
|
width={48}
|
|
height={48}
|
|
className="size-12 rounded-lg object-contain"
|
|
/>
|
|
) : null}
|
|
<h1 className="text-xl font-semibold text-foreground">
|
|
{theme?.nome ?? 'SeConectai Vendas'}
|
|
</h1>
|
|
<p className="text-sm text-muted-foreground">Entre com seu e-mail e senha</p>
|
|
</div>
|
|
|
|
<div
|
|
role="radiogroup"
|
|
aria-label="Tipo de acesso"
|
|
className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-1"
|
|
>
|
|
<button
|
|
type="button"
|
|
role="radio"
|
|
aria-checked={area === 'tenant'}
|
|
onClick={() => setArea('tenant')}
|
|
className={`min-h-9 rounded-md text-sm font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring ${
|
|
area === 'tenant' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground'
|
|
}`}
|
|
>
|
|
Sou cliente
|
|
</button>
|
|
<button
|
|
type="button"
|
|
role="radio"
|
|
aria-checked={area === 'master'}
|
|
onClick={() => setArea('master')}
|
|
className={`min-h-9 rounded-md text-sm font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring ${
|
|
area === 'master' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground'
|
|
}`}
|
|
>
|
|
Sou administrador
|
|
</button>
|
|
</div>
|
|
|
|
<form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)} noValidate>
|
|
<FormField label="E-mail" error={errors.email?.message}>
|
|
<Input type="email" autoComplete="email" {...register('email')} />
|
|
</FormField>
|
|
<FormField label="Senha" error={errors.senha?.message}>
|
|
<Input type="password" autoComplete="current-password" {...register('senha')} />
|
|
</FormField>
|
|
|
|
{submitError && (
|
|
<p role="alert" className="rounded-lg bg-danger/10 p-3 text-sm text-danger">
|
|
{submitError}
|
|
</p>
|
|
)}
|
|
|
|
<Button type="submit" loading={isSubmitting} className="w-full">
|
|
Entrar
|
|
</Button>
|
|
|
|
<Link
|
|
href="/esqueci-senha"
|
|
className="text-center text-sm text-primary-on-light underline-offset-4 hover:underline"
|
|
>
|
|
Esqueci minha senha
|
|
</Link>
|
|
</form>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function LoginForm() {
|
|
const searchParams = useSearchParams();
|
|
const tenantId = searchParams.get('tenant');
|
|
|
|
return (
|
|
<TenantThemeProvider tenantId={tenantId}>
|
|
<LoginFormInner />
|
|
</TenantThemeProvider>
|
|
);
|
|
}
|