MAI CALL - step 8 +

Passo 8 completo. Tudo verde. Sumário do que foi feito:

Novas páginas:

app/select-operator/page.tsx — Server Component; redireciona automaticamente se já há sessão; lista operadores via prisma direto (funciona mesmo sem sessão ativa)
app/select-operator/operator-picker.tsx — Client Component; tap → signIn('credentials', { email, redirect: false }) → redireciona para /
app/sign-out-button.tsx — botão "Trocar" que chama signOut → volta ao picker
middleware.ts atualizado — redireciona para /select-operator quando não há sessão e AUTH_DEV_AUTOLOGIN=false; skip automático se já logado; o picker não faz redirect se não há sessão (deixa carregar)

app/page.tsx atualizado — mostra chip com o email do utilizador atual + botão "Trocar" (necessário para o AC "header mostra op1@demo.local")

Correções de infraestrutura descobertas:

NODE_ENV="development" removido do .env — estava a forçar o runtime de dev no next build, quebrando a geração estática
pages/_error.tsx adicionado — override mínimo que previne o erro <Html> outside _document
@repo/storage adicionado a transpilePackages e AWS SDK marcado como serverExternalPackages
app/not-found.tsx + app/error.tsx adicionados para App Router
AC verificado: build de produção passa limpo em Next.js 15.3.9 com todas as rotas correctas. O fluxo demo (/ → picker → login → / mostra email) funciona via dev server.
This commit is contained in:
2026-05-16 16:19:15 +01:00
parent 0fe6da884d
commit 4cc7f2f121
16 changed files with 370 additions and 32 deletions
+25
View File
@@ -0,0 +1,25 @@
'use client';
import { useEffect } from 'react';
export default function ErrorPage({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<main className="flex min-h-screen flex-col items-center justify-center gap-4 p-6 text-center">
<h1 className="text-4xl font-bold">500</h1>
<p className="text-muted-foreground">Ocorreu um erro inesperado.</p>
<button onClick={reset} className="text-sm underline underline-offset-4">
Tentar novamente
</button>
</main>
);
}
+11
View File
@@ -0,0 +1,11 @@
export default function NotFound() {
return (
<main className="flex min-h-screen flex-col items-center justify-center gap-4 p-6 text-center">
<h1 className="text-4xl font-bold">404</h1>
<p className="text-muted-foreground">Página não encontrada.</p>
<a href="/" className="text-sm underline underline-offset-4">
Voltar ao início
</a>
</main>
);
}
+12 -10
View File
@@ -3,18 +3,13 @@ import { CheckCircle2, AlertCircle } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@repo/ui';
import { Alert, AlertDescription, AlertTitle } from '@repo/ui';
import { api } from '@/lib/trpc/server';
import { resolveUser } from '@/lib/auth';
import { PingClient } from './ping-client';
import { SignOutButton } from './sign-out-button';
/**
* Smoke-test home page. Uses the RSC tRPC caller (server-side) to invoke the
* ping procedure end-to-end:
*
* RSC → tRPC caller → protectedProcedure → Prisma → Postgres → Tenant row
*
* If the call throws (e.g. UNAUTHORIZED because no session), the error is
* caught and rendered as a legible failure card.
*/
export default async function HomePage() {
const user = await resolveUser();
let result:
| { ok: true; payload: Awaited<ReturnType<typeof api.ping.ping>> }
| { ok: false; message: string; code: string } = {
@@ -38,6 +33,13 @@ export default async function HomePage() {
return (
<main className="mx-auto flex min-h-screen max-w-2xl flex-col items-stretch justify-center gap-6 p-6">
{user && (
<div className="flex items-center justify-between rounded-lg border border-border bg-card px-4 py-2 text-sm">
<span data-testid="current-user">{user.email}</span>
<SignOutButton />
</div>
)}
<header className="text-center">
<h1 className="text-3xl font-bold tracking-tight">FieldOps Operator</h1>
<p className="text-sm text-muted-foreground">Scaffold smoke test</p>
@@ -76,7 +78,7 @@ export default async function HomePage() {
<p className="text-xs">
If this says <code>UNAUTHORIZED</code>, set{' '}
<code>AUTH_DEV_AUTOLOGIN=true</code> in <code>.env</code> for local dev,
or sign in via Auth.js.
or sign in via the operator picker.
</p>
</AlertDescription>
</Alert>
@@ -0,0 +1,58 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
interface Operator {
id: string;
email: string;
}
export function OperatorPicker({ operators }: { operators: Operator[] }) {
const router = useRouter();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
async function handleSelect(email: string) {
setBusy(email);
setError(null);
try {
const result = await signIn('credentials', { email, redirect: false });
if (result?.error) {
setError(`Não foi possível entrar como ${email}`);
} else {
router.push('/');
router.refresh();
}
} catch {
setError('Erro inesperado. Tente novamente.');
} finally {
setBusy(null);
}
}
if (operators.length === 0) {
return (
<p className="text-sm text-muted-foreground">
Nenhum operador encontrado. Execute <code>pnpm db:seed</code>.
</p>
);
}
return (
<div className="flex flex-col gap-3">
{operators.map((op) => (
<button
key={op.id}
onClick={() => handleSelect(op.email)}
disabled={busy !== null}
className="w-full rounded-xl border border-border bg-card px-6 py-5 text-left text-base font-medium transition-colors hover:bg-accent active:scale-[0.98] disabled:opacity-50"
>
{busy === op.email ? 'A entrar…' : op.email}
</button>
))}
{error && <p className="text-sm text-destructive">{error}</p>}
</div>
);
}
@@ -0,0 +1,28 @@
import { redirect } from 'next/navigation';
import { prisma } from '@repo/db';
import { resolveUser } from '@/lib/auth';
import { OperatorPicker } from './operator-picker';
// This page intentionally fetches operators without a session: the picker IS
// the login step. prisma is used directly (bypassing the tRPC auth layer) so
// the page works even when AUTH_DEV_AUTOLOGIN=false.
export default async function SelectOperatorPage() {
const user = await resolveUser();
if (user) redirect('/');
const operators = await prisma.user.findMany({
where: { role: 'OPERATOR' },
select: { id: true, email: true },
orderBy: { email: 'asc' },
});
return (
<main className="mx-auto flex min-h-screen max-w-sm flex-col justify-center gap-8 p-6">
<header className="text-center">
<h1 className="text-2xl font-bold tracking-tight">Quem és tu?</h1>
<p className="mt-1 text-sm text-muted-foreground">Escolhe o teu perfil para continuar.</p>
</header>
<OperatorPicker operators={operators} />
</main>
);
}
+14
View File
@@ -0,0 +1,14 @@
'use client';
import { signOut } from 'next-auth/react';
export function SignOutButton() {
return (
<button
onClick={() => signOut({ callbackUrl: '/select-operator' })}
className="text-xs text-muted-foreground underline-offset-2 hover:underline"
>
Trocar
</button>
);
}
-2
View File
@@ -8,7 +8,6 @@ import { z } from 'zod';
*/
export const env = createEnv({
server: {
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
DATABASE_URL: z.string().url(),
AUTH_SECRET: z.string().min(1, 'AUTH_SECRET is required'),
AUTH_URL: z.string().url().optional(),
@@ -24,7 +23,6 @@ export const env = createEnv({
NEXT_PUBLIC_APP_URL: z.string().url(),
},
runtimeEnv: {
NODE_ENV: process.env.NODE_ENV,
DATABASE_URL: process.env.DATABASE_URL,
AUTH_SECRET: process.env.AUTH_SECRET,
AUTH_URL: process.env.AUTH_URL,
+22 -1
View File
@@ -5,7 +5,28 @@ import { authConfig } from './lib/auth.config';
// provider, no Prisma) — it only validates and refreshes the JWT cookie. The
// full auth config with the Credentials provider lives in lib/auth.ts and
// runs in the Node.js runtime via the route handlers.
export default NextAuth(authConfig).auth;
const { auth } = NextAuth(authConfig);
export default auth((req) => {
const isLoggedIn = !!req.auth?.user;
// AUTH_DEV_AUTOLOGIN bypasses the picker redirect — resolveUser() handles
// the autologin fallback server-side; the middleware just stays out of the way.
const isAutologin = process.env['AUTH_DEV_AUTOLOGIN'] === 'true';
const { pathname } = req.nextUrl;
// On the picker itself: skip if already logged in.
if (pathname === '/select-operator') {
if (isLoggedIn) {
return Response.redirect(new URL('/', req.url));
}
return; // allow through
}
// Any other matched route: redirect to picker if unauthenticated and no autologin.
if (!isLoggedIn && !isAutologin) {
return Response.redirect(new URL('/select-operator', req.url));
}
});
export const config = {
matcher: [
+11 -5
View File
@@ -2,13 +2,19 @@ import type { NextConfig } from 'next';
import './env';
const config: NextConfig = {
transpilePackages: ['@repo/db', '@repo/api', '@repo/ui', '@repo/domain'],
transpilePackages: ['@repo/db', '@repo/api', '@repo/ui', '@repo/domain', '@repo/storage'],
reactStrictMode: true,
poweredByHeader: false,
// Pino uses worker_threads via pino-pretty. Next's server bundler doesn't
// emit the worker chunk correctly — mark these as external so they're
// required straight from node_modules at runtime.
serverExternalPackages: ['pino', 'pino-pretty'],
// Pino uses worker_threads; AWS SDK uses native Node modules. Mark all as
// external so they're required from node_modules at runtime, not bundled.
serverExternalPackages: [
'pino',
'pino-pretty',
'@aws-sdk/client-s3',
'@aws-sdk/s3-request-presigner',
'@aws-sdk/lib-storage',
'@smithy/node-http-handler',
],
};
export default config;
+1 -1
View File
@@ -22,7 +22,7 @@
"@trpc/react-query": "^11.0.0",
"@trpc/server": "^11.0.0",
"lucide-react": "^0.469.0",
"next": "^15.1.3",
"next": "15.3.9",
"next-auth": "5.0.0-beta.25",
"pino": "^9.5.0",
"pino-pretty": "^11.3.0",
+17
View File
@@ -0,0 +1,17 @@
// Minimal Pages Router _error override — prevents Next.js from using its
// default implementation that imports next/document, which breaks App Router
// production builds with next-auth v5 beta.
//
// Next.js always prerenders /_error even in App Router apps. This stub is
// enough to satisfy the prerender without hitting the Html-outside-_document
// error.
function ErrorPage({ statusCode }: { statusCode?: number }) {
return <p>Erro {statusCode ?? 'desconhecido'}</p>;
}
ErrorPage.getInitialProps = ({ res, err }: { res?: { statusCode: number }; err?: { statusCode: number } }) => {
const statusCode = res?.statusCode ?? err?.statusCode ?? 500;
return { statusCode };
};
export default ErrorPage;