commit correcoes

This commit is contained in:
2026-11-21 20:58:19 +02:00
parent 4ca54e7655
commit 9d7a14459b
581 changed files with 151192 additions and 1620 deletions
+2
View File
@@ -7,6 +7,7 @@ import AppLayout from '@/layouts/app-layout';
import AuthLayout from '@/layouts/auth-layout';
import SettingsLayout from '@/layouts/settings/layout';
import PortalNavigation from '@/layouts/portal-navigation';
import FormFieldHelp from '@/components/form-field-help';
const appName = import.meta.env.VITE_APP_NAME || 'InvesteMoz';
const pages = import.meta.glob<{ default: ComponentType }>('./pages/**/*.tsx');
@@ -45,6 +46,7 @@ void createInertiaApp({
return (
<TooltipProvider delayDuration={0}>
{app}
<FormFieldHelp />
<Toaster />
</TooltipProvider>
);
+403
View File
@@ -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>
);
}
+3 -3
View File
@@ -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
+176
View File
@@ -0,0 +1,176 @@
import type { HelpField } from './form-help';
export type HelpControl =
| HTMLInputElement
| HTMLSelectElement
| HTMLTextAreaElement
| HTMLElement;
export const formHelpControlSelector =
'input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]),select,textarea,[role="combobox"],[role="spinbutton"],[role="checkbox"],[role="radio"]';
function textWithoutControls(node: Element): string {
const walker = node.ownerDocument.createTreeWalker(
node,
NodeFilter.SHOW_TEXT,
);
const parts: string[] = [];
let text: Node | null;
while ((text = walker.nextNode())) {
if (
!text.parentElement?.closest(
'input,select,textarea,button,svg,[data-form-field-help]',
)
)
parts.push(text.textContent ?? '');
}
return parts.join(' ').replace(/\s+/g, ' ').trim().slice(0, 220);
}
export function formHelpControlVisible(control: HTMLElement): boolean {
if (
!control.isConnected ||
control.closest(
'[data-form-field-help],header,nav,[hidden],[inert],[aria-hidden="true"],details:not([open])',
)
)
return false;
if (
control.matches(
':disabled,[disabled],[aria-disabled="true"],[readonly]',
)
)
return false;
const style = control.ownerDocument.defaultView?.getComputedStyle(control);
return (
style?.display !== 'none' &&
style?.visibility !== 'hidden' &&
control.getClientRects().length > 0
);
}
export function formHelpControls(document: Document): HTMLElement[] {
const roots = document.querySelectorAll(
'main,[role="main"],[role="dialog"],dialog[open]',
);
return [
...new Set(
Array.from(roots).flatMap((root) =>
Array.from(
root.querySelectorAll<HTMLElement>(formHelpControlSelector),
),
),
),
].filter(formHelpControlVisible);
}
export function formHelpGroupControls(
document: Document,
control: HTMLElement | null,
): HTMLElement[] {
const scope = control?.closest(
'form,fieldset,[data-form-help-context],[role="dialog"],dialog[open]',
);
const controls = formHelpControls(document);
return scope ? controls.filter((node) => scope.contains(node)) : controls;
}
export function formHelpField(control: HTMLElement): HelpField {
const document = control.ownerDocument;
const labelledBy = (control.getAttribute('aria-labelledby') ?? '')
.split(/\s+/)
.filter(Boolean)
.map((id) => document.getElementById(id))
.filter((node): node is HTMLElement => Boolean(node));
const labels =
'labels' in control
? Array.from((control as HTMLInputElement).labels ?? [])
: Array.from(document.querySelectorAll('label')).filter(
(label) =>
Boolean(control.id) && label.htmlFor === control.id,
);
const label =
control.getAttribute('aria-label')?.trim() ||
labelledBy.map(textWithoutControls).join(' ') ||
labels.map(textWithoutControls).join(' ') ||
textWithoutControls(
control.closest('label') ?? document.createElement('span'),
) ||
control.getAttribute('placeholder') ||
(control.getAttribute('name') ?? '')
.replace(/[[\]_.-]+/g, ' ')
.trim() ||
'Campo deste formulário';
const role = control.getAttribute('role');
const type =
role && ['combobox', 'checkbox', 'radio', 'spinbutton'].includes(role)
? role === 'spinbutton'
? 'number'
: role
: control.tagName === 'SELECT'
? 'select'
: control.tagName === 'TEXTAREA'
? 'textarea'
: (control.getAttribute('type') ?? 'text');
const hint = (control.getAttribute('aria-describedby') ?? '')
.split(/\s+/)
.filter(Boolean)
.map((id) => document.getElementById(id))
.filter((node): node is HTMLElement => Boolean(node))
.map(textWithoutControls)
.join(' ')
.slice(0, 450);
return {
label,
type,
required:
control.hasAttribute('required') ||
control.getAttribute('aria-required') === 'true',
hint,
context: control.closest<HTMLElement>('[data-form-help-context]')
?.dataset.formHelpContext,
};
}
export function formHelpStep(control: HTMLElement): {
title: string;
code: string;
context: string;
} {
const explicit = control.closest<HTMLElement>('[data-form-help-context]');
if (explicit)
return {
title: explicit.dataset.formHelpTitle ?? 'Preencher este passo',
code: explicit.dataset.formHelpStep ?? '',
context: explicit.dataset.formHelpContext ?? '',
};
const investment = control.closest<HTMLElement>('[data-investment-step]');
if (investment)
return {
title: (
investment.querySelector(
':scope > summary,:scope > h2,:scope > h3',
)?.textContent ?? 'Preencher esta etapa'
)
.replace(/\s+/g, ' ')
.trim(),
code: investment.dataset.investmentStep ?? '',
context: 'investor-path',
};
const scope = control.closest(
'fieldset,section,form,[role="dialog"],dialog[open]',
);
const titleId = scope?.getAttribute('aria-labelledby');
const title =
(titleId
? control.ownerDocument.getElementById(titleId)?.textContent
: undefined) ||
scope?.getAttribute('aria-label') ||
scope?.querySelector('legend,h2,h3,h4')?.textContent ||
control.ownerDocument.querySelector('main h1')?.textContent ||
'Preencher o formulário';
return {
title: title.replace(/\s+/g, ' ').trim().slice(0, 180),
code: '',
context: '',
};
}
+234
View File
@@ -0,0 +1,234 @@
export type HelpField = {
label: string;
type: string;
required: boolean;
hint?: string;
context?: string;
};
export function normaliseHelpLabel(value: string): string {
return value
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase();
}
export function formFieldGuidance(field: HelpField): {
instruction: string;
example?: string;
} {
const label = normaliseHelpLabel(field.label);
if (field.type === 'password')
return {
instruction:
'Introduza a palavra-passe desta conta. Use o controlo de mostrar palavra-passe apenas se precisar de conferir o que escreveu.',
};
if (field.type === 'file')
return {
instruction:
'Escolha o ficheiro pedido neste campo. Confira o documento e os formatos indicados no formulário antes de o anexar.',
};
if (field.type === 'checkbox' || field.type === 'radio')
return {
instruction:
'Leia a declaração ou opção apresentada. Seleccione-a apenas se corresponder à sua situação ou à autorização que pretende dar.',
};
if (/nuit/.test(label))
return {
instruction:
'Transcreva o NUIT da pessoa ou entidade a que este formulário se refere. Confira-o no documento correspondente.',
};
if (
/email|e-mail|correio electronico/.test(label) ||
field.type === 'email'
)
return {
instruction:
'Indique um endereço de correio electrónico ao qual tenha acesso.',
example: 'nome@exemplo.co.mz',
};
if (
/telefone|telemovel|contacto telefonico/.test(label) ||
field.type === 'tel'
)
return {
instruction:
'Indique o número de contacto e confira o indicativo do país quando o formulário o pedir.',
};
if (/moeda|currency/.test(label))
return {
instruction:
'Escolha a moeda em que os montantes deste formulário estão expressos. Confira a coerência com os documentos e com os restantes valores.',
};
if (/residencia fiscal|regime fiscal|tipo de contribuinte/.test(label))
return {
instruction:
'Escolha o enquadramento que corresponde à pessoa ou entidade em análise. Consulte as indicações e fontes apresentadas no formulário se precisar de esclarecer a opção.',
};
if (/volume de negocios|volume de negocio|facturacao/.test(label))
return {
instruction:
'Indique o volume de negócios relativo ao período pedido, na moeda apresentada. Confira o período e a fonte do montante.',
};
if (/imposto.*liquidado|colecta/.test(label))
return {
instruction:
'Indique o montante identificado neste campo, a partir do apuramento ou documento correspondente. Confira o exercício e a referência apresentados.',
};
if (
/retenc|montante.*pago|pagamento.*efectuado|pec.*pago|ppc.*pago/.test(
label,
)
)
return {
instruction:
'Introduza apenas o montante documentado a que este campo se refere e confira o período. Distinga os valores já registados das estimativas ou hipóteses de tesouraria.',
};
if (/taxa|percentagem|percentual/.test(label))
return {
instruction:
'Confira a unidade e o enquadramento indicados neste campo. Se for editável, introduza a percentagem correspondente ao pressuposto ou documento pedido; use os parâmetros apresentados pelo simulador quando forem fornecidos.',
};
if (/receita|vendas|rendimento/.test(label))
return {
instruction:
'Indique o valor relativo ao período e à unidade pedidos. Quando se tratar de uma previsão, use o seu pressuposto de receitas e conserve a respectiva referência.',
};
if (/custo|despesa|encargo/.test(label))
return {
instruction:
'Indique o custo ou despesa relativo ao período pedido. Confira se o campo pede valor unitário, mensal, anual ou total.',
example:
'Se o campo pedir um custo mensal, introduza o valor de um mês.',
};
if (
/investimento|capital|financiamento|orcamento|montante|valor/.test(
label,
) &&
field.type !== 'textarea'
)
return {
instruction:
'Indique o montante pedido, na moeda e unidade apresentadas. Distinga recursos disponíveis, necessidades de financiamento e valores previstos.',
};
if (
/provincia|distrito|localidade|localizacao|territorio|posto administrativo/.test(
label,
)
)
return {
instruction:
'Escolha a localização correspondente ao investimento ou registo. Se existirem selecções dependentes, comece pela área mais abrangente e complete as opções seguintes.',
};
if (
/exercicio|ano fiscal|periodo.*fiscal|inicio.*periodo|fim.*periodo/.test(
label,
)
)
return {
instruction:
'Indique a data ou o período a que a informação se refere. Confira a correspondência com os documentos e com os restantes campos deste exercício.',
};
if (['date', 'month', 'time', 'datetime-local'].includes(field.type))
return {
instruction:
'Indique a data, o mês ou a hora pedidos neste campo, respeitando o formato apresentado. Confira a correspondência com o acontecimento ou prazo a que se refere.',
};
if (/referencia|fonte|fundamento/.test(label))
return {
instruction:
'Identifique o documento, a origem da informação ou o motivo pedido. Use uma referência que permita recuperar e conferir o que declarou.',
};
if (/titulo|designacao|nome do projecto|nome do investimento/.test(label))
return {
instruction:
'Escreva uma designação clara que permita reconhecer este investimento ou registo.',
example: 'Unidade de transformação de produtos agrícolas',
};
if (field.type === 'select' || field.type === 'combobox')
return {
instruction:
'Escolha a opção que corresponde à sua situação. As opções disponíveis e as instruções do formulário orientam esta escolha.',
};
if (field.type === 'number' || field.type === 'range')
return {
instruction:
'Introduza a quantidade ou o valor pedido e confira a unidade apresentada junto do campo. Respeite os limites indicados no formulário.',
};
if (field.type === 'url')
return {
instruction:
'Introduza a ligação completa para a página ou documento pedido.',
example: 'https://exemplo.co.mz/documento',
};
if (field.type === 'textarea')
return {
instruction:
'Explique a informação pedida neste campo de forma clara e concreta. Inclua os elementos necessários para compreender a sua declaração.',
};
return {
instruction: `Preencha «${field.label}» com a informação correspondente à pessoa, entidade ou investimento deste formulário. Confira as indicações junto do campo.`,
};
}
const simulationSteps: Record<string, string> = {
purpose:
'Indique o que pretende preparar, o nível de detalhe e o percurso adequado à sua situação. As respostas adaptam os passos seguintes.',
promoter:
'Identifique a situação do promotor e complete apenas os elementos pedidos para o perfil escolhido.',
identity:
'Confira a identificação e os contactos da pessoa ou entidade a que esta preparação se refere.',
project:
'Descreva o negócio, a actividade e os objectivos. Reutilize os dados já disponíveis e complete a informação em falta.',
market: 'Descreva os clientes, o mercado e os pressupostos de vendas. Indique as fontes disponíveis para sustentar as suas estimativas.',
location:
'Indique a localização e os recursos relevantes para o investimento. Complete as escolhas territoriais apresentadas.',
team: 'Descreva a equipa e a forma prevista de executar o investimento, incluindo as responsabilidades e recursos pedidos.',
investment:
'Organize o investimento inicial e confira a moeda, a unidade e os montantes previstos.',
financial:
'Complete os montantes e os pressupostos de investimento e financiamento pedidos. Confira a moeda e o período de cada valor.',
operating:
'Preencha as estimativas de receitas e custos, respeitando a unidade e o período de cada campo.',
cashflow:
'Distribua os pressupostos de tesouraria pelos períodos pedidos e compare os cenários apresentados.',
tax: 'Seleccione a operação e o enquadramento fiscal. Confira o contribuinte, o período, a moeda, os valores e as referências pedidos antes de calcular.',
impact: 'Indique os postos de trabalho e os impactos previstos, distinguindo estimativas de informação já documentada.',
opportunity:
'Explique a necessidade de negócio e os elementos pedidos para preparar a oportunidade.',
documents:
'Confira os documentos pedidos, associe os disponíveis e identifique a informação que ainda falta.',
scenarios:
'Compare os cenários com base nos pressupostos preenchidos. Reveja as entradas antes de interpretar diferenças nos resultados.',
procedures:
'Consulte os procedimentos e os documentos apresentados para o seu contexto e identifique o que precisa de preparar.',
review: 'Reveja as entradas, os resultados e as pendências. Se alterar pressupostos, recalcule quando o formulário o indicar; use a acção de guardar apenas quando pretender conservar as alterações.',
};
export function simulationStepGuidance(step: string): string {
return (
simulationSteps[step] ??
'Confira os dados pedidos neste passo, complete o que souber e consulte a ajuda de cada campo quando precisar.'
);
}
export function readFormHelpAutomatic(value: string | null): boolean {
return value !== 'off';
}
export function formHelpPlacement(
rect: { left: number; top: number; bottom: number },
width: number,
height: number,
) {
const above = Math.max(0, rect.top - 84);
const below = Math.max(0, height - rect.bottom - 16);
return {
side: rect.left > width / 2 ? ('left' as const) : ('right' as const),
vertical: above > below ? ('top' as const) : ('bottom' as const),
maxHeight: Math.max(
96,
Math.min(height * 0.45, Math.max(above, below) - 64),
),
};
}
+168
View File
@@ -0,0 +1,168 @@
export type InvestmentHelp = {
code: string;
title: string;
instruction: string;
example: string;
purpose: string;
};
// Orientation only: the existing path continues to determine applicability and permissions.
const stageHelp: Record<string, [string, string, string]> = {
S01: [
'Descreva a ideia, o produto ou serviço e os clientes que pretende servir.',
'Produzir hortícolas para fornecer mercados locais.',
'Definir o investimento que irá preparar nas etapas seguintes.',
],
S02: [
'Reúna informação sobre o mercado, os recursos necessários e os principais riscos. Consulte as ferramentas disponíveis no dossier.',
'Compare procura, fornecedores, localização e custos previstos.',
'Identificar o que já sabe e a informação que ainda precisa de obter.',
],
S03: [
'Compare as receitas e os custos estimados e registe a sua conclusão sobre a viabilidade.',
'Teste como uma redução das vendas afecta o resultado estimado.',
'Apoiar a sua decisão com pressupostos explícitos. Uma simulação é uma estimativa.',
],
S04: [
'Organize os recursos, os participantes e o plano de realização do investimento.',
'Indique quem fará o quê e quais os recursos a mobilizar.',
'Transformar a ideia num plano de preparação e execução.',
],
S05: [
'Confira a situação da entidade e os elementos de constituição e registo aplicáveis. Reutilize os dados já disponíveis.',
'Se a empresa já existe, confira os seus dados antes de os voltar a preencher.',
'Preparar a identificação da entidade que realizará o investimento.',
],
S06: [
'Reúna os dados e associe os documentos indicados para este investimento. Reveja o que ainda falta.',
'Associe um documento já disponível no dossier ao requisito correspondente.',
'Organizar o dossier antes de preparar uma entrega.',
],
S07: [
'Confira o destinatário e os requisitos da entrega aplicável. Se já entregou, registe a referência e a evidência disponível.',
'Registe a data e o protocolo de uma entrega efectivamente realizada.',
'Acompanhar a entrega sem confundir preparação com submissão.',
],
S08: [
'Consulte as licenças indicadas para a actividade e localização. Prepare os elementos em falta e registe os actos já documentados.',
'Identifique a entidade competente e associe a licença recebida, quando disponível.',
'Acompanhar o licenciamento aplicável ao seu projecto.',
],
S09: [
'Indique se o investimento necessita de terra e explique a situação conhecida.',
'Indique se utilizará instalações existentes ou se precisa de uma nova área.',
'Adaptar a preparação da terra às necessidades do investimento.',
],
S10: [
'Reúna a informação da localização e os documentos relativos à regularização da terra indicados no percurso.',
'Associe o documento disponível e identifique a área a que se refere.',
'Organizar a preparação da terra sem presumir direitos ainda não documentados.',
],
S11: [
'Confira a regularização aplicável e registe o resultado com o respectivo fundamento.',
'Registe a referência e a data do documento que comprova a situação declarada.',
'Distinguir a preparação da confirmação documental da regularização.',
],
S12: [
'Compare os recursos próprios com o investimento previsto e indique se necessita de financiamento externo.',
'Separe o capital disponível do montante que ainda precisa de mobilizar.',
'Dimensionar a necessidade de financiamento do projecto.',
],
S13: [
'Prepare a informação pedida pelo potencial financiador e registe os pontos de negociação.',
'Organize projecções, documentos solicitados e condições em discussão.',
'Acompanhar a análise e a negociação do financiamento.',
],
S14: [
'Registe a decisão recebida do financiador e associe a evidência disponível.',
'Indique a referência da comunicação recebida e as condições nela apresentadas.',
'Conservar a decisão real, sem tratar uma candidatura como aprovação.',
],
S15: [
'Confira as condições de fecho e acompanhe os desembolsos efectivamente documentados.',
'Registe a referência e a data de uma disponibilização de fundos confirmada.',
'Acompanhar a concretização do financiamento e as condições pendentes.',
],
S16: [
'Organize as actividades de implementação e acompanhe os recursos e os prazos.',
'Crie uma tarefa para instalar equipamento com responsável e data prevista.',
'Acompanhar a execução do investimento.',
],
S17: [
'Prepare as inspecções e os testes aplicáveis e reúna os documentos para a operação.',
'Associe um relatório de inspecção ou a licença recebida à etapa correspondente.',
'Identificar o que falta antes do início de operação.',
],
S18: [
'Confira as condições indicadas no percurso e registe o início de operação quando estiver documentado.',
'Indique a data efectiva de início e a respectiva referência documental.',
'Distinguir a previsão de arranque do início efectivo da actividade.',
],
S19: [
'Actualize o acompanhamento do projecto e reveja as tarefas e os documentos que necessitam de atenção.',
'Registe uma tarefa de acompanhamento com responsável e prazo.',
'Manter o dossier útil ao longo da operação.',
],
};
export function investmentStageHelp(
code: string,
title: string,
): InvestmentHelp {
const [instruction, example, purpose] = stageHelp[code] ?? [
'Consulte as indicações desta etapa, confira os dados disponíveis e complete o que estiver em falta.',
'Registe uma referência documental que sustente a informação preenchida.',
'Acompanhar a preparação desta etapa no seu dossier.',
];
return { code, title, instruction, example, purpose };
}
export const preparationHelp: InvestmentHelp[] = [
{
code: 'help-choices',
title: 'Escolhas e dados do investimento',
instruction:
'Escolha a oportunidade, o sector e a localização que correspondem ao seu investimento. Confira os dados já recuperados.',
example:
'Seleccione uma oportunidade existente ou indique o sector e a localização da sua ideia.',
purpose: 'Adaptar o percurso ao investimento que pretende realizar.',
},
{
code: 'help-declarations',
title: 'Declarações deste investimento',
instruction:
'Complete apenas as declarações conhecidas e confira os documentos associados. Use as opções apresentadas conforme a sua situação.',
example:
'Indique a moeda do projecto e confira a situação da entidade.',
purpose:
'Preparar os dados do processo e identificar o que ainda precisa de esclarecimento.',
},
{
code: 'help-review',
title: 'Revisão e confirmação',
instruction:
'Clique em “Rever dados antes de guardar”. Compare as alterações apresentadas e confirme apenas quando corresponderem ao que pretende.',
example:
'Ao mudar a localização, confira os dados alterados e as etapas que precisam de revisão.',
purpose: 'Permitir que avalie o impacto antes de guardar as escolhas.',
},
];
export function helpPreferenceKey(user: string | number, flow: string): string {
return `investemoz:step-help:v1:${encodeURIComponent(String(user))}:${encodeURIComponent(flow)}`;
}
export function readHelpPreference(value: string | null): {
automatic: boolean;
seen: boolean;
} {
try {
const parsed = JSON.parse(value ?? 'null');
return {
automatic: parsed?.automatic !== false,
seen: parsed?.seen === true,
};
} catch {
return { automatic: true, seen: false };
}
}
+614
View File
@@ -0,0 +1,614 @@
import { pathStates, type PathResult } from './investor-path.ts';
import { restoreFinancialToolsSnapshot } from './financial-calculators.ts';
import { buildProjectDossierRows } from './project-dossier.ts';
import type { SwotDraft } from './investment-preparation.ts';
import type {
DossierReportModel,
DossierReportRow,
} from './project-dossier-report.ts';
export type PreparationReport = {
case_id: string;
opportunity: string | null;
version: number;
context_revision: number;
href: string;
api_state: string;
api_issues: string[];
exports: {
id: string;
at: string;
context_revision: number;
fingerprint: string;
historical: boolean;
href: string;
}[];
external: {
kind: string;
date: string;
reference: string;
export_id: string;
outcome?: string;
}[];
swot: SwotDraft;
swot_review_required: boolean;
};
export type InvestorDossierReportInput = {
case: { id: string; title: string; version: number };
context_opportunity: string | null;
opportunity_options: unknown[];
investment_context: {
revision: number;
fields?: Record<string, string>;
} | null;
phases: Record<string, string>;
steps: {
code: string;
title: string;
phase: number;
version?: number;
state: string;
reason: string;
detail: {
scope?: string;
document_id?: string;
authority?: string;
reference?: string;
decision_date?: string;
recorded_at?: string;
};
}[];
results: PathResult[];
documents: {
id: string;
document_id?: string;
file_name: string;
status: string;
malware_scan_status: string;
version_no: number;
sha256: string;
}[];
preparation_report?: PreparationReport | null;
fiscal_reports?: {
simulation_id: string;
report_id: string;
report_version_no?: number;
report_sha256?: string;
consented_at?: string;
scope_state?: 'identified' | 'common' | 'unconfirmed';
}[];
land_report?: {
id: string;
version: number;
updated_at: string | null;
href: string;
} | null;
company_reports?: {
comparison?: { revision: number; at: string };
preparation?: { revision: number; at: string };
guides?: Record<
string,
{ revision: number; at: string; slug: string; title: string }
>;
};
};
export type DossierReportIndexEntry = {
id: string;
stage: string;
title: string;
version: string;
date: string;
state: string;
href: string;
action: string;
};
const externalStates: Record<string, string> = {
preparing: 'Em preparação',
ready: 'Pronto para entrega',
delivery_recorded: 'Entrega externa registada',
decision_received: 'Decisão recebida',
};
const externalRecords: Record<string, string> = {
delivery: 'Entrega externa',
clarification: 'Pedido de esclarecimento',
response: 'Resposta recebida',
decision: 'Decisão recebida',
};
const decisions: Record<string, string> = {
approved: 'Favorável',
refused: 'Desfavorável',
conditional: 'Condicionada',
other: 'Outra decisão',
};
const dimensions = {
strength: 'Forças',
weakness: 'Fraquezas',
opportunity: 'Oportunidades',
threat: 'Ameaças',
};
const classifications = {
documented_fact: 'Facto documentado',
hypothesis: 'Hipótese',
unconfirmed: 'Por confirmar',
};
function checkScope(input: InvestorDossierReportInput): void {
if (input.opportunity_options.length > 1 && !input.context_opportunity)
throw new Error(
'Seleccione a oportunidade antes de reunir os relatórios.',
);
const preparation = input.preparation_report;
if (
preparation &&
(preparation.case_id !== input.case.id ||
preparation.opportunity !== input.context_opportunity)
)
throw new Error(
'A preparação pertence a outro dossier ou oportunidade.',
);
}
function documentsInDossier(input: InvestorDossierReportInput) {
const seen = new Set<string>();
return input.documents.filter((document) => {
const key = `${document.document_id ?? document.id}:${document.version_no}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
export function investorDossierReportIndex(
input: InvestorDossierReportInput,
): DossierReportIndexEntry[] {
checkScope(input);
const base = `/investimentos/${encodeURIComponent(input.case.id)}`;
const query = input.context_opportunity
? `?opportunity=${encodeURIComponent(input.context_opportunity)}`
: '';
const entries: DossierReportIndexEntry[] = [];
const seen = new Set<string>();
const add = (entry: DossierReportIndexEntry) => {
if (!seen.has(entry.id)) {
seen.add(entry.id);
entries.push(entry);
}
};
for (const result of input.results) {
if ((result.context_opportunity ?? null) !== input.context_opportunity)
continue;
add({
id: `finance:${result.id}`,
stage: 'S03',
title: 'Resultado de viabilidade financeira',
version: String(result.draft_version),
date: result.recorded_at,
state:
result.context_state === 'review_required' ||
result.context_revision !== input.investment_context?.revision
? 'Histórico — requer revisão'
: 'Resultado guardado',
href: `${base}${query}#resultados-financeiros`,
action: 'Consultar resultado',
});
}
for (const source of input.fiscal_reports ?? [])
add({
id: `fiscal:${source.report_id}`,
stage: 'S03',
title: 'Relatório de simulação fiscal',
version: String(source.report_version_no ?? 'Por identificar'),
date: source.consented_at ?? '',
state:
source.scope_state === 'identified'
? 'Versão preservada — estimativa fiscal'
: source.scope_state === 'common'
? 'Versão preservada — contexto comum do dossier'
: 'Versão preservada — âmbito por confirmar',
href: `${base}/relatorios/fiscais/${encodeURIComponent(source.report_id)}${query}`,
action: 'Descarregar versão preservada (JSON)',
});
for (const kind of ['comparison', 'preparation'] as const) {
const saved = input.company_reports?.[kind];
if (saved)
add({
id: `company:${kind}`,
stage: 'S05',
title:
kind === 'comparison'
? 'Comparação de formas jurídicas'
: 'Preparação da empresa',
version: String(saved.revision),
date: saved.at,
state: 'Preparação guardada',
href: `${base}/${kind === 'comparison' ? 'forma-juridica' : 'preparar-empresa'}`,
action: 'Consultar preparação',
});
}
const preparation = input.preparation_report;
if (input.land_report) {
add({
id: `land:${input.land_report.id}`,
stage: 'S10',
title: 'Preparação de acesso à terra',
version: String(input.land_report.version),
date: input.land_report.updated_at ?? '',
state: 'Preparação guardada — não é título DUAT',
href: input.land_report.href,
action: 'Abrir versão para impressão',
});
}
for (const exported of preparation?.exports ?? [])
add({
id: `apiex:${exported.id}`,
stage: 'S06',
title: 'Dossier documental APIEX',
version: exported.id,
date: exported.at,
state: exported.historical
? 'Exportação histórica preservada'
: 'Exportação preparada',
href: exported.href,
action: 'Descarregar pacote',
});
if (preparation?.swot.rows.length)
add({
id: 'swot',
stage: 'S02',
title: 'Análise SWOT',
version: String(preparation.version),
date: preparation.swot.review?.at ?? '',
state: preparation.swot_review_required
? 'Revisão necessária'
: 'Revista pela equipa',
href: preparation.href,
action: 'Consultar análise',
});
for (const guide of Object.values(input.company_reports?.guides ?? {}))
add({
id: `guide:${guide.slug}`,
stage: 'S06',
title: guide.title,
version: String(guide.revision),
date: guide.at,
state: 'Referência guardada para o dossier',
href: `${base}/guias/${encodeURIComponent(guide.slug)}`,
action: 'Consultar guia',
});
for (const document of documentsInDossier(input)) {
const stages = input.steps.filter(
(step) => step.detail.document_id === document.document_id,
);
add({
id: `document:${document.id}`,
stage:
stages.map((step) => step.code).join(', ') || 'Anexos comuns',
title: document.file_name,
version: String(document.version_no),
date: '',
state:
document.malware_scan_status === 'clean' &&
document.status === 'active'
? 'Documento associado'
: 'Disponibilidade por conferir',
href: `/balcao-virtual/dossiers/${encodeURIComponent(input.case.id)}/documentos/${encodeURIComponent(document.id)}`,
action: 'Consultar documento',
});
}
for (const step of input.steps) {
if (
entries.some((entry) => entry.stage.split(', ').includes(step.code))
)
continue;
add({
id: `stage:${step.code}`,
stage: step.code,
title: step.title,
version: String(step.version ?? 'Não registada'),
date: step.detail.recorded_at ?? '',
state:
step.state === 'dispensed'
? 'Preparação dispensada — consultar fundamento'
: 'Sem relatório ou documento associado',
href: `${base}${query}#${step.code}`,
action: 'Consultar etapa',
});
}
return entries.sort((a, b) => a.stage.localeCompare(b.stage));
}
export function createInvestorDossierReport(
input: InvestorDossierReportInput,
generatedAt = new Date().toISOString(),
): DossierReportModel {
const index = investorDossierReportIndex(input);
const row = (
field: string,
value: string,
origin = 'Registo guardado neste dossier',
classification = 'Preparação do investimento',
): DossierReportRow => ({ field, value, origin, classification });
const finance: DossierReportRow[] = [];
for (const result of input.results.filter(
(item) =>
(item.context_opportunity ?? null) === input.context_opportunity,
)) {
const reference = `Resultado ${result.id}; rascunho ${result.draft_id}, versão ${result.draft_version}; ${result.recorded_at}`;
const state =
result.context_revision === input.investment_context?.revision &&
result.context_state !== 'review_required'
? 'Estimativa guardada'
: 'Histórico — rever antes de utilizar';
try {
if (
result.engine !== 'financial-calculators:v1' ||
!restoreFinancialToolsSnapshot(result.financial_snapshot)
)
throw new Error('Versão não recuperável');
const currency = result.currency ?? '';
const baseline = new Set(
buildProjectDossierRows({ currency }).map((item) =>
JSON.stringify(item),
),
);
const sections = new Set([
'Plano financeiro',
'Empréstimo educativo',
'Ponto de equilíbrio',
'Financiamento',
'Orçamento',
]);
const rows = buildProjectDossierRows({
currency,
financial_tools_snapshot: result.financial_snapshot,
});
for (const item of rows.filter(
(item) =>
sections.has(item[0]) &&
!baseline.has(JSON.stringify(item)),
)) {
finance.push(
row(
`${item[0]} — ${item[1]}`,
item[2],
`${reference}; ${item[3]}`,
state,
),
);
}
} catch {
finance.push(
row(
'Resultado preservado',
'Formato indisponível para cálculo; consulte a origem, sem substituir valores por zero.',
reference,
state,
),
);
}
}
const preparation = input.preparation_report;
const swot = preparation?.swot;
return {
title: input.case.title,
generatedAt,
version: `Dossier ${input.case.id} · v${input.case.version} · contexto v${input.investment_context?.revision ?? 'não identificado'} · oportunidade ${input.context_opportunity ?? 'contexto comum'}`,
references: [],
limitations: [
'Relatório privado de preparação; não comprova licenciamento, aprovação ou financiamento.',
'Os actos externos só valem pelo respectivo documento e entidade. Pendências e versões históricas permanecem identificadas.',
'O índice referencia os originais; não incorpora automaticamente os seus anexos nem envia dados a entidades externas.',
],
sections: [
{
id: 'project',
title: 'Investimento e localização em preparação',
private: true,
paragraphs: [
'Dados guardados no contexto seleccionado; não representam aprovação ou validação externa.',
],
rows: Object.entries({
project_title: 'Projecto',
project_summary: 'Descrição',
sector: 'Sector',
province: 'Província',
district: 'Distrito',
location: 'Localização',
total_investment: 'Investimento previsto',
currency: 'Moeda',
expected_start_date: 'Início previsto',
})
.filter(([key]) =>
input.investment_context?.fields?.[key]?.trim(),
)
.map(([key, label]) =>
row(
label,
input.investment_context?.fields?.[key] ?? '',
`Contexto v${input.investment_context?.revision ?? 'não identificado'}`,
),
),
},
{
id: 'summary',
title: 'Identificação e índice dos relatórios',
private: true,
paragraphs: [
`Dossier: ${input.case.id}`,
`Oportunidade: ${input.context_opportunity ?? 'Contexto comum do dossier'}`,
`Gerado em ${generatedAt}; versão do dossier ${input.case.version}.`,
],
rows: index.map((entry) =>
row(
`${entry.stage} — ${entry.title}`,
`${entry.state}; versão ${entry.version}; ${entry.date || 'data não registada'}`,
entry.href,
entry.action,
),
),
},
{
id: 'execution',
title: 'Etapas, resultados e pendências',
private: true,
paragraphs: [
'A situação de uma etapa não significa que o respectivo relatório ou acto externo tenha sido produzido.',
],
rows: input.steps.map((step) =>
row(
`${step.code} — ${step.title}`,
`${pathStates[step.state] ?? step.state}; versão ${step.version ?? 'não registada'}. ${step.reason || 'Sem fundamento adicional registado.'} ${step.detail.authority ?? ''} ${step.detail.reference ?? ''} ${step.detail.decision_date ?? ''}`,
`Fase ${step.phase}: ${input.phases[String(step.phase)] ?? ''}`,
step.state === 'not_started'
? 'Pendente'
: 'Estado guardado da etapa',
),
),
},
{
id: 'finance',
title: 'Viabilidade e relatórios fiscais',
private: true,
paragraphs: finance.length
? [
'Resultados recuperados das entradas guardadas pelo motor existente; impostos destinam-se à simulação de viabilidade.',
]
: [
'Nenhum resultado financeiro devolvido e autorizado neste âmbito. Não foi gerado um valor em falta.',
],
rows: [
...finance,
...(input.fiscal_reports ?? []).map((source) =>
row(
`Relatório fiscal ${source.report_id}`,
`Versão ${source.report_version_no ?? 'não indicada'}; SHA256 ${source.report_sha256 ?? 'não indicado'}`,
`/investimentos/${input.case.id}/relatorios/fiscais/${source.report_id}${input.context_opportunity ? `?opportunity=${encodeURIComponent(input.context_opportunity)}` : ''}`,
source.scope_state === 'identified'
? 'Versão fiscal preservada'
: source.scope_state === 'common'
? 'Versão preservada no contexto comum do dossier'
: 'Origem preservada no dossier; âmbito por confirmar',
),
),
],
},
{
id: 'market',
title: 'Análise SWOT',
private: true,
paragraphs: swot?.rows.length
? [
`Objecto: ${swot.object_key}; âmbito: ${swot.scope ?? 'não indicado'}. ${preparation?.swot_review_required ? 'Revisão necessária.' : 'Revisão guardada.'}`,
]
: ['Análise SWOT ainda não produzida neste âmbito.'],
rows: (swot?.rows ?? []).map((item) =>
row(
`${dimensions[item.dimension]} — ${item.text}`,
`${classifications[item.classification]}; data ${item.date ?? 'por confirmar'}`,
item.reference || 'Fonte por confirmar',
classifications[item.classification],
),
),
},
{
id: 'sources',
title: 'Preparação documental APIEX e actos externos',
private: true,
paragraphs: preparation
? [
`Estado: ${externalStates[preparation.api_state] ?? preparation.api_state}. Exportar não equivale a entregar; entrega não equivale a aprovação.`,
...preparation.api_issues,
]
: ['Preparação APIEX ainda não disponível neste âmbito.'],
rows: (preparation?.external ?? []).map((item) =>
row(
`${externalRecords[item.kind] ?? item.kind} — ${item.date}`,
`${item.reference}; ${item.outcome ? (decisions[item.outcome] ?? item.outcome) : 'sem decisão registada'}`,
`Exportação ${item.export_id}`,
'Registo de entrega ou resposta externa',
),
),
},
{
id: 'resources',
title: 'Documentos associados ao dossier',
private: true,
paragraphs: [
'Consulte os originais no dossier. Os controlos de acesso e disponibilidade mantêm-se em cada descarga.',
'Documentos comuns não comprovam a sua aplicabilidade a todas as oportunidades; confira a associação à etapa e ao pedido.',
],
rows: documentsInDossier(input).map((document) =>
row(
document.file_name,
`Versão ${document.version_no}; SHA256 ${document.sha256}`,
`/balcao-virtual/dossiers/${input.case.id}/documentos/${document.id}`,
document.status === 'active' &&
document.malware_scan_status === 'clean'
? 'Documento associado'
: 'Disponibilidade por conferir',
),
),
},
],
};
}
/** A preparation summary, never a substitute for an external act or its original. */
export function createInvestorStageReport(
input: InvestorDossierReportInput,
stageCode: string,
generatedAt = new Date().toISOString(),
): DossierReportModel {
const step = input.steps.find((item) => item.code === stageCode);
if (!step) throw new Error('Etapa não encontrada neste dossier.');
const report = createInvestorDossierReport(input, generatedAt);
const entries = investorDossierReportIndex(input).filter((entry) =>
entry.stage.split(', ').includes(stageCode),
);
const origins = new Set(entries.map((entry) => entry.href));
const specificSections = new Set([
...(stageCode === 'S02' ? ['market'] : []),
...(stageCode === 'S03' ? ['finance'] : []),
...(['S06', 'S07'].includes(stageCode) ? ['sources'] : []),
]);
return {
...report,
title: `${input.case.title} — ${stageCode}: ${step.title}`,
version: `${report.version} · etapa v${step.version ?? 'não registada'}`,
limitations: [
...report.limitations,
'Resumo dos registos disponíveis nesta etapa; não cria documentos, decisões ou resultados em falta.',
],
sections: report.sections
.filter(
(section) =>
['project', 'summary', 'execution', 'resources'].includes(
section.id,
) || specificSections.has(section.id),
)
.map((section) => {
if (section.id === 'summary')
return {
...section,
rows: section.rows.filter((item) =>
origins.has(item.origin),
),
};
if (section.id === 'execution')
return {
...section,
rows: section.rows.filter((item) =>
item.field.startsWith(`${stageCode} —`),
),
};
if (section.id === 'resources')
return {
...section,
rows: section.rows.filter((item) =>
origins.has(item.origin),
),
};
return section;
}),
};
}
+215
View File
@@ -0,0 +1,215 @@
export type AdvancePeriodDeclaration = {
version: 1;
mode: '' | 'annual_non_civil';
subjectNuit: string;
year: string;
currentFrom: string;
currentTo: string;
currentReference: string;
previousFrom: string;
previousTo: string;
previousReference: string;
ppcBasisKey: string;
pecBasisKey: string;
confirmed: '' | 'yes';
};
export type AdvanceFiscalPeriod = {
from?: string | null;
to?: string | null;
subjectNuit?: string;
ppcBasisKey?: string;
pecBasisKey?: string;
declaration?: AdvancePeriodDeclaration;
} | null;
export const advanceCalendarVersion = 'IRPC-annual-noncivil-calendar/1';
const iso = (s?: string | null): s is string =>
Boolean(
s &&
/^20\d{2}-\d{2}-\d{2}$/.test(s) &&
Number.isFinite(Date.parse(s)) &&
new Date(s).toISOString().slice(0, 10) === s,
);
const index = (s: string) =>
Number(s.slice(0, 4)) * 12 + Number(s.slice(5, 7)) - 1;
const month = (from: string, offset: number) =>
new Date(
Date.UTC(
Number(from.slice(0, 4)),
Number(from.slice(5, 7)) - 1 + offset,
1,
),
)
.toISOString()
.slice(0, 7);
const end = (s: string) =>
new Date(Date.UTC(Number(s.slice(0, 4)), Number(s.slice(5, 7)), 0))
.toISOString()
.slice(0, 10);
const previousDay = (s: string) =>
new Date(Date.parse(s) - 86400000).toISOString().slice(0, 10);
const annual = (from?: string | null, to?: string | null) =>
iso(from) &&
iso(to) &&
from.endsWith('-01') &&
to === end(to) &&
index(to) - index(from) === 11;
export function newAdvancePeriodDeclaration(
subjectNuit: string,
year: string,
period: AdvanceFiscalPeriod,
): AdvancePeriodDeclaration {
const from = period?.from ?? '',
to = period?.to ?? '';
return {
version: 1,
mode: 'annual_non_civil',
subjectNuit,
year,
currentFrom: from,
currentTo: to,
currentReference: '',
previousFrom: iso(from) ? month(from, -12) + '-01' : '',
previousTo: iso(from) ? previousDay(from) : '',
previousReference: '',
ppcBasisKey: '',
pecBasisKey: '',
confirmed: '',
};
}
export function validateAdvancePeriodDeclaration(d: AdvancePeriodDeclaration) {
if (
!d ||
d.version !== 1 ||
!['', 'annual_non_civil'].includes(d.mode) ||
!['', 'yes'].includes(d.confirmed) ||
[
'subjectNuit',
'year',
'currentFrom',
'currentTo',
'currentReference',
'previousFrom',
'previousTo',
'previousReference',
'ppcBasisKey',
'pecBasisKey',
].some(
(k) =>
typeof (d as unknown as Record<string, unknown>)[k] !==
'string',
)
)
throw Error(
'Correspondência de períodos não recuperável;original preservado.',
);
}
export function advanceCalendar(
period: AdvanceFiscalPeriod | undefined,
year: string,
subjectNuit?: string,
) {
const from = period?.from ?? '',
to = period?.to ?? '';
if (!/^20\d{2}$/.test(year))
return {
version: advanceCalendarVersion,
mode: 'unavailable' as const,
candidate: false,
pending: ['exercício das estimativas por confirmar'],
from,
to,
ppcMonths: [],
pecMonths: [],
previousFrom: '',
previousTo: '',
source: '',
};
const civil =
!period || (from === year + '-01-01' && to === year + '-12-31');
const candidate = annual(from, to) && to.slice(0, 4) === year && !civil;
let mode: 'civil' | 'annual_non_civil' | 'unavailable' = civil
? 'civil'
: 'unavailable';
let pending: string[] = [];
const d = period?.declaration;
if (!civil) {
if (d?.mode === 'annual_non_civil') {
validateAdvancePeriodDeclaration(d);
const issues: string[] = [];
if (!candidate)
issues.push(
'o período L6 deve conter doze meses civis completos com termo no exercício indicado',
);
if (
d.subjectNuit !== (subjectNuit ?? period?.subjectNuit) ||
d.year !== year ||
d.currentFrom !== from ||
d.currentTo !== to
)
issues.push(
'titular,exercício ou datas declaradas divergem de L6',
);
if (
!annual(d.previousFrom, d.previousTo) ||
!iso(from) ||
d.previousTo !== previousDay(from) ||
d.previousTo.slice(0, 4) !== String(Number(year) - 1)
)
issues.push(
'o período anterior deve ser anual completo e imediatamente anterior ao período L6',
);
if (
!d.currentReference.trim() ||
!d.previousReference.trim() ||
d.confirmed !== 'yes'
)
issues.push(
'faltam fontes e confirmação da correspondência dos dois períodos',
);
if (issues.length)
pending = [
'período anual não civil: ' +
issues.join('; ') +
'. Preparação conservada.',
];
else mode = 'annual_non_civil';
} else
pending = [
'o período L6 ' +
(from || 'por confirmar') +
' — ' +
(to || 'por confirmar') +
' não corresponde ao ano civil ' +
year +
'. Reconciliar o enquadramento antes de usar as estimativas ordinárias; a preparação fica conservada.',
];
}
const start = mode === 'civil' ? year + '-01-01' : from;
return {
version: advanceCalendarVersion,
mode,
candidate,
pending,
from: mode === 'civil' ? year + '-01-01' : from,
to: mode === 'civil' ? year + '-12-31' : to,
ppcMonths:
mode === 'unavailable' ? [] : [4, 6, 8].map((i) => month(start, i)),
pecMonths:
mode === 'unavailable' ? [] : [5, 7, 9].map((i) => month(start, i)),
previousFrom:
mode === 'annual_non_civil'
? d!.previousFrom
: String(Number(year) - 1) + '-01-01',
previousTo:
mode === 'annual_non_civil'
? d!.previousTo
: String(Number(year) - 1) + '-12-31',
source:
mode === 'annual_non_civil'
? 'CIRPC7(2),Lei34/2007,BR52,original SHA256cdbef875ad7ccc1517b12faf5de0e893a70ed2ed81e33913cd6dc4a674474e6e; RIRPC27(1)(a)/29(1),BR16/I16-04-2008,original SHA256fc373ff5637edf75ec6a9595dec8763a8503d4ee786e3b7d8f1c742eae9d80ee. Períodos anuais completos documentados;5.º/7.º/9.º mês PPC e6.º/8.º/10.º mês PEC. ' +
d!.currentReference +
'; ' +
d!.previousReference
: '',
};
}
+94 -4
View File
@@ -1,7 +1,10 @@
import {validateAdvancePeriodDeclaration,type AdvancePeriodDeclaration} from './irpc-advance-calendar.ts';
export {advanceCalendar,newAdvancePeriodDeclaration} from './irpc-advance-calendar.ts';
import { calculatePecPlan } from './irpc-pec-plan.ts';
import {pecCorrectionVersion} from './irpc-pec-correction.ts';
import {pecPlanVersion} from './irpc-pec-plan.ts';
import {validatePecObligation,pecObligationReport,pecObligationVersion,type PecObligation} from './irpc-pec-obligation.ts';
import { validatePpcObligation, ppcObligationReport, ppcObligationVersion, type PpcObligation } from './irpc-ppc-obligation.ts';
import {validatePecObligation,pecObligationReport,pecObligationVersion,pecPpcExcessVersion,calculatePecObligation,type PecObligation} from './irpc-pec-obligation.ts';
import { ordinaryAdvancePeriodIssues, type AdvanceFiscalPeriod, calculatePpcObligation, validatePpcObligation, ppcObligationReport, ppcObligationVersion, type PpcObligation } from './irpc-ppc-obligation.ts';
import {
newInvestmentCredit,
validateInvestmentCredit,
@@ -126,6 +129,7 @@ export type AnnualBook = {
creditCarry?: CreditCarry;
economicCredits?: EconomicCredits;
investmentCredit?: InvestmentCredit;
advancePeriodDeclaration?: AdvancePeriodDeclaration;
ppcObligation?: PpcObligation;
pecObligation?: PecObligation;
result?: AnnualRecord;
@@ -297,6 +301,7 @@ function books(d: Record<string, unknown>): Record<string, AnnualBook> {
return m;
}
export function validateAnnual(b: AnnualBook) {
if(b?.advancePeriodDeclaration!==undefined)validateAdvancePeriodDeclaration(b.advancePeriodDeclaration);
if(b?.pecObligation!==undefined)validatePecObligation(b.pecObligation);
if (b?.ppcObligation !== undefined) validatePpcObligation(b.ppcObligation);
if (b?.investmentCredit !== undefined)
@@ -421,6 +426,17 @@ export function annualAssessment(d: Record<string, unknown>) {
: zero(),
};
}
export function advancePeriodBasis(b:AnnualBook,kind:'ppc'|'pec'):string {
let value:unknown=b.ppcObligation??null;
if(kind==='pec'){if(b.pecObligation){const {plan:_,...basis}=b.pecObligation;value=basis;}else value=null;}
return closureFingerprint([b.subjectNuit,b.year,b.assessment,value]);
}
export function annualAdvancePeriod(d: Record<string, unknown>,b?: AnnualBook): AdvanceFiscalPeriod {
const prepared = normalBook(d).periodsFx;
const dates=prepared ? {from: prepared.from, to: prepared.to} : annualAssessment(d).period;
return b?.advancePeriodDeclaration ? {...dates,subjectNuit:b.subjectNuit,ppcBasisKey:advancePeriodBasis(b,'ppc'),pecBasisKey:advancePeriodBasis(b,'pec'),declaration:structuredClone(b.advancePeriodDeclaration)} : dates;
}
export function reuseAnnualAssessment(
d: Record<string, unknown>,
b: AnnualBook,
@@ -568,13 +584,18 @@ function dependencies(d: Record<string, unknown>, includeInvestment = false) {
}
function key(d: Record<string, unknown>, b: AnnualBook) {
const { result: _, history: __, ...input } = b;
const period = annualAdvancePeriod(d,b);
const periodGuard = ordinaryAdvancePeriodIssues(period, b.year).length > 0 &&
(b.ppcObligation || b.pecObligation && !calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment,period).notApplicable);
return closureFingerprint([
annualSettlementVersion,
...(periodGuard ? ['IRPC-advance-period-consistency/1'] : []),
acquisitionScope(d),
input,
dependencies(d, !!b.investmentCredit),
...(b.ppcObligation ? [ppcObligationVersion] : []),
...(b.pecObligation ? [pecObligationVersion] : []),
...(b.pecObligation && calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment).ppcExcess ? [pecPpcExcessVersion] : []),
...(b.pecObligation?.plan ? [pecPlanVersion] : []),
...(b.pecObligation?.correction ? [pecCorrectionVersion] : []),
...(b.investmentCredit && b.creditCarry?.lots.length
@@ -1592,6 +1613,7 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
return {
version: annualSettlementVersion,
input: structuredClone(input),
...(b.ppcObligation || b.pecObligation ? {advancePeriod: annualAdvancePeriod(d,b)} : {}),
subjectNuit: b.subjectNuit,
year: b.year,
assessment: assessment?.record
@@ -1724,8 +1746,9 @@ export function annualReportRows(
indeterminate: 'Indeterminado',
}[m.status];
return [
...(m.input.pecObligation ? pecObligationReport(m.input.pecObligation,m.subjectNuit,m.year,m.input.assessment) : []),
...(m.input.ppcObligation ? ppcObligationReport(m.input.ppcObligation,m.subjectNuit,m.year,m.input.assessment) : []),
...(m.input.pecObligation ? pecObligationReport(m.input.pecObligation,m.subjectNuit,m.year,m.input.assessment,m.advancePeriod ?? m.assessment?.period) : []),
...(m.input.ppcObligation ? ppcObligationReport(m.input.ppcObligation,m.subjectNuit,m.year,m.input.assessment,m.advancePeriod ?? m.assessment?.period) : []),
...annualAdvanceCashflowReport(m.input,m.advancePeriod ?? m.assessment?.period),
[
'IRPC — L8',
'Fecho anual — âmbito e origem',
@@ -2407,3 +2430,70 @@ export function annualHtml(d: Record<string, unknown>) {
'</html>'
);
}
/** Derived cash view only. Reuses the existing estimates; never changes the annual ledger. */
export function annualAdvanceCashflow(b: Pick<AnnualBook, 'subjectNuit' | 'year' | 'assessment' | 'ppcObligation' | 'pecObligation'>, period?: AdvanceFiscalPeriod) {
const pending: string[] = [];
const sources: string[] = [];
const amounts: Array<{month: string; kind: 'ppc' | 'pec'; amount: FiscalFraction}> = [];
let ppcKnown = false, pecKnown = false;
if (!b.ppcObligation) pending.push('Prepare a estimativa PPC para completar a projecção conjunta.');
else {
const p = calculatePpcObligation(b.ppcObligation, b.subjectNuit, b.year, b.assessment, period);
sources.push(b.ppcObligation.assessmentReference, b.ppcObligation.withholdingReference, p.source);
pending.push(...p.pending);
ppcKnown = p.pending.length === 0 && p.total !== null;
if (ppcKnown) amounts.push(...p.schedule.map(r => ({...r, kind: 'ppc' as const})));
}
if (!b.pecObligation) pending.push('Prepare a estimativa PEC para completar a projecção conjunta.');
else {
const p = calculatePecObligation(b.pecObligation, b.subjectNuit, b.year, b.assessment, period);
sources.push(b.pecObligation.turnoverReference, b.pecObligation.ppcReference, p.source);
pending.push(...p.pending);
if (!p.pending.length && p.total) {
if (BigInt(p.total.numerator) === 0n) pecKnown = true;
else if (!b.pecObligation.plan) pending.push('Distribua a hipótese de tesouraria PEC para completar os meses da projecção conjunta.');
else {
const allocation = calculatePecPlan(b.pecObligation.plan, p.total, p.notApplicable, b.year, period);
sources.push(b.pecObligation.plan.reference, allocation.source);
pending.push(...allocation.pending);
pecKnown = allocation.allocationReconciled;
if (pecKnown) amounts.push(...allocation.rows.map(r => ({...r, kind: 'pec' as const})));
}
}
}
const grouped = new Map<string, {month: string; ppc: FiscalFraction; pec: FiscalFraction}>();
for (const row of amounts) {
if (BigInt(row.amount.numerator) === 0n) continue;
const current = grouped.get(row.month) ?? {month: row.month, ppc: fraction(0n), pec: fraction(0n)};
current[row.kind] = addFractions([current[row.kind], row.amount]);
grouped.set(row.month, current);
}
const rows = [...grouped.values()].sort((a,b) => a.month.localeCompare(b.month)).map(r => ({...r, knownSubtotal: addFractions([r.ppc,r.pec])}));
const knownSubtotal = addFractions(rows.map(r => r.knownSubtotal));
let issues = [...new Set(pending)];
const periodIssues = ['PPC','PEC'].map(kind => ordinaryAdvancePeriodIssues(period,b.year,kind as 'PPC' | 'PEC')[0]);
if (periodIssues.every(issue => issue && issues.includes(issue))) {
issues = issues.filter(issue => !periodIssues.includes(issue));
issues.push(...ordinaryAdvancePeriodIssues(period,b.year));
}
return {version:'IRPC-advance-cashflow/1', ppcKnown, pecKnown, pending:issues, rows,
total: ppcKnown && pecKnown ? knownSubtotal : null, knownSubtotal, sources:[...new Set(sources.filter(s => s.trim()))]};
}
export function advanceCashflowAmount(value: FiscalFraction): string {
return fractionPresentation(value).decimal+' MZN';
}
export function annualAdvanceCashflowReport(b: Pick<AnnualBook, 'subjectNuit' | 'year' | 'assessment' | 'ppcObligation' | 'pecObligation'>, period?: AdvanceFiscalPeriod): Array<[string,string,string,string]> {
if (!b.ppcObligation && !b.pecObligation) return [];
const m = annualAdvanceCashflow(b, period);
const show = advanceCashflowAmount;
const source = m.sources.join('; ');
return [
['IRPC — L8', 'Projecção mensal conjunta PPC/PEC', (m.total ? 'Total da projecção: '+show(m.total)+'.' : 'Projecção parcial; total por determinar. '+m.pending.join(' '))+' Estimativas de tesouraria; comprovativos pagos, deduções e fecho anual separados. Esta vista não acrescenta outra saída ao fluxo financeiro.', source],
...m.rows.map(r => ['IRPC — L8', 'PPC/PEC — '+r.month,
'PPC: '+(m.ppcKnown ? show(r.ppc) : 'por determinar')+'; PEC: '+(m.pecKnown ? show(r.pec) : 'por determinar')+'; '+(m.total ? 'total previsto: ' : 'subtotal conhecido: ')+show(r.knownSubtotal)+'.', ''] as [string,string,string,string]),
];
}
+284 -35
View File
@@ -1,5 +1,19 @@
import {validatePecCorrection,correctedPecTurnover,pecCorrectionSource,type PecCorrection} from './irpc-pec-correction.ts';
import {validatePecPlan,pecPlanReport,type PecPlan} from './irpc-pec-plan.ts';
import { advanceCalendar } from './irpc-advance-calendar.ts';
import {
ordinaryAdvancePeriodIssues,
type AdvanceFiscalPeriod,
} from './irpc-ppc-obligation.ts';
import {
validatePecCorrection,
correctedPecTurnover,
pecCorrectionSource,
type PecCorrection,
} from './irpc-pec-correction.ts';
import {
validatePecPlan,
pecPlanReport,
type PecPlan,
} from './irpc-pec-plan.ts';
import {
decimalFraction,
fraction,
@@ -8,9 +22,21 @@ import {
type FiscalFraction,
} from './fiscal-rational.ts';
export const pecObligationVersion = 'IRPC-PEC-obligation/1';
export const pecPpcExcessVersion = 'IRPC-PEC-PPC-excess/1';
export const pecObligationSource =
'RIRPC,Decreto9/2008,art29(1–5),BR16/I16-04-2008,original SHA256 fc373ff5637edf75ec6a9595dec8763a8503d4ee786e3b7d8f1c742eae9d80ee.0,5% do volume de negócios anterior,limites30.000/100.000MZN,menos PPC efectivamente pagos no ano anterior.Junho/Agosto/Outubro;opção de pagamento único prevista,sem data ou repartição inventada. Ano de início excluído29(4);sem volume anterior exige último montante29(5). Recorte2026,residente geral comercial/industrial/agrícola,ano civil,MZN. Regimes/períodos especiais,rectificação29(3),base de anos anteriores29(5),guias/juros separados.';
export type PecLastAmount = {
version: 1;
subjectNuit: string;
year: string;
amount: string;
reference: string;
confirmed: '' | 'yes';
};
export const pecLastAmountSource =
'RIRPC,Decreto9/2008,art29(5),BR16/I16-04-2008,p122/PDF24,original SHA256 fc373ff5637edf75ec6a9595dec8763a8503d4ee786e3b7d8f1c742eae9d80ee. Hipótese documentada: último montante PEC já determinado,para titular/ano civil/MZN correspondentes;sem recalcular 0,5%,limites ou deduzir PPC pela segunda vez. Não demonstra por si a qualificação fiscal do caso.';
export type PecObligation = {
lastAmount?: PecLastAmount;
version: 1;
plan?: PecPlan;
correction?: PecCorrection;
@@ -42,8 +68,24 @@ export const newPecObligation = (
ppcReference: '',
});
export function validatePecObligation(p: PecObligation) {
if(p?.correction!==undefined)validatePecCorrection(p.correction);
if(p?.plan!==undefined)validatePecPlan(p.plan);
if (p?.lastAmount !== undefined) {
const v = p.lastAmount;
if (
!v ||
v.version !== 1 ||
!['', 'yes'].includes(v.confirmed) ||
['subjectNuit', 'year', 'amount', 'reference'].some(
(k) =>
typeof (v as unknown as Record<string, unknown>)[k] !==
'string',
)
)
throw Error(
'Referência PEC anterior não recuperável;original preservado.',
);
}
if (p?.correction !== undefined) validatePecCorrection(p.correction);
if (p?.plan !== undefined) validatePecPlan(p.plan);
if (
!p ||
p.version !== 1 ||
@@ -65,14 +107,23 @@ export function calculatePecObligation(
subjectNuit: string,
year: string,
assessment: string,
period?: AdvanceFiscalPeriod,
) {
validatePecObligation(p);
const pending: string[] = [];
const turnover=correctedPecTurnover(p.correction,p.previousTurnover,p.subjectNuit,p.previousYear);
const calendar = advanceCalendar(period, year, subjectNuit);
const turnover = correctedPecTurnover(
p.correction,
p.previousTurnover,
p.subjectNuit,
p.previousYear,
);
let percentage: FiscalFraction | null = null,
limited: FiscalFraction | null = null,
total: FiscalFraction | null = null,
notApplicable = false;
ppcExcess: FiscalFraction | null = null,
notApplicable = false,
lastAmountApplied = false;
if (
p.scope !== 'ordinary_resident' ||
assessment !== 'normal' ||
@@ -94,10 +145,58 @@ export function calculatePecObligation(
'PEC: falta ano de início efectivo da actividade e suporte;constituição da empresa não substitui início.',
);
if (!pending.length && p.activityStartYear === '2026') {
notApplicable = true;
total = fraction(0n);
const validStartDate = (value?: string | null) =>
Boolean(
value &&
/^2026-\d{2}-\d{2}$/.test(value) &&
Number.isFinite(Date.parse(value)) &&
new Date(value).toISOString().slice(0, 10) === value,
);
if (
period &&
!(
validStartDate(period.from) &&
validStartDate(period.to) &&
period.from! <= period.to!
)
)
pending.push(
...ordinaryAdvancePeriodIssues(
period,
year,
'PEC',
subjectNuit,
),
);
if (calendar.mode === 'annual_non_civil')
pending.push(
'PEC: início de actividade em período não civil exige correspondência própria;fora deste recorte de continuidade.',
);
if (!pending.length) {
notApplicable = true;
total = fraction(0n);
}
} else if (!pending.length) {
pending.push(
...ordinaryAdvancePeriodIssues(period, year, 'PEC', subjectNuit),
);
if (
calendar.mode === 'annual_non_civil' &&
(!period?.pecBasisKey ||
period.declaration?.pecBasisKey !== period.pecBasisKey)
)
pending.push(
'PEC: montantes ou fontes alterados;reconfira a sua correspondência com o período anterior,sem substituir os valores.',
);
pending.push(...turnover.pending);
if (
calendar.mode === 'annual_non_civil' &&
Number(p.activityStartYear) >=
Number(calendar.previousFrom.slice(0, 4))
)
pending.push(
'PEC: este recorte exige actividade já iniciada antes do período anterior documentado;início ou transição têm correspondência própria.',
);
if (
p.previousYear !== '2025' ||
!p.turnoverReference.trim() ||
@@ -117,11 +216,33 @@ export function calculatePecObligation(
if (!pending.length) {
const v = decimalFraction(turnover.value),
ppc = decimalFraction(p.previousPpcPaid);
if (BigInt(v.numerator) === 0n)
if (
BigInt(v.numerator) === 0n &&
calendar.mode === 'annual_non_civil'
) {
pending.push(
'PEC29(5):sem volume de negócios em2025,recuperar último montante dos anos anteriores;zero não determina automaticamente o mínimo.',
'PEC29(5): último montante num período não civil exige correspondência da sua origem;fora deste recorte de continuidade.',
);
else {
} else if (BigInt(v.numerator) === 0n) {
const last = p.lastAmount;
if (
!last ||
last.confirmed !== 'yes' ||
!last.reference.trim() ||
last.subjectNuit !== subjectNuit ||
!/^\d{4}$/.test(last.year) ||
Number(last.year) < Number(p.activityStartYear) ||
Number(last.year) >= Number(year) ||
!/^\d{1,18}(\.\d{1,2})?$/.test(last.amount)
) {
pending.push(
'PEC29(5):sem volume de negócios em2025,recuperar último montante PEC já determinado dos anos anteriores,com titular,exercício,fonte e confirmação de que é o último aplicável;zero não determina automaticamente o mínimo.',
);
} else {
total = decimalFraction(last.amount);
lastAmountApplied = true;
}
} else {
percentage = fraction(
BigInt(v.numerator),
BigInt(v.denominator) * 200n,
@@ -135,25 +256,67 @@ export function calculatePecObligation(
? fraction(100000n)
: percentage;
const residual = subtractFractions(limited, ppc);
if (BigInt(residual.numerator) < 0n)
pending.push(
'PEC:PPC anteriores excedem o montante limitado;caso separado para reconciliação,não gera estimativa negativa ou reembolso.',
);
else total = residual;
if (BigInt(residual.numerator) < 0n) {
total = fraction(0n);
ppcExcess = subtractFractions(ppc, limited);
} else total = residual;
}
}
}
let source = p.correction
? pecObligationSource.replace('rectificação29(3),', '') +
' ' +
pecCorrectionSource
: pecObligationSource;
if (p.lastAmount)
source =
source.replace('base de anos anteriores29(5),', '') +
' ' +
pecLastAmountSource;
if (calendar.mode === 'annual_non_civil')
source =
source
.replace(
'ano civil,MZN',
'período anual não civil completo,MZN',
)
.replace('Junho/Agosto/Outubro', '6.º/8.º/10.º mês do período')
.replace(
'Regimes/períodos especiais',
'Períodos curtos e outros regimes',
) +
' ' +
calendar.source;
if (ppcExcess)
source +=
' Reconciliação da estimativa29(2):PPC documentados cobrem a base limitada;diferença conservada sem gerar direito a reembolso ou crédito.';
return {
version: pecObligationVersion,
source: p.correction ? pecObligationSource.replace('rectificação29(3),','')+' '+pecCorrectionSource : pecObligationSource,
source,
nonCivil: calendar.mode === 'annual_non_civil',
lastAmountSource: p.lastAmount ? pecLastAmountSource : null,
pending,
percentage,
limited,
total,
notApplicable,
turnoverCorrection: p.correction ? {original:p.correction.originalTurnover,revised:p.correction.revisedTurnover,applied:!notApplicable&&turnover.applied,pending:turnover.pending,reference:p.correction.reference,source:pecCorrectionSource}:null,
months:
total && !notApplicable ? ['2026-06', '2026-08', '2026-10'] : [],
lastAmountApplied,
ppcExcess,
requiresLastAmount:
!notApplicable &&
turnover.pending.length === 0 &&
/^0+(\.0+)?$/.test(turnover.value),
turnoverCorrection: p.correction
? {
original: p.correction.originalTurnover,
revised: p.correction.revisedTurnover,
applied: !notApplicable && turnover.applied,
pending: turnover.pending,
reference: p.correction.reference,
source: pecCorrectionSource,
}
: null,
months: total && !notApplicable ? calendar.pecMonths : [],
instalmentAmountsDetermined: false,
paymentExecuted: false,
annualDeductionCreated: false,
@@ -164,15 +327,92 @@ export function pecObligationReport(
subjectNuit: string,
year: string,
assessment: string,
period?: AdvanceFiscalPeriod,
): Array<[string, string, string, string]> {
const m = calculatePecObligation(p, subjectNuit, year, assessment),
const m = calculatePecObligation(p, subjectNuit, year, assessment, period),
show = (v: FiscalFraction | null) =>
v ? fractionPresentation(v).decimal + ' MZN' : 'Indeterminado';
const originalEstimate=p.correction ? calculatePecObligation({...p,correction:undefined},subjectNuit,year,assessment).total:null;
const correctionEffect=originalEstimate&&m.total ? fractionPresentation(subtractFractions(m.total,originalEstimate)).decimal+' MZN':'por determinar';
const originalEstimate = p.correction
? calculatePecObligation(
{ ...p, correction: undefined },
subjectNuit,
year,
assessment,
period,
).total
: null;
const correctionEffect =
originalEstimate && m.total
? fractionPresentation(subtractFractions(m.total, originalEstimate))
.decimal + ' MZN'
: 'por determinar';
return [
...(p.correction ? [['IRPC — L8','PEC — rectificação do volume','Original: '+p.correction.originalTurnover+' MZN;corrigido: '+p.correction.revisedTurnover+' MZN;'+(m.turnoverCorrection?.applied?'aplicada à estimativa.':'conservada sem aplicação à estimativa.')+' Estimativa original: '+show(originalEstimate)+';efeito na estimativa: '+correctionEffect+'. '+turnoverCorrectionNotice(m.turnoverCorrection),p.correction.reference+'; '+pecCorrectionSource] as [string,string,string,string]]:[]),
...(p.plan ? pecPlanReport(p.plan,m.total,m.notApplicable,year) : []),
...(m.ppcExcess
? [
[
'IRPC — L8',
'PEC — PPC acima da base limitada',
'PPC documentados: ' +
p.previousPpcPaid +
' MZN;base limitada: ' +
show(m.limited) +
';diferença: ' +
show(m.ppcExcess) +
';estimativa PEC: 0 MZN. A diferença é apenas reconciliação desta hipótese; não cria reembolso,crédito,transporte ou dedução anual.',
p.ppcReference +
'; ' +
p.turnoverReference +
'; RIRPC29(2); ' +
pecPpcExcessVersion,
] as [string, string, string, string],
]
: []),
...(p.lastAmount
? [
[
'IRPC — L8',
'PEC — último montante documentado',
'Exercício ' +
(p.lastAmount.year || 'por confirmar') +
';montante PEC já determinado: ' +
(p.lastAmount.amount || 'por confirmar') +
' MZN;' +
(m.lastAmountApplied
? 'usado como hipótese documentada29(5),sem novo cálculo percentual ou segunda dedução de PPC.'
: 'conservado sem aplicação à estimativa.') +
' Não regista pagamento nem dedução anual.',
(p.lastAmount.reference || 'Fonte por indicar') +
'; ' +
pecLastAmountSource,
] as [string, string, string, string],
]
: []),
...(p.correction
? [
[
'IRPC — L8',
'PEC — rectificação do volume',
'Original: ' +
p.correction.originalTurnover +
' MZN;corrigido: ' +
p.correction.revisedTurnover +
' MZN;' +
(m.turnoverCorrection?.applied
? 'aplicada à estimativa.'
: 'conservada sem aplicação à estimativa.') +
' Estimativa original: ' +
show(originalEstimate) +
';efeito na estimativa: ' +
correctionEffect +
'. ' +
turnoverCorrectionNotice(m.turnoverCorrection),
p.correction.reference + '; ' + pecCorrectionSource,
] as [string, string, string, string],
]
: []),
...(p.plan
? pecPlanReport(p.plan, m.total, m.notApplicable, year, period)
: []),
[
'IRPC — L8',
'PEC — estimativa fiscal',
@@ -180,15 +420,22 @@ export function pecObligationReport(
? m.pending.join(' ')
: m.notApplicable
? 'Não aplicável no ano de início da actividade29(4);total0 MZN.'
: '0,5%: ' +
show(m.percentage) +
';limitado antes de PPC: ' +
show(m.limited) +
';total estimado: ' +
show(m.total) +
';meses: ' +
m.months.join(', ') +
(p.plan ? '. Plano explícito apresentado separadamente;prazo legal não validado.' : '. Montantes por prestação e opção de pagamento único não determinados neste recorte.') + ' Preparação não é pagamento nem dedução anual.',
: m.lastAmountApplied
? 'Hipótese documentada29(5): ' +
show(m.total) +
';último montante PEC já determinado,sem segunda dedução de PPC. Confirmar enquadramento com o suporte indicado.'
: '0,5%: ' +
show(m.percentage) +
';limitado antes de PPC: ' +
show(m.limited) +
';total estimado: ' +
show(m.total) +
';meses: ' +
m.months.join(', ') +
(p.plan
? '. Plano explícito apresentado separadamente;prazo legal não validado.'
: '. Montantes por prestação e opção de pagamento único não determinados neste recorte.') +
' Preparação não é pagamento nem dedução anual.',
p.activityReference +
'; ' +
p.turnoverReference +
@@ -200,4 +447,6 @@ export function pecObligationReport(
];
}
function turnoverCorrectionNotice(c:{pending:string[]}|null){return c?.pending.join(' ')??'';}
function turnoverCorrectionNotice(c: { pending: string[] } | null) {
return c?.pending.join(' ') ?? '';
}
+50 -5
View File
@@ -1,3 +1,7 @@
import {
advanceCalendar,
type AdvanceFiscalPeriod,
} from './irpc-advance-calendar.ts';
import {
decimalFraction,
addFractions,
@@ -10,6 +14,8 @@ export const pecPlanSource =
'RIRPC29(1):mesesJunho/Agosto/Outubro e opção de pagamento único. Montantes repartidos e mês único são hipótese explícita do utilizador,sem regra de igualdade,arredondamento,guia ou prazo legal presumidos. Conferência de prazo da opção única permanece separada.';
export type PecPlan = {
version: 1;
periodFrom?: string;
periodTo?: string;
mode: '' | 'three' | 'single';
reference: string;
singleMonth: string;
@@ -17,7 +23,10 @@ export type PecPlan = {
august: string;
october: string;
};
export const newPecPlan = (): PecPlan => ({
export const newPecPlan = (period?: AdvanceFiscalPeriod): PecPlan => ({
...(period?.from && period?.to
? { periodFrom: period.from, periodTo: period.to }
: {}),
version: 1,
mode: '',
reference: '',
@@ -27,6 +36,13 @@ export const newPecPlan = (): PecPlan => ({
october: '',
});
export function validatePecPlan(p: PecPlan) {
if (
(p?.periodFrom !== undefined || p?.periodTo !== undefined) &&
(typeof p.periodFrom !== 'string' || typeof p.periodTo !== 'string')
)
throw Error(
'Contexto da hipótese PEC não recuperável;original preservado.',
);
if (
!p ||
p.version !== 1 ||
@@ -46,9 +62,19 @@ export function calculatePecPlan(
total: FiscalFraction | null,
notApplicable: boolean,
year: string,
period?: AdvanceFiscalPeriod,
) {
validatePecPlan(p);
const pending: string[] = [];
const calendar = advanceCalendar(period, year);
pending.push(...calendar.pending.map((p) => 'Projecção PEC: ' + p));
const needsPeriodConfirmation =
(calendar.mode === 'annual_non_civil' || p.periodFrom !== undefined) &&
(p.periodFrom !== calendar.from || p.periodTo !== calendar.to);
if (needsPeriodConfirmation)
pending.push(
'Projecção PEC: reconfira a distribuição no período actual;montantes e mês anterior conservados sem deslocação automática.',
);
let rows: Array<{ month: string; amount: FiscalFraction }> = [];
if (!total)
pending.push(
@@ -92,11 +118,15 @@ export function calculatePecPlan(
);
else
rows = amounts.map((amount, i) => ({
month: ['2026-06', '2026-08', '2026-10'][i],
month: calendar.pecMonths[i],
amount,
}));
}
} else if (!/^2026-(0[1-9]|1[0-2])$/.test(p.singleMonth))
} else if (
!/^20\d{2}-(0[1-9]|1[0-2])$/.test(p.singleMonth) ||
p.singleMonth < calendar.from.slice(0, 7) ||
p.singleMonth > calendar.to.slice(0, 7)
)
pending.push(
'Projecção PEC:indique o mês previsto do pagamento único;isto não valida o prazo legal.',
);
@@ -104,7 +134,21 @@ export function calculatePecPlan(
}
return {
version: pecPlanVersion,
source: pecPlanSource,
source:
calendar.mode === 'annual_non_civil'
? pecPlanSource.replace(
'mesesJunho/Agosto/Outubro',
'6.º/8.º/10.º mês do período anual não civil',
) +
' ' +
calendar.source
: pecPlanSource,
months: calendar.pecMonths,
needsPeriodConfirmation,
contextFrom: calendar.from,
contextTo: calendar.to,
calendarPending: calendar.mode === 'unavailable',
nonCivil: calendar.mode === 'annual_non_civil',
mode: p.mode,
pending,
rows,
@@ -120,8 +164,9 @@ export function pecPlanReport(
total: FiscalFraction | null,
notApplicable: boolean,
year: string,
period?: AdvanceFiscalPeriod,
): Array<[string, string, string, string]> {
const m = calculatePecPlan(p, total, notApplicable, year);
const m = calculatePecPlan(p, total, notApplicable, year, period);
return [
[
'IRPC — L8',
+58 -6
View File
@@ -6,6 +6,22 @@ import {
type FiscalFraction,
} from './fiscal-rational.ts';
export type { AdvanceFiscalPeriod } from './irpc-advance-calendar.ts';
import {
advanceCalendar,
type AdvanceFiscalPeriod,
} from './irpc-advance-calendar.ts';
export function ordinaryAdvancePeriodIssues(
period: AdvanceFiscalPeriod | undefined,
year: string,
component: 'PPC' | 'PEC' | 'PPC/PEC' = 'PPC/PEC',
subjectNuit?: string,
): string[] {
return advanceCalendar(period, year, subjectNuit).pending.map(
(message) => component + ': ' + message,
);
}
export const ppcObligationVersion = 'IRPC-PPC-obligation/1';
export const ppcObligationSource =
'RIRPC, Decreto 9/2008, arts.27(1)(a) e28(1–3), BR16/I,16-04-2008,exemplar preservado SHA256 fc373ff5637edf75ec6a9595dec8763a8503d4ee786e3b7d8f1c742eae9d80ee: imposto liquidado no exercício anterior nos termos21(1), líquido das retenções na fonte;80%, dividido em três montantes iguais arredondados por excesso ao milhar de meticais. Maio,Julho,Setembro. Recorte2026,residente geral,actividade comercial/industrial/agrícola,ano civil e exercício anterior completo2025,MZN. Períodos especiais,anualização28(3),dispensas,juros e guias separados.';
@@ -57,16 +73,20 @@ export function calculatePpcObligation(
subjectNuit: string,
year: string,
assessment: string,
period?: AdvanceFiscalPeriod,
) {
validatePpcObligation(p);
const pending: string[] = [];
const calendar = advanceCalendar(period, year, subjectNuit);
const noncivilPreparation =
calendar.candidate && period?.declaration?.mode === 'annual_non_civil';
let base: FiscalFraction | null = null,
annualBeforeRounding: FiscalFraction | null = null,
instalment: FiscalFraction | null = null;
if (
p.scope !== 'ordinary_resident' ||
assessment !== 'normal' ||
p.previousFullCalendarYear !== 'yes' ||
p.previousFullCalendarYear !== (noncivilPreparation ? 'no' : 'yes') ||
year !== '2026' ||
p.year !== year ||
p.previousYear !== '2025' ||
@@ -74,7 +94,9 @@ export function calculatePpcObligation(
p.subjectNuit !== subjectNuit
)
pending.push(
'PPC: confirmar titular,2026,residente geral com actividade comercial/industrial/agrícola e exercício civil completo2025. Outros períodos/regimes e anualização permanecem separados.',
noncivilPreparation
? 'PPC: confirmar titular2026 e período anterior anual não civil com termo2025;indique Não em ano civil completo e confronte a correspondência documentada.'
: 'PPC: confirmar titular,2026,residente geral com actividade comercial/industrial/agrícola e exercício civil completo2025. Outros períodos/regimes e anualização permanecem separados.',
);
if (!p.assessmentReference.trim() || !p.withholdingReference.trim())
pending.push(
@@ -88,6 +110,17 @@ export function calculatePpcObligation(
pending.push(
'PPC: montantes anteriores em MZN desconhecidos ou inválidos; zero deve ser explícito.',
);
pending.push(
...ordinaryAdvancePeriodIssues(period, year, 'PPC', subjectNuit),
);
if (
calendar.mode === 'annual_non_civil' &&
(!period?.ppcBasisKey ||
period.declaration?.ppcBasisKey !== period.ppcBasisKey)
)
pending.push(
'PPC: montantes ou fontes alterados;reconfira a sua correspondência com o período anterior,sem substituir os valores.',
);
if (!pending.length) {
base = subtractFractions(
decimalFraction(p.previousTax),
@@ -109,7 +142,25 @@ export function calculatePpcObligation(
}
return {
version: ppcObligationVersion,
source: ppcObligationSource,
source:
calendar.mode === 'annual_non_civil'
? ppcObligationSource
.replace(
'ano civil e exercício anterior completo2025',
'períodos anuais completos não civis com termo2026/2025',
)
.replace(
'Maio,Julho,Setembro',
'5.º/7.º/9.º mês do período',
)
.replace(
'Períodos especiais,',
'Períodos curtos e outros regimes,',
) +
' ' +
calendar.source
: ppcObligationSource,
nonCivil: calendar.mode === 'annual_non_civil',
pending,
base,
annualBeforeRounding,
@@ -121,7 +172,7 @@ export function calculatePpcObligation(
)
: null,
schedule: instalment
? ['2026-05', '2026-07', '2026-09'].map((month) => ({
? calendar.ppcMonths.map((month) => ({
month,
amount: instalment,
}))
@@ -135,8 +186,9 @@ export function ppcObligationReport(
subjectNuit: string,
year: string,
assessment: string,
period?: AdvanceFiscalPeriod,
): Array<[string, string, string, string]> {
const m = calculatePpcObligation(p, subjectNuit, year, assessment),
const m = calculatePpcObligation(p, subjectNuit, year, assessment, period),
show = (v: FiscalFraction | null) =>
v ? fractionPresentation(v).decimal + ' MZN' : 'Indeterminado';
return [
@@ -157,7 +209,7 @@ export function ppcObligationReport(
m.schedule
.map((s) => s.month + ': ' + show(s.amount))
.join('; ') +
'. Previsão de obrigação; não é pagamento nem dedução anual.',
'. Estimativa fiscal para viabilidade; não é pagamento nem dedução anual.',
p.assessmentReference +
'; ' +
p.withholdingReference +
@@ -396,6 +396,11 @@ export async function generateProjectDossierDocx(
],
}),
];
for (const limitation of model.limitations) {
children.push(
new Paragraph({ children: [new TextRun({ text: limitation })] }),
);
}
for (const section of model.sections) {
if (section.id === 'annexes') {
if (!attachments.some((item) => item.include)) {
@@ -591,6 +596,8 @@ export async function createProjectDossierPrintHtml(
annexesIncluded: boolean,
): Promise<string> {
const content: string[] = [];
for (const limitation of model.limitations)
content.push(`<p>${escapeHtml(limitation)}</p>`);
for (const section of model.sections) {
if (
section.id === 'annexes' &&
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+48 -4
View File
@@ -23,6 +23,8 @@ type Result = {
description: string | null;
url: string;
category: string;
location?: string | null;
coverage?: string | null;
};
type Results = {
data: Result[];
@@ -33,9 +35,26 @@ type Results = {
unavailable: string[];
};
type SearchAnswer = {
type: 'count' | 'guide' | 'products' | 'list';
label: string;
count: number | null;
filter: string;
category?: 'all' | 'physical' | 'financial';
};
const ANSWER_HELP: Record<SearchAnswer['type'], string> = {
count: 'Contagem dos registos publicados e disponíveis para consulta no InvesteMoz.',
list: 'Registos publicados e disponíveis para consulta no InvesteMoz.',
guide: 'Consulte o roteiro público e prepare depois o licenciamento no seu dossier. Os requisitos dependem da actividade e localização.',
products: 'Produtos físicos e referências de cadeias de valor separados dos produtos financeiros. A presença física de uma instituição não determina a cobertura do financiamento.',
};
type CategoryMeta = { icon: LucideIcon; iconClass: string; badgeClass: string };
const CATEGORY_META: Record<string, CategoryMeta> = {
'Produtos e localizações': { icon: Factory, iconClass: 'bg-teal-50 text-teal-700', badgeClass: 'bg-teal-50 text-teal-700' },
'Produtos financeiros': { icon: Landmark, iconClass: 'bg-blue-50 text-blue-700', badgeClass: 'bg-blue-50 text-blue-700' },
'Páginas e serviços': {
icon: Compass,
iconClass: 'bg-slate-100 text-slate-700',
@@ -292,9 +311,11 @@ function QuickLinks() {
export default function Search({
query,
results,
answer = null,
}: {
query: string;
results: Results;
answer?: SearchAnswer | null;
}) {
const [input, setInput] = useState(query);
useEffect(() => setInput(query), [query]);
@@ -308,7 +329,7 @@ export default function Search({
unavailable,
} = results;
const pageUrl = (page: number) =>
`/pesquisa?${new URLSearchParams({ q: query, page: String(page) })}`;
`/pesquisa?${new URLSearchParams({ q: query, page: String(page), ...(answer?.category ? { category: answer.category } : {}) })}`;
const start = total ? (current - 1) * perPage + 1 : 0;
const end = Math.min(start + data.length - 1, total);
const highlight = useMemo(() => buildHighlightRegex(query), [query]);
@@ -340,6 +361,7 @@ export default function Search({
role="search"
className="mt-6 flex max-w-3xl flex-col gap-2 sm:flex-row"
>
{answer?.category && <input type="hidden" name="category" value={answer.category} />}
<label htmlFor="search-query" className="sr-only">
Pesquisar no InvesteMoz
</label>
@@ -376,6 +398,26 @@ export default function Search({
</section>
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-6">
{answer && (
<section aria-label="Resposta à pesquisa" className="mb-6 rounded-xl border border-slate-200 bg-white p-5">
<p className="text-xl font-semibold text-[#101820]" aria-live="polite">
{answer.type !== 'count' ? answer.label : answer.count === null ? 'Contagem indisponível de momento' : `${answer.count.toLocaleString('pt-MZ')} ${answer.label}`}
</p>
<p className="mt-2 text-sm text-slate-600">{ANSWER_HELP[answer.type]}</p>
{answer.filter && answer.type !== 'guide' && <p className="mt-1 text-sm text-slate-600">Correspondência textual: {answer.filter}.</p>}
{answer.type === 'products' && (
<nav aria-label="Categoria de produtos" className="mt-4 flex flex-wrap gap-2">
{([['all', 'Todos'], ['physical', 'Produtos físicos'], ['financial', 'Produtos financeiros']] as const).map(([category, label]) => (
<Link key={category} href={`/pesquisa?${new URLSearchParams({ q: answer.filter, category })}`}
aria-current={(answer.category ?? 'all') === category ? 'page' : undefined}
className={`rounded-full border px-3 py-2 text-sm font-semibold ${(answer.category ?? 'all') === category ? 'border-slate-800 bg-slate-800 text-white' : 'border-slate-200 text-slate-700 hover:bg-slate-100'}`}>
{label}
</Link>
))}
</nav>
)}
</section>
)}
{unavailable.length > 0 && (
<p
role="alert"
@@ -387,7 +429,7 @@ export default function Search({
</p>
)}
{query ? (
{query || answer ? (
<>
<div className="flex flex-wrap items-center justify-between gap-3">
<p
@@ -395,8 +437,8 @@ export default function Search({
className="text-sm text-slate-600"
>
{total > 0
? `Resultados ${start}–${end} de ${total} para “${query}”.`
: `Nenhum resultado nas fontes consultadas para “${query}”.`}
? `Resultados ${start}–${end} de ${total} para “${query || answer?.label}”.`
: `Nenhum resultado nas fontes consultadas para “${query || answer?.label}”.`}
</p>
{last > 1 && (
<span className="rounded-full bg-white px-3 py-1 text-xs font-semibold text-slate-600 ring-1 ring-slate-200">
@@ -473,6 +515,8 @@ export default function Search({
/>
</p>
)}
{item.location && <p className="mt-2 text-sm text-slate-700"><MapPin size={14} className="mr-1 inline" aria-hidden="true" />{item.location}</p>}
{item.coverage && <p className="mt-1 text-xs text-slate-600">{item.coverage}</p>}
</div>
<ArrowUpRight
size={20}
@@ -7,5 +7,6 @@
@foreach($plan['reasons'] as $reason)<p>{{ $reason }}</p>@endforeach
@if(!app(\App\Services\PortalProfileAccess::class)->mfa(request()->user()))<p><a href="{{ route('editorial.mfa') }}">Confirmar MFA e voltar à instalação</a></p>@endif
<p><a href="/management/editorial-installation">Atualizar prévia</a></p>
<aside aria-label="Ajuda ao preenchimento"><p>Confira o destino, a revisão e o esquema apresentados antes de confirmar esta instalação.</p><details><summary>❔ Ajuda neste passo</summary><p>Leia o destino, a única migration, a revisão técnica e o estado indicados na prévia. Marque a confirmação apenas se corresponderem à operação que pretende executar. O botão existente executa somente a instalação apresentada quando estiver disponível.</p></details></aside>
<form method="post" action="/management/editorial-installation">@csrf<input type="hidden" name="hash" value="{{ $plan['hash'] }}"><input type="hidden" name="idempotency_key" value="{{ $operationKey }}"><label><input type="checkbox" name="confirm" value="1" required>Confirmo o destino e apenas o esquema apresentado.</label><p><button @disabled(!$plan['ready'] || $plan['installed'])>Instalar apenas o esquema editorial indicado</button></p></form>
<p>A instalação não altera papéis ou permissões. Os acessos de criação, revisão e publicação mantêm as regras existentes da Tempo.</p></html>
@@ -1,4 +1,5 @@
<!doctype html><html lang="pt"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Confirmar MFA — gestão editorial</title><style>body{font:16px/1.6 system-ui;max-width:650px;margin:40px auto;padding:0 20px}input,button{font:inherit;padding:10px}label{display:block;margin-top:20px}</style>
<h1>Confirmar MFA</h1><p>A sessão mantém-se aberta. Confirma o MFA já configurado para regressar à instalação editorial.</p>
@foreach($errors->all() as $error)<p role="alert">{{ $error }}</p>@endforeach
<aside aria-label="Ajuda ao preenchimento"><p>Preencha o código da aplicação autenticadora ou o código de recuperação existente.</p><details><summary>❔ Ajuda neste passo</summary><p><strong>Código da aplicação autenticadora:</strong> introduza o código apresentado pela aplicação configurada nesta conta.</p><p><strong>Código de recuperação:</strong> se utilizar esta alternativa, introduza um dos códigos de recuperação que já possui.</p><p>Confira o campo preenchido antes de confirmar o MFA.</p></details></aside>
<form method="post" action="{{ route('editorial.mfa') }}">@csrf<label>Código da aplicação autenticadora<input name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="32"></label><p>Ou utiliza um código de recuperação existente.</p><label>Código de recuperação<input name="recovery_code" autocomplete="off" maxlength="255"></label><p><button>Confirmar MFA e voltar à instalação</button></p></form><p><a href="{{ route('editorial.installation') }}">Voltar sem confirmar</a></p></html>
@@ -2,4 +2,5 @@
<body><main><h1>Correção de sectores e duplicações</h1><p>Ator da sessão: {{ $plan['actor']['name'] }}. Permissão e MFA verificados no servidor.</p>
<dl><dt>Destino</dt><dd>{{ $plan['target']['database'] }}:{{ $plan['target']['port'] }}</dd><dt>Operação</dt><dd>{{ $plan['operation'] }}</dd><dt>Revisão autorizada</dt><dd>{{ $plan['revision'] }}</dd></dl>
<p>Apenas associação da oportunidade 2 a Energia 8, com auditoria. Sem migration, importação ou publicação. A atividade histórica e a oportunidade 6 permanecem sem reclassificação.</p>
<aside aria-label="Ajuda ao preenchimento"><p>Confira a correcção apresentada na prévia antes de confirmar.</p><details><summary>❔ Ajuda neste passo</summary><p>Leia o destino, a revisão, a oportunidade e o sector indicados. Marque a confirmação apenas se corresponderem à correcção que pretende executar. Use o botão existente para executar a operação apresentada.</p></details></aside>
<form method="POST" action="/management/sector-reconciliation">@csrf<input type="hidden" name="hash" value="{{ $plan['hash'] }}"><input type="hidden" name="operation_key" value="{{ $operationKey }}"><label><input type="checkbox" name="confirm" value="1" required>Confirmo o destino, a revisão e o preflight apresentados.</label><button type="submit">Executar apenas a correção indicada</button></form><a href="/sectores">Voltar aos sectores</a></main></body></html>