localization support

O que mudou
Infra (por app):

i18n/locales.ts — lista de locales (pt, en), default pt, labels para o seletor
i18n/request.ts — lê o cookie NEXT_LOCALE, carrega as mensagens
messages/pt.json + messages/en.json — todas as strings extraídas
next.config.ts — envolvido com withNextIntl (operator-pwa: withPWA(withNextIntl(...)))
app/layout.tsx — <html lang={locale}> dinâmico, NextIntlClientProvider
app/language-switcher.tsx — seletor PT | EN (cookie + router.refresh())
23 ficheiros de UI atualizados — todos os textos visíveis agora usam t('...') ou getTranslations.

Datas no relatório passaram de toLocaleString('pt-PT') fixo para useFormatter() do next-intl — localizam-se automaticamente.

Plurais em ICU no sync-chip: {count, plural, one {# pedido...} other {# pedidos...}}.

Resultado dos testes:

pnpm test:e2e — 3/3 ✓
pnpm test:e2e:auth — 4/4 ✓
tsc --noEmit em ambas as apps — limpo ✓
Para adicionar uma língua futura: criar messages/<locale>.json + adicionar o locale a i18n/locales.ts em cada app. O seletor aparece automaticamente.
This commit is contained in:
2026-05-30 16:46:07 +01:00
parent 2093f12d0a
commit 35e7027881
41 changed files with 1549 additions and 259 deletions
@@ -1,6 +1,11 @@
import { getTranslations } from 'next-intl/server';
import type { Metadata } from 'next';
import { ReportView } from './report-view';
export const metadata = { title: 'FieldOps — Relatório de turno' };
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations('report');
return { title: t('pageTitle') };
}
export default function ReportPage() {
return <ReportView />;
@@ -3,40 +3,30 @@
import { useMemo, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Printer, AlertCircle } from 'lucide-react';
import { useTranslations, useFormatter } from 'next-intl';
import { trpc } from '@/lib/trpc/client';
import { SHIFTS, shiftWindow, todayWindow, type ShiftKey } from '@/lib/shifts';
// ── Duration helper ─────────────────────────────────────────────────────────
function formatDuration(ms: number | null): string {
if (ms === null) return '—';
type TFn = ReturnType<typeof useTranslations<'report'>>;
function formatDuration(ms: number | null, t: TFn): string {
if (ms === null) return t('duration.dash');
const totalMin = Math.round(ms / 60_000);
if (totalMin < 1) return '< 1 min';
if (totalMin < 60) return `${totalMin} min`;
if (totalMin < 1) return t('duration.lessThan1Min');
if (totalMin < 60) return t('duration.minutes', { n: totalMin });
const h = Math.floor(totalMin / 60);
const m = totalMin % 60;
return m > 0 ? `${h} h ${m} min` : `${h} h`;
return m > 0 ? t('duration.hoursMinutes', { h, m }) : t('duration.hours', { h });
}
function formatDateTime(d: Date | string): string {
const dt = new Date(d);
return dt.toLocaleString('pt-PT', {
day: '2-digit',
month: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
}
// ── Status ───────────────────────────────────────────────────────────────────
function formatDate(d: Date | string): string {
return new Date(d).toLocaleDateString('pt-PT', { day: '2-digit', month: '2-digit' });
}
// ── Window label ─────────────────────────────────────────────────────────────
function windowLabel(from: Date, to: Date): string {
return `${formatDateTime(from)}${formatDateTime(to)}`;
}
const STATUS_CLASS: Record<'OPEN' | 'CLAIMED', string> = {
OPEN: 'bg-orange-100 text-orange-700',
CLAIMED: 'bg-blue-100 text-blue-700',
};
// ── Metric card ──────────────────────────────────────────────────────────────
@@ -52,16 +42,6 @@ function MetricCard({ label, value, sub }: { label: string; value: string; sub?:
);
}
const STATUS_LABEL: Record<'OPEN' | 'CLAIMED', string> = {
OPEN: 'Aberto',
CLAIMED: 'Em curso',
};
const STATUS_CLASS: Record<'OPEN' | 'CLAIMED', string> = {
OPEN: 'bg-orange-100 text-orange-700',
CLAIMED: 'bg-blue-100 text-blue-700',
};
// ── Main component ───────────────────────────────────────────────────────────
type WindowState =
@@ -87,7 +67,14 @@ function localDateTimeStr(d: Date): string {
return `${localDateStr(d)}T${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}
const DATE_TIME_FMT = { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' } as const;
const DATE_FMT = { day: '2-digit', month: '2-digit' } as const;
export function ReportView() {
const t = useTranslations('report');
const tc = useTranslations('common');
const format = useFormatter();
const [windowState, setWindowState] = useState<WindowState>({ type: 'today' });
const [dayInput, setDayInput] = useState(() => localDateStr(new Date()));
const [customActive, setCustomActive] = useState(false);
@@ -100,7 +87,7 @@ export function ReportView() {
// Stabilise the window so the query key only changes when the user picks a
// new window. Without this, the 'today' mode recomputes `to = new Date()` on
// every render → new query key → fetch loop. Re-selecting "Hoje" refreshes.
// every render → new query key → fetch loop. Re-selecting "Today" refreshes.
const win = useMemo(() => computeWindow(windowState), [windowState]);
const { data, isLoading, error } = trpc.maintenanceRequest.report.useQuery(
@@ -126,8 +113,16 @@ export function ReportView() {
setWindowState({ type: 'custom', from, to });
}
const activeShift =
windowState.type === 'shift' ? windowState.key : null;
const activeShift = windowState.type === 'shift' ? windowState.key : null;
const range = `${format.dateTime(win.from, DATE_TIME_FMT)}${format.dateTime(win.to, DATE_TIME_FMT)}`;
const windowLabelText =
windowState.type === 'today'
? t('windowLabel.today', { range })
: windowState.type === 'shift'
? t(`windowLabel.${windowState.key}`, { range })
: t('windowLabel.custom', { range });
return (
<div className="min-h-screen bg-background print:bg-white">
@@ -140,25 +135,25 @@ export function ReportView() {
className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Fila
{t('backToQueue')}
</Link>
<span className="text-muted-foreground">/</span>
<h1 className="text-lg font-bold">Relatório de turno</h1>
<h1 className="text-lg font-bold">{t('title')}</h1>
</div>
<button
onClick={() => window.print()}
className="flex items-center gap-1.5 rounded-lg bg-muted px-3 py-1.5 text-sm font-medium hover:bg-accent"
>
<Printer className="h-4 w-4" />
Imprimir
{t('print')}
</button>
</div>
</header>
{/* ── Print header (only in print) ── */}
<div className="hidden print:block px-8 pt-6 pb-2">
<p className="text-lg font-bold">FieldOps Relatório de manutenção</p>
<p className="text-sm text-gray-600">{windowLabel(win.from, win.to)}</p>
<p className="text-lg font-bold">{t('printHeader')}</p>
<p className="text-sm text-gray-600">{range}</p>
</div>
{/* ── Window selector (hidden in print) ── */}
@@ -174,7 +169,7 @@ export function ReportView() {
: 'bg-card border border-border hover:bg-accent'
}`}
>
Hoje
{t('today')}
</button>
{(Object.keys(SHIFTS) as ShiftKey[]).map((key) => (
<button
@@ -186,7 +181,7 @@ export function ReportView() {
: 'bg-card border border-border hover:bg-accent'
}`}
>
{SHIFTS[key].label}
{t(`shiftButton.${key}`)}
</button>
))}
@@ -211,7 +206,7 @@ export function ReportView() {
: 'bg-card border border-border hover:bg-accent'
}`}
>
Personalizado
{t('custom')}
</button>
</div>
@@ -224,7 +219,7 @@ export function ReportView() {
onChange={(e) => setCustomPending((p) => ({ ...p, from: e.target.value }))}
className="rounded-lg border border-border bg-card px-2 py-1 text-sm"
/>
<span className="text-sm text-muted-foreground">até</span>
<span className="text-sm text-muted-foreground">{t('customUntil')}</span>
<input
type="datetime-local"
value={customPending.to}
@@ -235,27 +230,20 @@ export function ReportView() {
onClick={applyCustom}
className="rounded-lg bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:opacity-90"
>
Aplicar
{t('customApply')}
</button>
</div>
)}
{/* Active window label */}
<p className="text-xs text-muted-foreground">
{windowState.type === 'shift'
? `Turno d${windowState.key === 'manha' ? 'a Manhã' : windowState.key === 'tarde' ? 'a Tarde' : 'a Noite'}`
: windowState.type === 'today'
? 'Hoje — '
: 'Personalizado — '}
{windowLabel(win.from, win.to)}
</p>
<p className="text-xs text-muted-foreground">{windowLabelText}</p>
</div>
</div>
{/* ── Body ── */}
<main className="mx-auto max-w-4xl px-4 py-6 print:px-8 print:py-4">
{isLoading && (
<p className="py-16 text-center text-muted-foreground">A carregar</p>
<p className="py-16 text-center text-muted-foreground">{tc('loading')}</p>
)}
{error && (
@@ -267,7 +255,7 @@ export function ReportView() {
{data && data.totals.created === 0 && (
<div className="py-16 text-center text-muted-foreground">
<p className="text-lg">Sem pedidos nesta janela.</p>
<p className="text-lg">{t('emptyWindow')}</p>
</div>
)}
@@ -276,41 +264,41 @@ export function ReportView() {
{/* Summary cards */}
<section>
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground print:text-gray-500">
Resumo
{t('sections.summary')}
</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 print:grid-cols-3">
<MetricCard label="Pedidos" value={String(data.totals.created)} />
<MetricCard label="Resolvidos" value={String(data.totals.resolved)} />
<MetricCard label={t('metrics.created')} value={String(data.totals.created)} />
<MetricCard label={t('metrics.resolved')} value={String(data.totals.resolved)} />
<MetricCard
label="Em aberto"
label={t('metrics.open')}
value={String(data.totals.open + data.totals.claimed)}
sub={
data.totals.open > 0 || data.totals.claimed > 0
? `${data.totals.open} aberto · ${data.totals.claimed} em curso`
? t('metrics.openSub', { open: data.totals.open, claimed: data.totals.claimed })
: undefined
}
/>
<MetricCard
label="Resposta média"
value={formatDuration(data.responseMs.avg)}
label={t('metrics.responseAvg')}
value={formatDuration(data.responseMs.avg, t)}
sub={
data.responseMs.count > 0
? `sobre ${data.responseMs.count} pedido${data.responseMs.count > 1 ? 's' : ''}`
: 'sem dados'
? t('metrics.requestsSub', { count: data.responseMs.count })
: t('metrics.noData')
}
/>
<MetricCard
label="Resolução média"
value={formatDuration(data.resolutionMs.avg)}
label={t('metrics.resolutionAvg')}
value={formatDuration(data.resolutionMs.avg, t)}
sub={
data.resolutionMs.count > 0
? `sobre ${data.resolutionMs.count} pedido${data.resolutionMs.count > 1 ? 's' : ''}`
: 'sem dados'
? t('metrics.requestsSub', { count: data.resolutionMs.count })
: t('metrics.noData')
}
/>
<MetricCard
label="Pior resposta"
value={formatDuration(data.responseMs.max)}
label={t('metrics.responseMax')}
value={formatDuration(data.responseMs.max, t)}
/>
</div>
</section>
@@ -319,16 +307,16 @@ export function ReportView() {
{data.byWorkstation.length > 0 && (
<section>
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground print:text-gray-500">
Por posto
{t('sections.byWorkstation')}
</h2>
<div className="overflow-hidden rounded-xl border border-border print:border-gray-300">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border bg-muted/50 text-left print:bg-gray-50 print:border-gray-300">
<th className="px-4 py-2 font-medium">Código</th>
<th className="px-4 py-2 font-medium">Nome</th>
<th className="px-4 py-2 font-medium">Área</th>
<th className="px-4 py-2 text-right font-medium">Pedidos</th>
<th className="px-4 py-2 font-medium">{t('table.code')}</th>
<th className="px-4 py-2 font-medium">{t('table.name')}</th>
<th className="px-4 py-2 font-medium">{t('table.area')}</th>
<th className="px-4 py-2 text-right font-medium">{t('table.requests')}</th>
</tr>
</thead>
<tbody>
@@ -357,7 +345,7 @@ export function ReportView() {
{data.byArea.length > 1 && (
<section>
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground print:text-gray-500">
Por área
{t('sections.byArea')}
</h2>
<div className="flex flex-wrap gap-3">
{data.byArea.map((a) => (
@@ -378,10 +366,10 @@ export function ReportView() {
{/* Still open */}
<section>
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground print:text-gray-500">
Em aberto à hora do relatório
{t('sections.stillOpen')}
</h2>
{data.stillOpen.length === 0 ? (
<p className="text-sm text-green-600">Nada em aberto neste turno. </p>
<p className="text-sm text-green-600">{t('allClear')}</p>
) : (
<div className="space-y-2">
{data.stillOpen.map((r) => (
@@ -400,13 +388,16 @@ export function ReportView() {
{r.description}
</p>
<p className="mt-0.5 text-xs text-muted-foreground print:text-gray-500">
Reportado por {r.reportedByEmail} · {formatDate(r.createdAt)}
{t('stillOpenReportedBy', {
email: r.reportedByEmail,
date: format.dateTime(new Date(r.createdAt), DATE_FMT),
})}
</p>
</div>
<span
className={`shrink-0 rounded-full px-2.5 py-0.5 text-xs font-medium print:border print:bg-transparent ${STATUS_CLASS[r.status]}`}
>
{STATUS_LABEL[r.status]}
{tc(`status.${r.status.toLowerCase() as 'open' | 'claimed'}`)}
</span>
</div>
))}