fix: validate simulator dates and reconcile QA calculations reports and language

This commit is contained in:
2026-10-20 21:00:52 +02:00
parent 59ab4fe956
commit a690c665fb
39 changed files with 757 additions and 184 deletions
+3 -3
View File
@@ -12,9 +12,9 @@ export default function AppearanceToggleTab({
const { appearance, updateAppearance } = useAppearance();
const tabs: { value: Appearance; icon: LucideIcon; label: string }[] = [
{ value: 'light', icon: Sun, label: 'Light' },
{ value: 'dark', icon: Moon, label: 'Dark' },
{ value: 'system', icon: Monitor, label: 'System' },
{ value: 'light', icon: Sun, label: 'Claro' },
{ value: 'dark', icon: Moon, label: 'Escuro' },
{ value: 'system', icon: Monitor, label: 'Sistema' },
];
return (
+20 -13
View File
@@ -23,14 +23,16 @@ export default function DeleteUser() {
<div className="space-y-6">
<Heading
variant="small"
title="Delete account"
description="Delete your account and all of its resources"
title="Eliminar conta"
description="Eliminar a sua conta e os recursos associados"
/>
<div className="space-y-4 rounded-lg border border-red-100 bg-red-50 p-4 dark:border-red-200/10 dark:bg-red-700/10">
<div className="relative space-y-0.5 text-red-600 dark:text-red-100">
<p className="font-medium">Warning</p>
<p className="text-sm">
Please proceed with caution, this cannot be undone.
{' '}
Esta operação é irreversível. Confirme os dados antes de
continuar.{' '}
</p>
</div>
@@ -40,18 +42,20 @@ export default function DeleteUser() {
variant="destructive"
data-test="delete-user-button"
>
Delete account
{' '}
Eliminar conta{' '}
</Button>
</DialogTrigger>
<DialogContent>
<DialogTitle>
Are you sure you want to delete your account?
{' '}
Pretende eliminar a sua conta?{' '}
</DialogTitle>
<DialogDescription>
Once your account is deleted, all of its resources
and data will also be permanently deleted. Please
enter your password to confirm you would like to
permanently delete your account.
{' '}
Ao eliminar a conta, os recursos e dados associados
também serão eliminados permanentemente. Introduza a
sua palavra-passe para confirmar.{' '}
</DialogDescription>
<Form
@@ -70,14 +74,15 @@ export default function DeleteUser() {
htmlFor="password"
className="sr-only"
>
Password
{' '}
Palavra-passe{' '}
</Label>
<PasswordInput
id="password"
name="password"
ref={passwordInput}
placeholder="Password"
placeholder="Palavra-passe"
autoComplete="current-password"
/>
@@ -92,7 +97,8 @@ export default function DeleteUser() {
resetAndClearErrors()
}
>
Cancel
{' '}
Cancelar{' '}
</Button>
</DialogClose>
@@ -105,7 +111,8 @@ export default function DeleteUser() {
type="submit"
data-test="confirm-delete-user-button"
>
Delete account
{' '}
Eliminar conta{' '}
</button>
</Button>
</DialogFooter>
+5 -4
View File
@@ -17,9 +17,10 @@ const EmptyState = () => {
<div className="bg-muted mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl">
<KeyRound className="text-muted-foreground h-7 w-7" />
</div>
<p className="font-medium">No passkeys yet</p>
<p className="font-medium"> Ainda não existem chaves de acesso </p>
<p className="text-muted-foreground mt-1 text-sm">
Add a passkey to sign in without a password
{' '}
Adicione uma chave de acesso para entrar sem palavra-passe{' '}
</p>
</div>
);
@@ -47,8 +48,8 @@ export default function ManagePasskeys(props: Props) {
<div className="space-y-6">
<Heading
variant="small"
title="Passkeys"
description="Manage your passkeys for passwordless sign-in"
title="Chaves de acesso"
description="Gerir as chaves de acesso para entrar sem palavra-passe"
/>
<div className="border-border overflow-hidden rounded-lg border">
+16 -13
View File
@@ -48,15 +48,15 @@ export default function ManageTwoFactor(props: Props) {
<div className="space-y-6">
<Heading
variant="small"
title="Two-factor authentication"
description="Manage your two-factor authentication settings"
title="Autenticação de dois factores"
description="Gerir a autenticação de dois factores"
/>
{twoFactorEnabled ? (
<div className="flex flex-col items-start justify-start space-y-4">
<p className="text-muted-foreground text-sm">
You will be prompted for a secure, random pin during
login, which you can retrieve from the TOTP-supported
application on your phone.
{' '}
Ao entrar, será solicitado o código temporário da
aplicação autenticadora do seu telefone.{' '}
</p>
<div className="relative inline">
@@ -67,7 +67,9 @@ export default function ManageTwoFactor(props: Props) {
type="submit"
disabled={processing}
>
Disable 2FA
{' '}
Desactivar autenticação de dois
factores{' '}
</Button>
)}
</Form>
@@ -82,17 +84,16 @@ export default function ManageTwoFactor(props: Props) {
) : (
<div className="flex flex-col items-start justify-start space-y-4">
<p className="text-muted-foreground text-sm">
When you enable two-factor authentication, you will be
prompted for a secure pin during login. This pin can be
retrieved from a TOTP-supported application on your
phone.
{' '}
Depois de activar a autenticação de dois factores, use o
código temporário da aplicação autenticadora para
entrar.{' '}
</p>
<div>
{hasSetupData ? (
<Button onClick={() => setShowSetupModal(true)}>
<ShieldCheck />
Continue setup
<ShieldCheck /> Continuar configuração{' '}
</Button>
) : (
<Form
@@ -101,7 +102,9 @@ export default function ManageTwoFactor(props: Props) {
>
{({ processing }) => (
<Button type="submit" disabled={processing}>
Enable 2FA
{' '}
Activar autenticação de dois
factores{' '}
</Button>
)}
</Form>
+9 -9
View File
@@ -43,13 +43,14 @@ export default function PasskeyItem({ passkey, onDelete }: Props) {
)}
</div>
<p className="text-muted-foreground text-sm">
Added {passkey.created_at_diff}
{' '}
Adicionada em {passkey.created_at_diff}
{passkey.last_used_at_diff && (
<>
<span className="text-muted-foreground/50 mx-1">
/
</span>
Last used {passkey.last_used_at_diff}
</span>{' '}
Última utilização {passkey.last_used_at_diff}
</>
)}
</p>
@@ -64,19 +65,18 @@ export default function PasskeyItem({ passkey, onDelete }: Props) {
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
<span className="sr-only">Remove</span>
<span className="sr-only"> Remover </span>
</Button>
</DialogTrigger>
<DialogContent>
<DialogTitle>Remove passkey</DialogTitle>
<DialogTitle>Remover chave de acesso</DialogTitle>
<DialogDescription>
Are you sure you want to remove the "{passkey.name}"
passkey? You will no longer be able to use it to sign
in.
Pretende remover a chave de acesso «{passkey.name}»?
Deixará de poder usá-la para entrar.
</DialogDescription>
<DialogFooter className="gap-2">
<DialogClose asChild>
<Button variant="secondary">Cancel</Button>
<Button variant="secondary"> Cancelar </Button>
</DialogClose>
<Button
variant="destructive"
+11 -7
View File
@@ -59,7 +59,8 @@ export default function PasskeyRegistration({ onSuccess }: Props) {
if (!isSupported) {
return (
<div className="text-muted-foreground text-sm">
Passkeys are not supported in this browser.
{' '}
Este navegador não suporta chaves de acesso.{' '}
</div>
);
}
@@ -67,7 +68,8 @@ export default function PasskeyRegistration({ onSuccess }: Props) {
if (!showForm) {
return (
<Button variant="outline" onClick={() => setShowForm(true)}>
Add passkey
{' '}
Adicionar chave de acesso{' '}
</Button>
);
}
@@ -78,18 +80,19 @@ export default function PasskeyRegistration({ onSuccess }: Props) {
className="border-border bg-muted/50 space-y-4 rounded-lg border p-4"
>
<div className="grid gap-2">
<Label htmlFor="passkey-name">Passkey name</Label>
<Label htmlFor="passkey-name"> Nome da chave de acesso </Label>
<Input
id="passkey-name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g., MacBook Pro, iPhone"
placeholder="Por exemplo, MacBook Pro ou iPhone"
className="border-foreground/20 mt-1 block w-full"
autoFocus
/>
<p className="text-muted-foreground text-xs">
A name helps you identify this passkey later.
{' '}
O nome permite identificar esta chave mais tarde.{' '}
</p>
</div>
@@ -97,10 +100,11 @@ export default function PasskeyRegistration({ onSuccess }: Props) {
<div className="flex gap-2">
<Button type="submit" disabled={isLoading || !name.trim()}>
{isLoading ? 'Registering...' : 'Register passkey'}
{isLoading ? 'Registering...' : 'Registar chave de acesso'}
</Button>
<Button type="button" variant="ghost" onClick={handleCancel}>
Cancel
{' '}
Cancelar{' '}
</Button>
</div>
</form>
+3 -3
View File
@@ -51,8 +51,8 @@ export default function PasskeyVerify({
>
{isLoading ? <Spinner /> : <KeyRound className="h-4 w-4" />}
{isLoading
? (loadingLabel ?? 'Authenticating...')
: (label ?? 'Sign in with a passkey')}
? (loadingLabel ?? 'A autenticar…')
: (label ?? 'Entrar com uma chave de acesso')}
</Button>
{error && (
<InputError message={error} className="text-center" />
@@ -65,7 +65,7 @@ export default function PasskeyVerify({
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background text-muted-foreground px-2">
{separator ?? 'Or continue with email'}
{separator ?? 'Ou continuar com email'}
</span>
</div>
</div>
@@ -66,6 +66,7 @@ export function SimulationFiscalStatus({
}) {
const [parameters, setParameters] = useState<Parameter[]>([]);
const [requestState, setRequestState] = useState('idle');
const [retry, setRetry] = useState(0);
useEffect(() => {
const apiComponent = component
@@ -104,12 +105,14 @@ export function SimulationFiscalStatus({
const payload = (await response.json()) as {
parameters?: Parameter[];
};
if (abort.signal.aborted) return;
setParameters(
Array.isArray(payload.parameters) ? payload.parameters : [],
);
setRequestState('done');
})
.catch((error: unknown) => {
if (abort.signal.aborted) return;
if (
error instanceof DOMException &&
error.name === 'AbortError'
@@ -125,6 +128,7 @@ export function SimulationFiscalStatus({
periodStart,
periodEnd,
JSON.stringify(context ?? {}),
retry,
]);
const salaryViewMessages: Record<string, string> = {
@@ -160,6 +164,16 @@ export function SimulationFiscalStatus({
: `Período consultado: ${periodStart} a ${periodEnd}.`}
</p>
)}
{requestState === 'error' &&
scenarioMode === 'approved_parameters' && (
<button
type="button"
onClick={() => setRetry((value) => value + 1)}
className="rounded border border-amber-900 px-4 py-2 text-amber-950 underline focus-visible:outline-2 focus-visible:outline-offset-2"
>
Tentar novamente
</button>
)}
{scenarioMode === 'custom_planning' && (
<p role="note" className="text-sm">
Modo de planeamento separado: pressupostos do utilizador,
+35 -1
View File
@@ -864,6 +864,10 @@ export function SimulationForm() {
const [isCalculating, setIsCalculating] = useState(false);
const [hasSaveConflict, setHasSaveConflict] = useState(false);
const [result, setResult] = useState<ApiSimulationExecutionV1 | null>(null);
const [calculationStale, setCalculationStale] = useState(false);
useEffect(() => {
if (result) setCalculationStale(false);
}, [result]);
const arithmeticResult = useMemo(
() => readArithmeticSnapshot(result?.result_snapshot),
[result],
@@ -1039,6 +1043,13 @@ export function SimulationForm() {
: (simulationFieldGroups[current.id] ?? []);
const fields = fieldsForCurrent.filter(
(field) =>
!(
current.id === 'tax' &&
draft.fiscal_scenario_mode === 'custom_planning' &&
!['fiscal_scenario_mode', 'base', 'rate', 'reduction'].includes(
field.key,
)
) &&
(!field.showWhen || field.showWhen(draft)) &&
!(
draft.purpose === 'simulate_only' &&
@@ -1943,7 +1954,8 @@ export function SimulationForm() {
return next;
});
if (key === 'purpose') setStep(0);
if (key !== 'purpose') setResult(null);
if (result) setCalculationStale(true);
setResult(null);
}
async function clearDraft() {
@@ -2274,6 +2286,18 @@ export function SimulationForm() {
)
setResult(simulation ?? null);
if (canSavePersonalData) void loadSimulationHistory();
if (simulation?.status === 'completed') {
setSaveStatus(
'Cálculo concluído. Reveja o resultado e os pressupostos.',
);
} else if (
simulation?.status === 'failed' ||
simulation?.status === 'cancelled'
) {
setSaveStatus(
'O cálculo não foi concluído. Os dados introduzidos foram preservados.',
);
}
sessionStorage.removeItem(idempotencyStorageKey);
} catch (cause) {
setServerError(
@@ -2396,6 +2420,16 @@ export function SimulationForm() {
aria-labelledby="simulator-step-title"
aria-busy={!ready}
>
{calculationStale && (
<p
role="status"
className="rounded border border-amber-700 bg-amber-50 p-3 text-amber-950"
>
As entradas foram alteradas. Calcule novamente antes de
guardar ou exportar um novo resultado. Os resultados
anteriores mantêm-se no histórico.
</p>
)}
{!ready && (
<p role="status">
A recuperar o rascunho. Aguarde para editar.
@@ -56,12 +56,14 @@ export default function TwoFactorRecoveryCodes({
<Card>
<CardHeader>
<CardTitle className="flex gap-3">
<LockKeyhole className="size-4" aria-hidden="true" />
2FA recovery codes
<LockKeyhole className="size-4" aria-hidden="true" />{' '}
Códigos de recuperação{' '}
</CardTitle>
<CardDescription>
Recovery codes let you regain access if you lose your 2FA
device. Store them in a secure password manager.
{' '}
Os códigos de recuperação permitem recuperar o acesso se
perder o dispositivo autenticador. Guarde-os num gestor de
palavras-passe seguro.{' '}
</CardDescription>
</CardHeader>
<CardContent>
@@ -76,7 +78,8 @@ export default function TwoFactorRecoveryCodes({
className="size-4"
aria-hidden="true"
/>
{codesAreVisible ? 'Hide' : 'View'} recovery codes
{codesAreVisible ? 'Ocultar' : 'Ver'} códigos de
recuperação{' '}
</Button>
{canRegenerateCodes && (
@@ -92,7 +95,7 @@ export default function TwoFactorRecoveryCodes({
disabled={processing}
aria-describedby="regenerate-warning"
>
<RefreshCw /> Regenerate codes
<RefreshCw /> Gerar novos códigos{' '}
</Button>
)}
</Form>
@@ -112,7 +115,7 @@ export default function TwoFactorRecoveryCodes({
ref={codesSectionRef}
className="bg-muted grid gap-1 rounded-lg p-4 font-mono text-sm"
role="list"
aria-label="Recovery codes"
aria-label="Códigos de recuperação"
>
{recoveryCodesList.length ? (
recoveryCodesList.map((code, index) => (
@@ -127,7 +130,7 @@ export default function TwoFactorRecoveryCodes({
) : (
<div
className="space-y-2"
aria-label="Loading recovery codes"
aria-label="A carregar os códigos de recuperação"
>
{Array.from(
{ length: 8 },
@@ -145,13 +148,15 @@ export default function TwoFactorRecoveryCodes({
<div className="text-muted-foreground text-xs select-none">
<p id="regenerate-warning">
Each recovery code can be used once to
access your account and will be removed
after use. If you need more, click{' '}
{' '}
Cada código permite uma única entrada e
deixa de ser válido após a utilização.
Para obter novos códigos, seleccione{' '}
<span className="font-bold">
Regenerate codes
{' '}
Gerar novos códigos{' '}
</span>{' '}
above.
acima.{' '}
</p>
</div>
</>
@@ -104,7 +104,8 @@ function TwoFactorSetupStep({
<div className="relative flex w-full items-center justify-center">
<div className="bg-border absolute inset-0 top-1/2 h-px w-full" />
<span className="bg-card relative px-2 py-1">
or, enter the code manually
{' '}
ou introduza a chave manualmente{' '}
</span>
</div>
@@ -210,7 +211,8 @@ function TwoFactorVerificationStep({
onClick={onBack}
disabled={processing}
>
Back
{' '}
Voltar{' '}
</Button>
<Button
type="submit"
@@ -219,7 +221,8 @@ function TwoFactorVerificationStep({
processing || code.length < OTP_MAX_LENGTH
}
>
Confirm
{' '}
Confirmar{' '}
</Button>
</div>
</div>
@@ -262,27 +265,27 @@ export default function TwoFactorSetupModal({
}>(() => {
if (twoFactorEnabled) {
return {
title: 'Two-factor authentication enabled',
title: 'Autenticação de dois factores activada',
description:
'Two-factor authentication is now enabled. Scan the QR code or enter the setup key in your authenticator app.',
buttonText: 'Close',
'A autenticação de dois factores está activada. Leia o código QR ou introduza a chave na aplicação autenticadora.',
buttonText: 'Fechar',
};
}
if (showVerificationStep) {
return {
title: 'Verify authentication code',
title: 'Confirmar código de autenticação',
description:
'Enter the 6-digit code from your authenticator app',
buttonText: 'Continue',
'Introduza o código de seis dígitos da aplicação autenticadora',
buttonText: 'Continuar',
};
}
return {
title: 'Enable two-factor authentication',
title: 'Activar autenticação de dois factores',
description:
'To finish enabling two-factor authentication, scan the QR code or enter the setup key in your authenticator app',
buttonText: 'Continue',
'Para concluir a configuração, leia o código QR ou introduza a chave na aplicação autenticadora.',
buttonText: 'Continuar',
};
}, [twoFactorEnabled, showVerificationStep]);
+1 -1
View File
@@ -63,7 +63,7 @@ function DialogContent({
{children}
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<XIcon />
<span className="sr-only">Close</span>
<span className="sr-only"> Fechar </span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
+1 -1
View File
@@ -72,7 +72,7 @@ function SheetContent({
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
<span className="sr-only"> Fechar </span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
@@ -40,8 +40,7 @@ export function UserMenuContent({ user }: Props) {
prefetch
onClick={cleanup}
>
<Settings className="mr-2" />
Settings
<Settings className="mr-2" /> Definições{' '}
</Link>
</DropdownMenuItem>
</DropdownMenuGroup>