Integrate authorised editorial package with current homologation changes
This commit is contained in:
@@ -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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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,9 @@ import { SimulationIrpcInternational } from './simulation-irpc-international';
|
||||
import { SimulationIrpcPec } from './simulation-irpc-pec';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
advanceCashflowAmount,
|
||||
annualAdvanceCashflow,
|
||||
annualAdvancePeriod,
|
||||
annualBook,
|
||||
newAnnualBook,
|
||||
saveAnnualBook,
|
||||
@@ -77,6 +81,7 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
|
||||
);
|
||||
const patch = (p: Partial<AnnualBook>) => save({ ...b, ...p }),
|
||||
a = annualAssessment(draft),
|
||||
advancePeriod = annualAdvancePeriod(draft),
|
||||
options = annualWithholdingOptions(draft);
|
||||
const field = (
|
||||
key: 'subjectNuit' | 'year' | 'reference' | 'assessmentReference',
|
||||
@@ -341,10 +346,14 @@ 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})}/>
|
||||
<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 +622,24 @@ 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>;
|
||||
}
|
||||
|
||||
@@ -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) =>
|
||||
@@ -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,31 @@ 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}
|
||||
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,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;
|
||||
@@ -37,6 +40,7 @@ export function SimulationIrpcPpcObligation({
|
||||
book.subjectNuit,
|
||||
book.year,
|
||||
book.assessment,
|
||||
period,
|
||||
);
|
||||
const patch = (changes: Partial<PpcObligation>) =>
|
||||
onChange({ ...p, ...changes });
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
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,
|
||||
@@ -421,6 +422,11 @@ export function annualAssessment(d: Record<string, unknown>) {
|
||||
: zero(),
|
||||
};
|
||||
}
|
||||
export function annualAdvancePeriod(d: Record<string, unknown>): AdvanceFiscalPeriod {
|
||||
const prepared = normalBook(d).periodsFx;
|
||||
return prepared ? {from: prepared.from, to: prepared.to} : annualAssessment(d).period;
|
||||
}
|
||||
|
||||
export function reuseAnnualAssessment(
|
||||
d: Record<string, unknown>,
|
||||
b: AnnualBook,
|
||||
@@ -568,13 +574,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);
|
||||
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 +1603,7 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
|
||||
return {
|
||||
version: annualSettlementVersion,
|
||||
input: structuredClone(input),
|
||||
...(b.ppcObligation || b.pecObligation ? {advancePeriod: annualAdvancePeriod(d)} : {}),
|
||||
subjectNuit: b.subjectNuit,
|
||||
year: b.year,
|
||||
assessment: assessment?.record
|
||||
@@ -1724,8 +1736,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 +2420,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);
|
||||
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]),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import {validatePecCorrection,correctedPecTurnover,pecCorrectionSource,type PecCorrection} from './irpc-pec-correction.ts';
|
||||
import {validatePecPlan,pecPlanReport,type PecPlan} from './irpc-pec-plan.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 +21,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 +67,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 +106,22 @@ 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 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,9 +143,28 @@ 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'));
|
||||
if (!pending.length) {
|
||||
notApplicable = true;
|
||||
total = fraction(0n);
|
||||
}
|
||||
} else if (!pending.length) {
|
||||
pending.push(...ordinaryAdvancePeriodIssues(period, year, 'PEC'));
|
||||
pending.push(...turnover.pending);
|
||||
if (
|
||||
p.previousYear !== '2025' ||
|
||||
@@ -117,11 +185,26 @@ export function calculatePecObligation(
|
||||
if (!pending.length) {
|
||||
const v = decimalFraction(turnover.value),
|
||||
ppc = decimalFraction(p.previousPpcPaid);
|
||||
if (BigInt(v.numerator) === 0n)
|
||||
pending.push(
|
||||
'PEC29(5):sem volume de negócios em2025,recuperar último montante dos anos anteriores;zero não determina automaticamente o mínimo.',
|
||||
);
|
||||
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,23 +218,51 @@ 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 (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,
|
||||
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,
|
||||
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 ? ['2026-06', '2026-08', '2026-10'] : [],
|
||||
instalmentAmountsDetermined: false,
|
||||
@@ -164,15 +275,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)
|
||||
: []),
|
||||
[
|
||||
'IRPC — L8',
|
||||
'PEC — estimativa fiscal',
|
||||
@@ -180,15 +368,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 +395,6 @@ export function pecObligationReport(
|
||||
];
|
||||
}
|
||||
|
||||
function turnoverCorrectionNotice(c:{pending:string[]}|null){return c?.pending.join(' ')??'';}
|
||||
function turnoverCorrectionNotice(c: { pending: string[] } | null) {
|
||||
return c?.pending.join(' ') ?? '';
|
||||
}
|
||||
|
||||
@@ -6,6 +6,30 @@ import {
|
||||
type FiscalFraction,
|
||||
} from './fiscal-rational.ts';
|
||||
|
||||
export type AdvanceFiscalPeriod = {
|
||||
from?: string | null;
|
||||
to?: string | null;
|
||||
} | null;
|
||||
export function ordinaryAdvancePeriodIssues(
|
||||
period: AdvanceFiscalPeriod | undefined,
|
||||
year: string,
|
||||
component: 'PPC' | 'PEC' | 'PPC/PEC' = 'PPC/PEC',
|
||||
): string[] {
|
||||
if (!period) return [];
|
||||
return period.from === year + '-01-01' && period.to === year + '-12-31'
|
||||
? []
|
||||
: [
|
||||
component +
|
||||
': o período L6 ' +
|
||||
(period.from || 'por confirmar') +
|
||||
' — ' +
|
||||
(period.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.',
|
||||
];
|
||||
}
|
||||
|
||||
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,6 +81,7 @@ export function calculatePpcObligation(
|
||||
subjectNuit: string,
|
||||
year: string,
|
||||
assessment: string,
|
||||
period?: AdvanceFiscalPeriod,
|
||||
) {
|
||||
validatePpcObligation(p);
|
||||
const pending: string[] = [];
|
||||
@@ -88,6 +113,7 @@ 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'));
|
||||
if (!pending.length) {
|
||||
base = subtractFractions(
|
||||
decimalFraction(p.previousTax),
|
||||
@@ -135,8 +161,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 [
|
||||
|
||||
Reference in New Issue
Block a user