Corrige validacao, recuperacao e acesso ao calculo do rascunho
This commit is contained in:
@@ -198,7 +198,12 @@ export function SimulationFiscalStatus({
|
||||
) : parameters.length === 0 ? (
|
||||
<p className="text-sm">
|
||||
Indeterminado — nenhum parâmetro publicado
|
||||
aplicável.
|
||||
aplicável. Faltam parâmetros aprovados para{' '}
|
||||
{code}, no período {periodStart} a{' '}
|
||||
{periodEnd} e no âmbito indicado. A consulta
|
||||
não identifica um conjunto obrigatório de
|
||||
parâmetros; não é possível determinar o
|
||||
imposto nem substituir as lacunas por zero.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2 text-sm">
|
||||
|
||||
@@ -57,6 +57,7 @@ import { ProjectReadiness } from '@/components/project-readiness';
|
||||
import {
|
||||
readSimulationApiJson,
|
||||
simulationApiErrorMessage,
|
||||
simulationApiFieldErrors,
|
||||
simulationPollingFailureMessage,
|
||||
simulationCatalogChoices,
|
||||
} from '@/lib/simulation-api';
|
||||
@@ -751,10 +752,59 @@ export function SimulationForm() {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [step, setStep] = useState(0);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [serverFieldErrors, setServerFieldErrors] = useState<
|
||||
Record<string, string>
|
||||
>({});
|
||||
const [saveStatus, setSaveStatus] = useState(
|
||||
'Rascunho ainda não guardado.',
|
||||
);
|
||||
const [serverError, setServerError] = useState('');
|
||||
const [reviewStatus, setReviewStatus] = useState('');
|
||||
const [openedTool, setOpenedTool] = useState<
|
||||
'calculation' | 'fiscal' | null
|
||||
>(null);
|
||||
const [toolError, setToolError] = useState('');
|
||||
useEffect(() => {
|
||||
if (!openedTool) return;
|
||||
const destination = document.getElementById(`draft-tool-${openedTool}`);
|
||||
if (!destination) {
|
||||
setToolError(
|
||||
'Não foi possível abrir a ferramenta. O rascunho foi preservado; volte a tentar.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
destination.focus();
|
||||
destination.scrollIntoView({ block: 'start' });
|
||||
}, [openedTool, step]);
|
||||
function openDraftTool(tool: 'calculation' | 'fiscal') {
|
||||
setToolError('');
|
||||
const index = journeySections.findIndex(
|
||||
(section) => section.id === 'tax',
|
||||
);
|
||||
if (index < 0) {
|
||||
setToolError(
|
||||
'Esta etapa não disponibiliza a operação fiscal. Reveja o percurso escolhido; os dados foram preservados.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setStep(index);
|
||||
setOpenedTool(tool);
|
||||
}
|
||||
const [reviewDetails, setReviewDetails] = useState<{
|
||||
checked: { key: string; label: string; value: string }[];
|
||||
pending: {
|
||||
key: string;
|
||||
label: string;
|
||||
message: string;
|
||||
step: number;
|
||||
}[];
|
||||
}>({ checked: [], pending: [] });
|
||||
const reviewSummaryRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!reviewStatus) return;
|
||||
reviewSummaryRef.current?.focus();
|
||||
reviewSummaryRef.current?.scrollIntoView({ block: 'start' });
|
||||
}, [reviewStatus, reviewDetails]);
|
||||
const [isCalculating, setIsCalculating] = useState(false);
|
||||
const [hasSaveConflict, setHasSaveConflict] = useState(false);
|
||||
const [result, setResult] = useState<ApiSimulationExecutionV1 | null>(null);
|
||||
@@ -1289,6 +1339,8 @@ export function SimulationForm() {
|
||||
}
|
||||
const payload: unknown =
|
||||
await readSimulationApiJson(response);
|
||||
if (response.status === 422)
|
||||
setServerFieldErrors(simulationApiFieldErrors(payload));
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
simulationApiErrorMessage(payload) ??
|
||||
@@ -1299,6 +1351,7 @@ export function SimulationForm() {
|
||||
'O servidor devolveu uma confirmação de gravação inválida.',
|
||||
);
|
||||
draftIdRef.current = payload.data.id;
|
||||
setServerFieldErrors({});
|
||||
draftEtagRef.current = response.headers.get('ETag');
|
||||
setDraftVersionNo(payload.data.version_no);
|
||||
lastSavedFingerprintRef.current = fingerprint;
|
||||
@@ -1719,6 +1772,12 @@ export function SimulationForm() {
|
||||
label?: string | string[],
|
||||
) {
|
||||
setContinueLaterSaved(false);
|
||||
setServerFieldErrors((previous) => {
|
||||
const next = { ...previous };
|
||||
delete next[key];
|
||||
return next;
|
||||
});
|
||||
setReviewStatus('');
|
||||
setDraft((currentDraft) => {
|
||||
const next = replaceSimulationValue(currentDraft, key, value);
|
||||
if (label) next[`${key}_label`] = label;
|
||||
@@ -1835,6 +1894,7 @@ export function SimulationForm() {
|
||||
}
|
||||
|
||||
function navigate(nextStep: number) {
|
||||
setOpenedTool(null);
|
||||
if (nextStep > step) {
|
||||
for (let index = step; index < nextStep; index++) {
|
||||
const validation = validateSimulationDraft(
|
||||
@@ -1860,6 +1920,80 @@ export function SimulationForm() {
|
||||
document.getElementById('simulator-step-title')?.focus();
|
||||
}
|
||||
|
||||
function validateFinalReview() {
|
||||
const checked: { key: string; label: string; value: string }[] = [];
|
||||
const privateFields = partitionSimulationDraft(
|
||||
draft,
|
||||
true,
|
||||
).personal_snapshot;
|
||||
const pending: {
|
||||
key: string;
|
||||
label: string;
|
||||
message: string;
|
||||
step: number;
|
||||
}[] = [];
|
||||
const allErrors: Record<string, string> = {};
|
||||
for (let index = 0; index < journeySections.length; index++) {
|
||||
const validation = validateSimulationDraft(
|
||||
draft,
|
||||
journeySections[index].id,
|
||||
);
|
||||
if (
|
||||
journeySections[index].id === 'tax' &&
|
||||
draft.fiscal_scenario_mode === 'custom_planning'
|
||||
) {
|
||||
Object.assign(validation, validateCustomFiscalPlanning(draft));
|
||||
}
|
||||
Object.assign(allErrors, validation);
|
||||
const fields =
|
||||
simulationFieldGroups[journeySections[index].id] ?? [];
|
||||
for (const field of fields) {
|
||||
if (field.showWhen && !field.showWhen(draft)) continue;
|
||||
const value = draft[field.key];
|
||||
if (
|
||||
!validation[field.key] &&
|
||||
value !== undefined &&
|
||||
value !== '' &&
|
||||
(!Array.isArray(value) || value.length > 0)
|
||||
)
|
||||
checked.push({
|
||||
key: field.key,
|
||||
label: field.label || field.key,
|
||||
value: Object.prototype.hasOwnProperty.call(
|
||||
privateFields,
|
||||
field.key,
|
||||
)
|
||||
? 'Dado pessoal preservado; consulte-o no campo original.'
|
||||
: Array.isArray(value)
|
||||
? value
|
||||
.map((entry) => labelFor(String(entry)))
|
||||
.join(', ')
|
||||
: field.options
|
||||
? labelFor(String(value))
|
||||
: displayValue(
|
||||
value,
|
||||
'Valor não textual; consulte o campo original.',
|
||||
),
|
||||
});
|
||||
}
|
||||
for (const [key, message] of Object.entries(validation))
|
||||
pending.push({
|
||||
key,
|
||||
label:
|
||||
fields.find((field) => field.key === key)?.label ?? key,
|
||||
message,
|
||||
step: index,
|
||||
});
|
||||
}
|
||||
setErrors(allErrors);
|
||||
setReviewDetails({ checked, pending });
|
||||
setReviewStatus(
|
||||
pending.length
|
||||
? 'Verificação concluída com campos pendentes ou inconsistências. Os dados foram preservados.'
|
||||
: 'Verificação dos campos concluída neste navegador.',
|
||||
);
|
||||
}
|
||||
|
||||
async function runSimulation() {
|
||||
if (calculationInFlightRef.current) return;
|
||||
const validation = validateSimulationDraft(draft, 'tax');
|
||||
@@ -2153,6 +2287,58 @@ export function SimulationForm() {
|
||||
<output aria-live="polite" className="block text-sm">
|
||||
{saveStatus}
|
||||
</output>
|
||||
{Object.keys(serverFieldErrors).length > 0 && (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded border border-red-300 bg-red-50 p-3"
|
||||
>
|
||||
<p>
|
||||
O servidor não confirmou a gravação. Os dados
|
||||
preenchidos foram preservados. Corrija os campos
|
||||
indicados:
|
||||
</p>
|
||||
<ul>
|
||||
{Object.entries(serverFieldErrors).map(
|
||||
([key, message]) => {
|
||||
const index = journeySections.findIndex(
|
||||
(section) =>
|
||||
(
|
||||
simulationFieldGroups[
|
||||
section.id
|
||||
] ?? []
|
||||
).some(
|
||||
(field) =>
|
||||
field.key === key,
|
||||
),
|
||||
);
|
||||
const label =
|
||||
index >= 0
|
||||
? simulationFieldGroups[
|
||||
journeySections[index].id
|
||||
].find(
|
||||
(field) =>
|
||||
field.key === key,
|
||||
)?.label
|
||||
: key;
|
||||
return (
|
||||
<li key={key}>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => {
|
||||
if (index >= 0)
|
||||
setStep(index);
|
||||
}}
|
||||
>
|
||||
{label}: {message}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
},
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{draft.purpose && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -2796,7 +2982,8 @@ export function SimulationForm() {
|
||||
: typeof field.required === 'function'
|
||||
? field.required(draft)
|
||||
: Boolean(field.required);
|
||||
const fieldError = errors[field.key];
|
||||
const fieldError =
|
||||
serverFieldErrors[field.key] ?? errors[field.key];
|
||||
if (field.options) {
|
||||
const parentKey =
|
||||
field.key === 'district_id'
|
||||
@@ -2942,14 +3129,20 @@ export function SimulationForm() {
|
||||
{(current.id === 'financial' ||
|
||||
(draft.purpose === 'simulate_only' &&
|
||||
current.id === 'tax')) && (
|
||||
<SimulationFinancialTools
|
||||
currency={String(draft.currency ?? '')}
|
||||
snapshot={String(draft.financial_tools_snapshot ?? '')}
|
||||
onSnapshotChange={(value) =>
|
||||
change('financial_tools_snapshot', value)
|
||||
}
|
||||
onCurrencyChange={(value) => change('currency', value)}
|
||||
/>
|
||||
<div
|
||||
id="draft-tool-calculation"
|
||||
tabIndex={-1}
|
||||
aria-label="Ferramentas de cálculo"
|
||||
>
|
||||
<SimulationFinancialTools
|
||||
currency={String(draft.currency ?? '')}
|
||||
snapshot={String(draft.financial_tools_snapshot ?? '')}
|
||||
onSnapshotChange={(value) =>
|
||||
change('financial_tools_snapshot', value)
|
||||
}
|
||||
onCurrencyChange={(value) => change('currency', value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{(current.id === 'financial' ||
|
||||
(draft.purpose === 'simulate_only' &&
|
||||
@@ -3172,30 +3365,41 @@ export function SimulationForm() {
|
||||
/>
|
||||
)}
|
||||
{current.id === 'tax' && (
|
||||
<SimulationFiscalStatus
|
||||
salaryView={String(draft.irps_salary_view ?? '')}
|
||||
scenarioMode={String(draft.fiscal_scenario_mode ?? '')}
|
||||
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]]
|
||||
: [],
|
||||
),
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
id="draft-tool-fiscal"
|
||||
tabIndex={-1}
|
||||
aria-label="Consulta de parâmetros fiscais"
|
||||
>
|
||||
<SimulationFiscalStatus
|
||||
salaryView={String(draft.irps_salary_view ?? '')}
|
||||
scenarioMode={
|
||||
openedTool === 'fiscal'
|
||||
? 'approved_parameters'
|
||||
: String(draft.fiscal_scenario_mode ?? '')
|
||||
}
|
||||
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]]
|
||||
: [],
|
||||
),
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{current.id === 'tax' &&
|
||||
draft.journey_type === 'investor' &&
|
||||
@@ -3307,6 +3511,14 @@ export function SimulationForm() {
|
||||
Simulação {simulationStatusLabel(result.status)}
|
||||
.
|
||||
</p>
|
||||
{result.status === 'completed' && (
|
||||
<p>
|
||||
Cálculo concluído no servidor. Próxima ação:
|
||||
reveja os pressupostos e o relatório antes
|
||||
de associar o resultado ao dossier. Nenhum
|
||||
pedido de apoio foi submetido.
|
||||
</p>
|
||||
)}
|
||||
{result.status === 'completed' && (
|
||||
<p>
|
||||
Resultado aritmético indicativo:{' '}
|
||||
@@ -3767,6 +3979,120 @@ export function SimulationForm() {
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{reviewStatus && (
|
||||
<div
|
||||
ref={reviewSummaryRef}
|
||||
tabIndex={-1}
|
||||
id="draft-validation-summary"
|
||||
role="status"
|
||||
aria-label="Resumo da validação do rascunho"
|
||||
className="max-h-[70vh] overflow-y-auto rounded border border-sky-300 bg-sky-50 p-3"
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
Resumo da validação do rascunho
|
||||
</h3>
|
||||
<p>{reviewStatus}</p>
|
||||
<p>
|
||||
Verificação local dos campos e regras disponíveis. Não
|
||||
calcula valores nem envia um pedido HTTP de validação. A
|
||||
gravação automática do rascunho tem um estado
|
||||
independente. Não confirma viabilidade, elegibilidade ou
|
||||
aprovação.
|
||||
</p>
|
||||
{reviewDetails.checked.length > 0 && (
|
||||
<div>
|
||||
<h4 className="font-semibold">
|
||||
Dados verificados (
|
||||
{reviewDetails.checked.length})
|
||||
</h4>
|
||||
<dl className="grid gap-2 text-slate-900">
|
||||
{reviewDetails.checked.map((field) => (
|
||||
<div
|
||||
key={field.key}
|
||||
className="rounded border bg-white p-2"
|
||||
>
|
||||
<dt className="font-medium">
|
||||
{field.label}
|
||||
</dt>
|
||||
<dd className="break-words">
|
||||
{field.value}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
<p>
|
||||
Campos pendentes e inconsistências:{' '}
|
||||
{reviewDetails.pending.length}.
|
||||
</p>
|
||||
{reviewDetails.pending.length > 0 && (
|
||||
<ul>
|
||||
{reviewDetails.pending.map((item) => (
|
||||
<li key={item.key}>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => {
|
||||
setStep(item.step);
|
||||
setErrors(
|
||||
Object.fromEntries(
|
||||
reviewDetails.pending.map(
|
||||
(entry) => [
|
||||
entry.key,
|
||||
entry.message,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
window.requestAnimationFrame(() =>
|
||||
document
|
||||
.getElementById(
|
||||
`field-${item.key}`,
|
||||
)
|
||||
?.focus(),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{item.label}: {item.message}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p>
|
||||
Próxima ação:{' '}
|
||||
{reviewDetails.pending.length
|
||||
? 'corrija os campos indicados e volte a validar.'
|
||||
: draft.purpose === 'simulate_only' &&
|
||||
draft.fiscal_scenario_mode === 'custom_planning'
|
||||
? 'abra a etapa fiscal e use “Validar e calcular no servidor” para obter um resultado separado.'
|
||||
: draft.purpose === 'simulate_only'
|
||||
? 'use a ferramenta de cálculo adequada aos resultados que pretende obter. A consulta de parâmetros fiscais não calcula impostos; para um cenário percentual hipotético, selecione o modo de planeamento personalizado na etapa fiscal.'
|
||||
: draft.purpose === 'request_facilitation'
|
||||
? 'confirme que o rascunho está guardado no servidor e continue no Balcão para preparar o pedido de apoio.'
|
||||
: draft.purpose === 'seek_partner'
|
||||
? 'confirme a gravação do rascunho e explore parceiros na Bolsa de Parcerias, preservando o contexto do projecto.'
|
||||
: draft.purpose === 'seek_investor'
|
||||
? 'confirme a gravação do rascunho e reveja o financiamento e a informação a apresentar a potenciais investidores.'
|
||||
: draft.purpose === 'present_opportunity'
|
||||
? 'confirme a gravação e reveja os dados e a autorização de divulgação antes de preparar a oportunidade.'
|
||||
: 'confirme a gravação e continue a preparar o dossier e o plano do seu investimento.'}{' '}
|
||||
Nenhum pedido foi submetido.
|
||||
</p>
|
||||
{draft.purpose === 'simulate_only' &&
|
||||
!reviewDetails.pending.length && (
|
||||
<div className="space-y-2">
|
||||
<p>
|
||||
{draft.fiscal_scenario_mode ===
|
||||
'custom_planning'
|
||||
? 'Modo personalizado escolhido: calcula uma operação percentual com a base, taxa e redução que introduziu. Não calcula um imposto legal.'
|
||||
: 'As ferramentas financeiras calculam prestações, ponto de equilíbrio e necessidades de financiamento com os seus pressupostos. A consulta fiscal identifica parâmetros e fontes; se faltarem parâmetros, o resultado fiscal permanece indeterminado. O modo escolhido será preservado.'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap justify-between gap-3 border-t pt-4">
|
||||
<button
|
||||
type="button"
|
||||
@@ -3785,15 +4111,56 @@ export function SimulationForm() {
|
||||
Guardar e continuar
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void clearDraft()}
|
||||
className="rounded border px-4 py-3 focus-visible:outline-2"
|
||||
>
|
||||
Limpar este rascunho
|
||||
</button>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
type="button"
|
||||
disabled={isCalculating}
|
||||
aria-busy={isCalculating}
|
||||
onClick={validateFinalReview}
|
||||
className="rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white disabled:opacity-60"
|
||||
>
|
||||
{isCalculating
|
||||
? 'A validar…'
|
||||
: 'Validar este rascunho'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void clearDraft()}
|
||||
className="rounded border px-4 py-3 focus-visible:outline-2"
|
||||
>
|
||||
Limpar este rascunho
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{draft.purpose === 'simulate_only' && (
|
||||
<div
|
||||
className="space-y-2 rounded border p-3"
|
||||
aria-label="Ações do simulador"
|
||||
>
|
||||
<p>
|
||||
Abrir cálculo apresenta as ferramentas financeiras e, se
|
||||
já escolhido, o cálculo percentual personalizado.
|
||||
Consultar parâmetros fiscais apresenta fontes e lacunas;
|
||||
não determina imposto devido.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded bg-emerald-800 px-4 py-3 font-semibold text-white"
|
||||
onClick={() => openDraftTool('calculation')}
|
||||
>
|
||||
Abrir cálculo
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-4 py-3"
|
||||
onClick={() => openDraftTool('fiscal')}
|
||||
>
|
||||
Consultar parâmetros fiscais
|
||||
</button>
|
||||
{toolError && <p role="alert">{toolError}</p>}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-slate-600">
|
||||
Os pressupostos não identificativos podem ser guardados de forma
|
||||
cifrada para recuperar o rascunho. Os dados pessoais e contactos
|
||||
|
||||
Reference in New Issue
Block a user