commit correcoes
This commit is contained in:
@@ -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: '',
|
||||
};
|
||||
}
|
||||
@@ -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),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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
|
||||
: '',
|
||||
};
|
||||
}
|
||||
@@ -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]),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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(' ') ?? '';
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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' &&
|
||||
|
||||
Reference in New Issue
Block a user