fix: complete InvesteMoz validation and error corrections
This commit is contained in:
@@ -1,14 +1,20 @@
|
||||
import {SimulationIrpcAnnual} from '@/components/simulation-irpc-annual';
|
||||
import {SimulationIrpcNormal} from '@/components/simulation-irpc-normal';
|
||||
import {SimulationIrpcWithholdings} from '@/components/simulation-irpc-withholdings';
|
||||
import {SimulationIspcResiduals} from '@/components/simulation-ispc-residuals';
|
||||
import {SimulationIspcWithholding} from '@/components/simulation-ispc-withholding';
|
||||
import {SimulationIspcQuarter} from '@/components/simulation-ispc-quarter';
|
||||
import {SimulationIspcEligibility} from './simulation-ispc-eligibility';
|
||||
import { SimulationIrpcAnnual } from '@/components/simulation-irpc-annual';
|
||||
import { SimulationIrpcNormal } from '@/components/simulation-irpc-normal';
|
||||
import { SimulationIrpcWithholdings } from '@/components/simulation-irpc-withholdings';
|
||||
import { SimulationIspcResiduals } from '@/components/simulation-ispc-residuals';
|
||||
import { SimulationIspcWithholding } from '@/components/simulation-ispc-withholding';
|
||||
import { SimulationIspcQuarter } from '@/components/simulation-ispc-quarter';
|
||||
import { SimulationIspcEligibility } from './simulation-ispc-eligibility';
|
||||
import { simulationDraftEtag } from '@/lib/simulation-draft-etag';
|
||||
import { SimulationPublishedIva, type PublishedIvaInput } from './simulation-published-iva';
|
||||
import {
|
||||
SimulationPublishedIva,
|
||||
type PublishedIvaInput,
|
||||
} from './simulation-published-iva';
|
||||
import { SimulationMonthlyIva } from './simulation-monthly-iva';
|
||||
import { inheritSimulatorFields, reusedInvestmentValue } from '@/lib/context-inheritance';
|
||||
import {
|
||||
inheritSimulatorFields,
|
||||
reusedInvestmentValue,
|
||||
} from '@/lib/context-inheritance';
|
||||
import { investmentLandPreparation } from '@/lib/investment-land-preparation';
|
||||
import {
|
||||
PublicDocumentContent,
|
||||
@@ -788,7 +794,9 @@ function SearchChoice({
|
||||
|
||||
export function SimulationForm() {
|
||||
const { auth } = usePage<{
|
||||
auth: { user: { id: number; email_verified_at?: string | null } | null };
|
||||
auth: {
|
||||
user: { id: number; email_verified_at?: string | null } | null;
|
||||
};
|
||||
}>().props;
|
||||
const pageUrl = usePage().url;
|
||||
const draftContext = useMemo(() => {
|
||||
@@ -818,7 +826,9 @@ export function SimulationForm() {
|
||||
const [draft, setDraft] = useState<SimulationDraft>({});
|
||||
const [editingReused, setEditingReused] = useState<string[]>([]);
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => { if (ready) setDraft(current => inheritSimulatorFields(current)); }, [draft, ready]);
|
||||
useEffect(() => {
|
||||
if (ready) setDraft((current) => inheritSimulatorFields(current));
|
||||
}, [draft, ready]);
|
||||
const [contextReview, setContextReview] = useState({
|
||||
revision: 0,
|
||||
reviewed: false,
|
||||
@@ -904,7 +914,10 @@ export function SimulationForm() {
|
||||
() => readVersionedArithmeticReportReference(result),
|
||||
[result],
|
||||
);
|
||||
const isFiscalQaPreview = ['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(arithmeticSnapshot?.scenario_kind));
|
||||
const isFiscalQaPreview = [
|
||||
'fiscal_rule_qa_preview',
|
||||
'fiscal_rule_published',
|
||||
].includes(String(arithmeticSnapshot?.scenario_kind));
|
||||
const versionedReportMissing =
|
||||
arithmeticResult.integrity === 'versioned' &&
|
||||
arithmeticReportReference === null;
|
||||
@@ -1256,7 +1269,9 @@ export function SimulationForm() {
|
||||
if (payload.data) {
|
||||
if (cancelled) return;
|
||||
draftIdRef.current = payload.data.id;
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
draftEtagRef.current = simulationDraftEtag(
|
||||
response.headers.get('ETag'),
|
||||
);
|
||||
setDraftVersionNo(payload.data.version_no);
|
||||
setDraftExpiresAt(payload.data.expires_at ?? null);
|
||||
if (canSavePersonalData)
|
||||
@@ -1377,8 +1392,9 @@ export function SimulationForm() {
|
||||
}
|
||||
if (currentDraft) {
|
||||
draftIdRef.current = currentDraft.id;
|
||||
draftEtagRef.current =
|
||||
simulationDraftEtag(currentResponse.headers.get('ETag'));
|
||||
draftEtagRef.current = simulationDraftEtag(
|
||||
currentResponse.headers.get('ETag'),
|
||||
);
|
||||
sessionStorage.setItem(draftIdKey, currentDraft.id);
|
||||
}
|
||||
}
|
||||
@@ -1440,7 +1456,9 @@ export function SimulationForm() {
|
||||
);
|
||||
draftIdRef.current = payload.data.id;
|
||||
setServerFieldErrors({});
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
draftEtagRef.current = simulationDraftEtag(
|
||||
response.headers.get('ETag'),
|
||||
);
|
||||
setDraftVersionNo(payload.data.version_no);
|
||||
lastSavedFingerprintRef.current = fingerprint;
|
||||
sessionStorage.setItem(draftIdKey, payload.data.id);
|
||||
@@ -1571,7 +1589,9 @@ export function SimulationForm() {
|
||||
'Não foi possível devolver as entradas financeiras guardadas ao dossier.',
|
||||
);
|
||||
}
|
||||
window.location.assign(`/investimentos/${contextId}${draft.context_opportunity ? "?opportunity="+encodeURIComponent(String(draft.context_opportunity)) : ""}`);
|
||||
window.location.assign(
|
||||
`/investimentos/${contextId}${draft.context_opportunity ? '?opportunity=' + encodeURIComponent(String(draft.context_opportunity)) : ''}`,
|
||||
);
|
||||
} catch (cause) {
|
||||
setContinuityError(
|
||||
cause instanceof Error
|
||||
@@ -1601,7 +1621,9 @@ export function SimulationForm() {
|
||||
)
|
||||
throw new Error('Não foi possível abrir este dossier privado.');
|
||||
draftIdRef.current = payload.data.id;
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
draftEtagRef.current = simulationDraftEtag(
|
||||
response.headers.get('ETag'),
|
||||
);
|
||||
setDraftVersionNo(payload.data.version_no);
|
||||
setDraftExpiresAt(null);
|
||||
setSelectedAccountDraftId(payload.data.id);
|
||||
@@ -1664,7 +1686,9 @@ export function SimulationForm() {
|
||||
);
|
||||
const record = (payload as { data: ApiSimulationDraftV1 }).data;
|
||||
draftIdRef.current = record.id;
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
draftEtagRef.current = simulationDraftEtag(
|
||||
response.headers.get('ETag'),
|
||||
);
|
||||
setDraftVersionNo(record.version_no);
|
||||
setDraftExpiresAt(null);
|
||||
setSelectedAccountDraftId(record.id);
|
||||
@@ -1764,7 +1788,8 @@ export function SimulationForm() {
|
||||
(payload as { expires_at: string }).expires_at,
|
||||
);
|
||||
draftEtagRef.current =
|
||||
simulationDraftEtag(response.headers.get('ETag')) ?? draftEtagRef.current;
|
||||
simulationDraftEtag(response.headers.get('ETag')) ??
|
||||
draftEtagRef.current;
|
||||
}
|
||||
setContinueLaterSaved(true);
|
||||
setSaveStatus(
|
||||
@@ -1952,7 +1977,9 @@ export function SimulationForm() {
|
||||
) {
|
||||
if (!ready) return;
|
||||
setContinueLaterSaved(false);
|
||||
setIvaIssues((previous) => previous.filter((issue) => issue.field !== key));
|
||||
setIvaIssues((previous) =>
|
||||
previous.filter((issue) => issue.field !== key),
|
||||
);
|
||||
setServerFieldErrors((previous) => {
|
||||
const next = { ...previous };
|
||||
delete next[key];
|
||||
@@ -2179,13 +2206,19 @@ export function SimulationForm() {
|
||||
|
||||
async function runSimulation(publishedInput?: PublishedIvaInput) {
|
||||
if (calculationInFlightRef.current) return;
|
||||
const validation = publishedInput ? {} : validateSimulationDraft(draft, 'tax');
|
||||
if (!publishedInput && draft.fiscal_scenario_mode === 'custom_planning') {
|
||||
const validation = publishedInput
|
||||
? {}
|
||||
: validateSimulationDraft(draft, 'tax');
|
||||
if (
|
||||
!publishedInput &&
|
||||
draft.fiscal_scenario_mode === 'custom_planning'
|
||||
) {
|
||||
Object.assign(validation, validateCustomFiscalPlanning(draft));
|
||||
}
|
||||
setErrors(validation);
|
||||
setServerError('');
|
||||
if (!publishedInput && draft.fiscal_scenario_mode !== 'custom_planning') return;
|
||||
if (!publishedInput && draft.fiscal_scenario_mode !== 'custom_planning')
|
||||
return;
|
||||
if (Object.keys(validation).length) {
|
||||
document
|
||||
.getElementById(`field-${Object.keys(validation)[0]}`)
|
||||
@@ -2304,7 +2337,8 @@ export function SimulationForm() {
|
||||
}
|
||||
}
|
||||
if (
|
||||
publishedInput || JSON.stringify({
|
||||
publishedInput ||
|
||||
JSON.stringify({
|
||||
base: draft.base,
|
||||
rate: draft.rate,
|
||||
reduction: draft.reduction,
|
||||
@@ -2324,7 +2358,8 @@ export function SimulationForm() {
|
||||
'O cálculo não foi concluído. Os dados introduzidos foram preservados.',
|
||||
);
|
||||
}
|
||||
if (!publishedInput) sessionStorage.removeItem(idempotencyStorageKey);
|
||||
if (!publishedInput)
|
||||
sessionStorage.removeItem(idempotencyStorageKey);
|
||||
return simulation ?? null;
|
||||
} catch (cause) {
|
||||
setServerError(
|
||||
@@ -2383,7 +2418,9 @@ export function SimulationForm() {
|
||||
);
|
||||
const draftId = draftIdValue;
|
||||
draftIdRef.current = draftId;
|
||||
draftEtagRef.current = simulationDraftEtag(currentResponse.headers.get('ETag'));
|
||||
draftEtagRef.current = simulationDraftEtag(
|
||||
currentResponse.headers.get('ETag'),
|
||||
);
|
||||
if (!draftEtagRef.current)
|
||||
throw new Error(
|
||||
'O servidor não devolveu a versão actual do rascunho. Recarregue e tente novamente.',
|
||||
@@ -2417,7 +2454,9 @@ export function SimulationForm() {
|
||||
throw new Error(
|
||||
'O servidor devolveu uma confirmação de anexação inválida.',
|
||||
);
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
draftEtagRef.current = simulationDraftEtag(
|
||||
response.headers.get('ETag'),
|
||||
);
|
||||
const sources = payload.data?.simulation_sources;
|
||||
if (Array.isArray(sources)) setSimulationSources(sources);
|
||||
setDraft((currentDraft) => ({
|
||||
@@ -2529,7 +2568,7 @@ export function SimulationForm() {
|
||||
)}
|
||||
<a
|
||||
className="ml-3 underline"
|
||||
href={`/investimentos/${contextId}${draft.context_opportunity ? "?opportunity="+encodeURIComponent(String(draft.context_opportunity)) : ""}`}
|
||||
href={`/investimentos/${contextId}${draft.context_opportunity ? '?opportunity=' + encodeURIComponent(String(draft.context_opportunity)) : ''}`}
|
||||
>
|
||||
Ver dossier
|
||||
</a>
|
||||
@@ -3293,13 +3332,27 @@ export function SimulationForm() {
|
||||
</output>
|
||||
)}
|
||||
{current.id === 'location' && contextId && (
|
||||
<aside className="rounded border p-3" aria-label="Necessidade de terra">
|
||||
<p>{investmentLandPreparation(draft.context_applicability_snapshot).need === 'no'
|
||||
? 'Não precisa de terra neste investimento. A situação do terreno não é pedida; os valores anteriores ficam conservados.'
|
||||
: investmentLandPreparation(draft.context_applicability_snapshot).need === 'yes'
|
||||
? 'Precisa de terra neste investimento. Reveja a situação do terreno já preenchida ou indique-a quando disponível.'
|
||||
: 'Falta definir se precisa de terra. Pode guardar o rascunho e continuar sem preencher a situação do terreno.'}</p>
|
||||
<a className="underline" href={`/investimentos/${contextId}${draft.context_opportunity ? "?opportunity="+encodeURIComponent(String(draft.context_opportunity)) : ""}`}>Rever a necessidade de terra no dossier</a>
|
||||
<aside
|
||||
className="rounded border p-3"
|
||||
aria-label="Necessidade de terra"
|
||||
>
|
||||
<p>
|
||||
{investmentLandPreparation(
|
||||
draft.context_applicability_snapshot,
|
||||
).need === 'no'
|
||||
? 'Não precisa de terra neste investimento. A situação do terreno não é pedida; os valores anteriores ficam conservados.'
|
||||
: investmentLandPreparation(
|
||||
draft.context_applicability_snapshot,
|
||||
).need === 'yes'
|
||||
? 'Precisa de terra neste investimento. Reveja a situação do terreno já preenchida ou indique-a quando disponível.'
|
||||
: 'Falta definir se precisa de terra. Pode guardar o rascunho e continuar sem preencher a situação do terreno.'}
|
||||
</p>
|
||||
<a
|
||||
className="underline"
|
||||
href={`/investimentos/${contextId}${draft.context_opportunity ? '?opportunity=' + encodeURIComponent(String(draft.context_opportunity)) : ''}`}
|
||||
>
|
||||
Rever a necessidade de terra no dossier
|
||||
</a>
|
||||
</aside>
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
@@ -3314,17 +3367,59 @@ export function SimulationForm() {
|
||||
: Boolean(field.required);
|
||||
const fieldError =
|
||||
serverFieldErrors[field.key] ?? errors[field.key];
|
||||
const reused = contextId && ready && !fieldError && !editingReused.includes(`${contextId}:${field.key}`)
|
||||
? reusedInvestmentValue(`dossier:${contextId}:simulator`, field.key, draft) : null;
|
||||
if (reused !== null) return (
|
||||
<div key={field.key} id={`field-${field.key}`} className="rounded border bg-emerald-50 p-3">
|
||||
<p className="font-semibold">{field.label}</p>
|
||||
<p className="whitespace-pre-wrap [overflow-wrap:anywhere]">{reused}</p>
|
||||
<p className="text-sm">Recuperado do dossier.</p>
|
||||
<button type="button" className="underline" onClick={() => setEditingReused((keys) => [...keys, `${contextId}:${field.key}`])}>Alterar {field.label.toLocaleLowerCase('pt-MZ')}</button>
|
||||
</div>
|
||||
);
|
||||
const ivaNotes = ivaIssues.filter((issue) => issue.field === field.key).map((issue, index) => <p key={index} role="note" className="mt-1 text-sm text-amber-950">{ivaIssueText(issue)}</p>);
|
||||
const reused =
|
||||
contextId &&
|
||||
ready &&
|
||||
!fieldError &&
|
||||
!editingReused.includes(`${contextId}:${field.key}`)
|
||||
? reusedInvestmentValue(
|
||||
`dossier:${contextId}:simulator`,
|
||||
field.key,
|
||||
draft,
|
||||
)
|
||||
: null;
|
||||
if (reused !== null)
|
||||
return (
|
||||
<div
|
||||
key={field.key}
|
||||
id={`field-${field.key}`}
|
||||
className="rounded border bg-emerald-50 p-3"
|
||||
>
|
||||
<p className="font-semibold">
|
||||
{field.label}
|
||||
</p>
|
||||
<p className="[overflow-wrap:anywhere] whitespace-pre-wrap">
|
||||
{reused}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Recuperado do dossier.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
setEditingReused((keys) => [
|
||||
...keys,
|
||||
`${contextId}:${field.key}`,
|
||||
])
|
||||
}
|
||||
>
|
||||
Alterar{' '}
|
||||
{field.label.toLocaleLowerCase('pt-MZ')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
const ivaNotes = ivaIssues
|
||||
.filter((issue) => issue.field === field.key)
|
||||
.map((issue, index) => (
|
||||
<p
|
||||
key={index}
|
||||
role="note"
|
||||
className="mt-1 text-sm text-amber-950"
|
||||
>
|
||||
{ivaIssueText(issue)}
|
||||
</p>
|
||||
));
|
||||
if (field.options) {
|
||||
const parentKey =
|
||||
field.key === 'district_id'
|
||||
@@ -3499,23 +3594,61 @@ export function SimulationForm() {
|
||||
{(current.id === 'financial' ||
|
||||
(draft.purpose === 'simulate_only' &&
|
||||
current.id === 'tax')) && (
|
||||
<details className="rounded border p-3"><summary>Cenário personalizado de tesouraria — imposto manual, separado do IVA calculado</summary><SimulationCashflowPlanner
|
||||
snapshot={String(draft.cashflow_snapshot ?? '')}
|
||||
onSnapshotChange={(value) =>
|
||||
change('cashflow_snapshot', value)
|
||||
}
|
||||
currency={String(draft.currency ?? '')}
|
||||
onCurrencyChange={(value) => change('currency', value)}
|
||||
/></details>
|
||||
<details className="rounded border p-3">
|
||||
<summary>
|
||||
Cenário personalizado de tesouraria — imposto
|
||||
manual, separado do IVA calculado
|
||||
</summary>
|
||||
<SimulationCashflowPlanner
|
||||
snapshot={String(draft.cashflow_snapshot ?? '')}
|
||||
onSnapshotChange={(value) =>
|
||||
change('cashflow_snapshot', value)
|
||||
}
|
||||
currency={String(draft.currency ?? '')}
|
||||
onCurrencyChange={(value) =>
|
||||
change('currency', value)
|
||||
}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && (
|
||||
<SimulationIspcEligibility
|
||||
draft={draft}
|
||||
onChange={change}
|
||||
/>
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && (
|
||||
<SimulationIspcQuarter draft={draft} onChange={change} />
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && (
|
||||
<SimulationIspcWithholding
|
||||
draft={draft}
|
||||
onChange={change}
|
||||
/>
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && (
|
||||
<SimulationIspcResiduals draft={draft} onChange={change} />
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && (
|
||||
<SimulationIrpcWithholdings
|
||||
draft={draft}
|
||||
onChange={change}
|
||||
/>
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && (
|
||||
<SimulationIrpcNormal draft={draft} onChange={change} />
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && (
|
||||
<SimulationIrpcAnnual draft={draft} onChange={change} />
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && (
|
||||
<SimulationMonthlyIva
|
||||
draft={draft}
|
||||
busy={isCalculating}
|
||||
onCalculate={runSimulation}
|
||||
onChange={change}
|
||||
/>
|
||||
)}
|
||||
{(current.id === 'financial' || current.id === 'tax') && <SimulationIspcEligibility draft={draft} onChange={change} />}
|
||||
{(current.id === 'financial' || current.id === 'tax') && <SimulationIspcQuarter draft={draft} onChange={change} />}
|
||||
{(current.id === 'financial' || current.id === 'tax') && <SimulationIspcWithholding draft={draft} onChange={change} />}
|
||||
{(current.id === 'financial' || current.id === 'tax') && <SimulationIspcResiduals draft={draft} onChange={change} />}
|
||||
{(current.id === 'financial' || current.id === 'tax') && <SimulationIrpcWithholdings draft={draft} onChange={change} />}
|
||||
{(current.id === 'financial' || current.id === 'tax') && <SimulationIrpcNormal draft={draft} onChange={change} />}
|
||||
{(current.id === 'financial' || current.id === 'tax') && <SimulationIrpcAnnual draft={draft} onChange={change} />}
|
||||
{(current.id === 'financial' || current.id === 'tax') && <SimulationMonthlyIva draft={draft} busy={isCalculating} onCalculate={runSimulation} onChange={change} />}
|
||||
{current.id === 'financial' &&
|
||||
(draft.detail_level === 'advanced' ||
|
||||
draft.journey_type === 'small_business') &&
|
||||
@@ -3651,7 +3784,14 @@ export function SimulationForm() {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{current.id === 'tax' && <SimulationPublishedIva draft={draft} onChange={change} busy={isCalculating} onCalculate={runSimulation} />}
|
||||
{current.id === 'tax' && (
|
||||
<SimulationPublishedIva
|
||||
draft={draft}
|
||||
onChange={change}
|
||||
busy={isCalculating}
|
||||
onCalculate={runSimulation}
|
||||
/>
|
||||
)}
|
||||
{current.id === 'tax' && (
|
||||
<div
|
||||
id="draft-tool-fiscal"
|
||||
@@ -3661,9 +3801,19 @@ export function SimulationForm() {
|
||||
<SimulationFiscalStatus
|
||||
onDiagnostics={setIvaIssues}
|
||||
onCorrect={(key) => {
|
||||
const target = journeySections.findIndex((section) => (simulationFieldGroups[section.id] ?? []).some((field) => field.key === key));
|
||||
const target = journeySections.findIndex(
|
||||
(section) =>
|
||||
(
|
||||
simulationFieldGroups[section.id] ??
|
||||
[]
|
||||
).some((field) => field.key === key),
|
||||
);
|
||||
if (target >= 0) setStep(target);
|
||||
window.requestAnimationFrame(() => document.getElementById(`field-${key}`)?.focus());
|
||||
window.requestAnimationFrame(() =>
|
||||
document
|
||||
.getElementById(`field-${key}`)
|
||||
?.focus(),
|
||||
);
|
||||
}}
|
||||
salaryView={String(draft.irps_salary_view ?? '')}
|
||||
scenarioMode={
|
||||
@@ -3674,24 +3824,30 @@ export function SimulationForm() {
|
||||
component={String(draft.fiscal_component ?? '')}
|
||||
periodStart={getFiscalPeriodRange(draft)?.start}
|
||||
periodEnd={getFiscalPeriodRange(draft)?.end}
|
||||
context={{ ...Object.fromEntries(
|
||||
[
|
||||
'fiscal_periodicity',
|
||||
'fiscal_operation',
|
||||
'fiscal_residency_assessment',
|
||||
'fiscal_residency_country',
|
||||
'fiscal_income_category',
|
||||
'fiscal_establishments',
|
||||
'fiscal_documentation',
|
||||
'fiscal_customs_code',
|
||||
'fiscal_vat_refund_state',
|
||||
].flatMap((key) =>
|
||||
typeof draft[key] === 'string' &&
|
||||
draft[key] !== ''
|
||||
? [[key, draft[key] as string]]
|
||||
: [],
|
||||
context={{
|
||||
...Object.fromEntries(
|
||||
[
|
||||
'fiscal_periodicity',
|
||||
'fiscal_operation',
|
||||
'fiscal_residency_assessment',
|
||||
'fiscal_residency_country',
|
||||
'fiscal_income_category',
|
||||
'fiscal_establishments',
|
||||
'fiscal_documentation',
|
||||
'fiscal_customs_code',
|
||||
'fiscal_vat_refund_state',
|
||||
].flatMap((key) =>
|
||||
typeof draft[key] === 'string' &&
|
||||
draft[key] !== ''
|
||||
? [[key, draft[key] as string]]
|
||||
: [],
|
||||
),
|
||||
),
|
||||
), ...(typeof draft.fiscal_currency === 'string' && draft.fiscal_currency !== '' ? {currency: draft.fiscal_currency} : {}) }}
|
||||
...(typeof draft.fiscal_currency === 'string' &&
|
||||
draft.fiscal_currency !== ''
|
||||
? { currency: draft.fiscal_currency }
|
||||
: {}),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -3755,19 +3911,24 @@ export function SimulationForm() {
|
||||
O período e as respostas servem para encaminhar uma
|
||||
exploração informativa. A residência é auto-indicada ou
|
||||
fica por determinar; não é inferida por nacionalidade ou
|
||||
dias de presença. Cada cálculo identifica a regra, versão, cobertura e
|
||||
limitações; este formulário não determina cumprimento
|
||||
fiscal. Um crédito estimado de IVA não significa pedido
|
||||
aprovado nem dinheiro disponível. Não carregue
|
||||
documentos nesta simulação exploratória.
|
||||
dias de presença. Cada cálculo identifica a regra,
|
||||
versão, cobertura e limitações; este formulário não
|
||||
determina cumprimento fiscal. Um crédito estimado de IVA
|
||||
não significa pedido aprovado nem dinheiro disponível.
|
||||
Não carregue documentos nesta simulação exploratória.
|
||||
</p>
|
||||
)}
|
||||
{(current.id === 'tax' || result) && (
|
||||
<div className="space-y-3 border-t pt-4">
|
||||
<h4 className="font-semibold">
|
||||
{isFiscalQaPreview ? (arithmeticSnapshot?.scenario_kind === 'fiscal_rule_published' ? 'IVA pela versão publicada seleccionada' : 'Pré-visualização fiscal QA seleccionada') : current.id === 'tax'
|
||||
? 'Cenário personalizado de planeamento'
|
||||
: 'Resultado histórico seleccionado'}
|
||||
{isFiscalQaPreview
|
||||
? arithmeticSnapshot?.scenario_kind ===
|
||||
'fiscal_rule_published'
|
||||
? 'IVA pela versão publicada seleccionada'
|
||||
: 'Pré-visualização fiscal QA seleccionada'
|
||||
: current.id === 'tax'
|
||||
? 'Cenário personalizado de planeamento'
|
||||
: 'Resultado histórico seleccionado'}
|
||||
</h4>
|
||||
{current.id !== 'tax' && result && (
|
||||
<p>
|
||||
@@ -3829,24 +3990,25 @@ export function SimulationForm() {
|
||||
submetido.
|
||||
</p>
|
||||
)}
|
||||
{result.status === 'completed' && !isFiscalQaPreview && (
|
||||
<p>
|
||||
Resultado aritmético indicativo:{' '}
|
||||
<strong className="break-all">
|
||||
{displayScalar(
|
||||
arithmeticResult.value ??
|
||||
(arithmeticResult.integrity ===
|
||||
'invalid'
|
||||
{result.status === 'completed' &&
|
||||
!isFiscalQaPreview && (
|
||||
<p>
|
||||
Resultado aritmético indicativo:{' '}
|
||||
<strong className="break-all">
|
||||
{displayScalar(
|
||||
arithmeticResult.value ??
|
||||
(arithmeticResult.integrity ===
|
||||
'invalid'
|
||||
? 'indisponível: snapshot inconsistente'
|
||||
: 'disponível no relatório'),
|
||||
arithmeticResult.integrity ===
|
||||
'invalid'
|
||||
? 'indisponível: snapshot inconsistente'
|
||||
: 'disponível no relatório'),
|
||||
arithmeticResult.integrity ===
|
||||
'invalid'
|
||||
? 'indisponível: snapshot inconsistente'
|
||||
: 'disponível no relatório',
|
||||
)}
|
||||
</strong>
|
||||
</p>
|
||||
)}
|
||||
: 'disponível no relatório',
|
||||
)}
|
||||
</strong>
|
||||
</p>
|
||||
)}
|
||||
{result.status === 'failed' && (
|
||||
<p role="alert">
|
||||
O cálculo não foi concluído. Reveja os
|
||||
@@ -3866,182 +4028,193 @@ export function SimulationForm() {
|
||||
taxas legais, elegibilidade ou obrigação
|
||||
fiscal.
|
||||
</p>
|
||||
{isFiscalQaPreview && <FiscalQaPreview snapshot={result.result_snapshot} />}
|
||||
{isFiscalQaPreview && (
|
||||
<FiscalQaPreview
|
||||
snapshot={result.result_snapshot}
|
||||
/>
|
||||
)}
|
||||
{result.status === 'completed' && (
|
||||
<div className="mt-3 space-y-2 border-t pt-3">
|
||||
{!isFiscalQaPreview && arithmeticResult.integrity !==
|
||||
'invalid' && (
|
||||
<details className="rounded border p-3">
|
||||
<summary className="cursor-pointer font-semibold focus-visible:outline-2">
|
||||
Detalhes do cálculo e da
|
||||
versão
|
||||
</summary>
|
||||
<dl className="mt-3 grid gap-2 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Base introduzida
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.base,
|
||||
'não disponível',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Taxa introduzida (%)
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.rate_percent,
|
||||
'não disponível',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Redução hipotética
|
||||
(%)
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.reduction_percent,
|
||||
'não disponível',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Moeda
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.currency,
|
||||
'não fornecida',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
{arithmeticResult.context && (
|
||||
<>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Período
|
||||
</dt>
|
||||
<dd>
|
||||
Cálculo
|
||||
pontual; sem
|
||||
período
|
||||
fiscal
|
||||
atribuído
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Data de
|
||||
referência
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticResult
|
||||
.context
|
||||
.reference_date,
|
||||
'não disponível',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Versão do
|
||||
motor
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticResult
|
||||
.context
|
||||
.engine_version,
|
||||
'não identificada',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Versão do
|
||||
cenário
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticResult
|
||||
.context
|
||||
.scenario_version,
|
||||
'não identificada',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Versão da
|
||||
fórmula
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.formula_version,
|
||||
'não identificada',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{arithmeticResult.integrity ===
|
||||
'versioned' &&
|
||||
arithmeticReportReference && (
|
||||
{!isFiscalQaPreview &&
|
||||
arithmeticResult.integrity !==
|
||||
'invalid' && (
|
||||
<details className="rounded border p-3">
|
||||
<summary className="cursor-pointer font-semibold focus-visible:outline-2">
|
||||
Detalhes do cálculo e da
|
||||
versão
|
||||
</summary>
|
||||
<dl className="mt-3 grid gap-2 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Base introduzida
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.base,
|
||||
'não disponível',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Taxa introduzida
|
||||
(%)
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.rate_percent,
|
||||
'não disponível',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Redução
|
||||
hipotética (%)
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.reduction_percent,
|
||||
'não disponível',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Moeda
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.currency,
|
||||
'não fornecida',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
{arithmeticResult.context && (
|
||||
<>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
ID do
|
||||
relatório
|
||||
imutável
|
||||
Período
|
||||
</dt>
|
||||
<dd className="break-all">
|
||||
{
|
||||
arithmeticReportReference.id
|
||||
}
|
||||
<dd>
|
||||
Cálculo
|
||||
pontual;
|
||||
sem
|
||||
período
|
||||
fiscal
|
||||
atribuído
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
SHA-256
|
||||
do
|
||||
relatório
|
||||
Data de
|
||||
referência
|
||||
</dt>
|
||||
<dd className="break-all">
|
||||
{
|
||||
arithmeticReportReference.report_sha256
|
||||
}
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticResult
|
||||
.context
|
||||
.reference_date,
|
||||
'não disponível',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Versão
|
||||
do motor
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticResult
|
||||
.context
|
||||
.engine_version,
|
||||
'não identificada',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Versão
|
||||
do
|
||||
cenário
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticResult
|
||||
.context
|
||||
.scenario_version,
|
||||
'não identificada',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Versão
|
||||
da
|
||||
fórmula
|
||||
</dt>
|
||||
<dd>
|
||||
{displayScalar(
|
||||
arithmeticSnapshot?.formula_version,
|
||||
'não identificada',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
<p className="mt-3 text-sm">
|
||||
Fórmula genérica: base ×
|
||||
taxa percentual ÷ 100 × (1 −
|
||||
redução percentual ÷ 100).
|
||||
Não foram aplicadas regras
|
||||
fiscais nem associadas
|
||||
fontes legais; os parâmetros
|
||||
foram introduzidos pelo
|
||||
utilizador.
|
||||
</p>
|
||||
{arithmeticResult.explanation && (
|
||||
<p className="mt-2 text-sm">
|
||||
{
|
||||
arithmeticResult.explanation
|
||||
}
|
||||
{arithmeticResult.integrity ===
|
||||
'versioned' &&
|
||||
arithmeticReportReference && (
|
||||
<>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
ID
|
||||
do
|
||||
relatório
|
||||
imutável
|
||||
</dt>
|
||||
<dd className="break-all">
|
||||
{
|
||||
arithmeticReportReference.id
|
||||
}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
SHA-256
|
||||
do
|
||||
relatório
|
||||
</dt>
|
||||
<dd className="break-all">
|
||||
{
|
||||
arithmeticReportReference.report_sha256
|
||||
}
|
||||
</dd>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
<p className="mt-3 text-sm">
|
||||
Fórmula genérica: base ×
|
||||
taxa percentual ÷ 100 ×
|
||||
(1 − redução percentual
|
||||
÷ 100). Não foram
|
||||
aplicadas regras fiscais
|
||||
nem associadas fontes
|
||||
legais; os parâmetros
|
||||
foram introduzidos pelo
|
||||
utilizador.
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
)}
|
||||
{arithmeticResult.explanation && (
|
||||
<p className="mt-2 text-sm">
|
||||
{
|
||||
arithmeticResult.explanation
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
@@ -4240,7 +4413,19 @@ export function SimulationForm() {
|
||||
'não identificada',
|
||||
'não identificada',
|
||||
)}{' '}
|
||||
· {['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(source.result_snapshot.scenario_kind)) ? 'IVA calculado exacto' : 'resultado aritmético'}{' '}
|
||||
·{' '}
|
||||
{[
|
||||
'fiscal_rule_qa_preview',
|
||||
'fiscal_rule_published',
|
||||
].includes(
|
||||
String(
|
||||
source
|
||||
.result_snapshot
|
||||
.scenario_kind,
|
||||
),
|
||||
)
|
||||
? 'IVA calculado exacto'
|
||||
: 'resultado aritmético'}{' '}
|
||||
{displayScalar(
|
||||
sourceResult.value ??
|
||||
(sourceResult.integrity ===
|
||||
@@ -4479,8 +4664,8 @@ export function SimulationForm() {
|
||||
e, se já escolhido, o cálculo percentual
|
||||
personalizado. Consultar parâmetros fiscais
|
||||
apresenta fontes e lacunas; não determina imposto
|
||||
devido. Na etapa Operação fiscal encontra também
|
||||
o cálculo de IVA geral sobre base líquida, quando
|
||||
devido. Na etapa Operação fiscal encontra também o
|
||||
cálculo de IVA geral sobre base líquida, quando
|
||||
activado, com âmbito e versão identificados.
|
||||
</p>
|
||||
<button
|
||||
|
||||
Reference in New Issue
Block a user