commit correcoes
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import {
|
||||
formFieldGuidance,
|
||||
formHelpPlacement,
|
||||
readFormHelpAutomatic,
|
||||
simulationStepGuidance,
|
||||
} from '@/lib/form-help';
|
||||
import {
|
||||
formHelpControls,
|
||||
formHelpGroupControls,
|
||||
formHelpControlSelector,
|
||||
formHelpControlVisible,
|
||||
formHelpField,
|
||||
formHelpStep,
|
||||
} from '@/lib/form-help-dom';
|
||||
|
||||
const preferenceKey = 'investemoz:form-field-help:v1';
|
||||
const button =
|
||||
'min-h-11 rounded-lg border px-3 py-2 text-sm font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700';
|
||||
type Step = { title: string; code: string; context: string };
|
||||
|
||||
/** Read-only assistance: observes labels and structure, never form values or submissions. */
|
||||
export default function FormFieldHelp() {
|
||||
const [control, setControl] = useState<HTMLElement | null>(null);
|
||||
const [step, setStep] = useState<Step | null>(null);
|
||||
const [available, setAvailable] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [automatic, setAutomatic] = useState(true);
|
||||
const [position, setPosition] = useState<'left' | 'right'>('right');
|
||||
const [vertical, setVertical] = useState<'top' | 'bottom'>('bottom');
|
||||
const [panelHeight, setPanelHeight] = useState<number | undefined>();
|
||||
const [dialog, setDialog] = useState<HTMLElement | null>(null);
|
||||
const automaticRef = useRef(true);
|
||||
const paused = useRef(false);
|
||||
const current = useRef<HTMLElement | null>(null);
|
||||
const root = useRef<HTMLElement>(null);
|
||||
const id = useId();
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
automaticRef.current = readFormHelpAutomatic(
|
||||
localStorage.getItem(preferenceKey),
|
||||
);
|
||||
} catch {
|
||||
/* Optional preference. */
|
||||
}
|
||||
setAutomatic(automaticRef.current);
|
||||
let frame = 0;
|
||||
let lastExplicitStep = '';
|
||||
let lastDescription = '';
|
||||
let page = location.pathname;
|
||||
function place(target: HTMLElement) {
|
||||
const layout = formHelpPlacement(
|
||||
target.getBoundingClientRect(),
|
||||
innerWidth,
|
||||
innerHeight,
|
||||
);
|
||||
setPosition(layout.side);
|
||||
setVertical(layout.vertical);
|
||||
setPanelHeight(layout.maxHeight);
|
||||
}
|
||||
function select(target: HTMLElement, show: boolean) {
|
||||
current.current = target;
|
||||
setControl(target);
|
||||
setStep(formHelpStep(target));
|
||||
setDialog(
|
||||
target.closest<HTMLElement>('[role="dialog"],dialog[open]'),
|
||||
);
|
||||
place(target);
|
||||
if (show) setOpen(true);
|
||||
}
|
||||
function scan() {
|
||||
frame = 0;
|
||||
if (page !== location.pathname) {
|
||||
page = location.pathname;
|
||||
current.current = null;
|
||||
paused.current = false;
|
||||
lastExplicitStep = '';
|
||||
setOpen(false);
|
||||
setDialog(null);
|
||||
}
|
||||
const controls = formHelpControls(document);
|
||||
const explicit = document.querySelector<HTMLElement>(
|
||||
'[data-form-help-context="simulator"]',
|
||||
);
|
||||
setAvailable(Boolean(controls.length || explicit));
|
||||
const signature = explicit
|
||||
? `${page}:${explicit.dataset.formHelpStep}`
|
||||
: '';
|
||||
if (signature && signature !== lastExplicitStep) {
|
||||
lastExplicitStep = signature;
|
||||
const first = controls.find((node) => explicit?.contains(node));
|
||||
current.current = first ?? null;
|
||||
setControl(first ?? null);
|
||||
setStep({
|
||||
title:
|
||||
explicit?.dataset.formHelpTitle ??
|
||||
'Preencher este passo',
|
||||
code: explicit?.dataset.formHelpStep ?? '',
|
||||
context: 'simulator',
|
||||
});
|
||||
if (automaticRef.current && !paused.current) setOpen(true);
|
||||
} else if (
|
||||
current.current &&
|
||||
!formHelpControlVisible(current.current)
|
||||
) {
|
||||
current.current = null;
|
||||
setControl(null);
|
||||
setOpen(false);
|
||||
setDialog(null);
|
||||
} else if (!current.current && controls[0] && !explicit) {
|
||||
select(controls[0], false);
|
||||
}
|
||||
if (current.current && formHelpControlVisible(current.current)) {
|
||||
place(current.current);
|
||||
const description = JSON.stringify([
|
||||
formHelpField(current.current),
|
||||
formHelpStep(current.current),
|
||||
]);
|
||||
if (description !== lastDescription) {
|
||||
lastDescription = description;
|
||||
setStep(formHelpStep(current.current));
|
||||
}
|
||||
}
|
||||
}
|
||||
const schedule = () => {
|
||||
if (!frame) frame = requestAnimationFrame(scan);
|
||||
};
|
||||
function focus(event: Event) {
|
||||
if (
|
||||
!(event.target instanceof Element) ||
|
||||
event.target.closest('[data-form-field-help]')
|
||||
)
|
||||
return;
|
||||
const target = event.target.closest<HTMLElement>(
|
||||
formHelpControlSelector,
|
||||
);
|
||||
if (
|
||||
target &&
|
||||
target.closest(
|
||||
'main,[role="main"],[role="dialog"],dialog[open]',
|
||||
) &&
|
||||
formHelpControlVisible(target)
|
||||
)
|
||||
select(target, automaticRef.current && !paused.current);
|
||||
}
|
||||
function click(event: Event) {
|
||||
if (!(event.target instanceof Element)) return;
|
||||
const trigger = event.target.closest<HTMLElement>(
|
||||
'[data-form-help-open]',
|
||||
);
|
||||
if (!trigger) return;
|
||||
paused.current = false;
|
||||
const scope = trigger.closest<HTMLElement>(
|
||||
'[data-form-help-context]',
|
||||
);
|
||||
if (scope) {
|
||||
current.current = null;
|
||||
setControl(null);
|
||||
setStep({
|
||||
title:
|
||||
scope.dataset.formHelpTitle ?? 'Preencher este passo',
|
||||
code: scope.dataset.formHelpStep ?? '',
|
||||
context: scope.dataset.formHelpContext ?? '',
|
||||
});
|
||||
}
|
||||
setOpen(true);
|
||||
requestAnimationFrame(() =>
|
||||
root.current
|
||||
?.querySelector<HTMLElement>('[data-form-help-panel]')
|
||||
?.focus({ preventScroll: true }),
|
||||
);
|
||||
}
|
||||
const observer = new MutationObserver((records) => {
|
||||
if (
|
||||
records.some(
|
||||
(record) =>
|
||||
!(
|
||||
record.target instanceof Element
|
||||
? record.target
|
||||
: record.target.parentElement
|
||||
)?.closest('[data-form-field-help]'),
|
||||
)
|
||||
)
|
||||
schedule();
|
||||
});
|
||||
observer.observe(document.body, {
|
||||
childList: true,
|
||||
characterData: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: [
|
||||
'hidden',
|
||||
'disabled',
|
||||
'readonly',
|
||||
'aria-hidden',
|
||||
'aria-disabled',
|
||||
'required',
|
||||
'aria-required',
|
||||
'aria-label',
|
||||
'aria-labelledby',
|
||||
'aria-describedby',
|
||||
'placeholder',
|
||||
'class',
|
||||
'style',
|
||||
'data-form-help-step',
|
||||
'data-form-help-title',
|
||||
],
|
||||
});
|
||||
document.addEventListener('focusin', focus);
|
||||
document.addEventListener('click', click);
|
||||
document.addEventListener('toggle', schedule, true);
|
||||
window.addEventListener('resize', schedule);
|
||||
const scroll = () => {
|
||||
if (current.current) place(current.current);
|
||||
};
|
||||
window.addEventListener('scroll', scroll, { passive: true });
|
||||
scan();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
if (frame) cancelAnimationFrame(frame);
|
||||
document.removeEventListener('focusin', focus);
|
||||
document.removeEventListener('click', click);
|
||||
document.removeEventListener('toggle', schedule, true);
|
||||
window.removeEventListener('resize', schedule);
|
||||
window.removeEventListener('scroll', scroll);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!available) return null;
|
||||
const field = control ? formHelpField(control) : null;
|
||||
const guidance = field ? formFieldGuidance(field) : null;
|
||||
function close() {
|
||||
paused.current = true;
|
||||
setOpen(false);
|
||||
root.current
|
||||
?.querySelector<HTMLButtonElement>('[data-form-help-toggle]')
|
||||
?.focus({ preventScroll: true });
|
||||
}
|
||||
function move(direction: number) {
|
||||
const fields = formHelpGroupControls(document, control);
|
||||
const index = control ? fields.indexOf(control) : -1;
|
||||
const target = fields[index + direction];
|
||||
if (!target) return;
|
||||
paused.current = false;
|
||||
target.focus({ preventScroll: true });
|
||||
target.scrollIntoView({ block: 'center', behavior: 'auto' });
|
||||
current.current = target;
|
||||
setControl(target);
|
||||
setStep(formHelpStep(target));
|
||||
}
|
||||
const fields = formHelpGroupControls(document, control);
|
||||
const index = control ? fields.indexOf(control) : -1;
|
||||
const content = (
|
||||
<aside
|
||||
ref={root}
|
||||
data-form-field-help
|
||||
aria-label="Ajuda ao preenchimento"
|
||||
className={
|
||||
dialog
|
||||
? 'mt-3 max-w-full min-w-0 text-slate-900'
|
||||
: `fixed z-40 max-w-[calc(100%-1.5rem)] text-slate-900 ${vertical === 'top' ? 'top-20' : 'bottom-3'} ${position === 'left' ? 'left-3' : 'right-3'}`
|
||||
}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape' && open) {
|
||||
event.preventDefault();
|
||||
close();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{open && (
|
||||
<section
|
||||
id={id}
|
||||
data-form-help-panel
|
||||
tabIndex={-1}
|
||||
aria-labelledby={`${id}-title`}
|
||||
style={{
|
||||
maxHeight: dialog
|
||||
? Math.min(innerHeight * 0.3, 260)
|
||||
: panelHeight,
|
||||
}}
|
||||
className="mb-2 max-h-[45dvh] w-96 max-w-full space-y-3 overflow-y-auto rounded-xl border-2 border-emerald-700 bg-white p-4 shadow-xl focus-visible:outline-2"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h2 id={`${id}-title`} className="font-semibold">
|
||||
{step?.title ?? 'Ajuda neste passo'}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={close}
|
||||
>
|
||||
Fechar ajuda
|
||||
</button>
|
||||
</div>
|
||||
{step?.context === 'simulator' && (
|
||||
<p className="text-sm">
|
||||
{simulationStepGuidance(step.code)}
|
||||
</p>
|
||||
)}
|
||||
{field && guidance ? (
|
||||
<div className="space-y-2 rounded-lg bg-emerald-50 p-3 text-sm">
|
||||
<h3 className="font-semibold">{field.label}</h3>
|
||||
<p>
|
||||
<strong>O que preencher:</strong>{' '}
|
||||
{guidance.instruction}
|
||||
</p>
|
||||
{guidance.example && (
|
||||
<p>
|
||||
<strong>Exemplo:</strong> {guidance.example}
|
||||
</p>
|
||||
)}
|
||||
{field.required && (
|
||||
<p>
|
||||
Este campo está assinalado como obrigatório
|
||||
no formulário.
|
||||
</p>
|
||||
)}
|
||||
{field.hint && (
|
||||
<p>
|
||||
<strong>Indicação do formulário:</strong>{' '}
|
||||
{field.hint}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm">
|
||||
Seleccione um campo do formulário para consultar a
|
||||
sua orientação.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={index <= 0}
|
||||
onClick={() => move(-1)}
|
||||
>
|
||||
Campo anterior
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
!fields.length || index >= fields.length - 1
|
||||
}
|
||||
onClick={() => move(1)}
|
||||
>
|
||||
{index < 0
|
||||
? 'Ver primeiro campo'
|
||||
: 'Campo seguinte'}
|
||||
</button>
|
||||
</div>
|
||||
<label className="flex min-h-11 items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={automatic}
|
||||
onChange={(event) => {
|
||||
const enabled = event.target.checked;
|
||||
setAutomatic(enabled);
|
||||
automaticRef.current = enabled;
|
||||
paused.current = !enabled;
|
||||
try {
|
||||
localStorage.setItem(
|
||||
preferenceKey,
|
||||
enabled ? 'on' : 'off',
|
||||
);
|
||||
} catch {
|
||||
/* Optional preference. */
|
||||
}
|
||||
}}
|
||||
/>
|
||||
Orientações automáticas neste navegador
|
||||
</label>
|
||||
</section>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
data-form-help-toggle
|
||||
aria-expanded={open}
|
||||
aria-controls={id}
|
||||
className={`${button} max-w-full border-emerald-800 bg-emerald-800 text-white shadow-lg`}
|
||||
onClick={() => {
|
||||
if (open) close();
|
||||
else {
|
||||
paused.current = false;
|
||||
setOpen(true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true">❔</span> Ajuda neste passo
|
||||
{field && (
|
||||
<span className="ml-2 hidden max-w-48 truncate align-bottom font-normal sm:inline">
|
||||
· {field.label}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</aside>
|
||||
);
|
||||
// Keep help inside a modal's focus scope instead of behind its backdrop.
|
||||
return dialog?.isConnected ? createPortal(content, dialog) : content;
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export type QuantitativeMapContext = {
|
||||
source_reference?: string | null;
|
||||
source_date?: string | null;
|
||||
knowledge: string;
|
||||
measure_kind?: 'unknown' | 'observed' | 'planned' | 'projected';
|
||||
missing_metadata: string[];
|
||||
}[];
|
||||
zones_consulted?: number;
|
||||
@@ -47,6 +48,17 @@ const metadataLabels: Record<string, string> = {
|
||||
source_date: 'data da fonte',
|
||||
};
|
||||
const text = (value?: string | null) => value?.trim() || 'Não indicado';
|
||||
const measureKinds: Record<string, string> = {
|
||||
unknown: 'Por confirmar',
|
||||
observed: 'Observado / efectivo',
|
||||
planned: 'Planeado / meta',
|
||||
projected: 'Projectado / estimado',
|
||||
};
|
||||
const measureKind = (row: QuantitativeMapContext['records'][number]) =>
|
||||
row.measure_kind &&
|
||||
['observed', 'planned', 'projected'].includes(row.measure_kind)
|
||||
? row.measure_kind
|
||||
: 'unknown';
|
||||
const completeDate = (value?: string | null) =>
|
||||
Boolean(
|
||||
value &&
|
||||
@@ -55,6 +67,286 @@ const completeDate = (value?: string | null) =>
|
||||
new Date(value).toISOString().slice(0, 10) === value,
|
||||
);
|
||||
|
||||
type MapObservation = QuantitativeMapContext['records'][number];
|
||||
// Calendar metadata only: inclusive source dates, never a rate or annualisation.
|
||||
function periodDays(row: MapObservation): number | null {
|
||||
if (
|
||||
!completeDate(row.period_start) ||
|
||||
!completeDate(row.period_end) ||
|
||||
row.period_start! > row.period_end!
|
||||
)
|
||||
return null;
|
||||
return (
|
||||
(Date.parse(row.period_end!) - Date.parse(row.period_start!)) /
|
||||
86_400_000 +
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
const observationKey = (row: MapObservation) =>
|
||||
JSON.stringify([row.zone_id, row.id, row.zone_version]);
|
||||
|
||||
export function compareMapObservations(
|
||||
first: MapObservation,
|
||||
second: MapObservation,
|
||||
) {
|
||||
const issues: string[] = [];
|
||||
if (observationKey(first) === observationKey(second))
|
||||
issues.push('Escolha duas observações distintas.');
|
||||
if (first.zone_id !== second.zone_id)
|
||||
issues.push(
|
||||
'Territórios distintos: os valores não representam uma série do mesmo local.',
|
||||
);
|
||||
for (const [label, row] of [
|
||||
['Primeira', first],
|
||||
['Segunda', second],
|
||||
] as const) {
|
||||
if (measureKind(row) === 'unknown')
|
||||
issues.push(
|
||||
`${label} observação: natureza do valor por confirmar na fonte.`,
|
||||
);
|
||||
if (row.knowledge !== 'documented')
|
||||
issues.push(
|
||||
`${label} observação: informação desconhecida ou em divergência.`,
|
||||
);
|
||||
if (
|
||||
row.value === null ||
|
||||
!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(row.value)
|
||||
)
|
||||
issues.push(
|
||||
`${label} observação: valor quantitativo por confirmar.`,
|
||||
);
|
||||
const comparisonMetadata: Record<string, string> = {
|
||||
...metadataLabels,
|
||||
description: 'descrição/natureza da grandeza',
|
||||
};
|
||||
const missing = Object.keys(comparisonMetadata).filter(
|
||||
(field) => !row[field as keyof MapObservation]?.toString().trim(),
|
||||
);
|
||||
if (missing.length)
|
||||
issues.push(
|
||||
`${label} observação sem ${missing.map((field) => comparisonMetadata[field]).join(', ')}.`,
|
||||
);
|
||||
if (
|
||||
!completeDate(row.period_start) ||
|
||||
!completeDate(row.period_end) ||
|
||||
(row.period_start ?? '') > (row.period_end ?? '')
|
||||
)
|
||||
issues.push(`${label} observação: período incompleto ou inválido.`);
|
||||
if (!completeDate(row.source_date))
|
||||
issues.push(
|
||||
`${label} observação: data da fonte incompleta ou inválida.`,
|
||||
);
|
||||
}
|
||||
const firstDays = periodDays(first);
|
||||
const secondDays = periodDays(second);
|
||||
if (firstDays !== null && secondDays !== null) {
|
||||
if (firstDays !== secondDays)
|
||||
issues.push(
|
||||
'Duração dos períodos diferente; não trate os valores como bases temporais equivalentes.',
|
||||
);
|
||||
if (
|
||||
(first.period_start !== second.period_start ||
|
||||
first.period_end !== second.period_end) &&
|
||||
first.period_start! <= second.period_end! &&
|
||||
second.period_start! <= first.period_end!
|
||||
)
|
||||
issues.push(
|
||||
'Os períodos sobrepõem-se; as observações podem abranger os mesmos dias.',
|
||||
);
|
||||
}
|
||||
if (measureKind(first) !== measureKind(second))
|
||||
issues.push(
|
||||
'Natureza do valor diferente: observado, planeado e projectado não são equivalentes.',
|
||||
);
|
||||
for (const [field, label] of Object.entries({
|
||||
indicator: 'Indicador',
|
||||
unit: 'Unidade',
|
||||
scope: 'Âmbito',
|
||||
population: 'População/base',
|
||||
methodology: 'Metodologia',
|
||||
})) {
|
||||
if (
|
||||
(first[field as keyof MapObservation] ?? '').toString().trim() !==
|
||||
(second[field as keyof MapObservation] ?? '').toString().trim()
|
||||
)
|
||||
issues.push(`${label} diferente entre as observações.`);
|
||||
}
|
||||
return {
|
||||
state: issues.length ? 'review_required' : 'metadata_aligned',
|
||||
issues,
|
||||
};
|
||||
}
|
||||
|
||||
export function MapObservationComparison({
|
||||
first,
|
||||
second,
|
||||
}: {
|
||||
first?: MapObservation;
|
||||
second?: MapObservation;
|
||||
}) {
|
||||
if (!first || !second)
|
||||
return (
|
||||
<p role="status">
|
||||
Seleccione duas observações disponíveis nos filtros actuais.
|
||||
</p>
|
||||
);
|
||||
const assessment = compareMapObservations(first, second);
|
||||
const fields: [string, (row: MapObservation) => string][] = [
|
||||
['Território', (row) => row.zone_name],
|
||||
['Observação', (row) => text(row.label)],
|
||||
['Descrição e natureza da grandeza', (row) => text(row.description)],
|
||||
['Natureza do valor', (row) => measureKinds[measureKind(row)]],
|
||||
['Indicador', (row) => labels[row.indicator] ?? row.indicator],
|
||||
[
|
||||
'Valor original',
|
||||
(row) => (row.value === null ? 'Por confirmar' : row.value),
|
||||
],
|
||||
['Unidade', (row) => text(row.unit)],
|
||||
[
|
||||
'Período',
|
||||
(row) => `${text(row.period_start)} — ${text(row.period_end)}`,
|
||||
],
|
||||
[
|
||||
'Duração do período (dias, limites incluídos)',
|
||||
(row) => {
|
||||
const days = periodDays(row);
|
||||
return days === null ? 'Por confirmar' : String(days);
|
||||
},
|
||||
],
|
||||
['Âmbito', (row) => text(row.scope)],
|
||||
['População/base', (row) => text(row.population)],
|
||||
['Metodologia', (row) => text(row.methodology)],
|
||||
[
|
||||
'Situação da informação',
|
||||
(row) =>
|
||||
row.knowledge === 'documented'
|
||||
? 'Documentada'
|
||||
: row.knowledge === 'disputed'
|
||||
? 'Em divergência'
|
||||
: 'Por confirmar',
|
||||
],
|
||||
['Fonte', (row) => text(row.source_reference)],
|
||||
['Data da fonte', (row) => text(row.source_date)],
|
||||
['Versão da ficha territorial', (row) => String(row.zone_version)],
|
||||
];
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p role="status">
|
||||
{assessment.state === 'metadata_aligned'
|
||||
? 'Metadados alinhados; confirme nas fontes se os valores podem ser comparados.'
|
||||
: 'Há diferenças ou lacunas a conferir antes de comparar os valores.'}
|
||||
</p>
|
||||
{!!assessment.issues.length && (
|
||||
<ul className="list-disc pl-5">
|
||||
{assessment.issues.map((issue) => (
|
||||
<li key={issue}>{issue}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p>
|
||||
Períodos distintos ou sobrepostos exigem conferência da duração
|
||||
e da base na fonte. Esta apresentação não calcula evolução,
|
||||
soma, conversão, pontuação ou estimativa regional. A natureza
|
||||
declarada deve ser conferida com a descrição e a fonte.
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<caption className="sr-only">
|
||||
Conferência de duas observações quantitativas
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2">Campo</th>
|
||||
<th className="p-2">Primeira observação</th>
|
||||
<th className="p-2">Segunda observação</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{fields.map(([label, value]) => (
|
||||
<tr key={label} className="border-t">
|
||||
<th className="p-2" scope="row">
|
||||
{label}
|
||||
</th>
|
||||
<td className="p-2 break-words">
|
||||
{value(first)}
|
||||
</td>
|
||||
<td className="p-2 break-words">
|
||||
{value(second)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MapObservationComparisonPicker({ rows }: { rows: MapObservation[] }) {
|
||||
const id = useId();
|
||||
const [firstKey, setFirst] = useState('');
|
||||
const [secondKey, setSecond] = useState('');
|
||||
const first = rows.find((row) => observationKey(row) === firstKey);
|
||||
const second = rows.find((row) => observationKey(row) === secondKey);
|
||||
return (
|
||||
<details className="space-y-3 rounded border p-3">
|
||||
<summary>Comparar duas observações</summary>
|
||||
<p>
|
||||
Confronte os dados e as fontes antes de os usar na decisão.
|
||||
Selecções fora dos filtros deixam de ser comparadas; uma versão
|
||||
nova exige nova selecção.
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{(['Primeira', 'Segunda'] as const).map((label, index) => (
|
||||
<label
|
||||
className="grid gap-1"
|
||||
key={label}
|
||||
htmlFor={`${id}-${index}`}
|
||||
>
|
||||
{label} observação
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
id={`${id}-${index}`}
|
||||
value={
|
||||
index === 0
|
||||
? first
|
||||
? firstKey
|
||||
: ''
|
||||
: second
|
||||
? secondKey
|
||||
: ''
|
||||
}
|
||||
onChange={(event) =>
|
||||
(index === 0 ? setFirst : setSecond)(
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar observação</option>
|
||||
{rows.map((row) => (
|
||||
<option
|
||||
key={observationKey(row)}
|
||||
value={observationKey(row)}
|
||||
>
|
||||
{row.zone_name} —{' '}
|
||||
{row.label ||
|
||||
labels[row.indicator] ||
|
||||
row.indicator}{' '}
|
||||
— {row.period_start || '?'} /{' '}
|
||||
{row.period_end || '?'} — v
|
||||
{row.zone_version}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<MapObservationComparison first={first} second={second} />
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
export function filterMapIndicators(
|
||||
records: QuantitativeMapContext['records'],
|
||||
indicator: string,
|
||||
@@ -114,9 +406,9 @@ export default function InvestmentMapIndicators({
|
||||
contexto territorial, independentes das evidências das
|
||||
oportunidades. Emprego não mede trabalhadores disponíveis;
|
||||
investimento, produção e exportações não constituem um índice de
|
||||
potencial ou garantia de retorno. A natureza prevista ou
|
||||
efectiva de cada valor depende da descrição da fonte, não é
|
||||
determinada automaticamente.
|
||||
potencial ou garantia de retorno. A natureza do valor é
|
||||
declarada segundo a fonte; sem essa indicação permanece por
|
||||
confirmar.
|
||||
</p>
|
||||
{!context ? (
|
||||
<p role="status">A carregar indicadores quantitativos…</p>
|
||||
@@ -242,6 +534,9 @@ export default function InvestmentMapIndicators({
|
||||
observações. Refine a localização.
|
||||
</p>
|
||||
)}
|
||||
{rows.length > 1 && (
|
||||
<MapObservationComparisonPicker rows={rows} />
|
||||
)}
|
||||
{rows.length === 0 ? (
|
||||
<p>
|
||||
{filtered
|
||||
@@ -308,6 +603,14 @@ export default function InvestmentMapIndicators({
|
||||
'Por determinar'}{' '}
|
||||
· {text(row.unit)}
|
||||
</p>
|
||||
<p>
|
||||
Natureza:{' '}
|
||||
{
|
||||
measureKinds[
|
||||
measureKind(row)
|
||||
]
|
||||
}
|
||||
</p>
|
||||
<p>
|
||||
{row.knowledge ===
|
||||
'documented'
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { CircleHelp } from 'lucide-react';
|
||||
import {
|
||||
helpPreferenceKey,
|
||||
readHelpPreference,
|
||||
type InvestmentHelp,
|
||||
} from '@/lib/investment-step-help';
|
||||
|
||||
type GuideState = {
|
||||
steps: InvestmentHelp[];
|
||||
active: string | null;
|
||||
automatic: boolean;
|
||||
choose: (code: string | null, reveal?: boolean) => void;
|
||||
};
|
||||
const GuideContext = createContext<GuideState | null>(null);
|
||||
const helpButton =
|
||||
'inline-flex min-h-11 items-center justify-center gap-2 rounded-lg border px-3 py-2 text-sm font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700';
|
||||
|
||||
export function InvestmentHelpGuide({
|
||||
steps,
|
||||
user,
|
||||
flow,
|
||||
initialCode,
|
||||
children,
|
||||
}: {
|
||||
steps: InvestmentHelp[];
|
||||
user: string | number;
|
||||
flow: string;
|
||||
initialCode?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const [active, setActive] = useState<string | null>(null);
|
||||
const [automatic, setAutomatic] = useState(true);
|
||||
const paused = useRef(false);
|
||||
const key = helpPreferenceKey(user, flow);
|
||||
const firstCode = steps.some((step) => step.code === initialCode)
|
||||
? initialCode
|
||||
: steps[0]?.code;
|
||||
|
||||
useEffect(() => {
|
||||
let preference = readHelpPreference(null);
|
||||
try {
|
||||
preference = readHelpPreference(window.localStorage.getItem(key));
|
||||
} catch {
|
||||
/* Help also works without browser storage. */
|
||||
}
|
||||
setAutomatic(preference.automatic);
|
||||
setActive(
|
||||
preference.automatic && !preference.seen
|
||||
? (firstCode ?? null)
|
||||
: null,
|
||||
);
|
||||
paused.current = false;
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
key,
|
||||
JSON.stringify({ ...preference, seen: true }),
|
||||
);
|
||||
} catch {
|
||||
/* Optional preference only. */
|
||||
}
|
||||
}, [key]); // A new applicable step does not restart a dismissed guide.
|
||||
|
||||
const visibleActive = steps.some((step) => step.code === active)
|
||||
? active
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (!visibleActive || !root.current) return;
|
||||
const target = Array.from(
|
||||
root.current.querySelectorAll<HTMLElement>(
|
||||
'[data-investment-step]',
|
||||
),
|
||||
).find((node) => node.dataset.investmentStep === visibleActive);
|
||||
let ancestor: HTMLElement | null = target ?? null;
|
||||
while (ancestor && ancestor !== root.current) {
|
||||
if (ancestor.tagName === 'DETAILS')
|
||||
(ancestor as HTMLDetailsElement).open = true;
|
||||
ancestor = ancestor.parentElement;
|
||||
}
|
||||
}, [visibleActive]);
|
||||
|
||||
function choose(code: string | null, reveal = false) {
|
||||
paused.current = code === null;
|
||||
if (code === null && visibleActive) {
|
||||
const panel = Array.from(
|
||||
root.current?.querySelectorAll<HTMLElement>(
|
||||
'[data-help-panel]',
|
||||
) ?? [],
|
||||
).find((node) => node.dataset.helpPanel === visibleActive);
|
||||
panel?.parentElement
|
||||
?.querySelector<HTMLButtonElement>('button')
|
||||
?.focus({ preventScroll: true });
|
||||
}
|
||||
setActive(code);
|
||||
if (code && reveal) {
|
||||
// Wait for the selected inline explanation to render before focusing it.
|
||||
requestAnimationFrame(() => {
|
||||
const target = Array.from(
|
||||
root.current?.querySelectorAll<HTMLElement>(
|
||||
'[data-help-panel]',
|
||||
) ?? [],
|
||||
).find((node) => node.dataset.helpPanel === code);
|
||||
target?.scrollIntoView({ block: 'nearest' });
|
||||
target?.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function orient(target: EventTarget, disclosure = false) {
|
||||
if (
|
||||
!automatic ||
|
||||
paused.current ||
|
||||
!(target instanceof Element) ||
|
||||
target.closest('[data-help-controls]') ||
|
||||
(!disclosure && target.closest('summary'))
|
||||
)
|
||||
return;
|
||||
const code = target.closest<HTMLElement>('[data-investment-step]')
|
||||
?.dataset.investmentStep;
|
||||
if (code && steps.some((step) => step.code === code)) setActive(code);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const node = root.current;
|
||||
if (!node) return;
|
||||
const onToggle = (event: Event) => {
|
||||
const target = event.target;
|
||||
// Native toggle follows the summary click. Observe the opened state
|
||||
// instead of changing it while focus/click is still being dispatched.
|
||||
if (target instanceof HTMLDetailsElement && target.open) {
|
||||
orient(target, true);
|
||||
}
|
||||
};
|
||||
node.addEventListener('toggle', onToggle, true);
|
||||
return () => node.removeEventListener('toggle', onToggle, true);
|
||||
}, [automatic, steps]);
|
||||
|
||||
return (
|
||||
<GuideContext.Provider
|
||||
value={{ steps, active: visibleActive, automatic, choose }}
|
||||
>
|
||||
<div
|
||||
ref={root}
|
||||
className="space-y-5"
|
||||
onFocusCapture={(event) => orient(event.target)}
|
||||
onClickCapture={(event) => orient(event.target)}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key === 'Escape' &&
|
||||
visibleActive &&
|
||||
(event.target as Element).closest('[data-help-panel]')
|
||||
) {
|
||||
event.preventDefault();
|
||||
choose(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<section
|
||||
aria-label="Guia de ajuda do Investemoz"
|
||||
data-help-controls
|
||||
className="flex flex-wrap items-center gap-3 rounded-xl border border-emerald-700/30 bg-emerald-50 p-4 text-slate-900 dark:bg-emerald-950 dark:text-slate-100"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-semibold">Guia do Investemoz</p>
|
||||
<p className="text-sm">
|
||||
Consulte o que fazer, veja um exemplo e avance ao
|
||||
seu ritmo.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
disabled={!steps.length}
|
||||
onClick={() =>
|
||||
choose(visibleActive ?? firstCode ?? null, true)
|
||||
}
|
||||
>
|
||||
Ver guia passo a passo
|
||||
</button>
|
||||
<label className="flex min-h-11 cursor-pointer items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={automatic}
|
||||
onChange={(event) => {
|
||||
const enabled = event.target.checked;
|
||||
setAutomatic(enabled);
|
||||
paused.current = !enabled;
|
||||
setActive(enabled ? (firstCode ?? null) : null);
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
key,
|
||||
JSON.stringify({
|
||||
automatic: enabled,
|
||||
seen: true,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
/* Optional preference only. */
|
||||
}
|
||||
}}
|
||||
/>
|
||||
Orientações automáticas
|
||||
</label>
|
||||
</section>
|
||||
{children}
|
||||
</div>
|
||||
</GuideContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function HelpAtStep({ code }: { code: string }) {
|
||||
const guide = useContext(GuideContext);
|
||||
const id = useId();
|
||||
const index = guide?.steps.findIndex((step) => step.code === code) ?? -1;
|
||||
if (!guide || index < 0) return null;
|
||||
const step = guide.steps[index];
|
||||
const open = guide.active === code;
|
||||
return (
|
||||
<div data-help-controls className="my-3">
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
aria-expanded={open}
|
||||
aria-controls={id}
|
||||
aria-label={`Ajuda neste passo: ${step.title}`}
|
||||
onClick={() => guide.choose(open ? null : code)}
|
||||
>
|
||||
<CircleHelp className="size-4 shrink-0" aria-hidden="true" />{' '}
|
||||
Ajuda neste passo
|
||||
</button>
|
||||
{open && (
|
||||
<section
|
||||
id={id}
|
||||
data-help-panel={code}
|
||||
tabIndex={-1}
|
||||
aria-labelledby={`${id}-title`}
|
||||
className="mt-3 space-y-3 rounded-xl border-2 border-emerald-700 bg-emerald-50 p-4 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 dark:bg-emerald-950 dark:text-slate-100"
|
||||
>
|
||||
<p className="text-sm" role="status">
|
||||
Ajuda · Passo {index + 1} de {guide.steps.length}
|
||||
</p>
|
||||
<h3 id={`${id}-title`} className="font-semibold">
|
||||
{step.title}
|
||||
</h3>
|
||||
<p>
|
||||
<strong>O que fazer:</strong> {step.instruction}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Exemplo:</strong> {step.example}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Para que serve:</strong> {step.purpose}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
disabled={index === 0}
|
||||
onClick={() =>
|
||||
guide.choose(guide.steps[index - 1].code, true)
|
||||
}
|
||||
>
|
||||
Voltar
|
||||
</button>
|
||||
{index < guide.steps.length - 1 ? (
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
onClick={() =>
|
||||
guide.choose(
|
||||
guide.steps[index + 1].code,
|
||||
true,
|
||||
)
|
||||
}
|
||||
>
|
||||
Seguinte
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
onClick={() => guide.choose(null)}
|
||||
>
|
||||
Concluir guia
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
onClick={() => guide.choose(null)}
|
||||
>
|
||||
Fechar guia
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -60,7 +60,8 @@ const labels: Record<string, string> = {
|
||||
geometry_id: 'Geometria já associada ao parque',
|
||||
zone_link_id: 'Relação económica já associada ao parque',
|
||||
indicator: 'Indicador',
|
||||
value: 'Valor observado',
|
||||
measure_kind: 'Natureza do valor segundo a fonte',
|
||||
value: 'Valor indicado na fonte',
|
||||
unit: 'Unidade de medida',
|
||||
period_start: 'Início do período',
|
||||
period_end: 'Fim do período',
|
||||
@@ -86,6 +87,7 @@ const extras: Record<Group, string[]> = {
|
||||
],
|
||||
observations: [
|
||||
'indicator',
|
||||
'measure_kind',
|
||||
'value',
|
||||
'unit',
|
||||
'period_start',
|
||||
@@ -105,6 +107,12 @@ const extras: Record<Group, string[]> = {
|
||||
],
|
||||
};
|
||||
const choices: Record<string, Record<string, string>> = {
|
||||
measure_kind: {
|
||||
unknown: 'Por confirmar',
|
||||
observed: 'Observado / efectivo',
|
||||
planned: 'Planeado / meta',
|
||||
projected: 'Projectado / estimado',
|
||||
},
|
||||
knowledge: {
|
||||
unknown: 'Não informado',
|
||||
documented: 'Documentado pela fonte',
|
||||
@@ -248,7 +256,11 @@ export default function ParkIntegralEditor({
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Não informado / sem associação</option>
|
||||
<option value="">
|
||||
{key === 'measure_kind'
|
||||
? 'Por confirmar na fonte'
|
||||
: 'Não informado / sem associação'}
|
||||
</option>
|
||||
{Object.entries(options).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
@@ -541,7 +553,9 @@ export function ParkIntegralPublic({ value }: { value?: ParkIntegral }) {
|
||||
)
|
||||
: item[k] == null ||
|
||||
item[k] === ''
|
||||
? 'Não informado'
|
||||
? k === 'measure_kind'
|
||||
? 'Por confirmar'
|
||||
: 'Não informado'
|
||||
: k === 'expansion'
|
||||
? item[k]
|
||||
? 'Sim, segundo a fonte'
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
createInvestorDossierReport,
|
||||
createInvestorStageReport,
|
||||
investorDossierReportIndex,
|
||||
type InvestorDossierReportInput,
|
||||
} from '@/lib/investor-dossier-report';
|
||||
import {
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '@/lib/project-dossier-report';
|
||||
|
||||
export function InvestorDossierReports({
|
||||
dossier,
|
||||
}: {
|
||||
dossier: InvestorDossierReportInput;
|
||||
}) {
|
||||
return (
|
||||
<InvestorDossierReportsContent
|
||||
key={`${dossier.case.id}:${dossier.case.version}:${dossier.context_opportunity ?? ''}`}
|
||||
dossier={dossier}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function InvestorDossierReportsContent({
|
||||
dossier,
|
||||
}: {
|
||||
dossier: InvestorDossierReportInput;
|
||||
}) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [stage, setStage] = useState('');
|
||||
const [download, setDownload] = useState<{
|
||||
url: string;
|
||||
name: string;
|
||||
} | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (download) URL.revokeObjectURL(download.url);
|
||||
},
|
||||
[download],
|
||||
);
|
||||
const requiresChoice =
|
||||
dossier.opportunity_options.length > 1 && !dossier.context_opportunity;
|
||||
const entries = requiresChoice ? [] : investorDossierReportIndex(dossier);
|
||||
async function exportReport(format: 'word' | 'html') {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const model = stage
|
||||
? createInvestorStageReport(dossier, stage)
|
||||
: createInvestorDossierReport(dossier);
|
||||
const blob =
|
||||
format === 'word'
|
||||
? await generateProjectDossierDocx(model, [], true)
|
||||
: new Blob(
|
||||
[
|
||||
await createProjectDossierPrintHtml(
|
||||
model,
|
||||
[],
|
||||
true,
|
||||
),
|
||||
],
|
||||
{ type: 'text/html;charset=utf-8' },
|
||||
);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const name = `dossier-${dossier.case.id}-v${dossier.case.version}-${dossier.context_opportunity ? encodeURIComponent(dossier.context_opportunity) : 'comum'}${stage ? `-${stage}` : ''}.${format === 'word' ? 'docx' : 'html'}`;
|
||||
setDownload({ url, name });
|
||||
} catch (cause) {
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Não foi possível preparar o relatório. Os registos foram preservados.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section id="relatorios" className="space-y-4 rounded-xl border p-4">
|
||||
<h2 className="text-lg font-semibold">Relatórios deste dossier</h2>
|
||||
<p>
|
||||
Dossier {dossier.case.title} · versão {dossier.case.version} ·
|
||||
oportunidade {dossier.context_opportunity ?? 'contexto comum'}.
|
||||
</p>
|
||||
<p>
|
||||
Reúna as etapas, a viabilidade, a análise SWOT e a preparação
|
||||
APIEX. O relatório mantém os estados e as pendências; os
|
||||
originais continuam nas respectivas versões.
|
||||
</p>
|
||||
{requiresChoice ? (
|
||||
<p role="status">
|
||||
Seleccione a oportunidade em tratamento para reunir os seus
|
||||
relatórios sem misturar contextos.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<label className="block">
|
||||
Relatório a consultar e descarregar
|
||||
<select
|
||||
className="mt-1 block w-full rounded border p-2"
|
||||
value={stage}
|
||||
disabled={busy}
|
||||
onChange={(event) => {
|
||||
setStage(event.target.value);
|
||||
setDownload(null);
|
||||
}}
|
||||
>
|
||||
<option value="">Dossier completo</option>
|
||||
{dossier.steps.map((step) => (
|
||||
<option key={step.code} value={step.code}>
|
||||
{step.code} — {step.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{stage && (
|
||||
<StageReportPreview dossier={dossier} stage={stage} />
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={busy}
|
||||
onClick={() => exportReport('word')}
|
||||
>
|
||||
Preparar{' '}
|
||||
{stage
|
||||
? `relatório ${stage}`
|
||||
: 'relatório consolidado'}{' '}
|
||||
(Word)
|
||||
</button>
|
||||
<button
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={busy}
|
||||
onClick={() => exportReport('html')}
|
||||
>
|
||||
Preparar versão para impressão/PDF
|
||||
</button>
|
||||
</div>
|
||||
{busy && <p role="status">A preparar o ficheiro…</p>}
|
||||
{download && (
|
||||
<p role="status">
|
||||
Ficheiro pronto.{' '}
|
||||
<a
|
||||
className="font-medium underline"
|
||||
href={download.url}
|
||||
download={download.name}
|
||||
>
|
||||
Descarregar {download.name}
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
A versão HTML pode ser aberta e impressa ou guardada
|
||||
como PDF. As descargas são privadas; não enviam
|
||||
processos ou mensagens a entidades externas.
|
||||
</p>
|
||||
{!!entries.length && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<caption className="sr-only">
|
||||
Índice por etapa, versão e data
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2">Etapa</th>
|
||||
<th className="p-2">
|
||||
Relatório ou documento
|
||||
</th>
|
||||
<th className="p-2">Versão e data</th>
|
||||
<th className="p-2">Estado</th>
|
||||
<th className="p-2">Consultar</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((entry) => (
|
||||
<tr key={entry.id} className="border-t">
|
||||
<td className="p-2">
|
||||
{entry.stage}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{entry.title}
|
||||
</td>
|
||||
<td className="max-w-56 p-2 break-words">
|
||||
{entry.version} ·{' '}
|
||||
{entry.date ||
|
||||
'Data não registada'}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{entry.state}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<a
|
||||
className="underline"
|
||||
href={entry.href}
|
||||
>
|
||||
{entry.action}
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{!entries.length && (
|
||||
<p>
|
||||
Nenhum relatório ou documento produzido e autorizado
|
||||
neste âmbito. O relatório consolidado identifica as
|
||||
etapas e as pendências existentes.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Os relatórios financeiros são apresentados apenas ao
|
||||
titular autorizado do rascunho. Consulte os documentos
|
||||
de cada acto antes de executar o investimento.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="text-red-700">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function StageReportPreview({
|
||||
dossier,
|
||||
stage,
|
||||
}: {
|
||||
dossier: InvestorDossierReportInput;
|
||||
stage: string;
|
||||
}) {
|
||||
const report = createInvestorStageReport(dossier, stage);
|
||||
return (
|
||||
<article
|
||||
className="space-y-3 rounded border p-3"
|
||||
aria-label={`Relatório da etapa ${stage}`}
|
||||
>
|
||||
<h3 className="font-semibold">{report.title}</h3>
|
||||
<p className="text-sm">{report.version}</p>
|
||||
{report.sections.map((section) => (
|
||||
<section key={section.id} className="space-y-2">
|
||||
<h4 className="font-medium">{section.title}</h4>
|
||||
{section.paragraphs.map((text) => (
|
||||
<p key={text}>{text}</p>
|
||||
))}
|
||||
<dl className="space-y-2">
|
||||
{section.rows.map((row, index) => (
|
||||
<div key={index} className="break-words">
|
||||
<dt className="font-medium">{row.field}</dt>
|
||||
<dd>{row.value}</dd>
|
||||
<dd className="text-sm">
|
||||
{row.classification} · {row.origin}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
{report.limitations.map((text) => (
|
||||
<p className="text-sm" key={text}>
|
||||
{text}
|
||||
</p>
|
||||
))}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -259,7 +259,7 @@ export default function PortalHero({
|
||||
aria-describedby="portal-opportunity-search-help"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Ex.: agronegócio, Nampula, legislação..."
|
||||
placeholder="Corredores, produtos e locais, licenciamento…"
|
||||
className="h-12 w-full min-w-0 flex-1 rounded-xl border-0 bg-white px-4 text-base text-slate-900 outline-none placeholder:text-slate-500"
|
||||
/>
|
||||
<button
|
||||
@@ -274,8 +274,8 @@ export default function PortalHero({
|
||||
id="portal-opportunity-search-help"
|
||||
className="mt-2 text-left text-sm text-white/90"
|
||||
>
|
||||
Combine palavras-chave, sector e localização. Ex.:
|
||||
plantio de algodão ou agronegócio Nampula.
|
||||
Ex.: quantos corredores existem; grafite Cabo Delgado;
|
||||
como licenciar uma empresa.
|
||||
</p>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { AdvanceFiscalPeriod } from '@/lib/irpc-ppc-obligation';
|
||||
import {SimulationIrpcPecObligation} from './simulation-irpc-pec-obligation';
|
||||
import { SimulationIrpcPpcObligation } from './simulation-irpc-ppc-obligation';
|
||||
import { SimulationIrpcInvestment } from './simulation-irpc-investment';
|
||||
@@ -8,6 +9,12 @@ import { SimulationIrpcInternational } from './simulation-irpc-international';
|
||||
import { SimulationIrpcPec } from './simulation-irpc-pec';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
advancePeriodBasis,
|
||||
advanceCalendar,
|
||||
newAdvancePeriodDeclaration,
|
||||
advanceCashflowAmount,
|
||||
annualAdvanceCashflow,
|
||||
annualAdvancePeriod,
|
||||
annualBook,
|
||||
newAnnualBook,
|
||||
saveAnnualBook,
|
||||
@@ -77,6 +84,7 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
|
||||
);
|
||||
const patch = (p: Partial<AnnualBook>) => save({ ...b, ...p }),
|
||||
a = annualAssessment(draft),
|
||||
advancePeriod = annualAdvancePeriod(draft,b),
|
||||
options = annualWithholdingOptions(draft);
|
||||
const field = (
|
||||
key: 'subjectNuit' | 'year' | 'reference' | 'assessmentReference',
|
||||
@@ -341,10 +349,15 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
|
||||
})}
|
||||
</fieldset>
|
||||
<fieldset className="space-y-2 rounded border p-3">
|
||||
<legend>PPC efectivamente pagos</legend>
|
||||
<legend>Estimativas PPC e PEC para a viabilidade</legend>
|
||||
<p>Simulação fiscal para avaliar a viabilidade do negócio e as necessidades de tesouraria. Os valores e meses previstos são estimativas; o portal não executa pagamentos nem submete declarações fiscais.</p>
|
||||
<SimulationIrpcPecObligation book={b} onChange={pecObligation=>patch({pecObligation})}/>
|
||||
<SimulationIrpcPpcObligation book={b} onChange={ppcObligation=>patch({ppcObligation})}/>
|
||||
<SimulationIrpcAdvancePeriodDeclaration draft={draft} book={b} onChange={declaration=>patch({advancePeriodDeclaration:declaration})}/>
|
||||
<SimulationIrpcPecObligation book={b} period={advancePeriod} onChange={pecObligation=>patch({pecObligation})}/>
|
||||
<SimulationIrpcPpcObligation book={b} period={advancePeriod} onChange={ppcObligation=>patch({ppcObligation})}/>
|
||||
<SimulationIrpcAdvanceCashflow book={b} period={advancePeriod}/>
|
||||
</fieldset>
|
||||
<fieldset className="space-y-2 rounded border p-3">
|
||||
<legend>PPC documentados como pagos</legend>
|
||||
{group('ppc', 'PPC efectuados')}
|
||||
<p>
|
||||
Regista comprovativos de pagamentos por conta; não
|
||||
@@ -613,3 +626,34 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function SimulationIrpcAdvanceCashflow({book,period}: {book: AnnualBook;period?: AdvanceFiscalPeriod}) {
|
||||
if (!book.ppcObligation && !book.pecObligation) return null;
|
||||
const m = annualAdvanceCashflow(book,period);
|
||||
const show = advanceCashflowAmount;
|
||||
return <section className="space-y-3 rounded border p-3" aria-label="Projecção conjunta PPC e PEC">
|
||||
<h5 className="font-semibold">Saídas previstas PPC/PEC por mês</h5>
|
||||
{period && <p>Período preparado em L6: {period.from || 'por confirmar'} — {period.to || 'por confirmar'}.</p>}
|
||||
<p>Reúne as estimativas PPC e a hipótese de tesouraria PEC. Os comprovativos pagos e o fecho anual permanecem separados; esta vista não acrescenta outra saída ao fluxo financeiro do negócio.</p>
|
||||
<p role="status">{m.total ? 'Total da projecção: '+show(m.total) : 'Projecção parcial — total por determinar.'}</p>
|
||||
{!!m.pending.length && <ul className="list-disc pl-5">{m.pending.map(p=><li key={p}>{p}</li>)}</ul>}
|
||||
{!!m.rows.length && <div className="overflow-x-auto"><table className="w-full text-left text-sm">
|
||||
<caption className="sr-only">Projecção mensal das estimativas PPC e PEC</caption>
|
||||
<thead><tr><th className="p-2">Mês</th><th className="p-2">PPC</th><th className="p-2">PEC</th><th className="p-2">{m.total ? 'Total previsto' : 'Subtotal conhecido'}</th></tr></thead>
|
||||
<tbody>{m.rows.map(r=><tr key={r.month} className="border-t"><th scope="row" className="p-2">{r.month}</th><td className="p-2">{m.ppcKnown ? show(r.ppc) : 'Por determinar'}</td><td className="p-2">{m.pecKnown ? show(r.pec) : 'Por determinar'}</td><td className="p-2">{show(r.knownSubtotal)}</td></tr>)}</tbody>
|
||||
</table></div>}
|
||||
{!m.rows.length && m.total && <p>Sem saída PPC/PEC estimada neste recorte.</p>}
|
||||
<p>Meses e montantes dependem das fontes e opções preparadas acima. A opção PEC concentrada conserva o mês escolhido; esta apresentação não certifica o prazo legal.</p>
|
||||
</section>;
|
||||
}
|
||||
|
||||
|
||||
export function SimulationIrpcAdvancePeriodDeclaration({draft,book,onChange}:{draft:Record<string,unknown>;book:AnnualBook;onChange:(value:NonNullable<AnnualBook['advancePeriodDeclaration']>)=>void}){
|
||||
const period=annualAdvancePeriod(draft,book),calendar=advanceCalendar(period,book.year,book.subjectNuit),d=book.advancePeriodDeclaration;
|
||||
if(!d&&!calendar.candidate)return null;
|
||||
if(!d)return <section className="rounded border p-3"><h5>Período anual não civil</h5><p>Confronte o fundamento do período L6 e os doze meses do período anterior. As datas sugeridas não substituem o suporte documental.</p><button type="button" className="rounded border p-2" onClick={()=>onChange(newAdvancePeriodDeclaration(book.subjectNuit,book.year,period))}>Preparar correspondência dos períodos</button></section>;
|
||||
const patch=(values:Partial<typeof d>)=>onChange({...d,...values,confirmed:''});
|
||||
const labels={subjectNuit:'NUIT dos períodos',year:'Exercício de termo',currentFrom:'Início do período L6 declarado',currentTo:'Termo do período L6 declarado',currentReference:'Fundamento documentado do período anual não civil',previousFrom:'Início do período anterior',previousTo:'Termo do período anterior',previousReference:'Fonte e correspondência do período anterior'};
|
||||
return <section className="space-y-2 rounded border p-3" aria-label="Correspondência dos períodos anuais"><h5>Correspondência dos períodos anuais</h5><p role="status">{calendar.mode==='annual_non_civil'?'Correspondência documental conferida;previsões nos meses do período L6.':calendar.mode==='civil'?'L6 usa o ano civil;referência anterior conservada sem aplicação.':calendar.pending.join(' ')}</p><p>PPC: imposto anterior {book.ppcObligation?.previousTax||'por confirmar'} MZN;retenções {book.ppcObligation?.previousWithholdings||'por confirmar'} MZN. PEC: volume anterior {book.pecObligation?.previousTurnover||'por confirmar'} MZN;PPC anteriores {book.pecObligation?.previousPpcPaid||'por confirmar'} MZN.</p>{d.confirmed==='yes'&&(d.ppcBasisKey!==advancePeriodBasis(book,'ppc')||d.pecBasisKey!==advancePeriodBasis(book,'pec'))&&<button type="button" className="rounded border p-2" onClick={()=>onChange({...d,ppcBasisKey:advancePeriodBasis(book,'ppc'),pecBasisKey:advancePeriodBasis(book,'pec')})}>Reconferi os montantes e as fontes neste período</button>}<details open={d.confirmed!=='yes'||calendar.pending.length>0}><summary>Conferir ou alterar períodos</summary><label className="block">Aplicação<select aria-label="Aplicação do período não civil" value={d.mode} onChange={e=>patch({mode:e.target.value as typeof d.mode})}><option value="annual_non_civil">Período anual não civil</option><option value="">Conservar sem aplicação</option></select></label>{(Object.keys(labels) as Array<keyof typeof labels>).map(key=><label className="block" key={key}>{labels[key]}<input className="mt-1 block w-full rounded border px-3 py-2" aria-label={labels[key]} value={d[key]} onChange={e=>patch({[key]:e.target.value})}/></label>)}<p>No PPC, indique que o período anterior não é um ano civil completo. Os doze meses e a continuidade são conferidos pelas datas e fontes aqui indicadas.</p><label className="block"><input type="checkbox" checked={d.confirmed==='yes'} onChange={e=>onChange({...d,confirmed:e.target.checked?'yes':'',ppcBasisKey:advancePeriodBasis(book,'ppc'),pecBasisKey:advancePeriodBasis(book,'pec')})}/>Conferi no suporte os dois períodos, o fundamento do enquadramento e a correspondência dos montantes e fontes PPC/PEC</label></details><p>Guardar conserva estas escolhas. Uma alteração nas datas L6 exige reconferência; o portal não autoriza uma mudança do período fiscal.</p></section>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {SimulationIrpcPecCorrection} from './simulation-irpc-pec-correction';
|
||||
import {SimulationIrpcPecPlan} from './simulation-irpc-pec-plan';
|
||||
import type { AdvanceFiscalPeriod } from '@/lib/irpc-ppc-obligation';
|
||||
import { SimulationIrpcPecCorrection } from './simulation-irpc-pec-correction';
|
||||
import { SimulationIrpcPecPlan } from './simulation-irpc-pec-plan';
|
||||
import {
|
||||
newPecObligation,
|
||||
calculatePecObligation,
|
||||
@@ -9,9 +10,11 @@ import { fractionPresentation } from '@/lib/fiscal-rational';
|
||||
import type { AnnualBook } from '@/lib/irpc-annual-settlement';
|
||||
export function SimulationIrpcPecObligation({
|
||||
book,
|
||||
period,
|
||||
onChange,
|
||||
}: {
|
||||
book: AnnualBook;
|
||||
period?: AdvanceFiscalPeriod;
|
||||
onChange: (p: PecObligation) => void;
|
||||
}) {
|
||||
const p = book.pecObligation;
|
||||
@@ -38,16 +41,21 @@ export function SimulationIrpcPecObligation({
|
||||
book.subjectNuit,
|
||||
book.year,
|
||||
book.assessment,
|
||||
period,
|
||||
),
|
||||
patch = (changes: Partial<PecObligation>) =>
|
||||
onChange({ ...p, ...changes });
|
||||
const field = (
|
||||
key: Exclude<keyof PecObligation, 'version' | 'scope' | 'plan' | 'correction'>,
|
||||
key: Exclude<
|
||||
keyof PecObligation,
|
||||
'version' | 'scope' | 'plan' | 'correction' | 'lastAmount'
|
||||
>,
|
||||
label: string,
|
||||
) => (
|
||||
<label className="block">
|
||||
{label}
|
||||
<input
|
||||
className="mt-1 block w-full rounded border px-3 py-2"
|
||||
aria-label={label}
|
||||
value={p[key]}
|
||||
onChange={(e) => patch({ [key]: e.target.value })}
|
||||
@@ -63,6 +71,7 @@ export function SimulationIrpcPecObligation({
|
||||
<label className="block">
|
||||
Enquadramento PEC
|
||||
<select
|
||||
className="mt-1 block w-full rounded border px-3 py-2"
|
||||
aria-label="Enquadramento PEC"
|
||||
value={p.scope}
|
||||
onChange={(e) =>
|
||||
@@ -74,7 +83,7 @@ export function SimulationIrpcPecObligation({
|
||||
<option value="">Por confirmar</option>
|
||||
<option value="ordinary_resident">
|
||||
Residente geral — comercial,industrial ou agrícola,ano
|
||||
civil
|
||||
civil ou anual não civil documentado
|
||||
</option>
|
||||
<option value="other">
|
||||
Outro enquadramento — separado
|
||||
@@ -104,7 +113,131 @@ export function SimulationIrpcPecObligation({
|
||||
'turnoverReference',
|
||||
'Fonte do volume de negócios — PEC',
|
||||
)}
|
||||
<SimulationIrpcPecCorrection value={p.correction} original={p.previousTurnover} subjectNuit={p.subjectNuit} onChange={correction=>patch({correction})}/>
|
||||
<SimulationIrpcPecCorrection
|
||||
value={p.correction}
|
||||
original={p.previousTurnover}
|
||||
subjectNuit={p.subjectNuit}
|
||||
onChange={(correction) => patch({ correction })}
|
||||
/>
|
||||
{(m.requiresLastAmount || p.lastAmount) && (
|
||||
<details className="rounded border p-3">
|
||||
<summary>
|
||||
Sem volume anterior — referência PEC dos
|
||||
anos anteriores
|
||||
</summary>
|
||||
<p>
|
||||
Indique o último montante PEC já
|
||||
determinado, com suporte do mesmo
|
||||
titular, ano civil e MZN. Não introduza
|
||||
volume de negócios ou somatório de
|
||||
pagamentos. A hipótese conserva o valor
|
||||
documental sem nova percentagem ou
|
||||
segunda dedução de PPC.
|
||||
</p>
|
||||
{!p.lastAmount ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
patch({
|
||||
lastAmount: {
|
||||
version: 1,
|
||||
subjectNuit:
|
||||
p.subjectNuit,
|
||||
year: '',
|
||||
amount: '',
|
||||
reference: '',
|
||||
confirmed: '',
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
Acrescentar referência PEC anterior
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
{(
|
||||
[
|
||||
'subjectNuit',
|
||||
'year',
|
||||
'amount',
|
||||
'reference',
|
||||
] as const
|
||||
).map((key) => {
|
||||
const names = {
|
||||
subjectNuit:
|
||||
'NUIT do montante PEC anterior',
|
||||
year: 'Exercício do último montante PEC',
|
||||
amount: 'Último montante PEC já determinado — MZN',
|
||||
reference:
|
||||
'Fonte e fundamento do último montante PEC',
|
||||
};
|
||||
return (
|
||||
<label
|
||||
className="block"
|
||||
key={key}
|
||||
>
|
||||
{names[key]}
|
||||
<input
|
||||
className="mt-1 block w-full rounded border px-3 py-2"
|
||||
aria-label={
|
||||
names[key]
|
||||
}
|
||||
value={
|
||||
p.lastAmount![
|
||||
key
|
||||
]
|
||||
}
|
||||
onChange={(e) =>
|
||||
patch({
|
||||
lastAmount:
|
||||
{
|
||||
...p.lastAmount!,
|
||||
[key]: e
|
||||
.target
|
||||
.value,
|
||||
confirmed:
|
||||
'',
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={
|
||||
p.lastAmount
|
||||
.confirmed === 'yes'
|
||||
}
|
||||
onChange={(e) =>
|
||||
patch({
|
||||
lastAmount: {
|
||||
...p.lastAmount!,
|
||||
confirmed: e
|
||||
.target
|
||||
.checked
|
||||
? 'yes'
|
||||
: '',
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
Conferi no suporte que é o
|
||||
último montante PEC aplicável a
|
||||
esta hipótese
|
||||
</label>
|
||||
<p>
|
||||
Alterar a referência exige nova
|
||||
conferência. Guardar conserva o
|
||||
original e o histórico; não
|
||||
certifica a situação fiscal.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</details>
|
||||
)}
|
||||
{field(
|
||||
'previousPpcPaid',
|
||||
'PPC efectivamente pagos no ano anterior — MZN',
|
||||
@@ -124,18 +257,32 @@ export function SimulationIrpcPecObligation({
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
Total estimado:{' '}
|
||||
{fractionPresentation(m.total!).decimal} MZN.
|
||||
Total estimado: {fractionPresentation(m.total!).decimal}{' '}
|
||||
MZN.
|
||||
</p>
|
||||
<ul>
|
||||
{m.months.map((month) => (
|
||||
<li key={month}>{month}</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
</>
|
||||
)}
|
||||
<SimulationIrpcPecPlan plan={p.plan} total={m.total} notApplicable={m.notApplicable} year={book.year} onChange={plan=>patch({plan})}/>
|
||||
{m.ppcExcess && (
|
||||
<p role="status">
|
||||
Os PPC anteriores cobrem a base limitada desta hipótese.
|
||||
Estimativa PEC: 0 MZN;diferença documental:{' '}
|
||||
{fractionPresentation(m.ppcExcess).decimal} MZN. Esta
|
||||
diferença não cria reembolso,crédito ou dedução anual.
|
||||
</p>
|
||||
)}
|
||||
<SimulationIrpcPecPlan
|
||||
plan={p.plan}
|
||||
total={m.total}
|
||||
notApplicable={m.notApplicable}
|
||||
year={book.year}
|
||||
period={period}
|
||||
onChange={(plan) => patch({ plan })}
|
||||
/>
|
||||
<p>
|
||||
Guardar o rascunho conserva esta preparação. Calcular o fecho
|
||||
anual inclui-a no relatório. Não regista pagamentos,cria
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { AdvanceFiscalPeriod } from '@/lib/irpc-ppc-obligation';
|
||||
import {
|
||||
newPecPlan,
|
||||
calculatePecPlan,
|
||||
pecPlanSource,
|
||||
type PecPlan,
|
||||
} from '@/lib/irpc-pec-plan';
|
||||
import {
|
||||
@@ -13,12 +13,14 @@ export function SimulationIrpcPecPlan({
|
||||
total,
|
||||
notApplicable,
|
||||
year,
|
||||
period,
|
||||
onChange,
|
||||
}: {
|
||||
plan?: PecPlan;
|
||||
total: FiscalFraction | null;
|
||||
notApplicable: boolean;
|
||||
year: string;
|
||||
period?: AdvanceFiscalPeriod;
|
||||
onChange: (p: PecPlan) => void;
|
||||
}) {
|
||||
if (!plan)
|
||||
@@ -33,13 +35,13 @@ export function SimulationIrpcPecPlan({
|
||||
disabled={
|
||||
!total || notApplicable || BigInt(total.numerator) <= 0n
|
||||
}
|
||||
onClick={() => onChange(newPecPlan())}
|
||||
onClick={() => onChange(newPecPlan(period))}
|
||||
>
|
||||
Simular tesouraria PEC
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
const m = calculatePecPlan(plan, total, notApplicable, year),
|
||||
const m = calculatePecPlan(plan, total, notApplicable, year, period),
|
||||
patch = (p: Partial<PecPlan>) => onChange({ ...plan, ...p });
|
||||
const field = (
|
||||
key: 'reference' | 'june' | 'august' | 'october',
|
||||
@@ -77,6 +79,20 @@ export function SimulationIrpcPecPlan({
|
||||
. Prazo legal não validado.
|
||||
</p>
|
||||
)}
|
||||
{m.needsPeriodConfirmation && !m.calendarPending && (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
patch({
|
||||
periodFrom: m.contextFrom,
|
||||
periodTo: m.contextTo,
|
||||
})
|
||||
}
|
||||
>
|
||||
Conferi a distribuição para {m.contextFrom} — {m.contextTo}
|
||||
</button>
|
||||
)}
|
||||
<details open={m.pending.length > 0}>
|
||||
<summary>Alterar projecção PEC</summary>
|
||||
<label className="block">
|
||||
@@ -100,9 +116,30 @@ export function SimulationIrpcPecPlan({
|
||||
{field('reference', 'Fundamento do projecção PEC')}
|
||||
{plan.mode === 'three' && (
|
||||
<>
|
||||
{field('june', 'PEC Junho — MZN')}
|
||||
{field('august', 'PEC Agosto — MZN')}
|
||||
{field('october', 'PEC Outubro — MZN')}
|
||||
{field(
|
||||
'june',
|
||||
m.calendarPending
|
||||
? 'PEC primeiro montante — mês por confirmar'
|
||||
: m.nonCivil
|
||||
? 'PEC 6.º mês (' + m.months[0] + ') — MZN'
|
||||
: 'PEC Junho — MZN',
|
||||
)}
|
||||
{field(
|
||||
'august',
|
||||
m.calendarPending
|
||||
? 'PEC segundo montante — mês por confirmar'
|
||||
: m.nonCivil
|
||||
? 'PEC 8.º mês (' + m.months[1] + ') — MZN'
|
||||
: 'PEC Agosto — MZN',
|
||||
)}
|
||||
{field(
|
||||
'october',
|
||||
m.calendarPending
|
||||
? 'PEC terceiro montante — mês por confirmar'
|
||||
: m.nonCivil
|
||||
? 'PEC 10.º mês (' + m.months[2] + ') — MZN'
|
||||
: 'PEC Outubro — MZN',
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{plan.mode === 'single' && (
|
||||
@@ -128,7 +165,7 @@ export function SimulationIrpcPecPlan({
|
||||
</p>
|
||||
<details>
|
||||
<summary>Fonte do projecção PEC</summary>
|
||||
<p>{pecPlanSource}</p>
|
||||
<p>{m.source}</p>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { AdvanceFiscalPeriod } from '@/lib/irpc-ppc-obligation';
|
||||
import {
|
||||
newPpcObligation,
|
||||
calculatePpcObligation,
|
||||
@@ -8,9 +9,11 @@ import { fractionPresentation } from '@/lib/fiscal-rational';
|
||||
import type { AnnualBook } from '@/lib/irpc-annual-settlement';
|
||||
export function SimulationIrpcPpcObligation({
|
||||
book,
|
||||
period,
|
||||
onChange,
|
||||
}: {
|
||||
book: AnnualBook;
|
||||
period?: AdvanceFiscalPeriod;
|
||||
onChange: (value: PpcObligation) => void;
|
||||
}) {
|
||||
const p = book.ppcObligation;
|
||||
@@ -19,7 +22,7 @@ export function SimulationIrpcPpcObligation({
|
||||
<section className="rounded border p-3">
|
||||
<h5>Estimativa PPC</h5>
|
||||
<p>
|
||||
Preparar a obrigação e os meses previstos não regista
|
||||
Preparar a estimativa e os meses previstos não regista
|
||||
pagamentos nem cria deduções na liquidação.
|
||||
</p>
|
||||
<button
|
||||
@@ -37,6 +40,7 @@ export function SimulationIrpcPpcObligation({
|
||||
book.subjectNuit,
|
||||
book.year,
|
||||
book.assessment,
|
||||
period,
|
||||
);
|
||||
const patch = (changes: Partial<PpcObligation>) =>
|
||||
onChange({ ...p, ...changes });
|
||||
@@ -85,7 +89,7 @@ export function SimulationIrpcPpcObligation({
|
||||
<option value="">Por confirmar</option>
|
||||
<option value="ordinary_resident">
|
||||
Residente geral — actividade comercial, industrial ou
|
||||
agrícola, ano civil
|
||||
agrícola, período documentado
|
||||
</option>
|
||||
<option value="other">
|
||||
Outro enquadramento — cálculo separado
|
||||
|
||||
Reference in New Issue
Block a user