Compare commits

..
37 changed files with 3880 additions and 1856 deletions
@@ -1561,3 +1561,78 @@ L8 permanece parcial. A avaliação real do percurso proactivo continua a aguard
| Pagamento/titular/uso anterior e correspondência temporal | Pagamento em2027 afecto a2026 sem suporte: anexar/identificar correspondência expressa; sem presumir transporte ou utilização zero. |
**L8 permanece parcial.** Crédito internacional apenas emQA; PEC instalado em`e182d1d7` mantém o âmbito demonstrado. Songo eGurué privados; L3,ISPC,câmbio,L5–L7 eSGFTEMPO preservados. Avaliação de utilização do percurso proactivo continua a aguardar retorno da equipa. Sem instalação, publicação ou nova estimativa global nesta passagem.
## 27/10/2026 — Crédito internacional corrente entregue pelo Git
**Instalado e conferido em `838ad941a24ae76ec4bf91ccc3f92012668fe8cf`**, sobre o PEC instalado`e182d1d7`, preservando a correcção dos sectores`669cb897`. A candidata é a própria revisãoQA aceite`838ad941`, sem alteração funcional na preparação; integração normal em`main`, sem sobrescrever outro trabalho. Os registosQA anteriores são históricos: este recorte deixa de estar pendente de instalação. Não encerra L8 ou o IRPC.
**Delta instalado:**5ficheiros de aplicação — detalhe internacional, projecção dos códigos do catálogo de países existente e integração no saldo anual. Todos idênticos à QA. Conferidas1002fontes antes/1005depois comGit; restantes fontes comparadas conservadas, incluindoPEC,L3,ISPC,câmbio,L5–L7,sectores,catálogoISO,rotas e configuração. Sem novas permissões,migrations ou importações. Fixtures sintéticas apenas no código de testes; não importadas para dados activos nem publicadas. Songo eGurué permanecem privados; SGFTEMPO separado.
**Recorte:** residente geral,ano civil2026,MZN comprovados. Inclusão do rendimento,fracção nacional,aplicabilidade/limiteCDT e utilizações anteriores documentados. Menor entre imposto pago e limites aplicáveis,menos uso anterior e até à colecta,antesPEC/RF/PPC;sem concessão pela escolha do país,conversão/arredondamento fiscal ou transporte presumidos. Exemplo condicionado aos dados e suportes sintéticos demonstrados:1 408−8de crédito−200PEC−500PPC=**700MZN de saldo simulado a pagar**. Os2acima do limite de elegibilidade não são transporte; insuficiência de colecta fica separada. Caso com500a recuperar deriva doPPC,sem reembolso do crédito ouPEC. Informação em falta e prova duplicada deixam o saldo dependente indeterminado.
**Recuperação e preservação:** capacidade antes superior a85GiB e23,69milhões de inodes; mínimo existente do instalador5GiB mais backup confrontado com espaço real e novamente conferido após backup. Backup fresco`/var/backups/investmoz-irpc-l8-international-20261027/backup`,dumpSHA256`b1e9740653a8664c23268e228efd3ed6a0514bf3e8786dd5adf43342cdb475e1`;restauro174tabelas com contagens/checksums iguais em contentor sem rede,porta55441.369ficheiros persistentes/configuração e172tabelas de negócio intactos depois da instalação;schema,papéis,grants e permissões iguais. Cache/sessões operacionais reconciliados individualmente com o backup e pedidos públicos;nenhum registo de negócio ou sessão sobrescrito pelo comparador. Release anterior mantida até compilação/verificações e troca atómica;runtimeQA fora da árvore servida.
**Provas:** reutilizadas18novas+31anuais/PEC,API171asserções e7recuperações comHTML/dossier e históricos conservados. Sem nova ronda manual das funcionalidades não afectadas. Controlos automáticos obrigatórios do instalador:OK (1 test, 3106 assertions); ✓ built in 31.55s; OK (59 tests, 317 assertions); # tests 1110; # pass 1110; # fail 0;TypeScript/Wayfinder/build e guardas aprovados. Revisão pública e hash do manifest conferidos,HTTP200do simulador e6marcadores compilados do novo delta/PEC identificados. Não foram criados casosQA no portal.
**SaldoL8 preservado:** derivação automática da fracção nacional/CDT específicas;créditos económicos/CBF;utilização interanual/transporte/caducidade próprios;obrigação/calendárioPPC/PEC;autónomos,períodos especiais,moedas eM20/M22 conforme dependências já discriminadas. Excedente/transportePEC fora do âmbito entregue. Informação de inclusão/CDT/prova/titular/uso bloqueia apenas o caso dependente. As condições concretas de retoma mantêm-se no saldo curtoQA anterior;sem repetir pesquisas ou exigir nova autenticação de fontes oficiais aceites.
Recibo:`docs/investmoz/simulations/irpc-l8-international-credit-delivery-20261027.json`. Cópia remota:`/var/backups/investmoz-irpc-l8-international-20261027/installed-receipt.json`,SHA256`d80324b898fd160ab3e7a2fd0b11ea2decd0b99a9324255850062ee4a13e0f0f`. Provas locais:`outputs/irpc-l8-international-delivery-20261027/`. Resolvida a colisão local`inspect.py`→`remote_delivery_inspection.py`;módulo padrão/Paramiko verificados no mesmoPython,guardaLinux/geteuid mantida,sem alteração de credenciais ou do servidor por essa correcção. A avaliação real do percurso proactivo continua dependente do retorno da equipa. **L8 permanece parcial.**
## 28/10/2026 — saldos anteriores internacionais e PEC: delta QA concluído
Implementado e demonstrado em QA isolada, **sem instalação**. Base `cf4e0638`, com internacional `838ad941`, PEC `e182d1d7` e sectores `669cb897` preservados. A pasta original estava noutro ramo; isso não foi tratado como eliminação de funcionalidades. Recibo: `docs/investmoz/simulations/irpc-l8-carry-qa-20261028.json`.
Extensão opcional do livro anual existente: uma origem consolidada por natureza/país/exercício, apuramento e regra de origem documentados, elegível menos dedução inicial e utilizações efectivas subsequentes. Internacional: cinco exercícios seguintes; PEC: três. Origem2021 internacional e PEC2023 chegam a2026; origem2020 internacional/PEC2022 ficam fora do prazo ordinário, conservadas com explicação e saldo histórico. Não se converte imposto acima do limite em crédito transportável. Situações transitórias/especiais não são qualificadas pela regra ordinária.
Escolha expressa das parcelas correntes e anteriores, vinculada à colecta seleccionada, sem ordem FIFO imposta nem redução automática. A soma não ultrapassa a colecta e os créditos internacionais precedem o PEC. Valores não escolhidos ficam separados da insuficiência de colecta; simulações não criam nem consomem saldos oficiais. Exemplo sintético:1408−8corrente internacional−50anterior internacional−200PECcorrente−100PECanterior−500PPC=**550MZN a pagar, simulado**.
**Provas:**16novos+49afectados=65testes aprovados; API1teste/119asserções,6casos POST/PUT/GET na base guardada `proactive_investment_20261027_test`,loopback55441,com rollback. Seis recuperações recalculadas integralmente,HTML/dossier concordantes e resultados anteriores congelados.55oportunidades,64documentos,1vínculo,19rascunhos,40utilizadores,3organizações e409eventos anteriores preservados.31ficheiros do acervo byte a byte iguais,sem nova importação/publicação. TypeScript,build QA com exit0 ePint aprovados. Não foi feita nova prova manual de interface ou avaliação pela equipa. Sem migrations,grants,contas,alteração activa ou operações de servidor.
**Saldo concreto:**L8 continua parcial. Próximo incremento independente:crédito económico64,com gross-up53(1)a/exclusão40,qualificação dos lucros/pagador/beneficiário/imposto e limite proporcional correspondidos; fonte aceite já disponível. Permanecem fracção nacional/CDT automática,créditos/benefícios próprios,obrigação/calendárioPPC/PEC,autónomos,períodos especiais,outras moedas eM20/M22. Não declarar IRPC concluído nem repetir a validação das entregas independentes aceites.
## 28/10/2026 — crédito económico ordinário demonstrado em QA; agrupamento compatível
**Implementado e demonstrado em QA isolada, sem instalação.** Ramo `codex/irpc-l8-economic-qa-20261028`, base `6ededb59`, incluindo os saldos anteriores `d134a92d`. A última referência instalada documentada continua `838ad941`; não foi feita nova leitura do servidor. Não se reabre a aceitação dos históricos ou das provas anteriores.
**Cobertura:**CIRPC64(1–2),53(1)a,40(1)na redacção20/2009 eRIRPC21(2/5). Lucros ordinários distribuídos e IRPC correspondente documentados,beneficiário/distribuidor com sede/direcção efectiva emMoçambique,distribuidor sujeito/não isento,exclusão40(1)não aplicável com suporte. A selecção explícita da colecta corrente reutiliza NUIT/exercício/residência válidos e conserva edições divergentes. Novo detalhe opcional; resumo económico deliberado anterior e resultados congelados conservados.
**Cálculo:**60%doIRPCdocumentadamente correspondente aos lucros;confere o acréscimo53 já incluído emL6 e limita pela quota proporcional documentada,menos utilização efectiva anterior,até à colecta. O portal não deriva IRPC do dividendo líquido nem altera a base/colecta silenciosamente;inclusão/acréscimo e quota exigem correspondência do caso. A existência de perdas que reduzam a base abaixo dos lucros não é tratada como impedimento genérico. Crédito económico precede o internacional ePEC,sem reembolso ou transporte económico presumido. Exemplo sintético condicionado aos suportes:IRPC20→nominal12;1408−12−8internacional−200PEC−500PPC=**688MZN a pagar,simulado**.
**Mesma parcela:**identidade por emitente/documento/parcela com suporte;duplicação dos lucros também conferida independentemente de trocar o comprovativo de imposto,a data ou oID. O mesmo documento pode suportar parcelas de imposto distintas quando a separação estiver documentada em ambos os registos. Um comprovativo anterior sem parcela continua a abranger o documento inteiro,não se torna livre por receber novo nome noutro mapa. Atribuições anteriores e capacidade do comprovativo conferidas neste e noutros contextos do snapshot;divergências não são apagadas. ProtecçõesL5 conservadas. Não é reconciliação global de conta fiscal entre dossiers independentes.
**Agrupamento:**composição demonstrada com os saldos anteriores:1408−12económico−8internacionalcorrente−50internacionalanterior−200PECcorrente−100PECanterior−500PPC=**538MZN a pagar,simulado**. A prioridade económica não reduz automaticamente a afectação entre exercícios já escolhida;se exceder a colecta remanescente,o caso pede reconciliação conservando as escolhas. Os dois incrementos podem integrar uma entrega Git comum;nenhum foi instalado nesta passagem.
**Provas do delta:**20testes económicos novos+65afectados aceites=85aprovados;API1teste/210asserções,11casos POST/PUT/GET na base guardada `proactive_investment_20261027_test`,loopback55441,transacção com rollback. Onze recuperações recalculadas integralmente,HTML/dossier concordantes e históricos anteriores conservados.55oportunidades,64documentos,1vínculo,19rascunhos,40utilizadores,3organizações e409eventos anteriores intactos. TypeScript,build QA ePint aprovados.31ficheiros do acervo preservados por bytes,sem novas importações,publicações,scan declarado,migrations,contas ougrants. Não foi feita nova prova manual da interface nem avaliação pela equipa.
**Pendências concretas:**inclusão/correcção automática do dividendo/acréscimo emL6 e derivação da quota proporcional;exclusão40(1)na base com todas as suas condições;liquidação64(3)/associações64(4);créditos/benefícios específicos;fracção internacional/CDT automática;obrigação/calendárioPPC/PEC;autónomos,períodos especiais,outras moedas eM20/M22. Correspondências e parâmetros em falta afectam o caso dependente,sem revalidação genérica de fontes oficiais. Saldos anteriores mantêm o recorte ordinário já demonstrado. **L8 permanece parcial.** Recibo:`docs/investmoz/simulations/irpc-l8-economic-qa-20261028.json`.
## 28/10/2026 — entrega agrupada de saldos anteriores e crédito económico pelo Git
**Instalado e conferido em `569a1cd750f3d2a0b87f130e992e73e070bbd1ab`**, sobre `838ad941`, por fast-forward normal em `main`,sem force. Foram entregues em conjunto os saldos anteriores `d134a92d` e o crédito económico ordinário `aae67c1`, já demonstrados emQA. Os estadosQA anteriores permanecem históricos;estes recortes deixam de estar pendentes de instalação. **L8 permanece parcial;esta entrega não fecha integralmente a liquidação anual.**
**Delta e preservação:**12ficheiros de aplicação,byte a byte correspondentes à candidata aceite;1005fontes antes e1011depois conferidas comGit. Demais fontes comparadas,PECcorrente,internacionalcorrente,sectores,L3/ISPC/câmbio/L5–L7,originais e contexto adaptativo preservados. Sem alterações de schema/configuração/rotas/grants,migrations ou importações de conteúdo. RuntimeQA conservado fora da árvore servida. Songo/Gurué permanecem privados eSGFTEMPO separado.
**Capacidade/recuperação:**82,71GiB e23,52milhões de inodes livres antes;capacidade novamente conferida após backup,com o mínimo existente do instalador e espaço real do backup. Backup fresco `2026-10-28T12:38:25Z` (14:38:25locais),em `/var/backups/investmoz-irpc-l8-grouped-20261028/backup`;dumpSHA256`007cd1851d5bd51a54265ab99a342d6a312de06ef642fc42b38b7a5e771d4d9a`. Restauro174tabelas com contagens/checksums iguais emcontentorsemrede/porta55441;369ficheiros/configuração conferidos. Depois da entrega:172tabelas de negócio e369ficheiros persistentes/configuração intactos;schema,papéis,grants epermissões iguais,identidades de comparação equivalentes. Delta operacional delimitado a `queue:restart` e2sessões anónimas do agente de entrega,correlacionadas com pedidos públicos;nenhum dado ou sessão sobrescrito para obter igualdade. Release anterior mantida até todos os controlos e troca atómica;manifest/revisão servidos confirmados.
**Provas reutilizadas e controlos da entrega:**85testes afectados/20económicos novos,API210asserções/11recuperações HTML/dossier e históricos aceites reutilizados;sem repetir avaliação manual de funcionalidades independentes. Instalador obrigatório:PostgreSQL1teste/3106asserções;Unit59/317;frontend1146aprovados/0falhas;TypeScript/Wayfinder/build aprovados (30,82s). SimuladorHTTP200 e8marcadores compilados dos saldos anteriores/económico/internacional/PEC conferidos. Não foram criados casosQA no portal e não se declara nova aceitação manual da equipa.
### Saldo concreto de L8 após a entrega
| Grupo | Cobertura entregue ou trabalho restante |
| --- | --- |
| Saldos anteriores65(3)/66 | Entregues no recorte de origens anuais ordinárias documentadas,mesmo sujeito/2026/MZN,prazos próprios5/3exercícios,utilizações efectivas e afectação explícita. Não cria nem consome saldos oficiais;casos transitórios/especiais permanecem próprios. |
| Económico64(1–2) | Entregue para lucros ordinários qualificados,IRPC correspondente documentado,acréscimo53 já incluído emL6 e quota proporcional documentada,antes do internacional/PEC,sem dupla utilização da mesma parcela. Parcela excluída40(1)não recebe também64. |
| Inclusão/correcção económica e quota | Ainda por implementar a inclusão/correcção automática do dividendo/acréscimo emL6,a derivação automática da quota e o tratamento completo40(1)na base. A comprovação manual corrente não é declarada automação desses grupos. |
| Económico64(3/4) e benefícios | Liquidação,associações ecréditos/benefícios específicos mantêm qualificação,limites,cumulação e uso próprios por implementar;sem os transformar emcrédito internacional. |
| Internacional automático | Derivação da fracção nacional e correspondência específicaCDT continuam pendentes;qualificação/dedução internacional documentada entregue preservada. |
| Obrigações e representação | Obrigação/calendárioPPC/PEC,juros/multas/guias,autónomos,períodos especiais,outras moedas eM20/M22/transporte/submissão continuam nos grupos concretos anteriores. |
A falta de prova do caso (titular/rendimento/imposto/inclusão/uso/regra do período ou quota) limita só o resultado dependente;não é reabertura da autenticidade das fontes oficiais aceites nem novo aprovador. Exemplo agrupado condicionado aos suportes sintéticos já aceites:1408−12económico−8internacionalcorrente−50internacionalanterior−200PECcorrente−100PECanterior−500PPC=**538MZN de saldo simulado a pagar**;não é declaração submetida ou saldo fiscal consumido.
Recibo consolidado:`docs/investmoz/simulations/irpc-l8-grouped-delivery-20261028.json`. Cópia remota:`/var/backups/investmoz-irpc-l8-grouped-20261028/installed-receipt.json`. Provas locais:`outputs/irpc-l8-grouped-delivery-20261028/`. Actualização documental segue ramo próprio de recibos,sem alterar novamente a revisão servida.
Cópia remota do recibo conferida:SHA256`b70fe154f95162f029b5ca712b41962757360d73b0ff07f52b8ce14848d990df`;a matriz existente recebeu saldoL8 nos camposEstado,Disponibilidade activa,Evidências,Critérios restantes eDependências,só em `AUD-SIM-INT02`.
@@ -0,0 +1,185 @@
{
"date": "2026-10-28",
"status": "implemented and demonstrated in isolated QA; not installed",
"branch": "codex/irpc-l8-carry-qa-20261028",
"base": "cf4e0638",
"installed_reference_unchanged": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"scope": {
"year": "2026",
"subject": "same subject, resident general",
"period": "annual ordinary origins; calendar-year current close",
"currency": "documented MZN; exact foreign-credit fractions supported",
"international": "eligible origin credit minus origin deduction and documented actual later uses; five subsequent exercises, art65(3)",
"pec": "actual PEC eligible origin minus origin deduction and actual later uses; three subsequent exercises, art66(1–2)",
"allocation": "explicit documented selection between current and prior exercises, confirmed against current assessment; no presumed FIFO or automatic reduction",
"expiry": "ordinary window ended excludes current deduction but keeps source and arithmetic historical remainder",
"origin_rules": "origin assessment, inclusion/limits/insufficient collection and applicable period documented; exceptional/transitional rules outside scope"
},
"restriction_origins": {
"Tempo": "preserve approved sources, accepted deliveries, data/history, QA isolation; continue L8",
"accepted_requirement": "CIRPC65(3),66(1–2), source already accepted; no new provenance approval",
"technical_choices": "optional versioned snapshot extension; consolidated nature/country/origin-year balance; explicit selection avoids invented interyear priority"
},
"verification": {
"new_frontend_tests": 16,
"affected_previously_accepted_tests": 49,
"total_frontend_pass": 65,
"frontend_fail": 0,
"API_tests": 1,
"API_assertions": 119,
"API_cases": 6,
"API_database": "proactive_investment_20261027_test",
"API_port": 55441,
"API_transactions_rolled_back": true,
"recovered_recalculated_HTML_dossier": 6,
"frozen_prior_results_preserved": true,
"typescript": "passed",
"build": "passed, actual subprocess exit0",
"PHP_formatting": "pint passed",
"browser_manual": "not performed; no manual UI acceptance claimed"
},
"preservation": {
"previous_deliveries": [
"international838ad941",
"PECe182d1d7",
"sectors669cb897"
],
"source_files_byte_identical": 31,
"existing_QA_records": {
"database": "proactive_investment_20261027_test",
"tables": {
"opportunities": {
"existing_rows": 55,
"unchanged": true
},
"documents": {
"existing_rows": 64,
"unchanged": true
},
"opportunity_documents": {
"existing_rows": 1,
"unchanged": true
},
"simulation_form_drafts": {
"existing_rows": 19,
"unchanged": true
},
"users": {
"existing_rows": 40,
"unchanged": true
},
"organizations": {
"existing_rows": 3,
"unchanged": true
},
"audit_events": {
"existing_rows": 409,
"unchanged": true
}
},
"transaction_rollback": true
},
"matrix": "existing AUD-SIM-INT02 updated; all other rows semantically unchanged",
"new_accounts_permissions_migrations": false,
"active_data_or_configuration_written": false,
"remote_deployment_or_publication": false,
"Songo_Gurue": "no pilot changes; remain private",
"other_dossiers": "same-snapshot origins checked, no global official account reconciliation"
},
"cases": [
{
"name": "payable",
"status": "payable",
"balance": {
"numerator": "550",
"denominator": "1"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "expired",
"status": "indeterminate",
"balance": null,
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "missing-use",
"status": "indeterminate",
"balance": null,
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "overallocated",
"status": "indeterminate",
"balance": null,
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "fractional",
"status": "payable",
"balance": {
"numerator": "1822",
"denominator": "3"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "recoverable",
"status": "recoverable",
"balance": {
"numerator": "-500",
"denominator": "1"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
}
],
"remaining_L8": [
"automatic national-fraction derivation and case-specific treaty correspondence",
"economic credit art64/53 and benefit-specific credits with own qualification/limits",
"PPC/PEC obligation and calendar, interest/penalties and payment guides with applicable edition",
"autonomous taxation, special periods, other currencies, M20/M22 transport/submission",
"exceptional or transitional interyear cases outside ordinary source window; no official ledger created"
],
"next_independent_increment": {
"item": "economic double-tax credit",
"source": "existing accepted CIRPC64,53(1)a and exclusion40; BR52 original",
"required_correspondence": "distributed profits included, payer/recipient residence and IRPC nonexemption, art40 distinction, source tax, gross-up53, proportional cap64, actual use and nonduplication; do not infer from declared dividend alone"
},
"L8_complete": false,
"evidence": {
"api.log": "ef604fbe7a289930cb0b6dfa35407e0f115092894d32fd98c04a9e1f3b732415",
"build-result.json": "80bb1b6bb0ccadaf94f241ace9b0b19f77461b193b8b7522afa655d414d36198",
"build.log": "d93839f94f37e181acafe3f6295c10982e036475b1f5186aedba9a9ae3cd6bd9",
"existing-records-preservation.json": "b45b3306d3c9dee63fbbaf9a04bba31008019e65892bd16322460b5ef53eda7d",
"frontend-tests.log": "86a878a794a8f1ed7db56d689f0b9d5a2bdbc6079aa66e3cfe4b65ae64e656f6",
"protected-consumers.json": "9f147ea688a79a77a8d7507cf1c322a6a3c03b959be8fc5ed114db63dac05761",
"recovered-report-receipt.json": "82df86eaabbb79d760e4f2f1efb0f900d9e9607e11ea49502746dbafc46fed03",
"source-preservation.json": "c28df37db83989fe5746dcb5382a75c4f39471a16a7cbe64670260209cf6ad79"
},
"qa_commit": "d134a92d169f9159a692ed158e3a051889f7ab3a",
"qa_branch_pushed": false
}
@@ -0,0 +1,318 @@
{
"date": "2026-10-28",
"status": "ordinary economic credit implemented and demonstrated in isolated QA; not installed",
"branch": "codex/irpc-l8-economic-qa-20261028",
"base": "6ededb59",
"last_installed_receipt_reference": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"remote_status_read_this_turn": false,
"scope": {
"current_year": "2026",
"current_period": "calendar year, resident general",
"currency": "documented MZN; exact fractions without fiscal rounding",
"profit_kind": "ordinary distributions art64(1–2)",
"eligibility": "same-country seat/effective management; payer subject to IRPC and nonexempt; nonapplication of40(1) documented, including2009 version",
"nominal_credit": "60 percent of documented IRPC corresponding to included distributed profits; no assumed rate on net dividend",
"gross_up": "expected nominal60 percent reconciled with53(1)a amount already included in current L6; does not overwrite or recalculate source base",
"proportional_ceiling": "case-specific documented input tied to current assessment; not automatically derived",
"prior_use": "actual documented economic credit use, distinct from simulation history and prior source-tax attributions",
"order": [
"economic credit up to collecta",
"international credit current/prior according to existing explicit selection",
"PEC current/prior according to existing explicit selection",
"own withholdings and PPC"
],
"refund": "no economic-credit refund or carry created; PPC can create simulated recoverable balance"
},
"proof_parcels": {
"stable_identity": "issuer/document/parcel; distribution identity also independent of source-tax document,date and row id",
"economic_vs_international": "same physical tax parcel cannot fund both credit natures",
"same_paper_different_tax": "supported distinct parcels can coexist; old proof without a parcel overlaps the whole paper until reconciled",
"capacity": "same proof parcel amounts and prior attributions must agree and total allocation remains within available amount across snapshot contexts",
"L5": "existing withholding source/allocation checks preserved; parcel relabelling cannot turn repeated L5 use into new tax",
"partial_information": "saved and recovered as indeterminate, never reset or silently assumed absent",
"global_official_account_reconciliation": false
},
"compatibility_group": {
"included_prior_QA": "d134a92d169f9159a692ed158e3a051889f7ab3a; receipt6ededb59",
"candidate_contains_carry_increment": true,
"combined_API_case": "1408-12economic-8currentInternational-50priorInternational-200currentPEC-100priorPEC-500PPC=538MZN payable simulated",
"previous_carry_history_preserved": "550 MZN prior simulated result retained unchanged",
"changed_allocation": "economic priority checks remaining collecta but keeps user prior/current allocations; over-allocation becomes pending rather than reduced automatically",
"installation": false
},
"restriction_origins": {
"Tempo": "next economic increment, distinction from international, no duplicate same parcel, preserve approved evidence/history; compatible grouping allowed",
"accepted_requirement": "CIRPC64(1–2),53(1)a,40(1) amended by20/2009; RIRPC21(2/5)",
"implementation_choices": "optional versioned detail; normal resident general2026/MZN scope; documentary inclusion/gross-up/proportional quota; optional parcel annotations on existing proof types; no additional organizational authority"
},
"verification": {
"economic_new_frontend_tests": 20,
"previous_affected_tests": 65,
"frontend_pass": 85,
"frontend_fail": 0,
"API_tests": 1,
"API_assertions": 210,
"API_cases": 11,
"database": "proactive_investment_20261027_test",
"loopback_port": 55441,
"API_transactions_rolled_back": true,
"recovered_cases_recalculated_with_HTML_and_dossier": 11,
"frozen_histories_preserved": true,
"typescript": "passed",
"build": "isolated QA, subprocess exit0, final component hashes recorded",
"PHP_formatting": "pint passed",
"new_browser_manual_proof": false,
"team_usability_evaluation": "unchanged; awaiting team feedback"
},
"preservation": {
"protected_files_same_git_content": 558,
"raw_checkout_difference": {
"kind": "LF/CRLF environment difference only, no semantic loss",
"files": [
"docs/investmoz/simulations/irpc-l8-carry-qa-20261028.json"
]
},
"source_originals_same_bytes": 31,
"existing_QA_records": {
"database": "proactive_investment_20261027_test",
"tables": {
"opportunities": {
"existing_rows": 55,
"unchanged": true
},
"documents": {
"existing_rows": 64,
"unchanged": true
},
"opportunity_documents": {
"existing_rows": 1,
"unchanged": true
},
"simulation_form_drafts": {
"existing_rows": 19,
"unchanged": true
},
"users": {
"existing_rows": 40,
"unchanged": true
},
"organizations": {
"existing_rows": 3,
"unchanged": true
},
"audit_events": {
"existing_rows": 409,
"unchanged": true
}
},
"transaction_rollback": true
},
"existing_matrix": "only AUD-SIM-INT02 evidence updated; other records unchanged semantically",
"old_carry_receipt_and_fixture": "unchanged",
"schema_permissions_configuration": "no schema/configuration/migration/grant changes; no new live comparison claimed",
"active_data_writes": false,
"new_accounts": false,
"new_imports_or_publication": false,
"remote_operations": false,
"Songo_Gurue_SGF_TEMPO": "untouched"
},
"cases": [
{
"name": "payable",
"status": "payable",
"balance": {
"numerator": "688",
"denominator": "1"
},
"economicDeduction": {
"numerator": "12",
"denominator": "1"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "combined",
"status": "payable",
"balance": {
"numerator": "538",
"denominator": "1"
},
"economicDeduction": {
"numerator": "12",
"denominator": "1"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "quota",
"status": "payable",
"balance": {
"numerator": "695",
"denominator": "1"
},
"economicDeduction": {
"numerator": "5",
"denominator": "1"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "prior-use",
"status": "payable",
"balance": {
"numerator": "691",
"denominator": "1"
},
"economicDeduction": {
"numerator": "9",
"denominator": "1"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "duplicate",
"status": "indeterminate",
"balance": null,
"economicDeduction": null,
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "missing-gross-up",
"status": "indeterminate",
"balance": null,
"economicDeduction": null,
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "article40",
"status": "indeterminate",
"balance": null,
"economicDeduction": null,
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "shared-paper",
"status": "payable",
"balance": {
"numerator": "688",
"denominator": "1"
},
"economicDeduction": {
"numerator": "12",
"denominator": "1"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "partial-parcel",
"status": "indeterminate",
"balance": null,
"economicDeduction": null,
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "fractional",
"status": "payable",
"balance": {
"numerator": "349997",
"denominator": "500"
},
"economicDeduction": {
"numerator": "3",
"denominator": "500"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
},
{
"name": "recoverable",
"status": "recoverable",
"balance": {
"numerator": "-500",
"denominator": "1"
},
"economicDeduction": {
"numerator": "12",
"denominator": "1"
},
"apiRecovered": true,
"recalculationEqual": true,
"html": true,
"dossier": true,
"frozenHistoryPreserved": true
}
],
"remaining": {
"economic": [
"automatic inclusion/correction of distributed profits and53 addition in L6",
"automatic proportional ceiling derivation and complete40(1) exclusion treatment at base stage",
"liquidation64(3),associations64(4),special-period and other-currency cases"
],
"other_L8": [
"specific benefit credits and their qualification,cumulation and limits",
"automatic international national-fraction and case-specific treaty matching",
"PPC/PEC obligation/calendar,interest/penalties and payment guides with applicable edition",
"autonomous taxation,special periods,other currencies and M20/M22 transport/submission",
"exceptional/transitional interyear cases beyond accepted ordinary carry scope"
]
},
"L8_complete": false,
"evidence": {
"api-result.json": "124fd50cb6d223cdd18fedc166d00af7254199b6e6dedf9be82f71db87af6d01",
"api.log": "e5cb58ba25c82feb1a14a8259cd112a58455b8cc1c17d8540b08ec30b87583c7",
"build-result.json": "256bb54e1d47ec73de37810b9673f10464c65fb970ea3b7ae28bbea36ba222e3",
"build.log": "69f17893b47b8d748651933f6a88a5f4206d58173397c1695d58472db9a26cf6",
"existing-records-preservation.json": "b45b3306d3c9dee63fbbaf9a04bba31008019e65892bd16322460b5ef53eda7d",
"frontend-result.json": "f73293b96cda7c81c86a6716a04a18d632e10361bf7d3f616695dbdc7695aeb0",
"frontend.log": "ff784389cda3f2c232f4760f74c053bc16b6d134ef975d0aad13132373e5e275",
"pint-result.json": "124fd50cb6d223cdd18fedc166d00af7254199b6e6dedf9be82f71db87af6d01",
"pint.log": "cd1a94fc2cf6a965b86e1a4809d6c7fb9148b1ee374e1010ed2ac96ff4876ec2",
"protected-consumers.json": "172542788e44fe604ca90d95a71d87f47a3baeae0c61950bc50d342658aa82ad",
"recovered-report-receipt.json": "ecce91a9c00c3a88d234486c020b5aa1681928eb1b1aeaeef0e7a569a2e17654",
"source-preservation.json": "6aceebe1cf883ca709ccbbbef7f2a756ee5dc51c12b3281c3659e83abfd90b70",
"types-result.json": "256bb54e1d47ec73de37810b9673f10464c65fb970ea3b7ae28bbea36ba222e3",
"types.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"qa_commit": "aae67c169dc0d14f95cf2ee6fa28e5ff05341dcf",
"qa_branch_pushed": false,
"grouped_delivery_manifest": "outputs/irpc-l8-economic-20261028/grouped-delivery-prepared.json"
}
@@ -0,0 +1,793 @@
{
"date": "2026-10-28",
"status": "installed_and_verified",
"served_commit": "569a1cd750f3d2a0b87f130e992e73e070bbd1ab",
"previous_commit": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"accepted_QA": {
"economic": "aae67c169dc0d14f95cf2ee6fa28e5ff05341dcf",
"carry": "d134a92d169f9159a692ed158e3a051889f7ab3a"
},
"scope": {
"economic": {
"current_year": "2026",
"current_period": "calendar year, resident general",
"currency": "documented MZN; exact fractions without fiscal rounding",
"profit_kind": "ordinary distributions art64(1–2)",
"eligibility": "same-country seat/effective management; payer subject to IRPC and nonexempt; nonapplication of40(1) documented, including2009 version",
"nominal_credit": "60 percent of documented IRPC corresponding to included distributed profits; no assumed rate on net dividend",
"gross_up": "expected nominal60 percent reconciled with53(1)a amount already included in current L6; does not overwrite or recalculate source base",
"proportional_ceiling": "case-specific documented input tied to current assessment; not automatically derived",
"prior_use": "actual documented economic credit use, distinct from simulation history and prior source-tax attributions",
"order": [
"economic credit up to collecta",
"international credit current/prior according to existing explicit selection",
"PEC current/prior according to existing explicit selection",
"own withholdings and PPC"
],
"refund": "no economic-credit refund or carry created; PPC can create simulated recoverable balance"
},
"carry": {
"year": "2026",
"subject": "same subject, resident general",
"period": "annual ordinary origins; calendar-year current close",
"currency": "documented MZN; exact foreign-credit fractions supported",
"international": "eligible origin credit minus origin deduction and documented actual later uses; five subsequent exercises, art65(3)",
"pec": "actual PEC eligible origin minus origin deduction and actual later uses; three subsequent exercises, art66(1–2)",
"allocation": "explicit documented selection between current and prior exercises, confirmed against current assessment; no presumed FIFO or automatic reduction",
"expiry": "ordinary window ended excludes current deduction but keeps source and arithmetic historical remainder",
"origin_rules": "origin assessment, inclusion/limits/insufficient collection and applicable period documented; exceptional/transitional rules outside scope"
},
"grouped_example": "1408-12economic-8currentInternational-50priorInternational-200currentPEC-100priorPEC-500PPC=538MZN payable simulated",
"same_parcel_nonduplication": {
"stable_identity": "issuer/document/parcel; distribution identity also independent of source-tax document,date and row id",
"economic_vs_international": "same physical tax parcel cannot fund both credit natures",
"same_paper_different_tax": "supported distinct parcels can coexist; old proof without a parcel overlaps the whole paper until reconciled",
"capacity": "same proof parcel amounts and prior attributions must agree and total allocation remains within available amount across snapshot contexts",
"L5": "existing withholding source/allocation checks preserved; parcel relabelling cannot turn repeated L5 use into new tax",
"partial_information": "saved and recovered as indeterminate, never reset or silently assumed absent",
"global_official_account_reconciliation": false
}
},
"compatibility": {
"main_normal_fast_forward": true,
"force_used": false,
"runtime_files_identical_to_accepted_QA": true,
"runtime_delta": [
{
"file": "resources/js/components/fiscal-proof-parcel.tsx",
"before_sha256": null,
"after_sha256": "9712108707e20c60ed625b296aa8cec92a6ce1b7f6af5c51355d52b6b08a4f7a"
},
{
"file": "resources/js/components/simulation-irpc-annual.tsx",
"before_sha256": "307725306df321fc89caf3d1a9efcf7463bb93d9d515d44347f8e14d4fd3136b",
"after_sha256": "75176ae721b88f2686987be5b499bf8909fc1d958a497bfdffde8ae22fca9586"
},
{
"file": "resources/js/components/simulation-irpc-carry.tsx",
"before_sha256": null,
"after_sha256": "020e2c26643b8b0dcf31d673db55217a7285b2187bdb8abf020bdfc6cc78e868"
},
{
"file": "resources/js/components/simulation-irpc-economic.tsx",
"before_sha256": null,
"after_sha256": "57a019d4359f0ee119d9d52202104ca846518b1bfba2bfb8fddb769c168ecd44"
},
{
"file": "resources/js/components/simulation-irpc-international.tsx",
"before_sha256": "6a9f796cc1e678823ed1dc14fbc28ca0e270752b2650518de239424dc75d167c",
"after_sha256": "64b6077bfb673b918476f923a045d39cfde73c07aca2ae066772a24bef9a396d"
},
{
"file": "resources/js/components/simulation-irpc-pec.tsx",
"before_sha256": "c3f0ea9ff9389cf856ecda3894c7a1486f44193eb893c341ef10c67f888a2fc6",
"after_sha256": "d0bba7015521d9d143c819e4203e03cf2f6d076093f5cd29deb96c3a11fc6aa1"
},
{
"file": "resources/js/lib/fiscal-proof-parcel.ts",
"before_sha256": null,
"after_sha256": "9eb500a7be2e05f39203c5cebf86cd3c64bbace7a615b9b62161f34dbe4a63da"
},
{
"file": "resources/js/lib/irpc-annual-settlement.ts",
"before_sha256": "47d4167d0f80c649e6d89a586e0d206d2d2a12b8553a7e98be362ea56203a540",
"after_sha256": "ac2896dca3002b27bf5f6bfd2e670295dcfaa3dc24f77b8e52469ed551cb1877"
},
{
"file": "resources/js/lib/irpc-credit-carry.ts",
"before_sha256": null,
"after_sha256": "5e88833842304f8e8e580916e2be657c33ad1fc53b7d544fa453b51ea27004e1"
},
{
"file": "resources/js/lib/irpc-economic-credit.ts",
"before_sha256": null,
"after_sha256": "fa19b289cba504d3636d76b3232694327e63674c907305425c2043d847046af1"
},
{
"file": "resources/js/lib/irpc-international-credit.ts",
"before_sha256": "40b46fbaaff6071ce6a35fd82de586158bf1f58fae8f46bcf6e4ddbbf84287f1",
"after_sha256": "4fc68f1fbe0cb82ca01a3c30dcb505adb60eced1de92213260b9a5ea1711fe7b"
},
{
"file": "resources/js/lib/irpc-pec.ts",
"before_sha256": "eb40b0601b6a1a69a6e81ad210589cc8744d74c6ef65e12132de13a5fcd6a90e",
"after_sha256": "9715ba106fd44b9ef16a55f2e85c2169ad09413a75167990e78ee644556fa381"
}
],
"source_files_before": 1005,
"source_files_after": 1011,
"all_other_compared_sources_preserved": true,
"schema_configuration_routes_permissions_preserved": true,
"previous_accepted_receipts_and_frozen_history_preserved": true
},
"accepted_QA_reused": {
"economic_new_frontend_tests": 20,
"previous_affected_tests": 65,
"frontend_pass": 85,
"frontend_fail": 0,
"API_tests": 1,
"API_assertions": 210,
"API_cases": 11,
"database": "proactive_investment_20261027_test",
"loopback_port": 55441,
"API_transactions_rolled_back": true,
"recovered_cases_recalculated_with_HTML_and_dossier": 11,
"frozen_histories_preserved": true,
"typescript": "passed",
"build": "isolated QA, subprocess exit0, final component hashes recorded",
"PHP_formatting": "pint passed",
"new_browser_manual_proof": false,
"team_usability_evaluation": "unchanged; awaiting team feedback"
},
"backup": {
"stage": "/var/backups/investmoz-irpc-l8-grouped-20261028/backup",
"created_at": "2026-10-28T12:38:25Z",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "007cd1851d5bd51a54265ab99a342d6a312de06ef642fc42b38b7a5e771d4d9a",
"files_sha256": "cd81cc9421e1d324648c706d8e56cbb6ad8766eb13e9a1a9cfda87814388b51f",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "irpc_grouped_restore_20261028",
"port": 55441,
"source_dump_sha256": "007cd1851d5bd51a54265ab99a342d6a312de06ef642fc42b38b7a5e771d4d9a",
"active_database_writes": 0
},
"capacity_before": {
"checked_at_UTC": "2026-10-28T12:38:00.155432+00:00",
"installed": {
"status": "installed",
"commit": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"release": "/var/www/investmoz-homologacao/releases/838ad941a24ae76ec4bf91ccc3f92012668fe8cf-ca7817df",
"previous_release": "/var/www/investmoz-homologacao/releases/e182d1d79dc945f35d2079c6b8ca2ac93048cec3-e2a185b3",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/838ad941a24ae76ec4bf91ccc3f92012668fe8cf-ca7817df",
"release_revision": {
"commit": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"branch": "main",
"built_at": "2026-10-27T13:20:18.055286+00:00",
"manifest_sha256": "b873c14f3e0e43435fa8f67fa9a65ff8978123cd8792c5f7c2e0cf6f8f84a3b2"
},
"service": "MainPID=0\nExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"volumes": [
{
"path": "/var/www/investmoz-homologacao/releases",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 88808570880,
"available_inodes": 23523855,
"total_inodes": 29089792
},
{
"path": "/var/lib/investmoz-deploy",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 88808570880,
"available_inodes": 23523855,
"total_inodes": 29089792
},
{
"path": "/var/backups",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 88808570880,
"available_inodes": 23523855,
"total_inodes": 29089792
},
{
"path": "/tmp",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 88808570880,
"available_inodes": 23523855,
"total_inodes": 29089792
},
{
"path": "/var/lib/docker",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 88808570880,
"available_inodes": 23523855,
"total_inodes": 29089792
}
],
"free_bytes": 88808570880,
"existing_pipeline_minimum_bytes": 5368709120,
"observed_previous_backup_bytes": 175921269,
"same_partition_release_and_backup": true,
"space_guard_satisfied": true,
"current_release_entry_reference": 31327,
"inodes_available_vs_reference": true,
"inode_note": "Observed current release footprint for scale;no new arbitrary inode threshold. Capacity rechecked after fresh backup.",
"pipeline_sha256": "adec1c17654f3a8658b83b134f1e75f95391b235738552721906c3236e388604",
"active_writes": 0
},
"capacity_after_backup": {
"at": "2026-10-28T12:40:09.841070+00:00",
"baseline": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"capacity_after_backup_satisfied": true,
"volumes": [
{
"path": "/var/www/investmoz-homologacao/releases",
"free_bytes": 88629272576,
"free_inodes": 23523836
},
{
"path": "/var/lib/investmoz-deploy",
"free_bytes": 88629272576,
"free_inodes": 23523836
},
{
"path": "/var/backups",
"free_bytes": 88629272576,
"free_inodes": 23523836
},
{
"path": "/tmp",
"free_bytes": 88629272576,
"free_inodes": 23523836
},
{
"path": "/var/lib/docker",
"free_bytes": 88629272576,
"free_inodes": 23523836
}
],
"backup_age_seconds": 104.841034,
"backup_dump_sha256": "007cd1851d5bd51a54265ab99a342d6a312de06ef642fc42b38b7a5e771d4d9a",
"restore_verified": true,
"tables_verified": 174,
"files_verified": 369,
"backup_paths": {
"dump": "/var/backups/investmoz-irpc-l8-grouped-20261028/backup/database.dump",
"files": "/var/backups/investmoz-irpc-l8-grouped-20261028/backup/files-before.tar.gz"
},
"active_writes": 0
},
"schema_permissions": {
"schema_sha256": "5045b3e51d2185377aa3d9ac7fa07a44fad3ec620cdfa83ffe31c8884ee1601d",
"roles_grants_sha256": "5f0c554373e879fa9db81c3e746886a40a3c47875e6f41c61cfc0b3aee2dfd2b",
"filesystem_permissions": {
".env": {
"mode": 416,
"uid": 1001,
"gid": 33
},
"storage": {
"mode": 1533,
"uid": 1001,
"gid": 33
},
"storage/app": {
"mode": 1533,
"uid": 1001,
"gid": 33
},
"bootstrap/cache": {
"mode": 1528,
"uid": 1001,
"gid": 33
}
},
"comparison_identity": "postgres;catalogue read only;no passwords collected",
"unchanged": true
},
"preservation": {
"checked_at": "2026-10-28T12:47:37.401210+00:00",
"installed": "569a1cd750f3d2a0b87f130e992e73e070bbd1ab",
"business_tables_unchanged": 172,
"total_tables": 174,
"operational_tables_to_reconcile": {
"cache": {
"before": {
"rows": 110,
"checksum": "59099e8b28be3b1cd3b30a0be1b22519"
},
"after": {
"rows": 110,
"checksum": "832a86e7c4ccd6c9b5d725a45a63f2cb"
}
},
"sessions": {
"before": {
"rows": 2,
"checksum": "09d77c0790973a0ed80f9dbb177f186c"
},
"after": {
"rows": 4,
"checksum": "570c460243c35d5c20b2e700077c15b3"
}
}
},
"persistent_files_unchanged": 369,
"original_configuration_preserved": true,
"synthetic_QA_storage_not_served": true,
"QA_storage_saved_outside_active": "/var/lib/investmoz-deploy/qa-runtime/569a1cd750f3d2a0b87f130e992e73e070bbd1ab-53a57d6f",
"fixture_or_content_imports": 0,
"migrations": 0,
"comparison_identity": "postgres;UTC;consistent before snapshot and after read-only transaction",
"active_database_writes": 0
},
"operational_delta": {
"status": "operational_delta_reconciled",
"comparison_identity": "postgres before/after;isolated restored baseline;no RLS visibility inference",
"cache": "queue:restart;requestthrottle;identical home-sector cached value with refreshed expiry(HomeController remember10min);no deletedcache",
"sessions": "anonymous sessions from delivery user-agent or exactUA/time correlated with nginx public request;deleted sessions individually expired beyond configured lifetime,normal database session garbage collection(config/session lottery2/100)",
"delta": {
"cache": {
"before_rows": 110,
"after_rows": 110,
"changes": [
{
"key_sha256": "7f7dd83f47f5bf404d55e6e9f1367948721579970b195680645e356031a070ff",
"kind": "updated",
"fields": [
"value",
"expiration"
],
"key_pattern": "investemoz-cache-illuminate:queue:restart",
"is_queue_restart_key": true,
"expiration_unchanged": false,
"throttle_timer_pair": false,
"same_value_home_cache_expiry_refresh": false
}
]
},
"sessions": {
"before_rows": 2,
"after_rows": 4,
"changes": [
{
"key_sha256": "61ee61858f50dc6bb6b3c42a15ea2a158e29a8de51071570a48e245072f35647",
"kind": "added",
"fields": [
"id",
"ip_address",
"user_agent",
"payload",
"last_activity"
],
"anonymous_user": true,
"delivery_user_agent": true,
"expired_before_comparison": false,
"session_lifetime_minutes": 120,
"anonymous_public_request_logged": true
},
{
"key_sha256": "93d2f8d1f352499a4b04fe6ffe15ecd52738871794282140a78bfef2ad6ba80b",
"kind": "added",
"fields": [
"id",
"ip_address",
"user_agent",
"payload",
"last_activity"
],
"anonymous_user": true,
"delivery_user_agent": true,
"expired_before_comparison": false,
"session_lifetime_minutes": 120,
"anonymous_public_request_logged": true
}
]
}
},
"business_tables_to_confirm_separately": 172,
"active_data_writes_by_comparison": 0,
"restore_network": "none"
},
"installer": {
"service": "MainPID=0\nExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"installed": {
"status": "installed",
"commit": "569a1cd750f3d2a0b87f130e992e73e070bbd1ab",
"release": "/var/www/investmoz-homologacao/releases/569a1cd750f3d2a0b87f130e992e73e070bbd1ab-53a57d6f",
"previous_release": "/var/www/investmoz-homologacao/releases/838ad941a24ae76ec4bf91ccc3f92012668fe8cf-ca7817df",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "569a1cd750f3d2a0b87f130e992e73e070bbd1ab",
"release": "/var/www/investmoz-homologacao/releases/569a1cd750f3d2a0b87f130e992e73e070bbd1ab-53a57d6f",
"previous_release": "/var/www/investmoz-homologacao/releases/838ad941a24ae76ec4bf91ccc3f92012668fe8cf-ca7817df",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"569a1cd750f3d2a0b87f130e992e73e070bbd1ab"
],
"finished_at": "2026-10-28T12:44:28.780095+00:00"
},
"log_file": "1793191252185211711.log",
"mandatory_summaries": [
"OK (1 test, 3106 assertions)",
"✓ built in 30.82s",
"OK (59 tests, 317 assertions)",
"# tests 1146",
"# pass 1146",
"# fail 0"
]
},
"public_delta": {
"phase": "after",
"revision": {
"commit": "569a1cd750f3d2a0b87f130e992e73e070bbd1ab",
"branch": "main",
"built_at": "2026-10-28T12:44:25.642859+00:00",
"manifest_sha256": "9cb557f62c0dbe49ec87d7ccb532f6c7dc29fc980658ffc51ff024755c26f186"
},
"manifest_verified": true,
"simulator_HTTP": 200,
"simulator_component": "portal/services",
"active_QA_records_created": false,
"compiled_markers": {
"IRPC-credit-carry/1": [
"assets/project-dossier-BUI-Tqnq.js"
],
"IRPC-economic-credit/1": [
"assets/project-dossier-BUI-Tqnq.js"
],
"Preparar saldos anteriores": [
"assets/services-DOMV1YET.js"
],
"Preparar crédito económico": [
"assets/services-DOMV1YET.js"
],
"Crédito económico — antes do internacional": [
"assets/project-dossier-BUI-Tqnq.js"
],
"Confirmar afectação à colecta seleccionada": [
"assets/services-DOMV1YET.js"
],
"IRPC-international-credit/1": [
"assets/project-dossier-BUI-Tqnq.js"
],
"IRPC-PEC/1": [
"assets/project-dossier-BUI-Tqnq.js"
]
}
},
"remote_backup": "/var/backups/investmoz-irpc-l8-grouped-20261028/backup",
"remote_receipt": "/var/backups/investmoz-irpc-l8-grouped-20261028/installed-receipt.json",
"remaining": {
"economic": [
"automatic inclusion/correction of distributed profits and53 addition in L6",
"automatic proportional ceiling derivation and complete40(1) exclusion treatment at base stage",
"liquidation64(3),associations64(4),special-period and other-currency cases"
],
"other_L8": [
"specific benefit credits and their qualification,cumulation and limits",
"automatic international national-fraction and case-specific treaty matching",
"PPC/PEC obligation/calendar,interest/penalties and payment guides with applicable edition",
"autonomous taxation,special periods,other currencies and M20/M22 transport/submission",
"exceptional/transitional interyear cases beyond accepted ordinary carry scope"
]
},
"L8_complete": false,
"limits": [
"No global annual IRPC closure claimed",
"No official tax-account balance consumed,submitted or refunded",
"Economic credit limited to ordinary documented current-year case;source inclusion/gross-up and proportional quota not automatically derived",
"Carry retains its documented ordinary-year scope;no exceptional/transitional rule inferred",
"No new manual team usability acceptance claimed",
"Songo/Gurue remain private;SGF TEMPO untouched;no active QA fixture/content imports"
],
"local_evidence_directory": "outputs/irpc-l8-grouped-delivery-20261028",
"local_artifacts": [
{
"file": "authenticate.ps1",
"sha256": "80109eafe4fe5c065debcb3ebf626638904f09c04450565b0be940a6372ddc1d",
"bytes": 214
},
{
"file": "backup.py",
"sha256": "f1e02236d97caaed537249dfc8c7a002c18bd8cc067af5bd11f94cc4dc1ad027",
"bytes": 5448
},
{
"file": "capacity-after.py",
"sha256": "9f1e2df54963469c670098b77392020f2719bb3f795cd04e5ecdad6f1fad1b84",
"bytes": 1621
},
{
"file": "compatibility-and-preservation-plan.json",
"sha256": "00e4f0b33e5ea46007c74a2d8a7976fec363baf5cace55063b764fa3fceb822a",
"bytes": 1160
},
{
"file": "git-main-delivery.json",
"sha256": "28c6503ad9229afdefd7f3466e7ab235417c1f2f7a7372ce269951db0657ef6f",
"bytes": 242
},
{
"file": "group-backup-20261028-response.json",
"sha256": "9860fd3a9f4c1abb5e9298965a604cfa5efc0198ee8069aaf7ed9844b2bf00d6",
"bytes": 606
},
{
"file": "group-backup-20261028.json",
"sha256": "f1e0096263b3b8a83401c3a83035e67e0c8f50e647030812811fe1b1700c6dea",
"bytes": 437
},
{
"file": "group-capacity-after-20261028-response.json",
"sha256": "ce5b65cc2e31b9f938dac177d0420baaca6ad2df95e417c43e6fd79b474bc2d5",
"bytes": 1394
},
{
"file": "group-capacity-after-20261028.json",
"sha256": "0d63c97cecd57683cd4046f3d327d489a966b67508e5f8c54c5829da85e8e869",
"bytes": 1200
},
{
"file": "group-operational-20261028-response.json",
"sha256": "d7ca760c85a2deb24084167701aafb389bcd0a807c95bce5a6a9cddd4f6480ff",
"bytes": 2483
},
{
"file": "group-operational-20261028.json",
"sha256": "dd0476edc7212ca0cc25646441c7f73aa5e406201563070e9adb3930751d21b6",
"bytes": 2434
},
{
"file": "group-preflight-20261028-response.json",
"sha256": "b98a6d1970dc4f681e99c8500e863b24dc30bafe3d536d256183924911c2da6c",
"bytes": 3029
},
{
"file": "group-preflight-20261028.json",
"sha256": "5f70b0af720beb1199c09cb21118a6d13f47e07ab55f4eeef3ae969ad1fcac14",
"bytes": 2595
},
{
"file": "group-preserve-20261028-response.json",
"sha256": "9f96f52a494c5d29702cc9abd1ace94d314a8cda54281ec6ac1b810efc6b8c50",
"bytes": 1324
},
{
"file": "group-preserve-20261028.json",
"sha256": "f655c23059156461f49200a419fafffdf0cecab62df99b5995bcab59eaf7e7de",
"bytes": 1137
},
{
"file": "group-progress-a1-20261028-response.json",
"sha256": "b968fa1a79f043c1b2f9440e7e1828eea466c7b77e45c8f66dec47cc59202305",
"bytes": 2715
},
{
"file": "group-progress-a1-20261028.json",
"sha256": "8f3cd7de2b9c10ea72a04783f2740301a96f641f07189515c386908aad7bf139",
"bytes": 2294
},
{
"file": "group-progress-a2-20261028-response.json",
"sha256": "05432b187845dd4ea7ba3a966fea54023877c7bc0cb1c5721539f9591b8c174d",
"bytes": 1567
},
{
"file": "group-progress-a2-20261028.json",
"sha256": "19ee1ec59ed4d91487a765c079cb042d84e70d8c6f575385425132832f4a8f88",
"bytes": 1247
},
{
"file": "group-restore-20261028-response.json",
"sha256": "4ce2051902d1c00d04bef1f34fd88671c0be6b5b65228d4c13271bb541453a0f",
"bytes": 427
},
{
"file": "group-restore-20261028.json",
"sha256": "aa3a90c80a037d4977988d7d9935a52f226b25ea414e54012446e528b69769c2",
"bytes": 282
},
{
"file": "group-schema-after-20261028-response.json",
"sha256": "740062552f5a4747fc0151ab32956774f8cb8cef6be6fef116a9c8b0505db67c",
"bytes": 772
},
{
"file": "group-schema-after-20261028.json",
"sha256": "265a0f0bb3b8e8232c8a8f2f72802664091ff8f9127e7a3868694f1373fc7b51",
"bytes": 668
},
{
"file": "group-schema-before-20261028-response.json",
"sha256": "ba122cba99109784b22699391efc6359c53d17e44dbe4bb14184389589cb0d80",
"bytes": 745
},
{
"file": "group-schema-before-20261028.json",
"sha256": "8c171cfaae6feef78fbd43f8046ffb62c1daad9a258d95e6df43d20ba4b335c4",
"bytes": 646
},
{
"file": "group-source-after-20261028-response.json",
"sha256": "be446ca8152ea5d940a8650d38fc8d141ee94cebafab8406d7c33b9a97cb6b4f",
"bytes": 284
},
{
"file": "group-source-after-20261028.json",
"sha256": "f9a457698c36c0e433ff5c10956cef3f4548534ae0a9d8718a03af2f3101360b",
"bytes": 165
},
{
"file": "group-source-before-20261028-response.json",
"sha256": "e2f155845283962a0729a295856d0ba0b631530faa40074c317a57b90836e1b5",
"bytes": 285
},
{
"file": "group-source-before-20261028.json",
"sha256": "3383b6c77419378eac7fb078dad3e57989a8def0965c29477f0a827e1972a67c",
"bytes": 166
},
{
"file": "group-status-a1-20261028-response.json",
"sha256": "860ba2f40d709ff491113c54cd253926adb0b21e22179b02e978a388ef6e2bc9",
"bytes": 1809
},
{
"file": "group-status-a1-20261028.json",
"sha256": "38c718738dad722e06069993894ad9eba2f61b946d6e2042cfbc33e6d1c6aa10",
"bytes": 1442
},
{
"file": "group-status-a2-20261028-response.json",
"sha256": "2f6815214d9b0240cc298f78b7838fd2b7061333e4cfda1ecab2779a688be130",
"bytes": 2117
},
{
"file": "group-status-a2-20261028.json",
"sha256": "328e6fc9e8ce7f488e83c9c7154472f76cacf08381ad48ea38af8c6139317b7f",
"bytes": 1706
},
{
"file": "group-status-a3-20261028-response.json",
"sha256": "a9af2b8c3c53341a0dbc030ceaa984818af1710b9be1f13437026093edc9b9ea",
"bytes": 2117
},
{
"file": "group-status-a3-20261028.json",
"sha256": "e79288f392bd00c31059031c653ba703a4546d853945f0859f426bbccb8f381d",
"bytes": 1706
},
{
"file": "group-status-final-20261028-response.json",
"sha256": "1e54588459017ee079eae4759d07cf4629287f053df50679fcf4026052696a9c",
"bytes": 2220
},
{
"file": "group-status-final-20261028.json",
"sha256": "dca34a8237f9d019d3f36976668dd8b4a86e492e3d29c3eac8294c0d5294edee",
"bytes": 1795
},
{
"file": "pipeline-progress.py",
"sha256": "848be5b9c462802395e2944fb30487407d86668ff27640125885994acdd4c241",
"bytes": 1006
},
{
"file": "preflight.py",
"sha256": "92113ce782cc6cce88e3146dcc34363ad21d888f83b26b4e5a0d26fbf60e640f",
"bytes": 2338
},
{
"file": "preparation.json",
"sha256": "47007bfe846aa9e22dc723b320e4a580396e413a75bb846c44c9cfda60ad84eb",
"bytes": 251405
},
{
"file": "preserve-data.py",
"sha256": "e56d27b726c5e710b9bd5721d729cc019d57011b2ea1e2699fee6685f1f1bfbd",
"bytes": 2304
},
{
"file": "public-after.json",
"sha256": "db39a1bd518eddcc4b23ee1fa28ae7a06d51e289d549790cfb64b04100976b6b",
"bytes": 1149
},
{
"file": "public-before.json",
"sha256": "05a748e8a0f08ba438026f4e53c2d8260586c93061748ad3428188afe86e9b2a",
"bytes": 414
},
{
"file": "reconcile-operational-delta.py",
"sha256": "1ad5c3663364e59d54bfaff2a0686b43fe7d658f5445076f670fb9aa69c1321c",
"bytes": 5336
},
{
"file": "remote_delivery_inspection.py",
"sha256": "7c95ba88a9d5a62a15ec2bf581fa62f5151e548014d106f081487889e56b2703",
"bytes": 1947
},
{
"file": "restore.py",
"sha256": "dcb4952f56d2524f36bc4b24164f8041f99de8e98d461bd40bafbb5102c28349",
"bytes": 2792
},
{
"file": "rpc.py",
"sha256": "9c9ebe126d345d20ab46a07469f41bac3e76dbfbcdb64ac32606796c9c0f9520",
"bytes": 1650
},
{
"file": "schema-permissions-after.py",
"sha256": "44fd24feb568ca5b9488c923fbd3967756c0fbb2e6fee4016f6c0272c536cac1",
"bytes": 1862
},
{
"file": "schema-permissions-before.py",
"sha256": "d17fbac06b88b189171da56ea2d4e501eae331a39bd78c14cbd3fc65d19e59c4",
"bytes": 1705
},
{
"file": "source-after-input.json",
"sha256": "3716126155fcff9b74fb34c408b57bc7b9482e62ed1b3f29dfd994d1c894f11a",
"bytes": 240716
},
{
"file": "source-before-input.json",
"sha256": "8ca115700b7df7db7b306d7a0ff1063a54716977465674a31d5d2cd588d8f2e2",
"bytes": 240717
},
{
"file": "source-check.py",
"sha256": "1cec620043b013e6b6f79b9f67e4e5588117d91ee7dc0c93592fc6b8d6d0557f",
"bytes": 676
},
{
"file": "ssh-session.py",
"sha256": "e81df6aae12e03b0faac33e03108ef6dcdc5c0d3598538c4db5bb4bb65e9f3f4",
"bytes": 3084
},
{
"file": "status.py",
"sha256": "41d3a13211c4d4725178477aa48e10f27fe313f41a2b33e555f7ae04a8a14bdd",
"bytes": 1204
},
{
"file": "store-receipt.py",
"sha256": "9c671b6019c7fd80df91c9af795b16a8a80c119a79877ad6cf57c8fea436ef9c",
"bytes": 864
},
{
"file": "update-existing-docs.py",
"sha256": "e088143d2e3e24390b36c5a08dd3312537b2b3f5778633c8086fcbdde00b2b60",
"bytes": 1478
},
{
"file": "verify-public.py",
"sha256": "f6b5ad42ead0f6a7f2ddcb6f16a648293ad5eba1001b591dc32f4ddfa4f68f00",
"bytes": 2107
}
]
}
@@ -0,0 +1,722 @@
{
"date": "2026-10-27",
"status": "installed_and_verified",
"served_commit": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"accepted_qa": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"previous_commit": "e182d1d79dc945f35d2079c6b8ca2ac93048cec3",
"sector_fix_preserved": "669cb8979b0c372659fc2ad3876aebc919d5df19",
"scope": {
"year": "2026",
"resident": "general",
"period": "calendar year",
"currency": "documented MZN",
"foreign_tax": "actual income tax paid; inclusion in taxable base documented",
"national_fraction": "documented exact input, not automatically derived",
"treaty": "case-specific applicability and ceiling documented, not inferred from country",
"order": [
"international credit limited to eligible available amount and collection",
"PEC limited to remaining collection",
"withholdings and PPC"
],
"known_absent_missing_distinct": true,
"proof_deduplication": "issuer/document across tax natures, dates and snapshot contexts; consolidate country-year quota",
"officialBalancesConsumed": false,
"carryCreated": false
},
"example": {
"foreign_tax_paid": "10 MZN",
"documented_national_limit": "8 MZN",
"documented_treaty_nonapplication": "synthetic only, not actual country entitlement",
"credit": "8 MZN",
"calculation": "1408 - 8 = 1400; - PEC200 = 1200; - PPC500 = 700 MZN simulated payable",
"above_eligibility_limit": "2 MZN, not a carry",
"insufficient_collection_example": "available2000, deducted1408, insufficient592; PEC200 not deducted; recoverable500 derives from PPC only"
},
"accepted_QA_reused": {
"frontend_new": 18,
"frontend_affected_annual_pec": 31,
"api_assertions": 171,
"recovered_HTML_dossier_cases": 7
},
"cases": [
{
"name": "payable",
"status": "payable",
"balance": {
"numerator": "700",
"denominator": "1"
},
"current": true,
"history_records": 0,
"apiRoundTrip": true,
"dossier": true
},
{
"name": "treaty",
"status": "payable",
"balance": {
"numerator": "702",
"denominator": "1"
},
"current": true,
"history_records": 1,
"apiRoundTrip": true,
"dossier": true
},
{
"name": "missing",
"status": "indeterminate",
"balance": null,
"current": true,
"history_records": 1,
"apiRoundTrip": true,
"dossier": true
},
{
"name": "limited-collecta",
"status": "recoverable",
"balance": {
"numerator": "-500",
"denominator": "1"
},
"current": true,
"history_records": 1,
"apiRoundTrip": true,
"dossier": true
},
{
"name": "duplicate",
"status": "indeterminate",
"balance": null,
"current": true,
"history_records": 1,
"apiRoundTrip": true,
"dossier": true
},
{
"name": "absent",
"status": "payable",
"balance": {
"numerator": "708",
"denominator": "1"
},
"current": true,
"history_records": 1,
"apiRoundTrip": true,
"dossier": true
},
{
"name": "prior-use",
"status": "payable",
"balance": {
"numerator": "703",
"denominator": "1"
},
"current": true,
"history_records": 1,
"apiRoundTrip": true,
"dossier": true
}
],
"compatibility": {
"fast_forward_over": "e182d1d79dc945f35d2079c6b8ca2ac93048cec3",
"runtime_files_byte_identical_to_accepted_QA": true,
"runtime_delta": [
{
"file": "resources/js/components/simulation-irpc-annual.tsx",
"before_sha256": "7f18abcaa1100251c5c2780fdfac32e21979d8e6ffed52f732e4a0d345ab4f40",
"after_sha256": "307725306df321fc89caf3d1a9efcf7463bb93d9d515d44347f8e14d4fd3136b"
},
{
"file": "resources/js/components/simulation-irpc-international.tsx",
"before_sha256": null,
"after_sha256": "6a9f796cc1e678823ed1dc14fbc28ca0e270752b2650518de239424dc75d167c"
},
{
"file": "resources/js/lib/country-iso-codes.ts",
"before_sha256": null,
"after_sha256": "1c4e2b6d67457ea2dba3dda28a9b6ce09242c36dfcf04855a8bc1f44506a9fac"
},
{
"file": "resources/js/lib/irpc-annual-settlement.ts",
"before_sha256": "6d80889677c1904b3236b5e43fa5a3dc28327745679392529dfb5fbf5a273f7d",
"after_sha256": "47d4167d0f80c649e6d89a586e0d206d2d2a12b8553a7e98be362ea56203a540"
},
{
"file": "resources/js/lib/irpc-international-credit.ts",
"before_sha256": null,
"after_sha256": "40b46fbaaff6071ce6a35fd82de586158bf1f58fae8f46bcf6e4ddbbf84287f1"
}
],
"all_other_compared_sources_unchanged": true,
"schema_config_routes_permissions_unchanged": true,
"legacy_annual_and_PEC_history_preserved": true,
"no_new_manual_retest_of_independent_accepted_proofs": true
},
"source_files_verified": {
"before": 1002,
"after": 1005
},
"backup": {
"stage": "/var/backups/investmoz-irpc-l8-international-20261027/backup",
"created_at": "2026-10-27T13:15:39Z",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "b1e9740653a8664c23268e228efd3ed6a0514bf3e8786dd5adf43342cdb475e1",
"files_sha256": "9d3a790f9c7f4a35ebf660d304e92d69f86557d20d2f8be1e996c828711b19ac",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "irpc_international_restore_20261027",
"port": 55441,
"source_dump_sha256": "b1e9740653a8664c23268e228efd3ed6a0514bf3e8786dd5adf43342cdb475e1",
"active_database_writes": 0
},
"capacity_before": {
"checked_at_UTC": "2026-10-27T13:15:02.501911+00:00",
"installed": {
"status": "installed",
"commit": "e182d1d79dc945f35d2079c6b8ca2ac93048cec3",
"release": "/var/www/investmoz-homologacao/releases/e182d1d79dc945f35d2079c6b8ca2ac93048cec3-e2a185b3",
"previous_release": "/var/www/investmoz-homologacao/releases/669cb8979b0c372659fc2ad3876aebc919d5df19-6a2f00c6",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/e182d1d79dc945f35d2079c6b8ca2ac93048cec3-e2a185b3",
"release_revision": {
"commit": "e182d1d79dc945f35d2079c6b8ca2ac93048cec3",
"branch": "main",
"built_at": "2026-10-27T12:10:18.923517+00:00",
"manifest_sha256": "47bbdd09864d0587133deec179781018e439f9c83b7b328c9dcd52482eaf6d31"
},
"service": "MainPID=0\nExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"volumes": [
{
"path": "/var/www/investmoz-homologacao/releases",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 92293206016,
"available_inodes": 23699087,
"total_inodes": 29089792
},
{
"path": "/var/lib/investmoz-deploy",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 92293206016,
"available_inodes": 23699087,
"total_inodes": 29089792
},
{
"path": "/var/backups",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 92293206016,
"available_inodes": 23699087,
"total_inodes": 29089792
},
{
"path": "/tmp",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 92293206016,
"available_inodes": 23699087,
"total_inodes": 29089792
},
{
"path": "/var/lib/docker",
"mount": "/dev/md2 / ext4",
"device": 2306,
"available_bytes": 92293206016,
"available_inodes": 23699087,
"total_inodes": 29089792
}
],
"free_bytes": 92293206016,
"existing_pipeline_minimum_bytes": 5368709120,
"observed_previous_backup_bytes": 175920446,
"same_partition_release_and_backup": true,
"space_guard_satisfied": true,
"current_release_entry_reference": 31315,
"inodes_available_vs_reference": true,
"inode_note": "Observed current release footprint for scale;no new arbitrary inode threshold. Capacity rechecked after fresh backup.",
"pipeline_sha256": "adec1c17654f3a8658b83b134f1e75f95391b235738552721906c3236e388604",
"active_writes": 0
},
"capacity_after_backup": {
"at": "2026-10-27T13:16:13.360261+00:00",
"baseline": "e182d1d79dc945f35d2079c6b8ca2ac93048cec3",
"capacity_after_backup_satisfied": true,
"volumes": [
{
"path": "/var/www/investmoz-homologacao/releases",
"free_bytes": 92114915328,
"free_inodes": 23699075
},
{
"path": "/var/lib/investmoz-deploy",
"free_bytes": 92114915328,
"free_inodes": 23699075
},
{
"path": "/var/backups",
"free_bytes": 92114915328,
"free_inodes": 23699075
},
{
"path": "/tmp",
"free_bytes": 92114915328,
"free_inodes": 23699075
},
{
"path": "/var/lib/docker",
"free_bytes": 92114915328,
"free_inodes": 23699075
}
],
"backup_age_seconds": 34.36022,
"backup_dump_sha256": "b1e9740653a8664c23268e228efd3ed6a0514bf3e8786dd5adf43342cdb475e1",
"restore_verified": true,
"tables_verified": 174,
"files_verified": 369,
"backup_paths": {
"dump": "/var/backups/investmoz-irpc-l8-international-20261027/backup/database.dump",
"files": "/var/backups/investmoz-irpc-l8-international-20261027/backup/files-before.tar.gz"
},
"active_writes": 0
},
"schema_permissions": {
"schema_sha256": "5045b3e51d2185377aa3d9ac7fa07a44fad3ec620cdfa83ffe31c8884ee1601d",
"roles_grants_sha256": "1530c33cb016e67bfdc64891ddfce7f185b13b56b2cd87c012871a685e118109",
"filesystem_permissions": {
".env": {
"mode": 416,
"uid": 1001,
"gid": 33
},
"storage": {
"mode": 1533,
"uid": 1001,
"gid": 33
},
"storage/app": {
"mode": 1533,
"uid": 1001,
"gid": 33
},
"bootstrap/cache": {
"mode": 1528,
"uid": 1001,
"gid": 33
}
},
"comparison_identity": "postgres;catalogue read only;no passwords collected",
"unchanged": true
},
"preservation": {
"checked_at": "2026-10-27T13:21:25.836367+00:00",
"installed": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"business_tables_unchanged": 172,
"total_tables": 174,
"operational_tables_to_reconcile": {
"cache": {
"before": {
"rows": 108,
"checksum": "c5e94e4bb71bf085e36447c1da35696e"
},
"after": {
"rows": 108,
"checksum": "ddbdb9e11a50777bd84bc353d178608a"
}
},
"sessions": {
"before": {
"rows": 53,
"checksum": "fe52dca3e79f71d1f5a3bd474c7d72d1"
},
"after": {
"rows": 55,
"checksum": "359f4b80ea80b807a1f3a50687fe2309"
}
}
},
"persistent_files_unchanged": 369,
"original_configuration_preserved": true,
"synthetic_QA_storage_not_served": true,
"QA_storage_saved_outside_active": "/var/lib/investmoz-deploy/qa-runtime/838ad941a24ae76ec4bf91ccc3f92012668fe8cf-ca7817df",
"fixture_or_content_imports": 0,
"migrations": 0,
"comparison_identity": "postgres;UTC;consistent before snapshot and after read-only transaction",
"active_database_writes": 0
},
"operational_delta": {
"status": "operational_delta_reconciled",
"comparison_identity": "postgres before/after;isolated restored baseline;no RLS visibility inference",
"cache": "queue:restart;requestthrottle;identical home-sector cached value with refreshed expiry(HomeController remember10min);no deletedcache",
"sessions": "anonymous sessions from delivery user-agent or exactUA/time correlated with nginx public request;deleted sessions individually expired beyond configured lifetime,normal database session garbage collection(config/session lottery2/100)",
"delta": {
"cache": {
"before_rows": 108,
"after_rows": 108,
"changes": [
{
"key_sha256": "7f7dd83f47f5bf404d55e6e9f1367948721579970b195680645e356031a070ff",
"kind": "updated",
"fields": [
"value",
"expiration"
],
"key_pattern": "investemoz-cache-illuminate:queue:restart",
"is_queue_restart_key": true,
"expiration_unchanged": false,
"throttle_timer_pair": false,
"same_value_home_cache_expiry_refresh": false
}
]
},
"sessions": {
"before_rows": 53,
"after_rows": 55,
"changes": [
{
"key_sha256": "cc9234289e8c94733fb352f52407a2863d547165e1ee7f6eb4523c1ed7b33c1a",
"kind": "added",
"fields": [
"id",
"ip_address",
"user_agent",
"payload",
"last_activity"
],
"anonymous_user": true,
"delivery_user_agent": true,
"expired_before_comparison": false,
"session_lifetime_minutes": 120,
"anonymous_public_request_logged": true
},
{
"key_sha256": "dbf3b24ccc55e4bf0a14aad872309de7d890942acb4f68b0c1ec608ff5e49035",
"kind": "added",
"fields": [
"id",
"ip_address",
"user_agent",
"payload",
"last_activity"
],
"anonymous_user": true,
"delivery_user_agent": true,
"expired_before_comparison": false,
"session_lifetime_minutes": 120,
"anonymous_public_request_logged": true
}
]
}
},
"business_tables_to_confirm_separately": 172,
"active_data_writes_by_comparison": 0,
"restore_network": "none"
},
"installer": {
"service": "MainPID=0\nExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"installed": {
"status": "installed",
"commit": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"release": "/var/www/investmoz-homologacao/releases/838ad941a24ae76ec4bf91ccc3f92012668fe8cf-ca7817df",
"previous_release": "/var/www/investmoz-homologacao/releases/e182d1d79dc945f35d2079c6b8ca2ac93048cec3-e2a185b3",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"release": "/var/www/investmoz-homologacao/releases/838ad941a24ae76ec4bf91ccc3f92012668fe8cf-ca7817df",
"previous_release": "/var/www/investmoz-homologacao/releases/e182d1d79dc945f35d2079c6b8ca2ac93048cec3-e2a185b3",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"838ad941a24ae76ec4bf91ccc3f92012668fe8cf"
],
"finished_at": "2026-10-27T13:20:20.796156+00:00"
},
"log_file": "1793107006281021543.log",
"log_bytes": 313361,
"mandatory_summaries": [
"OK (1 test, 3106 assertions)",
"✓ built in 31.55s",
"OK (59 tests, 317 assertions)",
"# tests 1110",
"# pass 1110",
"# fail 0"
]
},
"public_delta": {
"phase": "after",
"revision": {
"commit": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"branch": "main",
"built_at": "2026-10-27T13:20:18.055286+00:00",
"manifest_sha256": "b873c14f3e0e43435fa8f67fa9a65ff8978123cd8792c5f7c2e0cf6f8f84a3b2"
},
"manifest_verified": true,
"simulator_HTTP": 200,
"simulator_component": "portal/services",
"active_QA_records_created": false,
"compiled_markers": {
"IRPC-international-credit/1": [
"assets/project-dossier-bSv3Ugr2.js"
],
"Preparar crédito internacional": [
"assets/services-YUy8XgPr.js"
],
"Vincular inclusão e limites ao país": [
"assets/services-YUy8XgPr.js"
],
"Crédito internacional — antes do PEC": [
"assets/project-dossier-bSv3Ugr2.js"
],
"Não determina a fracção nacional": [
"assets/project-dossier-bSv3Ugr2.js"
],
"IRPC-PEC/1": [
"assets/project-dossier-bSv3Ugr2.js"
]
}
},
"remote_backup": "/var/backups/investmoz-irpc-l8-international-20261027/backup",
"remote_receipt": "/var/backups/investmoz-irpc-l8-international-20261027/installed-receipt.json",
"limits": [
"L8 partial",
"no new PEC excess/carry scope",
"no automatic foreign exchange or official rounding rule",
"no official tax balance consumption, submission or refund execution",
"same-snapshot deduplication is not a global inter-dossier official ledger",
"synthetic QA examples do not assert any actual foreign treaty",
"L8 partial after this bounded delivery",
"Songo/Gurue remain private; no QA fixture or content import into active data"
],
"remaining_code": [
"automatic national fraction and case-specific treaty matching",
"economic double-tax and CBF benefit credits with own rules",
"international carry/expiry65(3), separate from PEC66 carry/expiry",
"PPC/PEC obligation/calendar; autonomous tax, special periods, other currencies and M20/M22 transport/submission"
],
"document_dependencies": [
{
"missing": "income inclusion and national fraction",
"example": "tax10 but no included income/base correspondence",
"resume_when": "income/base and documented fraction matched"
},
{
"missing": "treaty article/period/ceiling",
"example": "country selected but no applicable article or eligible tax",
"resume_when": "case-specific article, effective period and eligible ceiling identified"
},
{
"missing": "proof/titular/previous actual use/temporal link",
"example": "payment2027 selected for2026 without correspondence",
"resume_when": "actual payment and explicit2026 link supported, prior use reconciled"
}
],
"local_startup_fix": {
"cause": "Local inspect.py shadowed Python stdlib before SSH connection",
"renamed_to": "remote_delivery_inspection.py",
"inspect_module": "C:/laragon/bin/python/python-3.10/lib/inspect.py",
"python": "C:/laragon/bin/python/python-3.10/python.exe",
"paramiko": "5.1.0",
"remote_linux_geteuid_ssh_guard_preserved": true,
"credentials_changed": false,
"server_failure_inferred": false
},
"local_evidence_directory": "outputs/irpc-l8-international-delivery-20261027",
"local_artifacts": [
{
"file": "authenticate.ps1",
"bytes": 237,
"sha256": "89492b8a16b8d5ec8dbe1d6a1a44af0bfbf8e99ccef2abfc5568a831623c05ba"
},
{
"file": "backup.py",
"bytes": 5460,
"sha256": "ef5406ffa735d3d563e9b4da0e8ac067c6978710df455d24e2c8e2cbc305fa49"
},
{
"file": "capacity-after.py",
"bytes": 1621,
"sha256": "9f1e2df54963469c670098b77392020f2719bb3f795cd04e5ecdad6f1fad1b84"
},
{
"file": "diagnose-session-delta.py",
"bytes": 7395,
"sha256": "312e2446a489a99bf9060797e785de4d16d28866b6f9a05a9d99fb60e3a9c838"
},
{
"file": "int-backup-20261027.json",
"bytes": 443,
"sha256": "5314107e4438ea22bc6c3261dda9b893faac3cf131c596f30dc6517bc35cd30f"
},
{
"file": "int-capacity-after-20261027.json",
"bytes": 1210,
"sha256": "72934b91dcc7ecf5370d7a667ef26ecf8a78a0ceeeeeb71a3062abab33925767"
},
{
"file": "int-operational-20261027.json",
"bytes": 2436,
"sha256": "f8936062bdf569740ea4bafc618c88c08ef8a1def30dcf1240c6afa3113ec1c3"
},
{
"file": "int-preflight-20261027.json",
"bytes": 2595,
"sha256": "cd339ef9913f8d89644e45ee5d337003cecb758d827764a79f4cfacc1b350dca"
},
{
"file": "int-preserve-20261027.json",
"bytes": 1139,
"sha256": "110ec10adf5d2a4de426dd3e6f947026dbff6ef828a56c0353b1e7a0426e2c78"
},
{
"file": "int-read-20261027.json",
"bytes": 2919,
"sha256": "12ba15343b9485e08f654a7abb0305e4f10f396b1d20f7aaca844e9ea5317fdc"
},
{
"file": "int-restore-20261027.json",
"bytes": 288,
"sha256": "7d9c3fb60ea87407441db867edf8e872e58aeb9aaf209c1b89830b0e0eedea59"
},
{
"file": "int-schema-after-20261027.json",
"bytes": 668,
"sha256": "e1767424312345a28a28223c67c424df1ac68d9d1aecec30a4856a71fbe91bfc"
},
{
"file": "int-schema-before-20261027.json",
"bytes": 646,
"sha256": "da666867fc18a60b0473e04bcd7966328135dcb684fb974b405b66e53e5a4377"
},
{
"file": "int-source-after-20261027.json",
"bytes": 165,
"sha256": "46c3a8f356197988ebbb4325a7a43807a0e5f097eb5eee5c09c063f68dc022cc"
},
{
"file": "int-source-before-20261027.json",
"bytes": 166,
"sha256": "3130bda62b9b5b736d8b3a884c34973e2c7387564c1f3e9edfcf626075d4fbbd"
},
{
"file": "int-status-a1-20261027.json",
"bytes": 1442,
"sha256": "c895209842c6f59f552a5b9af9542e0a4c58515d91213b188c1ee4300037b3ba"
},
{
"file": "int-status-final-20261027.json",
"bytes": 1795,
"sha256": "2c57678c23eabf455295695214f9d87cca99be25245417310c12d25a6ac69e41"
},
{
"file": "preflight.py",
"bytes": 2328,
"sha256": "2fccdc6dcd727db3b9599f5c4882b3ca389036ccbf12b91f2953d3789726e13c"
},
{
"file": "preparation.json",
"bytes": 247525,
"sha256": "61d83eb63dd5f14d99cd0cce2f460150812b1831a27850c876a991d847b7febc"
},
{
"file": "preserve-data.py",
"bytes": 2304,
"sha256": "e56d27b726c5e710b9bd5721d729cc019d57011b2ea1e2699fee6685f1f1bfbd"
},
{
"file": "public-after.json",
"bytes": 986,
"sha256": "65a39cc9e37575d5da4731e185728d8762387d28abf34c7991c1f81b8c24479d"
},
{
"file": "public-before.json",
"bytes": 414,
"sha256": "010725fedaa5b820efaea13d52140f07b450221f14d71624b6141fbdf5bb6b33"
},
{
"file": "reconcile-operational-delta.py",
"bytes": 5342,
"sha256": "1fa90ff8496d2210dee1e01c0ee409abe0f4f1713f844ac99fa6f4b4c889e645"
},
{
"file": "remote_delivery_inspection.py",
"bytes": 1947,
"sha256": "7c95ba88a9d5a62a15ec2bf581fa62f5151e548014d106f081487889e56b2703"
},
{
"file": "restore.py",
"bytes": 2828,
"sha256": "fcfd6eb0adfff107ee9259b5825ac1afc550c9bd8eabf111fa0b1739d7dd3efd"
},
{
"file": "schema-permissions-after.py",
"bytes": 1868,
"sha256": "d71436183c0cf121381e4119560d70f1bcaf850439830b822b728b6e86a04005"
},
{
"file": "schema-permissions-before.py",
"bytes": 1711,
"sha256": "10c8acceabaebaeeb5d2e5161d37c3b7927b9f4e44e725e19f0a2eb738638b07"
},
{
"file": "source-after-input.json",
"bytes": 237267,
"sha256": "b735f3c10108a40de67eba37cdac203329baea164fe8e48020087ee636462481"
},
{
"file": "source-before-input.json",
"bytes": 237268,
"sha256": "3835b8ab18392212a54c4560be32807b5573b22378ff3403ecd10637ff81d59f"
},
{
"file": "source-check.py",
"bytes": 676,
"sha256": "1cec620043b013e6b6f79b9f67e4e5588117d91ee7dc0c93592fc6b8d6d0557f"
},
{
"file": "ssh-import-collision-resolution.json",
"bytes": 411,
"sha256": "a997a96b0ab7fcd9cb8797c788f4ec27b46df8e70a7008f59400a3af57b99286"
},
{
"file": "ssh-session.py",
"bytes": 3058,
"sha256": "f506635c84dcc7c75c1b1cb244f8d1ffa98bcb6a1d906d6c70c5bfc5771bf177"
},
{
"file": "status.py",
"bytes": 1195,
"sha256": "2282805a03dcbc4c82d5f8be3504c6408f49a5ddb63d7a3deeed1dbd650d021f"
},
{
"file": "store-receipt.py",
"bytes": 870,
"sha256": "e407ff7db3b36fd554f6760dbd05c574c656770a18bf4631b430a8457293b6ea"
},
{
"file": "update-docs.py",
"bytes": 8322,
"sha256": "be77002ecad1640fc1999a05d5a50584290e03294c2328cf403768005d4e2b35"
},
{
"file": "verify-public.py",
"bytes": 2037,
"sha256": "df9aa7ec8b8581192abf8b3c726668205b4c50413005faa872a3fc8ecefbd5ad"
}
],
"remote_receipt_sha256": "d80324b898fd160ab3e7a2fd0b11ea2decd0b99a9324255850062ee4a13e0f0f"
}
@@ -204,3 +204,18 @@ Consulta primária dirigida identificou anúncio do Governo de alterações regu
### 27/10/2026 — Reutilização executável: crédito internacional corrente em QA
CIRPC65(1–2), Lei34/2007, exemplarBR52, PDF18/p768-(72), e ordem face aoPEC em66/RIRPC21 já aceites: usados no menor entre imposto estrangeiro efectivamente pago, fracção nacional documentada e limiteCDT aplicável, antes doPEC e até à colecta. Conferência da página existente para aplicação da fonte, sem nova exigência de autenticação. Original preservado, sem activação por importação/publicação. Afracção nacional eCDT do caso continuam documentadas pelo utilizador; aQA não estabelece correspondências oficiais de convenções.65(3), transportes, créditos económicos/CBF e obrigaçãoPEC continuam separados. Ver recibo `irpc-l8-international-credit-qa-20261027.json`; não instalado.
### 27/10/2026 — Crédito internacional entregue
A implementaçãoQA documentada acima foi instalada em`838ad941`,sem alterar fontes ou concederCDT automaticamente. CIRPC65(1–2)/66/RIRPC21 reutilizados no recorte demonstrado;65(3) e transportePEC continuam separados. Ver `irpc-l8-international-credit-delivery-20261027.json`.
## 28/10/2026 — aplicação de65(3)/66 aos saldos anteriores
Reutilizados os31ficheiros do acervo, todos iguais por bytes a `cf4e0638`. Lei34/2007,BR52,PDF18/p768-(72),SHA256`cdbef875ad7ccc1517b12faf5de0e893a70ed2ed81e33913cd6dc4a674474e6e`: página conferida visualmente;65(3)cinco exercícios seguintes,66(1–2)três paraPEC,sem reembolso. Referência à regra/apuramento aplicáveis na origem é correspondência de período, não nova validação de autenticidade da fonte. Leitura remota do URL arquivado falhou por timeout; usado o exemplar oficial exacto já aceite. Nenhum original alterado,scan declarado ou novo cálculo activado por publicação. Recorte:origens anuais ordinárias documentadas,mesmo sujeito,fecho2026/MZN;sem situações transitórias/especiais presumidas. Recibo `irpc-l8-carry-qa-20261028.json`.
## 28/10/2026 — crédito económico64 e distinção de40/65
Inventário anterior reutilizado:31ficheiros do acervo byte a byte iguais a6ededb59. Sem novo original. Lei34/2007BR52,SHA256`cdbef875ad7ccc1517b12faf5de0e893a70ed2ed81e33913cd6dc4a674474e6e`,PDF18/p768-(72),64(1–2),ePDF15/p768-(69),53(1)a,conferidos visualmente.40(1):Lei20/2009,exemplarAT19/2009,PDF4/p272-(16),redacção20%/dois anos e condições próprias,substitui a redacção original25%. Listas dasLeis4/2012 e19/2013 conferidas;cadeias20/2022 e12/2025 já aceites reutilizadas nos seus âmbitos. Decreto9/2008,RIRPC21(2/5),PDF6/p121:económico,internacional,benefícios,PEC,até à colecta,sem reembolso. Qualificação do caso,inclusão/acréscimo e quota proporcional documentados;sem automatizar a exclusão40 ou alterarL6por presunção. Sem nova exigência de autenticidade de fonte,scan ou publicação/importação. Pesquisa dirigida não substituiu os exemplares oficiais arquivados. Recibo:`irpc-l8-economic-qa-20261028.json`.
@@ -1,174 +0,0 @@
{
"date": "2026-10-29",
"scope": "Reorganização visual local do catálogo autorizada pela Tempo; sem instalação no portal.",
"base": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
"design": {
"desktop": "Painel lateral de filtros e resultados em duas colunas; lista com acções na coluna lateral do cartão.",
"mobile": "Filtros expansíveis; cartões numa coluna; áreas de toque e foco visível.",
"content": "Todos os campos, descrições, avisos e acções conservados; 29 fichas agrupadas por tipo. Aviso provincial e título dos resultados recuperados do pedido fornecido."
},
"checks": {
"types": {
"command": "npm run types:check",
"exit": 0
},
"build": {
"command": "INVESTMOZ_QA_BUILD=1 npm run build",
"exit": 0,
"target": "public/build-qa-opportunities",
"limitations": "Avisos existentes de fontaine opcional e chunks grandes. Compilação anterior à formatação final, apenas cosmética."
},
"browser": {
"result": "passed",
"scope": "Local compiled React application with public document-based preview fixtures and mocked HTTP, no database or external requests. Does not prove backend or live availability.",
"layouts": [
{
"width": 1440,
"scrollWidth": 1440,
"count": 12,
"headingY": 296.65625,
"sidebarVisible": true,
"groups": [
"Corredores6",
"Clusters8",
"Projectos âncora15"
]
},
{
"width": 1024,
"scrollWidth": 1024,
"count": 12,
"headingY": 292.234375,
"sidebarVisible": true,
"groups": [
"Corredores6",
"Clusters8",
"Projectos âncora15"
]
},
{
"width": 768,
"scrollWidth": 768,
"count": 12,
"headingY": 368.078125,
"sidebarVisible": false,
"groups": [
"Corredores6",
"Clusters8",
"Projectos âncora15"
]
},
{
"width": 390,
"scrollWidth": 390,
"count": 12,
"headingY": 395.265625,
"sidebarVisible": false,
"groups": [
"Corredores6",
"Clusters8",
"Projectos âncora15"
]
},
{
"width": 320,
"scrollWidth": 320,
"count": 12,
"headingY": 425.96875,
"sidebarVisible": false,
"groups": [
"Corredores6",
"Clusters8",
"Projectos âncora15"
]
}
],
"checks": [
"All 12 sample titles, full descriptions and territorial caveats preserved at every width; expanded filter controls fit 320/390/1024px.",
"Missing currency error remains visible on mobile.",
"Keyboard opens mobile filters; search preserved through collapse, reopen and reload.",
"Hierarchical territory selector still loads and updates filter context (synthetic QA territory).",
"Investment selection and dossier link survive reload.",
"Comparison still limits four selections and renders the existing comparison table.",
"All 29 territorial reference cards remain accessible in three expandable groups.",
"All five views activate and fit mobile width; map uses explicit no-coordinates preview data."
],
"pageErrors": 0
},
"logic": [
{
"file": "resources/js/pages/investment/catalogue.tsx",
"existingNonPresentationLogicBlocks": 33,
"missing": 0,
"excludes": "JSX and its inline handlers; those reviewed in source diff and directed browser checks."
},
{
"file": "resources/js/components/opportunity-search-filters.tsx",
"existingNonPresentationLogicBlocks": 5,
"missing": 0,
"excludes": "JSX and its inline handlers; those reviewed in source diff and directed browser checks."
}
]
},
"preservation": {
"schema": "Sem alterações.",
"data": "Sem acesso à base de dados; prévia baseada nos documentos locais e referências públicas já guardadas.",
"configuration": "Sem alterações.",
"permissions": "Sem alterações.",
"queries": "Filtros, endpoints e regras preservados; testes de backend anteriores reutilizados, sem nova prova de backend ou autenticação.",
"sourceFiles": [
{
"file": "resources/js/pages/investment/catalogue.tsx",
"sha256": "d4697cb83c2f92a786108286c7743401b44d61c5b367e9ff322b05d0424b0d70"
},
{
"file": "resources/js/components/opportunity-search-filters.tsx",
"sha256": "d5b75fc78f7dc272b745117d37e040f1bb921cec2783c3f50ddaaafff7e2df66"
},
{
"file": "resources/js/components/catalogue-filter-group.tsx",
"sha256": "f2728dfc2393de7d4f4338d3ea1057ed84317603980a2dc44f8a208d225cda45"
},
{
"file": "resources/css/investment-catalogue.css",
"sha256": "034a79a62ba13220f814027afd62e43c49e2947afd1d9e25a87ba37d3648fd93"
}
]
},
"evidence": {
"directory": "outputs/catalogue-layout-20261029/",
"screenshots": [
"catalogue-1440.png",
"catalogue-1024.png",
"catalogue-768.png",
"catalogue-390.png",
"catalogue-320.png",
"filters-expanded-390.png",
"territorial-expanded.png",
"list-1440.png"
]
},
"matrix": [
"RF-MN-010",
"RF-PII-003",
"RNF-EDU-008",
"MASTER-471012ab-0124"
],
"deployment": "Não realizada; alteração activa fora desta entrega local.",
"dynamicMoreFilters": {
"origin": "Pedido expresso da Tempo, 29/10/2026",
"collapsed": "Mais filtros",
"expanded": "Menos filtros",
"verification": {
"result": "passed",
"checks": [
"Mais filtros quando recolhido",
"Menos filtros quando aberto",
"Alternância por clique e teclado",
"Escolhas e contagem conservadas"
],
"scope": "Componente React real, compilado e exercitado em Chromium; sem backend ou base de dados."
},
"deployment": "Alteração local; sem instalação."
}
}
@@ -7105,24 +7105,92 @@ L8 permanece parcial. A avaliação real do percurso proactivo continua a aguard
**L8 permanece parcial.** Crédito internacional apenas emQA; PEC instalado em`e182d1d7` mantém o âmbito demonstrado. Songo eGurué privados; L3,ISPC,câmbio,L5–L7 eSGFTEMPO preservados. Avaliação de utilização do percurso proactivo continua a aguardar retorno da equipa. Sem instalação, publicação ou nova estimativa global nesta passagem.
## 29/10/2026 — ergonomia do catálogo: inventário antes da verificação
## 27/10/2026 — Crédito internacional corrente entregue pelo Git
Origem: pedido expresso da Tempo para analisar alternativas e reorganizar a página sem alterar conteúdos. Escolha de implementação: painel lateral no computador, filtros expansíveis no móvel, grupos por finalidade e cartões com hierarquia visual; corredores, clusters e projectos âncora agrupados em secções expansíveis. Não introduz regra organizacional. Alternativas ponderadas: formulário integral no topo conserva o bloqueio vertical; janela sobreposta afasta o contexto dos resultados; painel responsivo permite consulta lado a lado e mantém os campos montados ao recolher.
**Instalado e conferido em `838ad941a24ae76ec4bf91ccc3f92012668fe8cf`**, sobre o PEC instalado`e182d1d7`, preservando a correcção dos sectores`669cb897`. A candidata é a própria revisãoQA aceite`838ad941`, sem alteração funcional na preparação; integração normal em`main`, sem sobrescrever outro trabalho. Os registosQA anteriores são históricos: este recorte deixa de estar pendente de instalação. Não encerra L8 ou o IRPC.
Inventário do concluído consultado antes de nova ronda: selectores públicos independentes dos resultados e provas 22/10; agronegócio e escolha múltipla/dossier 23/10; vista por corredor e percurso proactivo 27/10; registos de reposição territorial e carteira mantidos. Preservar pesquisa combinada AND, filtros simples/avançados e geográficos, classificação histórica, montantes/moedas sem conversão, estados/erros, cinco vistas, CSV, favoritos/pedidos, comparação, escolha para investimento, paginação, guias e todas as fichas territoriais. Não existe eliminação funcional confirmada neste delta de código; não se infere disponibilidade activa pela apresentação local. O título dos resultados e o aviso provincial fornecidos no pedido estavam ausentes no componente local e são recuperados textualmente.
**Delta instalado:**5ficheiros de aplicação — detalhe internacional, projecção dos códigos do catálogo de países existente e integração no saldo anual. Todos idênticos à QA. Conferidas1002fontes antes/1005depois comGit; restantes fontes comparadas conservadas, incluindoPEC,L3,ISPC,câmbio,L5–L7,sectores,catálogoISO,rotas e configuração. Sem novas permissões,migrations ou importações. Fixtures sintéticas apenas no código de testes; não importadas para dados activos nem publicadas. Songo eGurué permanecem privados; SGFTEMPO separado.
Comparação delimitada: só componentes de apresentação e CSS; schema, dados, configuração, fontes, relações e permissões sem alteração. Não se ligou à base activa nem se declarou perda por leitura sem actor. A candidata não modifica aceitação anterior ou limitações de outros incrementos. Matriz existente: RF-MN-010, RF-PII-003, RNF-EDU-008 e MASTER-471012ab-0124; sem nova matriz.
**Recorte:** residente geral,ano civil2026,MZN comprovados. Inclusão do rendimento,fracção nacional,aplicabilidade/limiteCDT e utilizações anteriores documentados. Menor entre imposto pago e limites aplicáveis,menos uso anterior e até à colecta,antesPEC/RF/PPC;sem concessão pela escolha do país,conversão/arredondamento fiscal ou transporte presumidos. Exemplo condicionado aos dados e suportes sintéticos demonstrados:1 408−8de crédito−200PEC−500PPC=**700MZN de saldo simulado a pagar**. Os2acima do limite de elegibilidade não são transporte; insuficiência de colecta fica separada. Caso com500a recuperar deriva doPPC,sem reembolso do crédito ouPEC. Informação em falta e prova duplicada deixam o saldo dependente indeterminado.
Verificação do delta por realizar: compilação/tipos, apresentação 320/390/768/1024/1440px, teclado, expansão sem perda de campos, vistas, conservação das acções/conteúdo e ausência de transbordo horizontal. Preparação local, sem instalação ou alteração de dados activos.
**Recuperação e preservação:** capacidade antes superior a85GiB e23,69milhões de inodes; mínimo existente do instalador5GiB mais backup confrontado com espaço real e novamente conferido após backup. Backup fresco`/var/backups/investmoz-irpc-l8-international-20261027/backup`,dumpSHA256`b1e9740653a8664c23268e228efd3ed6a0514bf3e8786dd5adf43342cdb475e1`;restauro174tabelas com contagens/checksums iguais em contentor sem rede,porta55441.369ficheiros persistentes/configuração e172tabelas de negócio intactos depois da instalação;schema,papéis,grants e permissões iguais. Cache/sessões operacionais reconciliados individualmente com o backup e pedidos públicos;nenhum registo de negócio ou sessão sobrescrito pelo comparador. Release anterior mantida até compilação/verificações e troca atómica;runtimeQA fora da árvore servida.
### Resultado do delta de apresentação — 29/10/2026
**Provas:** reutilizadas18novas+31anuais/PEC,API171asserções e7recuperações comHTML/dossier e históricos conservados. Sem nova ronda manual das funcionalidades não afectadas. Controlos automáticos obrigatórios do instalador:OK (1 test, 3106 assertions); ✓ built in 31.55s; OK (59 tests, 317 assertions); # tests 1110; # pass 1110; # fail 0;TypeScript/Wayfinder/build e guardas aprovados. Revisão pública e hash do manifest conferidos,HTTP200do simulador e6marcadores compilados do novo delta/PEC identificados. Não foram criados casosQA no portal.
Concluído localmente. TypeScript e build isolado aprovados, sem instalação. Navegador Chromium com a aplicação React compilada e respostas HTTP de prévia locais, sem base de dados nem pedidos externos:320/390/768/1024/1440px sem transbordo horizontal; campos expandidos cabem no painel em320/390/1024px. Conferidas integralmente as descrições e avisos territoriais dos12cartões da amostra em cada largura, teclado para expandir, erro de moeda, recolher/reabrir/recarregar sem perder pesquisa, selectores hierárquicos, escolha persistente para dossier, limite/comparação de4, cinco vistas e acesso às29fichas(6corredores,8clusters,15âncoras). Zero erros JavaScript. Capturas efectivamente inspeccionadas:1440/1024/390/320px, filtros expandidos390px e lista1440px.
**SaldoL8 preservado:** derivação automática da fracção nacional/CDT específicas;créditos económicos/CBF;utilização interanual/transporte/caducidade próprios;obrigação/calendárioPPC/PEC;autónomos,períodos especiais,moedas eM20/M22 conforme dependências já discriminadas. Excedente/transportePEC fora do âmbito entregue. Informação de inclusão/CDT/prova/titular/uso bloqueia apenas o caso dependente. As condições concretas de retoma mantêm-se no saldo curtoQA anterior;sem repetir pesquisas ou exigir nova autenticação de fontes oficiais aceites.
Comparação estrutural:33blocos preexistentes de lógica da página e5auxiliares dos filtros preservados; JSX/callbacks revistos no delta e nas interacções acima. Os avisos de ausência, a consulta pública e as ligações anteriores mantêm-se. Favoritos autenticados, backend de pesquisa/mapa, guias e permissões conservam os contratos/provas anteriores; esta prévia não é nova demonstração desses serviços nem da disponibilidade activa. Mapa exercitado com ausência explícita de coordenadas, sem criar pontos.
Recibo:`docs/investmoz/simulations/irpc-l8-international-credit-delivery-20261027.json`. Cópia remota:`/var/backups/investmoz-irpc-l8-international-20261027/installed-receipt.json`,SHA256`d80324b898fd160ab3e7a2fd0b11ea2decd0b99a9324255850062ee4a13e0f0f`. Provas locais:`outputs/irpc-l8-international-delivery-20261027/`. Resolvida a colisão local`inspect.py`→`remote_delivery_inspection.py`;módulo padrão/Paramiko verificados no mesmoPython,guardaLinux/geteuid mantida,sem alteração de credenciais ou do servidor por essa correcção. A avaliação real do percurso proactivo continua dependente do retorno da equipa. **L8 permanece parcial.**
Recibo:docs/investmoz/unification/catalogue-layout-qa-20261029.json. Evidência local:outputs/catalogue-layout-20261029/. Nenhuma redução funcional pretendida; todas as fichas estão nos grupos expansíveis. Sem publicação, dados alterados, migrações, configuração ou permissões novas. Não encerra os critérios globais das quatro linhas da matriz.
Ajuste solicitado pela Tempo em29/10/2026: o controlo dos filtros avançados alterna entre “Mais filtros” (recolhido) e “Menos filtros” (aberto). O estado segue a abertura nativa da secção; os campos e escolhas continuam montados. Prova dirigida no componente React real em Chromium: clique/teclado, ambos os textos, valor editado e contagem conservados; sem errosJavaScript. Recibo local:outputs/catalogue-layout-20261029/toggle-receipt.json. Sem nova ronda global, instalação ou alteração de dados.
## 28/10/2026 — retoma de L8 e preservação antes do novo delta
Ajuste visual solicitado pela Tempo em29/10/2026: títulos, cabeçalhos, rótulos de grupos e conteúdo do catálogo em negrito apresentados em vermelho; os botões com fundo colorido mantêm texto legível. CSS validado por análise sintáctica; alteração local de apresentação, sem instalação.
28/10/2026: inventário prévio à QA dos saldos anteriores: internacional corrente838ad941, PECe182d1d7 e sectores669cb897 preservados na basecf4e0638; todos os ficheiros do acervo iguais por bytes. Diferença da pasta original é de ramo/ambiente, não perda confirmada. Sem leitura ou escrita de dados activos; recibos aceites reutilizados. Continuação emQA de65(3)/66, sem declarar L8 concluído.
Escolha técnica: novo worktree `portal-investidor-irpc-carry-qa-20261028`, ramo `codex/irpc-l8-carry-qa-20261028`, a partir de `cf4e0638`. Sem migrations, novas permissões ou alterações no activo. Nenhuma perda funcional confirmada nesta comparação de fontes; não se declara nova comparação de dados/schema/permissões no servidor. Songo/Gurué e a avaliação pela equipa conservam os estados anteriores.
## 28/10/2026 — saldos anteriores internacionais e PEC: delta QA concluído
Implementado e demonstrado em QA isolada, **sem instalação**. Base `cf4e0638`, com internacional `838ad941`, PEC `e182d1d7` e sectores `669cb897` preservados. A pasta original estava noutro ramo; isso não foi tratado como eliminação de funcionalidades. Recibo: `docs/investmoz/simulations/irpc-l8-carry-qa-20261028.json`.
Extensão opcional do livro anual existente: uma origem consolidada por natureza/país/exercício, apuramento e regra de origem documentados, elegível menos dedução inicial e utilizações efectivas subsequentes. Internacional: cinco exercícios seguintes; PEC: três. Origem2021 internacional e PEC2023 chegam a2026; origem2020 internacional/PEC2022 ficam fora do prazo ordinário, conservadas com explicação e saldo histórico. Não se converte imposto acima do limite em crédito transportável. Situações transitórias/especiais não são qualificadas pela regra ordinária.
Escolha expressa das parcelas correntes e anteriores, vinculada à colecta seleccionada, sem ordem FIFO imposta nem redução automática. A soma não ultrapassa a colecta e os créditos internacionais precedem o PEC. Valores não escolhidos ficam separados da insuficiência de colecta; simulações não criam nem consomem saldos oficiais. Exemplo sintético:1408−8corrente internacional−50anterior internacional−200PECcorrente−100PECanterior−500PPC=**550MZN a pagar, simulado**.
**Provas:**16novos+49afectados=65testes aprovados; API1teste/119asserções,6casos POST/PUT/GET na base guardada `proactive_investment_20261027_test`,loopback55441,com rollback. Seis recuperações recalculadas integralmente,HTML/dossier concordantes e resultados anteriores congelados.55oportunidades,64documentos,1vínculo,19rascunhos,40utilizadores,3organizações e409eventos anteriores preservados.31ficheiros do acervo byte a byte iguais,sem nova importação/publicação. TypeScript,build QA com exit0 ePint aprovados. Não foi feita nova prova manual de interface ou avaliação pela equipa. Sem migrations,grants,contas,alteração activa ou operações de servidor.
**Saldo concreto:**L8 continua parcial. Próximo incremento independente:crédito económico64,com gross-up53(1)a/exclusão40,qualificação dos lucros/pagador/beneficiário/imposto e limite proporcional correspondidos; fonte aceite já disponível. Permanecem fracção nacional/CDT automática,créditos/benefícios próprios,obrigação/calendárioPPC/PEC,autónomos,períodos especiais,outras moedas eM20/M22. Não declarar IRPC concluído nem repetir a validação das entregas independentes aceites.
## 28/10/2026 — crédito económico: preservação e limites antes do novo delta
28/10/2026, antes de novos ensaios: inventário preservado do internacional838ad941/PECe182d1d7/sectores669cb897 instalados e saldos anterioresd134a92d/6ededb59 emQA sem instalação. Novo ramo económico parte de6ededb59, agregável com o delta compatível, sem reapresentar a aprovação dos anteriores.31ficheiros do acervo iguais por bytes;nenhuma perda de fontes confirmada. Sem acesso ao activo nesta preparação;comparação de dados/schema/permissões do destino só na entrega autorizada.
CIRPC64(1–2)/53(1)a e40(1) na redacçãoLei20/2009 são correspondidos no próprio acervo aceite. Regra económica distinta da internacional65;na liquidação precede65/PEC (RIRPC21). Novo detalhe opcional,sem alterar resultados congelados ou sobrescrever deliberadamente o resumo económico anterior. Sem instalação/publicação.
## 28/10/2026 — crédito económico ordinário demonstrado em QA; agrupamento compatível
**Implementado e demonstrado em QA isolada, sem instalação.** Ramo `codex/irpc-l8-economic-qa-20261028`, base `6ededb59`, incluindo os saldos anteriores `d134a92d`. A última referência instalada documentada continua `838ad941`; não foi feita nova leitura do servidor. Não se reabre a aceitação dos históricos ou das provas anteriores.
**Cobertura:**CIRPC64(1–2),53(1)a,40(1)na redacção20/2009 eRIRPC21(2/5). Lucros ordinários distribuídos e IRPC correspondente documentados,beneficiário/distribuidor com sede/direcção efectiva emMoçambique,distribuidor sujeito/não isento,exclusão40(1)não aplicável com suporte. A selecção explícita da colecta corrente reutiliza NUIT/exercício/residência válidos e conserva edições divergentes. Novo detalhe opcional; resumo económico deliberado anterior e resultados congelados conservados.
**Cálculo:**60%doIRPCdocumentadamente correspondente aos lucros;confere o acréscimo53 já incluído emL6 e limita pela quota proporcional documentada,menos utilização efectiva anterior,até à colecta. O portal não deriva IRPC do dividendo líquido nem altera a base/colecta silenciosamente;inclusão/acréscimo e quota exigem correspondência do caso. A existência de perdas que reduzam a base abaixo dos lucros não é tratada como impedimento genérico. Crédito económico precede o internacional ePEC,sem reembolso ou transporte económico presumido. Exemplo sintético condicionado aos suportes:IRPC20→nominal12;1408−12−8internacional−200PEC−500PPC=**688MZN a pagar,simulado**.
**Mesma parcela:**identidade por emitente/documento/parcela com suporte;duplicação dos lucros também conferida independentemente de trocar o comprovativo de imposto,a data ou oID. O mesmo documento pode suportar parcelas de imposto distintas quando a separação estiver documentada em ambos os registos. Um comprovativo anterior sem parcela continua a abranger o documento inteiro,não se torna livre por receber novo nome noutro mapa. Atribuições anteriores e capacidade do comprovativo conferidas neste e noutros contextos do snapshot;divergências não são apagadas. ProtecçõesL5 conservadas. Não é reconciliação global de conta fiscal entre dossiers independentes.
**Agrupamento:**composição demonstrada com os saldos anteriores:1408−12económico−8internacionalcorrente−50internacionalanterior−200PECcorrente−100PECanterior−500PPC=**538MZN a pagar,simulado**. A prioridade económica não reduz automaticamente a afectação entre exercícios já escolhida;se exceder a colecta remanescente,o caso pede reconciliação conservando as escolhas. Os dois incrementos podem integrar uma entrega Git comum;nenhum foi instalado nesta passagem.
**Provas do delta:**20testes económicos novos+65afectados aceites=85aprovados;API1teste/210asserções,11casos POST/PUT/GET na base guardada `proactive_investment_20261027_test`,loopback55441,transacção com rollback. Onze recuperações recalculadas integralmente,HTML/dossier concordantes e históricos anteriores conservados.55oportunidades,64documentos,1vínculo,19rascunhos,40utilizadores,3organizações e409eventos anteriores intactos. TypeScript,build QA ePint aprovados.31ficheiros do acervo preservados por bytes,sem novas importações,publicações,scan declarado,migrations,contas ougrants. Não foi feita nova prova manual da interface nem avaliação pela equipa.
**Pendências concretas:**inclusão/correcção automática do dividendo/acréscimo emL6 e derivação da quota proporcional;exclusão40(1)na base com todas as suas condições;liquidação64(3)/associações64(4);créditos/benefícios específicos;fracção internacional/CDT automática;obrigação/calendárioPPC/PEC;autónomos,períodos especiais,outras moedas eM20/M22. Correspondências e parâmetros em falta afectam o caso dependente,sem revalidação genérica de fontes oficiais. Saldos anteriores mantêm o recorte ordinário já demonstrado. **L8 permanece parcial.** Recibo:`docs/investmoz/simulations/irpc-l8-economic-qa-20261028.json`.
Preservação delimitada:558ficheiros protegidos com conteúdo Git idêntico à baseQA;uma diferençaLF/CRLF em `docs/investmoz/simulations/irpc-l8-carry-qa-20261028.json` entre checkouts,conferida como normalização de ambiente,sem perda de conteúdo. Os31originais do acervo são iguais por bytes.
## 28/10/2026 — entrega agrupada de saldos anteriores e crédito económico pelo Git
**Instalado e conferido em `569a1cd750f3d2a0b87f130e992e73e070bbd1ab`**, sobre `838ad941`, por fast-forward normal em `main`,sem force. Foram entregues em conjunto os saldos anteriores `d134a92d` e o crédito económico ordinário `aae67c1`, já demonstrados emQA. Os estadosQA anteriores permanecem históricos;estes recortes deixam de estar pendentes de instalação. **L8 permanece parcial;esta entrega não fecha integralmente a liquidação anual.**
**Delta e preservação:**12ficheiros de aplicação,byte a byte correspondentes à candidata aceite;1005fontes antes e1011depois conferidas comGit. Demais fontes comparadas,PECcorrente,internacionalcorrente,sectores,L3/ISPC/câmbio/L5–L7,originais e contexto adaptativo preservados. Sem alterações de schema/configuração/rotas/grants,migrations ou importações de conteúdo. RuntimeQA conservado fora da árvore servida. Songo/Gurué permanecem privados eSGFTEMPO separado.
**Capacidade/recuperação:**82,71GiB e23,52milhões de inodes livres antes;capacidade novamente conferida após backup,com o mínimo existente do instalador e espaço real do backup. Backup fresco `2026-10-28T12:38:25Z` (14:38:25locais),em `/var/backups/investmoz-irpc-l8-grouped-20261028/backup`;dumpSHA256`007cd1851d5bd51a54265ab99a342d6a312de06ef642fc42b38b7a5e771d4d9a`. Restauro174tabelas com contagens/checksums iguais emcontentorsemrede/porta55441;369ficheiros/configuração conferidos. Depois da entrega:172tabelas de negócio e369ficheiros persistentes/configuração intactos;schema,papéis,grants epermissões iguais,identidades de comparação equivalentes. Delta operacional delimitado a `queue:restart` e2sessões anónimas do agente de entrega,correlacionadas com pedidos públicos;nenhum dado ou sessão sobrescrito para obter igualdade. Release anterior mantida até todos os controlos e troca atómica;manifest/revisão servidos confirmados.
**Provas reutilizadas e controlos da entrega:**85testes afectados/20económicos novos,API210asserções/11recuperações HTML/dossier e históricos aceites reutilizados;sem repetir avaliação manual de funcionalidades independentes. Instalador obrigatório:PostgreSQL1teste/3106asserções;Unit59/317;frontend1146aprovados/0falhas;TypeScript/Wayfinder/build aprovados (30,82s). SimuladorHTTP200 e8marcadores compilados dos saldos anteriores/económico/internacional/PEC conferidos. Não foram criados casosQA no portal e não se declara nova aceitação manual da equipa.
### Saldo concreto de L8 após a entrega
| Grupo | Cobertura entregue ou trabalho restante |
| --- | --- |
| Saldos anteriores65(3)/66 | Entregues no recorte de origens anuais ordinárias documentadas,mesmo sujeito/2026/MZN,prazos próprios5/3exercícios,utilizações efectivas e afectação explícita. Não cria nem consome saldos oficiais;casos transitórios/especiais permanecem próprios. |
| Económico64(1–2) | Entregue para lucros ordinários qualificados,IRPC correspondente documentado,acréscimo53 já incluído emL6 e quota proporcional documentada,antes do internacional/PEC,sem dupla utilização da mesma parcela. Parcela excluída40(1)não recebe também64. |
| Inclusão/correcção económica e quota | Ainda por implementar a inclusão/correcção automática do dividendo/acréscimo emL6,a derivação automática da quota e o tratamento completo40(1)na base. A comprovação manual corrente não é declarada automação desses grupos. |
| Económico64(3/4) e benefícios | Liquidação,associações ecréditos/benefícios específicos mantêm qualificação,limites,cumulação e uso próprios por implementar;sem os transformar emcrédito internacional. |
| Internacional automático | Derivação da fracção nacional e correspondência específicaCDT continuam pendentes;qualificação/dedução internacional documentada entregue preservada. |
| Obrigações e representação | Obrigação/calendárioPPC/PEC,juros/multas/guias,autónomos,períodos especiais,outras moedas eM20/M22/transporte/submissão continuam nos grupos concretos anteriores. |
A falta de prova do caso (titular/rendimento/imposto/inclusão/uso/regra do período ou quota) limita só o resultado dependente;não é reabertura da autenticidade das fontes oficiais aceites nem novo aprovador. Exemplo agrupado condicionado aos suportes sintéticos já aceites:1408−12económico−8internacionalcorrente−50internacionalanterior−200PECcorrente−100PECanterior−500PPC=**538MZN de saldo simulado a pagar**;não é declaração submetida ou saldo fiscal consumido.
Recibo consolidado:`docs/investmoz/simulations/irpc-l8-grouped-delivery-20261028.json`. Cópia remota:`/var/backups/investmoz-irpc-l8-grouped-20261028/installed-receipt.json`. Provas locais:`outputs/irpc-l8-grouped-delivery-20261028/`. Actualização documental segue ramo próprio de recibos,sem alterar novamente a revisão servida.
Cópia remota do recibo conferida:SHA256`b70fe154f95162f029b5ca712b41962757360d73b0ff07f52b8ce14848d990df`;a matriz existente recebeu saldoL8 nos camposEstado,Disponibilidade activa,Evidências,Critérios restantes eDependências,só em `AUD-SIM-INT02`.
File diff suppressed because one or more lines are too long
-445
View File
@@ -1,445 +0,0 @@
/* Presentation only: catalogue queries, records and permissions retain their contracts. */
.investment-catalogue {
--catalogue-accent: #c9141b;
--catalogue-ink: #17324d;
max-width: 1440px;
color: var(--catalogue-ink);
}
.investment-catalogue > h1 {
font-size: clamp(1.6rem, 3vw, 2.15rem);
letter-spacing: -0.035em;
}
.investment-catalogue .catalogue-intro {
margin-top: 0.65rem;
max-width: 76ch;
color: #526477;
line-height: 1.7;
}
.catalogue-workspace {
display: grid;
gap: 1.5rem;
align-items: start;
}
.catalogue-workspace > *,
.catalogue-results > *,
.catalogue-opportunity > * {
min-width: 0;
}
.catalogue-filters {
border: 1px solid #dce3eb;
border-radius: 1rem;
background: #fff;
overflow: clip;
}
.catalogue-filters-toggle,
.catalogue-filters-heading {
align-items: center;
gap: 0.65rem;
padding: 1rem 1.15rem;
font-weight: 650;
}
.catalogue-filters-toggle {
display: flex;
width: 100%;
text-align: left;
min-height: 52px;
}
.catalogue-filters-toggle > svg:last-child {
margin-left: auto;
transition: transform 0.15s;
}
.catalogue-filters-toggle[aria-expanded='true'] > svg:last-child {
transform: rotate(180deg);
}
.catalogue-filters-heading {
display: none;
}
#catalogue-filter-fields {
padding: 0 1.15rem 1.15rem;
}
.catalogue-filters input:not([type='checkbox']),
.catalogue-filters select {
min-height: 44px;
max-width: 100%;
font-size: 0.875rem;
}
.catalogue-filter-group {
border-top: 1px solid #e5eaf0;
}
.catalogue-filter-group > summary {
display: flex;
align-items: center;
gap: 0.6rem;
min-height: 52px;
padding: 0.65rem 0;
cursor: pointer;
list-style: none;
font-size: 0.875rem;
font-weight: 650;
}
.catalogue-filter-group > summary::-webkit-details-marker {
display: none;
}
.catalogue-filter-group > summary > svg {
margin-left: auto;
flex-shrink: 0;
transition: transform 0.15s;
}
.catalogue-filter-group[open] > summary > svg {
transform: rotate(180deg);
}
.catalogue-filter-group-content {
padding: 0.4rem 0 1rem;
display: grid;
gap: 1rem;
}
.catalogue-count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 1.5rem;
padding: 0.15rem 0.45rem;
border-radius: 99px;
background: #f0f3f7;
color: #526477;
font-size: 0.75rem;
}
.catalogue-filters .catalogue-filter-group {
margin-top: 0;
}
.catalogue-active-filters:empty {
display: none;
}
.catalogue-active-filters button {
border-radius: 0.5rem;
background: #f5f7fa;
border-color: #dce3eb;
font-size: 0.75rem;
overflow-wrap: anywhere;
}
.catalogue-filter-submit > button:first-of-type {
gap: 0.5rem;
background: var(--catalogue-accent);
min-height: 44px;
}
.catalogue-filter-submit > button:last-child {
min-height: 44px;
color: #526477;
font-size: 0.875rem;
border: 0;
text-decoration: none;
}
.catalogue-results {
display: flex;
flex-direction: column;
gap: 1.25rem;
scroll-margin-top: 2rem;
}
.catalogue-results-heading {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 0.35rem 1rem;
}
.catalogue-results-heading > h2 {
font-size: 1.125rem;
font-weight: 700;
letter-spacing: -0.02em;
}
.catalogue-results-heading > [role] {
border: 0;
padding: 0;
margin: 0;
color: #526477;
font-size: 0.875rem;
}
.catalogue-results-toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.8rem 1.25rem;
padding-bottom: 1.1rem;
border-bottom: 1px solid #dce3eb;
}
.catalogue-view-options {
display: flex;
flex-wrap: wrap;
gap: 0.2rem;
padding: 0.25rem;
border: 1px solid #dce3eb;
border-radius: 0.75rem;
background: #fff;
}
.catalogue-view-button {
display: inline-flex;
gap: 0.4rem;
align-items: center;
justify-content: center;
min-height: 42px;
padding: 0.5rem 0.7rem;
border-radius: 0.5rem;
color: #526477;
font-size: 0.8rem;
}
.catalogue-view-button[aria-pressed='true'] {
background: #17324d;
color: #fff;
}
.catalogue-view-button:not(:disabled):hover {
color: var(--catalogue-accent);
}
.catalogue-view-button[aria-pressed='true']:not(:disabled):hover {
background: var(--catalogue-accent);
color: #fff;
}
.catalogue-view-button:disabled {
opacity: 0.5;
cursor: wait;
}
.catalogue-utility-actions {
display: flex;
flex-wrap: wrap;
gap: 0.25rem 1.25rem;
}
.catalogue-utility-link {
display: inline-flex;
align-items: center;
gap: 0.4rem;
min-height: 44px;
font-size: 0.8rem;
color: #526477;
}
.catalogue-utility-link[aria-disabled='true'] {
opacity: 0.5;
}
.catalogue-cards {
display: grid;
gap: 1rem;
}
.catalogue-opportunity {
display: flex;
flex-direction: column;
border: 1px solid #dce3eb;
border-radius: 1rem;
background: white;
overflow: clip;
transition:
border-color 0.15s,
box-shadow 0.15s;
}
.catalogue-opportunity:hover,
.catalogue-opportunity:focus-within {
border-color: #9cabbc;
box-shadow: 0 5px 18px #17324d0a;
}
.catalogue-opportunity-body {
display: flex;
flex: 1;
flex-direction: column;
align-items: start;
gap: 0.85rem;
padding: 1.25rem;
}
.catalogue-sector {
padding: 0.25rem 0.6rem;
background: #f0f4f8;
color: #3d5268;
border-radius: 0.4rem;
font-size: 0.75rem;
font-weight: 600;
}
.catalogue-location {
display: flex;
align-items: flex-start;
gap: 0.4rem;
color: #526477;
font-size: 0.8rem;
line-height: 1.6;
}
.catalogue-location svg {
flex-shrink: 0;
margin-top: 0.2rem;
}
.catalogue-opportunity h2 {
font-size: 1.125rem;
line-height: 1.45;
letter-spacing: -0.015em;
color: var(--catalogue-ink);
overflow-wrap: anywhere;
}
.catalogue-summary {
color: #526477;
font-size: 0.875rem;
line-height: 1.7;
}
.catalogue-opportunity-facts {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 0.65rem;
width: 100%;
margin-top: auto;
padding-top: 0.5rem;
font-size: 0.875rem;
}
.catalogue-maturity {
padding: 0.25rem 0.6rem;
border-radius: 99px;
background: #f5f6f8;
color: #526477;
font-size: 0.75rem;
}
.catalogue-opportunity-actions {
padding: 0.45rem 1.25rem 0.75rem;
border-top: 1px solid #e5eaf0;
}
.catalogue-opportunity-links {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 0.25rem 0.75rem;
}
.catalogue-detail-link,
.catalogue-favourite {
display: inline-flex;
align-items: center;
gap: 0.4rem;
min-height: 44px;
font-size: 0.8rem;
}
.catalogue-detail-link {
color: var(--catalogue-accent);
font-weight: 650;
}
.catalogue-favourite {
color: #526477;
text-align: left;
}
.catalogue-favourite[aria-pressed='true'] {
color: var(--catalogue-accent);
}
.catalogue-opportunity-choices {
display: grid;
gap: 0.15rem;
padding-top: 0.35rem;
border-top: 1px solid #eef1f5;
}
.catalogue-opportunity-choices label {
display: flex;
align-items: center;
gap: 0.6rem;
min-height: 44px;
font-size: 0.8rem;
line-height: 1.5;
cursor: pointer;
}
.catalogue-opportunity-choices input {
width: 1rem;
height: 1rem;
flex-shrink: 0;
accent-color: var(--catalogue-accent);
}
.catalogue-pagination {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: 0.75rem;
}
.catalogue-pagination a {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 44px;
padding: 0.5rem 1rem;
border: 1px solid #dce3eb;
border-radius: 0.5rem;
background: #fff;
font-size: 0.875rem;
}
.catalogue-territorial {
padding-top: 1.5rem;
border-top: 1px solid #dce3eb;
}
.catalogue-territorial > h2 {
font-size: 1.125rem;
font-weight: 700;
}
.catalogue-territorial > p {
margin: 0.5rem 0 1.2rem;
color: #526477;
font-size: 0.875rem;
line-height: 1.7;
}
.catalogue-territorial-links {
display: grid;
gap: 0.75rem;
}
.catalogue-territorial-link {
border: 1px solid #e5eaf0;
border-radius: 0.65rem;
padding: 0.85rem 1rem;
background: #fff;
}
.catalogue-territorial-link > span {
color: #526477;
font-size: 0.75rem;
}
.catalogue-territorial-link h3 {
font-size: 0.875rem;
line-height: 1.6;
}
/* Headings and emphasized catalogue content use Tempo's red. */
.investment-catalogue :is(h1, h2, h3, h4, h5, h6, caption, th, strong),
.investment-catalogue :is(p.font-bold, p.font-semibold),
.investment-catalogue .catalogue-sector,
.investment-catalogue .catalogue-filters-toggle,
.investment-catalogue .catalogue-territorial .catalogue-filter-group > summary {
color: var(--catalogue-accent);
}
.investment-catalogue :is(a, button, summary, input, select):focus-visible {
outline: 2px solid #17324d;
outline-offset: 3px;
}
.investment-catalogue :is(a, button, summary):hover {
text-decoration: underline;
text-underline-offset: 3px;
}
@media (min-width: 640px) {
.catalogue-cards-grid,
.catalogue-territorial-links {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (min-width: 1024px) {
.catalogue-workspace {
grid-template-columns: 290px minmax(0, 1fr);
gap: 2rem;
}
.catalogue-filters-toggle {
display: none;
}
.catalogue-filters-heading {
display: flex;
}
.catalogue-results-heading {
min-height: 48px;
}
.catalogue-cards-list .catalogue-opportunity {
flex-direction: row;
}
.catalogue-cards-list .catalogue-opportunity-actions {
flex: 0 0 235px;
display: flex;
flex-direction: column;
justify-content: center;
border-top: 0;
border-left: 1px solid #e5eaf0;
}
}
@media (prefers-reduced-motion: reduce) {
.investment-catalogue * {
transition: none;
scroll-behavior: auto;
}
}
@@ -1,30 +0,0 @@
import { ChevronDown } from 'lucide-react';
import { useState, type ReactNode } from 'react';
export default function CatalogueFilterGroup({
title,
expandedTitle,
count = 0,
children,
}: {
title: string;
expandedTitle?: string;
count?: number;
children: ReactNode;
}) {
const [open, setOpen] = useState(false);
return (
<details
className="catalogue-filter-group"
onToggle={(event) => setOpen(event.currentTarget.open)}
>
<summary>
<span>{open && expandedTitle ? expandedTitle : title}</span>
{count > 0 && <span className="catalogue-count">{count}</span>}
<ChevronDown size={16} aria-hidden="true" />
</summary>
<div className="catalogue-filter-group-content">{children}</div>
</details>
);
}
@@ -0,0 +1,10 @@
import type {FiscalProofParcel} from '@/lib/fiscal-proof-parcel';
export function FiscalProofParcelFields({value, change, label}: {value: FiscalProofParcel; change: (value: FiscalProofParcel) => void; label: string}) {
return <details className="rounded border p-2" open={!!value.parcel || !!value.parcelReference}>
<summary>Identificar parcela quando o documento suporta várias parcelas — {label}</summary>
<p>Sem identificação específica, o comprovativo existente abrange o documento inteiro. Para distinguir impostos ou parcelas, indique a linha/identificador exacto e o suporte dessa separação. Os montantes comprovado e seleccionado devem corresponder à parcela identificada. A mudança do identificador não comprova uma parcela diferente.</p>
<label className="block">Identificador da parcela<input aria-label={label + ' — Parcela documental'} value={value.parcel ?? ''} onChange={e => change({parcel: e.target.value})}/></label>
<label className="block">Suporte da separação das parcelas<input aria-label={label + ' — Suporte da parcela'} value={value.parcelReference ?? ''} onChange={e => change({parcelReference: e.target.value})}/></label>
</details>;
}
@@ -1,9 +1,6 @@
import { Field, input, button, groupLabels } from '@/pages/investment/shared';
import type { References } from '@/pages/investment/shared';
import { TerritoryLevel, type TerritoryOption } from './investment-territory';
import CatalogueFilterGroup from './catalogue-filter-group';
import { useEffect, useState } from 'react';
import { ChevronDown, Search, SlidersHorizontal } from 'lucide-react';
export const modalityLabels: Record<string, string> = {
investment_project: 'Projecto de investimento',
@@ -53,19 +50,14 @@ const labels: Record<string, string> = {
publication_state: 'Critério herdado',
};
const specialisedEmpty: Record<string, string> = {
corridor_id:
'Não existem corredores públicos cadastrados para esta localização.',
cluster_id:
'Não existem clusters públicos cadastrados para esta localização.',
corridor_id: 'Não existem corredores públicos cadastrados para esta localização.',
cluster_id: 'Não existem clusters públicos cadastrados para esta localização.',
zee_id: 'Não existem ZEE públicas cadastradas para esta localização.',
zfi_id: 'Não existem ZFI públicas cadastradas para esta localização.',
park_id:
'Não existem parques industriais públicos cadastrados para esta localização.',
project_id:
'Não existem projectos âncora públicos cadastrados para esta localização.',
park_id: 'Não existem parques industriais públicos cadastrados para esta localização.',
project_id: 'Não existem projectos âncora públicos cadastrados para esta localização.',
subsector_id: 'Não existem actividades disponíveis no catálogo público.',
chain_id:
'Não existem cadeias de valor públicas cadastradas para esta localização.',
chain_id: 'Não existem cadeias de valor públicas cadastradas para esta localização.',
};
export default function OpportunitySearchFilters({
data,
@@ -86,10 +78,6 @@ export default function OpportunitySearchFilters({
clear: () => void;
errors: Record<string, string>;
}) {
const [expanded, setExpanded] = useState(false);
useEffect(() => {
if (Object.keys(errors).length) setExpanded(true);
}, [errors]);
const select = (
key: string,
choices: { value: string; label: string }[],
@@ -99,14 +87,8 @@ export default function OpportunitySearchFilters({
<select
className={input}
aria-label={labels[key]}
aria-describedby={
specialisedEmpty[key] ? `filter-help-${key}` : undefined
}
disabled={
Boolean(specialisedEmpty[key]) &&
choices.length === 0 &&
!data[key]
}
aria-describedby={specialisedEmpty[key] ? `filter-help-${key}` : undefined}
disabled={Boolean(specialisedEmpty[key]) && choices.length === 0 && !data[key]}
value={String(data[key] ?? '')}
onChange={(e) =>
change({
@@ -118,13 +100,9 @@ export default function OpportunitySearchFilters({
}
>
<option value="">Todos</option>
{data[key] &&
!choices.some((o) => o.value === String(data[key])) && (
<option value={String(data[key])}>
Selecção indisponível neste contexto — remova o
filtro
</option>
)}
{data[key] && !choices.some((o) => o.value === String(data[key])) && (
<option value={String(data[key])}>Selecção indisponível neste contexto — remova o filtro</option>
)}
{choices.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
@@ -136,9 +114,7 @@ export default function OpportunitySearchFilters({
{choices.length === 0
? specialisedEmpty[key]
: `${choices.length} opções públicas disponíveis, mesmo sem oportunidades associadas.`}
{key === 'subsector_id' &&
choices.length > 0 &&
' Classificação de actividades; não confirma a existência de investimentos nesta localização.'}
{key === 'subsector_id' && choices.length > 0 && ' Classificação de actividades; não confirma a existência de investimentos nesta localização.'}
</p>
)}
{hint && <p className="text-sm text-slate-600">{hint}</p>}
@@ -224,394 +200,306 @@ export default function OpportunitySearchFilters({
);
return (
<form
className="catalogue-filters"
className="space-y-5 rounded-xl border bg-white p-4 sm:p-6"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
aria-label="Pesquisar oportunidades"
>
<button
type="button"
className="catalogue-filters-toggle"
aria-expanded={expanded}
aria-controls="catalogue-filter-fields"
onClick={() => setExpanded((value) => !value)}
>
<SlidersHorizontal size={18} aria-hidden="true" />
<span>Filtros</span>
{active.length + path.length > 0 && (
<span className="catalogue-count">
{active.length + path.length}
</span>
)}
<ChevronDown size={18} aria-hidden="true" />
</button>
<h2 className="catalogue-filters-heading">
<SlidersHorizontal size={17} aria-hidden="true" />
Filtros
</h2>
<div
id="catalogue-filter-fields"
className={`${expanded ? 'block' : 'hidden'} space-y-5 lg:block`}
>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
<Field label="O que procura">
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
<Field label="O que procura">
<input
className={input}
value={String(data.q)}
placeholder="Palavras do título ou da descrição"
onChange={(e) => change({ q: e.target.value })}
/>
</Field>
{select('perspective', [{value:'exists',label:'O que existe'},{value:'needs',label:'Necessidades identificadas'},{value:'ideas',label:'Ideias de investimento'},{value:'opportunities',label:'Oportunidades cadastradas — disponibilidade na ficha'}])}
{select('sector', choicesFor('sector'))}
{select('category', choicesFor('category'))}
</div>
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<legend className="mb-2 font-semibold">Localização</legend>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${path[index - 1]?.id ?? ''}`}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint="/api/v1/investment/territory-options"
onChange={(value) =>
territory([
...path.slice(0, index),
...(value ? [value] : []),
])
}
/>
))}
</fieldset>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Field label="Estado de preparação">
<select
className={input}
value={String(data.preparation ?? '')}
onChange={(e) =>
change({
preparation: e.target.value,
maturity_level: '',
})
}
>
<option value="">Todos os estados</option>
{[
'Etapas de preparação',
'Classificações históricas',
].map((group) => (
<optgroup key={group} label={group}>
{(references.preparationOptions ?? [])
.filter((o) => o.group === group)
.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</optgroup>
))}
</select>
<p className="text-sm text-slate-600">
Os registos históricos são apresentados separadamente e
conservam a classificação indicada na ficha.
</p>
</Field>
{(['min_amount', 'max_amount'] as const).map((key) => (
<Field key={key} label={labels[key]}>
<input
className={input}
value={String(data.q)}
placeholder="Palavras do título ou da descrição"
onChange={(e) => change({ q: e.target.value })}
type="number"
min="0"
step="0.01"
value={String(data[key])}
onChange={(e) => change({ [key]: e.target.value })}
/>
</Field>
{select('perspective', [
{ value: 'exists', label: 'O que existe' },
{ value: 'needs', label: 'Necessidades identificadas' },
{ value: 'ideas', label: 'Ideias de investimento' },
{
value: 'opportunities',
label: 'Oportunidades cadastradas — disponibilidade na ficha',
},
])}
{select('sector', choicesFor('sector'))}
{select('category', choicesFor('category'))}
</div>
<CatalogueFilterGroup title="Localização" count={path.length}>
<p className="text-sm leading-relaxed text-slate-600">
A província inclui as oportunidades dos seus distritos,
postos administrativos e localidades. Não é necessário
escolher todos os níveis. O contexto provincial de um
corredor é identificado nos resultados; não confirma uma
implantação distrital.
</p>
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
<legend className="sr-only">Localização</legend>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${path[index - 1]?.id ?? ''}`}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint="/api/v1/investment/territory-options"
onChange={(value) =>
territory([
...path.slice(0, index),
...(value ? [value] : []),
])
}
/>
))}
</fieldset>
</CatalogueFilterGroup>
<CatalogueFilterGroup
title="Preparação e investimento"
count={
[
'preparation',
'min_amount',
'max_amount',
'currency',
].filter((key) => data[key]).length
}
>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
<Field label="Estado de preparação">
<select
className={input}
value={String(data.preparation ?? '')}
onChange={(e) =>
change({
preparation: e.target.value,
maturity_level: '',
})
}
>
<option value="">Todos os estados</option>
{[
'Etapas de preparação',
'Classificações históricas',
].map((group) => (
<optgroup key={group} label={group}>
{(references.preparationOptions ?? [])
.filter((o) => o.group === group)
.map((o) => (
<option
key={o.value}
value={o.value}
>
{o.label}
</option>
))}
</optgroup>
))}
</select>
<p className="text-sm text-slate-600">
Os registos históricos são apresentados
separadamente e conservam a classificação
indicada na ficha.
</p>
</Field>
{(['min_amount', 'max_amount'] as const).map((key) => (
<Field key={key} label={labels[key]}>
<input
className={input}
type="number"
min="0"
step="0.01"
value={String(data[key])}
onChange={(e) =>
change({ [key]: e.target.value })
}
/>
</Field>
))}
{select(
'currency',
['MZN', 'USD', 'EUR', 'ZAR'].map((c) => ({
value: c,
label: c,
})),
'Seleccione uma moeda para comparar montantes. Não se efectuam conversões cambiais.',
)}
</div>
</CatalogueFilterGroup>
<CatalogueFilterGroup
title="Mais filtros"
expandedTitle="Menos filtros"
count={
active.filter(([key]) =>
[
'corridor_id',
'cluster_id',
'zee_id',
'zfi_id',
'park_id',
'project_id',
'subsector_id',
'chain_id',
'before',
'include_national',
'facets',
].includes(key),
).length
}
>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
{[
'corridor_id',
'cluster_id',
'zee_id',
'zfi_id',
'park_id',
'project_id',
'subsector_id',
'chain_id',
].map((key) => select(key, choicesFor(key)))}
<Field label="Data-alvo até">
<input
className={input}
type="date"
value={String(data.before)}
onChange={(e) =>
change({ before: e.target.value })
}
/>
</Field>
</div>
<p className="my-3 text-sm">
Estes filtros procuram associações documentadas. Estar
perto de um parque ou no mesmo distrito não constitui
associação, nem confirma incentivos ou disponibilidade.
</p>
<label className="flex gap-2">
))}
{select(
'currency',
['MZN', 'USD', 'EUR', 'ZAR'].map((c) => ({
value: c,
label: c,
})),
'Seleccione uma moeda para comparar montantes. Não se efectuam conversões cambiais.',
)}
</div>
<details>
<summary className="cursor-pointer rounded border p-3 font-semibold focus-visible:outline-2">
Mais filtros
</summary>
<div className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{[
'corridor_id',
'cluster_id',
'zee_id',
'zfi_id',
'park_id',
'project_id',
'subsector_id',
'chain_id',
].map((key) => select(key, choicesFor(key)))}
<Field label="Data-alvo até">
<input
type="checkbox"
checked={Boolean(data.include_national)}
onChange={(e) =>
change({ include_national: e.target.checked })
}
className={input}
type="date"
value={String(data.before)}
onChange={(e) => change({ before: e.target.value })}
/>
Incluir oportunidades de âmbito nacional
</label>
<details className="mt-3">
<summary className="cursor-pointer font-medium">
Outras características
</summary>
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
{[
'education',
'infrastructure',
'labour',
'qualification',
'support',
'impact',
'partnership',
]
.filter((group) =>
references.options.some(
(o) => o.group === group,
),
)
.map((group) => (
<fieldset
key={group}
className="rounded border p-3"
>
<legend>{groupLabels[group]}</legend>
{references.options
.filter((o) => o.group === group)
.map((option) => (
<label
key={option.id}
className="flex gap-2 py-1"
>
<input
type="checkbox"
checked={
</Field>
</div>
<p className="my-3 text-sm">
Estes filtros procuram associações documentadas. Estar perto
de um parque ou no mesmo distrito não constitui associação,
nem confirma incentivos ou disponibilidade.
</p>
<label className="flex gap-2">
<input
type="checkbox"
checked={Boolean(data.include_national)}
onChange={(e) =>
change({ include_national: e.target.checked })
}
/>
Incluir oportunidades de âmbito nacional
</label>
<details className="mt-3">
<summary className="cursor-pointer font-medium">
Outras características
</summary>
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{[
'education',
'infrastructure',
'labour',
'qualification',
'support',
'impact',
'partnership',
]
.filter((group) =>
references.options.some(
(o) => o.group === group,
),
)
.map((group) => (
<fieldset
key={group}
className="rounded border p-3"
>
<legend>{groupLabels[group]}</legend>
{references.options
.filter((o) => o.group === group)
.map((option) => (
<label
key={option.id}
className="flex gap-2 py-1"
>
<input
type="checkbox"
checked={
Array.isArray(
data.facets,
) &&
data.facets.includes(
option.id,
)
}
onChange={(e) => {
const selected =
Array.isArray(
data.facets,
) &&
data.facets.includes(
option.id,
)
}
onChange={(e) => {
const selected =
Array.isArray(
data.facets,
)
? data.facets
: [];
change({
facets: e.target
.checked
? [
...selected,
? data.facets
: [];
change({
facets: e.target
.checked
? [
...selected,
option.id,
]
: selected.filter(
(id) =>
id !==
option.id,
]
: selected.filter(
(
id,
) =>
id !==
option.id,
),
});
}}
/>
{option.label}
</label>
))}
</fieldset>
))}
</div>
</details>
</CatalogueFilterGroup>
<section
aria-label="Filtros activos"
className="catalogue-active-filters flex flex-wrap gap-2"
>
{path.map((node, index) => (
<button
className="rounded border px-3 py-2"
type="button"
key={node.id}
aria-label={`Remover localização ${node.name}`}
onClick={() => territory(path.slice(0, index))}
>
{node.name} ×
</button>
))}
{active.flatMap(([key, value]) =>
key === 'facets' && Array.isArray(value)
? value.map((id) => (
<button
key={`facet-${id}`}
type="button"
className="rounded border px-3 py-2"
onClick={() =>
change({
facets: value.filter(
(x) => x !== id,
),
})
}
>
{' '}
{references.options.find(
(o) => o.id === id,
)?.label ?? 'Critério adicional'}{' '}
×
</button>
))
: [
<button
key={key}
type="button"
className="rounded border px-3 py-2 text-left"
aria-label={`Remover ${labels[key] ?? 'critério adicional'}`}
onClick={() => remove(key)}
>
{labels[key] ?? 'Critério adicional'}:{' '}
{typeof value === 'boolean'
? 'Sim'
: (choicesFor(key).find(
(o) =>
o.value === String(value),
)?.label ??
([
'q',
'min_amount',
'max_amount',
'currency',
'before',
'province',
'district',
].includes(key)
? String(value)
: 'seleccionado'))}{' '}
×
</button>,
],
)}
</section>
{Object.entries(errors).map(([key, value]) => (
<p key={key} role="alert">
{value}
</p>
))}
<div className="catalogue-filter-submit grid gap-3">
{select('sort', [
{ value: 'recent', label: 'Mais recentes' },
{ value: 'title', label: 'Título' },
{
value: 'amount_asc',
label: 'Montante crescente, por moeda',
},
{
value: 'amount_desc',
label: 'Montante decrescente, por moeda',
},
])}
<button className={button}>
<Search size={16} aria-hidden="true" />
Pesquisar
</button>
),
});
}}
/>
{option.label}
</label>
))}
</fieldset>
))}
</div>
</details>
</details>
<section
aria-label="Filtros activos"
className="flex flex-wrap gap-2"
>
{path.map((node, index) => (
<button
className="rounded border px-3 py-2"
type="button"
className="rounded border px-4 py-2 underline"
onClick={clear}
key={node.id}
aria-label={`Remover localização ${node.name}`}
onClick={() => territory(path.slice(0, index))}
>
Limpar filtros
{node.name} ×
</button>
</div>
))}
{active.flatMap(([key, value]) =>
key === 'facets' && Array.isArray(value)
? value.map((id) => (
<button
key={`facet-${id}`}
type="button"
className="rounded border px-3 py-2"
onClick={() =>
change({
facets: value.filter((x) => x !== id),
})
}
>
{' '}
{references.options.find((o) => o.id === id)
?.label ?? 'Critério adicional'}{' '}
×
</button>
))
: [
<button
key={key}
type="button"
className="rounded border px-3 py-2 text-left"
aria-label={`Remover ${labels[key] ?? 'critério adicional'}`}
onClick={() => remove(key)}
>
{labels[key] ?? 'Critério adicional'}:{' '}
{typeof value === 'boolean'
? 'Sim'
: (choicesFor(key).find(
(o) => o.value === String(value),
)?.label ??
([
'q',
'min_amount',
'max_amount',
'currency',
'before',
'province',
'district',
].includes(key)
? String(value)
: 'seleccionado'))}{' '}
×
</button>,
],
)}
</section>
{Object.entries(errors).map(([key, value]) => (
<p key={key} role="alert">
{value}
</p>
))}
<div className="flex flex-wrap items-end gap-4">
{select('sort', [
{ value: 'recent', label: 'Mais recentes' },
{ value: 'title', label: 'Título' },
{
value: 'amount_asc',
label: 'Montante crescente, por moeda',
},
{
value: 'amount_desc',
label: 'Montante decrescente, por moeda',
},
])}
<button className={button}>Pesquisar</button>
<button
type="button"
className="rounded border px-4 py-2 underline"
onClick={clear}
>
Limpar filtros
</button>
</div>
</form>
);
@@ -1,3 +1,6 @@
import {SimulationIrpcEconomic} from './simulation-irpc-economic';
import {FiscalProofParcelFields} from './fiscal-proof-parcel';
import {SimulationIrpcCarry} from './simulation-irpc-carry';
import {SimulationIrpcInternational} from './simulation-irpc-international';
import {SimulationIrpcPec} from './simulation-irpc-pec';
import {useState} from 'react';
@@ -17,10 +20,10 @@ export function SimulationIrpcAnnual({draft,onChange}:Props){
<p>Colecta disponível:{a.colecta?a.colecta.numerator+'/'+a.colecta.denominator+' MZN':'Indeterminada'};origem:{a.kind==='special'?'L7 qualificado':'L6 normal'};NUIT:{a.subjectNuit||'Por identificar'};exercício:{a.year||'Por identificar'}.</p><button type="button" onClick={()=>{try{save(reuseAnnualAssessment(draft,b));}catch(e){setError(String(e));}}}>Reutilizar colecta corrente L6/L7</button>{field('assessmentReference','Suporte da colecta reutilizada L8')}
<fieldset className="space-y-2 rounded border p-3"><legend>Retenções efectivamente sofridas por conta</legend>{group('withholdings','Retenções sofridas')}
{options.length===0?<p>Não há afectações de comprovativosL5 neste contexto. Reutilize e reconcilie a retenção recebida emL5 ou declare ausência com suporte.</p>:options.map(o=><div key={o.rowId+'|'+o.paymentId} className="rounded border p-2"><p>{o.document||'Prova por identificar'};emitente:{o.issuer};data:{o.date};parcelaL5:{o.amount}MZN;{o.reason||'Retenção recebida/efectiva por conta reconciliada emL5.'}</p><button type="button" disabled={!o.ready||b.withholdings.rows.some(r=>r.rowId===o.rowId&&r.paymentId===o.paymentId)} onClick={()=>{try{save(reuseAnnualWithholding(draft,b,o.rowId,o.paymentId,crypto.randomUUID()));}catch(e){setError(String(e));}}}>Seleccionar prova L5 {o.document||o.paymentId}</button></div>)}
{b.withholdings.rows.map((r,index)=>{const change=(p:Partial<typeof r>)=>patch({withholdings:{...b.withholdings,rows:b.withholdings.rows.map(x=>x.id===r.id?{...x,...p}:x)}});return<fieldset key={r.id} className="rounded border p-2"><legend>Retenção seleccionada {index+1}</legend><p>Rendimento:{r.rowId};prova:{r.paymentId};NUIT:{r.subjectNuit};exercício:{r.year}. Fonte conservada. Se mudou, retire esta selecção e seleccione a prova actual. O histórico mantém-se.</p><label className="block">Parcela a abater<input aria-label={'Parcela da retenção L8 '+(index+1)} value={r.amount} onChange={e=>change({amount:e.target.value})}/></label><label className="block">O próprio sujeito é beneficiário e o rendimento está incluído na base deste exercício<select aria-label={'Rendimento incluído L8 '+(index+1)} value={r.incomeIncluded} onChange={e=>change({incomeIncluded:e.target.value as ''|'yes'|'no'})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — crédito não aplicável neste fecho</option></select></label><label className="block">Suporte da titularidade e inclusão<input aria-label={'Suporte da retenção L8 '+(index+1)} value={r.reference} onChange={e=>change({reference:e.target.value})}/></label><button type="button" onClick={()=>patch({withholdings:{...b.withholdings,rows:b.withholdings.rows.filter(x=>x.id!==r.id)}})}>Retirar selecção L8 da retenção {index+1}</button></fieldset>;})}</fieldset>
{b.withholdings.rows.map((r,index)=>{const change=(p:Partial<typeof r>)=>patch({withholdings:{...b.withholdings,rows:b.withholdings.rows.map(x=>x.id===r.id?{...x,...p}:x)}});return<fieldset key={r.id} className="rounded border p-2"><legend>Retenção seleccionada {index+1}</legend><p>Rendimento:{r.rowId};prova:{r.paymentId};NUIT:{r.subjectNuit};exercício:{r.year}. Fonte conservada. Se mudou, retire esta selecção e seleccione a prova actual. O histórico mantém-se.</p><label className="block">Parcela a abater<input aria-label={'Parcela da retenção L8 '+(index+1)} value={r.amount} onChange={e=>change({amount:e.target.value})}/></label><label className="block">O próprio sujeito é beneficiário e o rendimento está incluído na base deste exercício<select aria-label={'Rendimento incluído L8 '+(index+1)} value={r.incomeIncluded} onChange={e=>change({incomeIncluded:e.target.value as ''|'yes'|'no'})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — crédito não aplicável neste fecho</option></select></label><label className="block">Suporte da titularidade e inclusão<input aria-label={'Suporte da retenção L8 '+(index+1)} value={r.reference} onChange={e=>change({reference:e.target.value})}/></label><FiscalProofParcelFields value={r} change={change} label={"Retenção L8 "+(index+1)}/><button type="button" onClick={()=>patch({withholdings:{...b.withholdings,rows:b.withholdings.rows.filter(x=>x.id!==r.id)}})}>Retirar selecção L8 da retenção {index+1}</button></fieldset>;})}</fieldset>
<fieldset className="space-y-2 rounded border p-3"><legend>PPC efectivamente pagos</legend>{group('ppc','PPC efectuados')}<p>Regista comprovativos de pagamentos por conta; não calcula automaticamente a obrigação PPC nem usa pagamentos previstos no plano.</p><button type="button" onClick={()=>patch({ppc:{...b.ppc,rows:[...b.ppc.rows,{...newAnnualPpc(crypto.randomUUID()),subjectNuit:b.subjectNuit,year:b.year}]}})}>Registar comprovativo PPC</button>
{b.ppc.rows.map((r,index)=>{const change=(p:Partial<AnnualPpc>)=>patch({ppc:{...b.ppc,rows:b.ppc.rows.map(x=>x.id===r.id?{...x,...p}:x)}});return<fieldset key={r.id} className="rounded border p-2"><legend>PPC {index+1}</legend>{([['document','Comprovativo'],['issuer','Emitente'],['date','Data (AAAA-MM-DD)'],['subjectNuit','NUIT beneficiário'],['year','Exercício do comprovativo'],['currency','Moeda do comprovativo'],['proofAmount','Montante comprovado'],['amount','Parcela a abater'],['reference','Suporte do pagamento e afectação']]as const).map(([key,label])=><label key={key} className="block">{label}<input aria-label={'PPC L8 '+(index+1)+' — '+label} value={r[key]} onChange={e=>change({[key]:e.target.value})}/></label>)}<label className="block">Pagamento efectivamente comprovado<select aria-label={'PPC L8 '+(index+1)+' — Efectivo'} value={r.effective} onChange={e=>change({effective:e.target.value as ''|'yes'|'no'})}><option value="">Informação em falta</option><option value="yes">Sim — comprovativo reconciliado</option><option value="no">Não — apenas previsão/outro estado</option></select></label><button type="button" onClick={()=>patch({ppc:{...b.ppc,rows:b.ppc.rows.filter(x=>x.id!==r.id)}})}>Retirar PPC {index+1}</button></fieldset>;})}</fieldset>
<SimulationIrpcInternational book={b} save={save}/><SimulationIrpcPec book={b} save={save}/>{([...(b.pecPayments?[]:[['pec','PEC']as const]),...(b.internationalCredits?[]:[['credits','Créditos com regras próprias']as const])]).map(([key,label])=><fieldset key={key} className="rounded border p-3"><legend>{label} — tratamento separado</legend><label className="block">Estado — {label}<select aria-label={'Estado L8 — '+label} value={b[key].state} onChange={e=>patch({[key]:{...b[key],state:e.target.value as ''|'known'|'absent'}})}><option value="">Informação em falta</option><option value="absent">Ausência declarada com suporte</option><option value="known">Valor conhecido — positivo exige regra própria</option></select></label>{(b[key].state==='known'||b[key].amount)&&<label className="block">Montante declarado<input aria-label={'Montante L8 — '+label} value={b[key].amount} onChange={e=>patch({[key]:{...b[key],amount:e.target.value}})}/></label>}<label className="block">Suporte<input aria-label={'Suporte L8 — '+label} value={b[key].reference} onChange={e=>patch({[key]:{...b[key],reference:e.target.value}})}/></label></fieldset>)}
{b.ppc.rows.map((r,index)=>{const change=(p:Partial<AnnualPpc>)=>patch({ppc:{...b.ppc,rows:b.ppc.rows.map(x=>x.id===r.id?{...x,...p}:x)}});return<fieldset key={r.id} className="rounded border p-2"><legend>PPC {index+1}</legend>{([['document','Comprovativo'],['issuer','Emitente'],['date','Data (AAAA-MM-DD)'],['subjectNuit','NUIT beneficiário'],['year','Exercício do comprovativo'],['currency','Moeda do comprovativo'],['proofAmount','Montante comprovado'],['amount','Parcela a abater'],['reference','Suporte do pagamento e afectação']]as const).map(([key,label])=><label key={key} className="block">{label}<input aria-label={'PPC L8 '+(index+1)+' — '+label} value={r[key]} onChange={e=>change({[key]:e.target.value})}/></label>)}<label className="block">Pagamento efectivamente comprovado<select aria-label={'PPC L8 '+(index+1)+' — Efectivo'} value={r.effective} onChange={e=>change({effective:e.target.value as ''|'yes'|'no'})}><option value="">Informação em falta</option><option value="yes">Sim — comprovativo reconciliado</option><option value="no">Não — apenas previsão/outro estado</option></select></label><FiscalProofParcelFields value={r} change={change} label={"PPC L8 "+(index+1)}/><button type="button" onClick={()=>patch({ppc:{...b.ppc,rows:b.ppc.rows.filter(x=>x.id!==r.id)}})}>Retirar PPC {index+1}</button></fieldset>;})}</fieldset>
<SimulationIrpcEconomic book={b} save={save} residentConfirmed={a.current&&a.book.scope==='resident_general'&&b.subjectNuit===a.subjectNuit&&b.year===a.year&&b.assessmentKey===a.key}/><SimulationIrpcInternational book={b} save={save}/><SimulationIrpcPec book={b} save={save}/><SimulationIrpcCarry book={b} save={save}/>{([...(b.pecPayments?[]:[['pec','PEC']as const]),...(b.internationalCredits?[]:[['credits','Créditos com regras próprias']as const])]).map(([key,label])=><fieldset key={key} className="rounded border p-3"><legend>{label} — tratamento separado</legend><label className="block">Estado — {label}<select aria-label={'Estado L8 — '+label} value={b[key].state} onChange={e=>patch({[key]:{...b[key],state:e.target.value as ''|'known'|'absent'}})}><option value="">Informação em falta</option><option value="absent">Ausência declarada com suporte</option><option value="known">Valor conhecido — positivo exige regra própria</option></select></label>{(b[key].state==='known'||b[key].amount)&&<label className="block">Montante declarado<input aria-label={'Montante L8 — '+label} value={b[key].amount} onChange={e=>patch({[key]:{...b[key],amount:e.target.value}})}/></label>}<label className="block">Suporte<input aria-label={'Suporte L8 — '+label} value={b[key].reference} onChange={e=>patch({[key]:{...b[key],reference:e.target.value}})}/></label></fieldset>)}
<button type="button" onClick={()=>{try{save(recordAnnual(draft,b));}catch(e){setError(String(e));}}}>Calcular e guardar saldo anual L8</button><button type="button" onClick={()=>{try{const html=annualHtml(draft),url=URL.createObjectURL(new Blob([html],{type:'text/html;charset=utf-8'})),link=document.createElement('a');link.href=url;link.download='IRPC-L8-saldo-simulado.html';link.click();URL.revokeObjectURL(url);setError('');}catch(e){setError(String(e));}}}>Exportar saldo anual L8</button>
{annualReportRows(draft).map((r,n)=><p key={n}>{r[1]} — {r[2]} — {r[3]}</p>)}</section>;
}catch(e){return<p role="alert">PreparaçãoL8 não recuperável:{String(e)}. Originais e históricos conservados.</p>;}
@@ -0,0 +1,53 @@
import {prepareCreditCarry, type AnnualBook} from '@/lib/irpc-annual-settlement';
import {carrySource, newCarryLot, newCarryUse, type CarryLot, type CreditCarry} from '@/lib/irpc-credit-carry';
import CountrySelect, {type Country} from '@/components/country-select';
import {countryIsoCodes} from '@/lib/country-iso-codes';
const pt = new Intl.DisplayNames(['pt'], {type: 'region'});
const en = new Intl.DisplayNames(['en'], {type: 'region'});
const countries: Country[] = countryIsoCodes.filter(code => code !== 'MZ').map(code => ({code, name: pt.of(code) ?? code, name_en: en.of(code) ?? code})).sort((a, b) => a.name.localeCompare(b.name, 'pt'));
export function SimulationIrpcCarry({book, save}: {book: AnnualBook; save: (book: AnnualBook) => void}) {
const c = book.creditCarry;
if (!c) return <fieldset className="rounded border p-3"><legend>Saldos de exercícios anteriores</legend><p>Se dispõe de remanescentes documentados de crédito internacional ou PEC, prepare a origem e as utilizações efectivas. Os resultados anteriores ficam conservados.</p><button type="button" onClick={() => save(prepareCreditCarry(book))}>Preparar saldos anteriores</button></fieldset>;
const update = (value: CreditCarry) => save({...book, creditCarry: value});
const lotChange = (r: CarryLot) => update({...c, lots: c.lots.map(x => x.id === r.id ? r : x)});
return <fieldset className="space-y-3 rounded border p-3"><legend>Crédito internacional e PEC — exercícios anteriores</legend>
<p>{carrySource}</p>
<label className="block">Inventário de saldos anteriores<select aria-label="Estado dos saldos anteriores L8" value={c.state} onChange={e => update({...c, state: e.target.value as CreditCarry['state']})}><option value="">Informação em falta</option><option value="known">Saldos conhecidos</option><option value="absent">Ausência documentada</option></select></label>
<label className="block">Suporte do inventário<input aria-label="Suporte dos saldos anteriores L8" value={c.reference} onChange={e => update({...c, reference: e.target.value})}/></label>
{(c.state === 'known' || c.lots.length > 0) && <>
<p>Consolide uma origem por natureza, país e exercício. Transcreva o montante elegível apurado e o deduzido na origem, com o suporte da regra desse exercício. Imposto estrangeiro acima dos limites de elegibilidade não é remanescente por insuficiência de colecta. Só se aplica aqui o prazo ordinário a exercícios anuais; situações transitórias ou especiais exigem correspondência própria.</p>
<button type="button" onClick={() => update({...c, lots: [...c.lots, {...newCarryLot(crypto.randomUUID()), subjectNuit: book.subjectNuit}]})}>Registar origem de saldo anterior</button>
</>}
{c.lots.map((r, i) => {
const patch = (v: Partial<CarryLot>) => lotChange({...r, ...v});
const prefix = 'Saldo anterior ' + (i + 1) + ' — ';
return <fieldset key={r.id} className="space-y-2 rounded border p-3"><legend>Origem {i + 1}</legend>
<label className="block">Natureza<select aria-label={prefix + 'Natureza'} value={r.kind} onChange={e => patch({kind: e.target.value as CarryLot['kind']})}><option value="">Por identificar</option><option value="international">Crédito por dupla tributação internacional</option><option value="pec">PEC efectivamente pago</option></select></label>
{(r.kind === 'international' || r.country) && <CountrySelect countries={countries} label={prefix + 'País estrangeiro'} value={r.country} onChange={country => patch({country})} allowLegacyValue/>}
{r.kind === 'pec' && <p>O PEC não tem país estrangeiro. A escolha da natureza conserva os valores introduzidos; reconcilie qualquer país anterior.</p>}
{([['subjectNuit', 'NUIT titular'], ['year', 'Exercício de origem'], ['currency', 'Moeda comprovada'], ['originDocument', 'Declaração/apuramento de origem'], ['originReference', 'Suporte da origem e insuficiência de colecta'], ['ruleReference', 'Regra e período aplicáveis na origem'], ['eligible', 'Montante elegível na origem — MZN'], ['originDeducted', 'Deduzido na origem — MZN'], ['selected', 'Parcela escolhida para este fecho — MZN']] as const).map(([key, label]) => <label key={key} className="block">{label}<input aria-label={prefix + label} value={r[key]} onChange={e => patch({[key]: e.target.value})}/></label>)}
<label className="block">Exercício de origem anual ordinário<select aria-label={prefix + 'Período ordinário'} value={r.ordinary} onChange={e => patch({ordinary: e.target.value as CarryLot['ordinary']})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — regra específica por corresponder</option></select></label>
<label className="block">Remanescente por insuficiência de colecta<select aria-label={prefix + 'Insuficiência de colecta'} value={r.insufficient} onChange={e => patch({insufficient: e.target.value as CarryLot['insufficient']})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — não é saldo elegível neste percurso</option></select></label>
<label className="block">Utilizações efectivas posteriores à origem<select aria-label={prefix + 'Estado dos usos'} value={r.usesState} onChange={e => patch({usesState: e.target.value as CarryLot['usesState']})}><option value="">Informação em falta</option><option value="known">Utilizações conhecidas</option><option value="absent">Ausência documentada</option></select></label>
<label className="block">Suporte do inventário de utilizações<input aria-label={prefix + 'Suporte dos usos'} value={r.usesReference} onChange={e => patch({usesReference: e.target.value})}/></label>
<p>Inclua utilizações efectivas já ocorridas neste exercício antes desta parcela. Não registe simulações históricas como utilizações fiscais. Crédito internacional admite fracção exacta n/d; não é aplicado arredondamento fiscal.</p>
{r.usesState === 'known' && <button type="button" onClick={() => patch({uses: [...r.uses, newCarryUse(crypto.randomUUID())]})}>Registar utilização efectiva da origem {i + 1}</button>}
{r.uses.map((u, j) => <fieldset key={u.id} className="rounded border p-2"><legend>Utilização {i + 1}.{j + 1}</legend>
{([['year', 'Exercício'], ['amount', 'Montante MZN'], ['document', 'Documento de utilização'], ['reference', 'Suporte']] as const).map(([key, label]) => <label key={key} className="block">{label}<input aria-label={prefix + 'Uso ' + (j + 1) + ' — ' + label} value={u[key]} onChange={e => patch({uses: r.uses.map(x => x.id === u.id ? {...x, [key]: e.target.value} : x)})}/></label>)}
<button type="button" onClick={() => patch({uses: r.uses.filter(x => x.id !== u.id)})}>Retirar utilização {i + 1}.{j + 1}</button>
</fieldset>)}
<button type="button" onClick={() => update({...c, lots: c.lots.filter(x => x.id !== r.id)})}>Retirar origem {i + 1}</button>
</fieldset>;
})}
{(c.state === 'known' || c.currentInternational || c.currentPec || c.allocationReference) && <fieldset className="space-y-2 rounded border p-3"><legend>Escolha das parcelas entre exercícios</legend>
<p>Escolha quanto deduzir dos créditos correntes e de cada origem anterior. Os créditos internacionais precedem o PEC; a soma fica limitada à colecta. Não se presume prioridade entre exercícios e nenhuma parcela é reduzida automaticamente. Valores não escolhidos ficam identificados, sem criação de transporte oficial.</p>
<label className="block">Crédito internacional corrente a deduzir — MZN<input aria-label="Parcela corrente internacional L8" value={c.currentInternational} onChange={e => update({...c, currentInternational: e.target.value})}/></label>
<label className="block">PEC corrente a deduzir — MZN<input aria-label="Parcela corrente PEC L8" value={c.currentPec} onChange={e => update({...c, currentPec: e.target.value})}/></label>
<label className="block">Suporte da escolha e seus impactos<input aria-label="Suporte da afectação entre exercícios L8" value={c.allocationReference} onChange={e => update({...c, allocationReference: e.target.value})}/></label>
<button type="button" onClick={() => update({...c, assessmentKey: book.assessmentKey})}>Confirmar afectação à colecta seleccionada</button>
<p>{c.assessmentKey && c.assessmentKey === book.assessmentKey ? 'Escolha vinculada à colecta seleccionada; o cálculo verifica disponibilidade e limites.' : 'Falta confirmar a escolha na colecta seleccionada. Valores conservados.'}</p>
</fieldset>}
</fieldset>;
}
@@ -0,0 +1,41 @@
import {prepareEconomicBook, type AnnualBook} from '@/lib/irpc-annual-settlement';
import {economicSource, newEconomicPosition, type EconomicPosition} from '@/lib/irpc-economic-credit';
export function SimulationIrpcEconomic({book, save, residentConfirmed}: {book: AnnualBook; save: (book: AnnualBook) => void; residentConfirmed: boolean}) {
const c = book.economicCredits;
if (!c) return <fieldset className="rounded border p-3"><legend>Crédito por dupla tributação económica</legend><p>Para lucros distribuídos por entidade moçambicana sujeita e não isenta de IRPC, distinga o imposto correspondente aos lucros da retenção sofrida e do imposto estrangeiro. Reutiliza a colecta e conserva o resumo de créditos anterior.</p><button type="button" onClick={() => save(prepareEconomicBook(book))}>Preparar crédito económico</button></fieldset>;
const update = (next: typeof c) => save({...book, economicCredits: next});
const rowChange = (r: EconomicPosition) => update({...c, rows: c.rows.map(x => x.id === r.id ? r : x)});
return <fieldset className="space-y-3 rounded border p-3"><legend>Crédito económico — lucros distribuídos</legend>
<p>{economicSource}</p>
<p>O detalhe substitui nesta execução o resumo económico anterior, que permanece conservado: {book.internationalCredits?.economic.state || 'informação em falta'}; montante {book.internationalCredits?.economic.amount || 'não preenchido'}. Os benefícios e o crédito internacional mantêm os seus estados próprios.</p>
<label className="block">Estado do crédito económico<select aria-label="Estado do crédito económico L8" value={c.state} onChange={e => update({...c, state: e.target.value as typeof c.state})}><option value="">Informação em falta</option><option value="known">Lucros e IRPC conhecidos</option><option value="absent">Ausência documentada</option></select></label>
<label className="block">Suporte do inventário económico<input aria-label="Suporte económico L8" value={c.reference} onChange={e => update({...c, reference: e.target.value})}/></label>
{(c.state === 'known' || c.rows.length > 0) && <button type="button" onClick={() => update({...c, state: 'known', rows: [...c.rows, {...newEconomicPosition(crypto.randomUUID()), subjectNuit: book.subjectNuit, year: book.year, recipientResident: residentConfirmed ? 'yes' : ''}]})}>Registar lucros distribuídos</button>}
{c.rows.map((r, i) => {
const patch = (v: Partial<EconomicPosition>) => rowChange({...r, ...v});
const prefix = 'Crédito económico ' + (i + 1) + ' — ';
const field = (key: Exclude<keyof EconomicPosition, 'previousUse'>, label: string) => <label key={key} className="block">{label}<input aria-label={prefix + label} value={r[key]} onChange={e => patch({[key]: e.target.value})}/></label>;
const choice = (key: 'recipientResident' | 'payerResident' | 'payerIrpc' | 'payerExempt' | 'article40' | 'incomeIncluded', label: string) => <label key={key} className="block">{label}<select aria-label={prefix + label} value={r[key]} onChange={e => patch({[key]: e.target.value})}><option value="">Informação em falta</option><option value="yes">Sim — documentado</option><option value="no">Não — documentado</option></select></label>;
const outside = !!r.kind && r.kind !== 'ordinary_profit' || r.article40 === 'yes';
const detail = <>
{([['distributionDocument', 'Documento da distribuição'], ['distributionParcel', 'Parcela dos lucros no documento'], ['distributionDate', 'Data da distribuição (AAAA-MM-DD)'], ['income', 'Lucros incluídos antes do crédito — MZN, ilíquidos de retenção'], ['incomeReference', 'Suporte da inclusão e do valor ilíquido na base corrente'], ['taxIssuer', 'Emitente do comprovativo de IRPC correspondente'], ['taxDocument', 'Documento do IRPC correspondente aos lucros'], ['taxParcel', 'Parcela desse IRPC no documento'], ['parcelReference', 'Suporte da identificação da parcela de imposto'], ['currency', 'Moeda comprovada'], ['proofAmount', 'IRPC comprovado nesta parcela — MZN'], ['taxAmount', 'IRPC correspondente aos lucros seleccionados — MZN'], ['attributionReference', 'Suporte da correspondência entre imposto e lucros'], ['previouslyAttributed', 'IRPC desta parcela já atribuído a outros lucros — MZN'], ['priorAttributionReference', 'Suporte das atribuições anteriores, incluindo zero conhecido'], ['grossUpIncluded', 'Crédito nominal já acrescido à base (art.53) — MZN'], ['grossUpReference', 'Suporte do acréscimo art.53 já incluído em L6'], ['nationalLimit', 'Quota proporcional da colecta após acréscimo — MZN'], ['nationalLimitReference', 'Suporte da quota proporcional da colecta']] as const).map(([key, label]) => field(key, label))}
{choice('incomeIncluded', 'Lucros ilíquidos e acréscimo incluídos na base corrente')}
<p>O cálculo confere 60% do IRPC correspondente com o acréscimo já incluído em L6 e a quota proporcional documentada. Se a base estiver incompleta, reconcilie-a no percurso existente. Esta acção conserva os valores e não altera a colecta automaticamente.</p>
<button type="button" onClick={() => patch({assessmentKey: book.assessmentKey})}>Confirmar inclusão e quota na colecta seleccionada</button>
<label className="block">Utilização anterior efectiva do crédito<select aria-label={prefix + 'Estado do uso anterior'} value={r.previousUse.state} onChange={e => patch({previousUse: {...r.previousUse, state: e.target.value as EconomicPosition['previousUse']['state']}})}><option value="">Informação em falta</option><option value="known">Montante conhecido</option><option value="absent">Ausência documentada</option></select></label>
{(r.previousUse.state === 'known' || r.previousUse.amount) && <label className="block">Crédito já utilizado — MZN<input aria-label={prefix + 'Uso anterior MZN'} value={r.previousUse.amount} onChange={e => patch({previousUse: {...r.previousUse, amount: e.target.value}})}/></label>}
<label className="block">Suporte do uso anterior ou da sua ausência<input aria-label={prefix + 'Suporte do uso anterior'} value={r.previousUse.reference} onChange={e => patch({previousUse: {...r.previousUse, reference: e.target.value}})}/></label>
</>;
return <fieldset key={r.id} className="space-y-2 rounded border p-3"><legend>Lucros {i + 1}</legend>
{field('subjectNuit', 'NUIT beneficiário')}{field('payerNuit', 'NUIT distribuidor')}{field('year', 'Exercício')}
<label className="block">Natureza<select aria-label={prefix + 'Natureza'} value={r.kind} onChange={e => patch({kind: e.target.value as EconomicPosition['kind']})}><option value="">Por identificar</option><option value="ordinary_profit">Lucros ordinários — art.64(1–2)</option><option value="liquidation">Partilha em liquidação — art.64(3)</option><option value="association">Associação — art.64(4)</option></select></label>
{residentConfirmed && r.recipientResident === 'yes' ? <p>Residência do beneficiário reutilizada da colecta corrente no regime geral. NUIT e exercício conservados.</p> : choice('recipientResident', 'Beneficiário com sede/direcção efectiva em Moçambique')}{choice('payerResident', 'Distribuidor com sede/direcção efectiva em Moçambique')}{choice('payerIrpc', 'Distribuidor sujeito a IRPC')}{choice('payerExempt', 'Distribuidor isento de IRPC')}{field('qualificationReference', 'Suporte da qualificação das entidades e dos lucros')}
{choice('article40', 'Esta parcela está abrangida pela exclusão do art.40(1)')}{field('article40Reference', 'Suporte da correspondência do art.40(1) e seu período')}
<p>O art.40(1), na redacção de 2009, contempla as entidades e condições próprias, incluindo participação directa de pelo menos20% e prazo de dois anos, nos termos da fonte. Uma parcela excluída da base não recebe também o crédito64. A simples percentagem de participação não decide todas as condições.</p>
{outside ? <><p>Esta parcela exige o tratamento específico identificado. O crédito ordinário não é aplicado; os valores introduzidos ficam conservados.</p><details><summary>Consultar ou reconciliar dados conservados</summary>{detail}</details></> : detail}
<button type="button" onClick={() => update({...c, rows: c.rows.filter(x => x.id !== r.id)})}>Retirar lucros {i + 1}</button>
</fieldset>;
})}
</fieldset>;
}
@@ -1,3 +1,4 @@
import {FiscalProofParcelFields} from './fiscal-proof-parcel';
import CountrySelect, {type Country} from '@/components/country-select';
import {countryIsoCodes} from '@/lib/country-iso-codes';
import {newInternationalProof, prepareInternationalBook, type AnnualBook} from '@/lib/irpc-annual-settlement';
@@ -22,9 +23,9 @@ export function SimulationIrpcInternational({book, save}: {book: AnnualBook; sav
<p>Reúna os comprovativos de cada país numa posição por exercício. Indique a fracção nacional e a convenção conforme o suporte do caso. Limites admitem decimal ou fracção exacta n/d; a apresentação não constitui arredondamento fiscal. Valores MZN exigem correspondência documental; uma previsão de câmbio ou de pagamento não comprova o crédito.</p>
<label className="block">Estado internacional<select aria-label="Estado do crédito internacional L8" value={c.state} onChange={e => update({...c, state: e.target.value as InternationalCredits['state']})}><option value="">Informação em falta</option><option value="known">Posições conhecidas</option><option value="absent">Ausência declarada</option></select></label>
<label className="block">Suporte do inventário<input aria-label="Suporte do crédito internacional L8" value={c.reference} onChange={e => update({...c, reference: e.target.value})}/></label>
<Evidence label="Crédito económico — regra própria" value={c.economic} change={economic => update({...c, economic})}/>
{book.economicCredits ? <p>Resumo económico anterior conservado: {c.economic.state || "Informação em falta"}; {c.economic.amount || "Montante não preenchido"}. Nesta execução é usado o detalhe económico acima.</p> : <Evidence label="Crédito económico — regra própria" value={c.economic} change={economic => update({...c, economic})}/>}
<Evidence label="Benefícios/créditos próprios — regra própria" value={c.benefits} change={benefits => update({...c, benefits})}/>
<p>Créditos económicos e benefícios positivos exigem regras próprias; informação em falta mantém o saldo dependente indeterminado.</p>
<p>{book.economicCredits ? "Benefícios positivos exigem regras próprias; o crédito económico tem o seu detalhe separado. Informação em falta mantém o saldo dependente indeterminado." : "Créditos económicos e benefícios positivos exigem regras próprias; informação em falta mantém o saldo dependente indeterminado."}</p>
<button type="button" onClick={() => update({...c, state: 'known', positions: [...c.positions, {...newInternationalPosition(crypto.randomUUID()), subjectNuit: book.subjectNuit, year: book.year, assessmentKey: book.assessmentKey}]})}>Registar posição internacional</button>
{c.positions.map((p, index) => {
const patch = (v: Partial<InternationalPosition>) => positionChange({...p, ...v});
@@ -47,7 +48,7 @@ export function SimulationIrpcInternational({book, save}: {book: AnnualBook; sav
{(r.exerciseReference || r.date && !r.date.startsWith(p.year + '-')) && <label className="block">Suporte da correspondência da data ao exercício<input aria-label={'Imposto estrangeiro ' + (index + 1) + '.' + (ri + 1) + ' — Correspondência temporal'} value={r.exerciseReference} onChange={e => change({exerciseReference: e.target.value})}/></label>}
<label className="block">Pagamento efectivo<select aria-label={'Imposto estrangeiro ' + (index + 1) + '.' + (ri + 1) + ' — Efectivo'} value={r.effective} onChange={e => change({effective: e.target.value as InternationalTaxProof['effective']})}><option value="">Informação em falta</option><option value="yes">Sim — comprovado</option><option value="no">Não — previsão/outra situação</option></select></label>
<label className="block">Imposto sobre o rendimento elegível<select aria-label={'Imposto estrangeiro ' + (index + 1) + '.' + (ri + 1) + ' — Natureza'} value={r.incomeTax} onChange={e => change({incomeTax: e.target.value as InternationalTaxProof['incomeTax']})}><option value="">Informação em falta</option><option value="yes">Sim — natureza documentada</option><option value="no">Não — outra natureza, sem crédito presumido</option></select></label>
<button type="button" onClick={() => patch({payments: p.payments.filter(x => x.id !== r.id)})}>Retirar imposto estrangeiro {index + 1}.{ri + 1}</button>
<FiscalProofParcelFields value={r} change={change} label={"Imposto estrangeiro " + (index + 1) + "." + (ri + 1)}/><button type="button" onClick={() => patch({payments: p.payments.filter(x => x.id !== r.id)})}>Retirar imposto estrangeiro {index + 1}.{ri + 1}</button>
</fieldset>;
})}
<button type="button" onClick={() => update({...c, positions: c.positions.filter(x => x.id !== p.id)})}>Retirar posição internacional {index + 1}</button>
@@ -1,3 +1,4 @@
import {FiscalProofParcelFields} from './fiscal-proof-parcel';
import {newPecPayment, pecSource, type PecPayment} from '@/lib/irpc-pec';
import type {AnnualBook} from '@/lib/irpc-annual-settlement';
@@ -15,7 +16,7 @@ export function SimulationIrpcPec({book, save}: {book: AnnualBook; save: (book:
return <fieldset key={r.id} className="rounded border p-2"><legend>PEC {index + 1}</legend>
{([['document', 'Comprovativo PEC'], ['issuer', 'Emitente'], ['date', 'Data (AAAA-MM-DD)'], ['subjectNuit', 'NUIT beneficiário'], ['year', 'Exercício de origem'], ['currency', 'Moeda'], ['proofAmount', 'Montante comprovado'], ['previouslyUsed', 'Já utilizado fora destas parcelas'], ['priorUseReference', 'Suporte das utilizações anteriores ou do zero conhecido'], ['amount', 'Parcela disponível seleccionada'], ['reference', 'Suporte do pagamento PEC e afectação']] as const).map(([key, label]) => <label key={key} className="block">{label}<input aria-label={'PEC L8 ' + (index + 1) + ' — ' + label} value={r[key]} onChange={e => change({[key]: e.target.value})}/></label>)}
<label className="block">Pagamento PEC efectivamente comprovado<select aria-label={'PEC L8 ' + (index + 1) + ' — Efectivo'} value={r.effective} onChange={e => change({effective: e.target.value as PecPayment['effective']})}><option value="">Informação em falta</option><option value="yes">Sim — natureza PEC e pagamento reconciliados</option><option value="no">Não — previsão ou outra natureza</option></select></label>
<button type="button" onClick={() => update({...detail, rows: detail.rows.filter(x => x.id !== r.id)})}>Retirar selecção PEC {index + 1}</button>
<FiscalProofParcelFields value={r} change={change} label={"PEC L8 " + (index + 1)}/><button type="button" onClick={() => update({...detail, rows: detail.rows.filter(x => x.id !== r.id)})}>Retirar selecção PEC {index + 1}</button>
</fieldset>;
})}
<p>O detalhe substitui o resumo PEC apenas nesta execução. Os comprovativos e resultados de execuções anteriores permanecem no histórico; não há consumo automático de saldos oficiais.</p>
+12
View File
@@ -0,0 +1,12 @@
export type FiscalProofParcel = {parcel?: string; parcelReference?: string};
export const canonicalParcel = (s: string) => s.normalize('NFKC').trim().toLocaleLowerCase('pt').replace(/\s+/g, ' ');
export function validateProofParcel(r: FiscalProofParcel) {
if (r.parcel !== undefined && typeof r.parcel !== 'string' || r.parcelReference !== undefined && typeof r.parcelReference !== 'string') throw Error('Identificação da parcela documental não recuperável; original conservado.');
}
export function requireProofParcel(r: FiscalProofParcel) {
validateProofParcel(r);
if (!!r.parcel?.trim() !== !!r.parcelReference?.trim()) throw Error('Parcela documental e suporte devem corresponder; não se presume que linhas distintas representam impostos diferentes.');
}
export const parcelProjection = (r: FiscalProofParcel): FiscalProofParcel => ({...(r.parcel === undefined ? {} : {parcel: r.parcel}), ...(r.parcelReference === undefined ? {} : {parcelReference: r.parcelReference})});
// Old proofs without a parcel cover the physical document. They overlap any newly identified parcel until reconciled.
export const overlappingProofParcels = (a: FiscalProofParcel & {identity: string}, b: FiscalProofParcel & {identity: string}) => a.identity === b.identity && (!a.parcel?.trim() || !b.parcel?.trim() || canonicalParcel(a.parcel) === canonicalParcel(b.parcel));
+84 -26
View File
@@ -1,3 +1,6 @@
import {carryPlan,carryIdentity,carrySource,newCreditCarry,validateCreditCarry,type CreditCarry} from './irpc-credit-carry.ts';
import {economicTaxProof,economicGroupPending,economicDistributionIdentity,economicPosition,economicDeduction,economicSource,newEconomicCredits,validateEconomic,type EconomicCredits} from './irpc-economic-credit.ts';
import {validateProofParcel,requireProofParcel,parcelProjection,overlappingProofParcels,type FiscalProofParcel} from './fiscal-proof-parcel.ts';
import {validateInternational,internationalProofValue,internationalGroupPending,internationalPosition,internationalDeduction,internationalCreditSource,newInternationalCredits,type InternationalCredits,type InternationalTaxProof} from './irpc-international-credit.ts';
import {validatePec,pecPaymentValue,pecDeduction,pecSource,type PecPayments} from './irpc-pec.ts';
import {normalBook,normalCurrent} from './irpc-normal.ts';
@@ -11,14 +14,21 @@ export const annualSettlementSource='CIRPC, arts. 63 e 67 (Lei 34/2007 e naturez
type State=''|'known'|'absent';
type Evidence={state:State;amount:string;reference:string};
type Group={state:State;reference:string};
export type AnnualWithholding={id:string;rowId:string;paymentId:string;sourceKey:string;subjectNuit:string;year:string;amount:string;incomeIncluded:''|'yes'|'no';reference:string};
export type AnnualPpc={id:string;document:string;issuer:string;date:string;subjectNuit:string;year:string;currency:string;proofAmount:string;amount:string;effective:''|'yes'|'no';reference:string};
export type AnnualWithholding=FiscalProofParcel&{id:string;rowId:string;paymentId:string;sourceKey:string;subjectNuit:string;year:string;amount:string;incomeIncluded:''|'yes'|'no';reference:string};
export type AnnualPpc=FiscalProofParcel&{id:string;document:string;issuer:string;date:string;subjectNuit:string;year:string;currency:string;proofAmount:string;amount:string;effective:''|'yes'|'no';reference:string};
type AnnualRecord={version:typeof annualSettlementVersion;key:string;createdAt:string;model:AnnualModel};
export type AnnualBook={version:1;subjectNuit:string;year:string;reference:string;assessment:''|'normal'|'special';assessmentKey:string;assessmentReference:string;withholdings:Group&{rows:AnnualWithholding[]};ppc:Group&{rows:AnnualPpc[]};pec:Evidence;pecPayments?:PecPayments;credits:Evidence;internationalCredits?:InternationalCredits;result?:AnnualRecord;history:AnnualRecord[]};
export type AnnualBook={version:1;subjectNuit:string;year:string;reference:string;assessment:''|'normal'|'special';assessmentKey:string;assessmentReference:string;withholdings:Group&{rows:AnnualWithholding[]};ppc:Group&{rows:AnnualPpc[]};pec:Evidence;pecPayments?:PecPayments;credits:Evidence;internationalCredits?:InternationalCredits;creditCarry?:CreditCarry;economicCredits?:EconomicCredits;result?:AnnualRecord;history:AnnualRecord[]};
export const annualSource=(b:AnnualBook)=>{
const excluded=b.internationalCredits?(b.pecPayments?'Créditos económicos/benefícios positivos':'PEC/créditos económicos/benefícios positivos'):(b.pecPayments?'Créditos próprios positivos':'PEC/créditos positivos');
return annualSettlementSource.replace('PEC/créditos positivos',excluded)+(b.pecPayments?' '+pecSource:'')+(b.internationalCredits?' '+internationalCreditSource:'');
return annualSettlementSource.replace('PEC/créditos positivos',b.economicCredits?(b.pecPayments?'Benefícios positivos':'PEC/benefícios positivos'):excluded)+(b.pecPayments?' '+pecSource:'')+(b.internationalCredits?' '+internationalCreditSource:'')+(b.creditCarry?' '+carrySource:'')+(b.economicCredits?' '+economicSource:'');
};
export function prepareEconomicBook(b:AnnualBook):AnnualBook{
if(b.economicCredits)return b;
const next=prepareInternationalBook(b),e=newEconomicCredits(),old=next.internationalCredits!.economic;
if(old.state==='absent'){e.state='absent';e.reference=old.reference;}
return{...next,economicCredits:e};
}
export function prepareCreditCarry(b:AnnualBook):AnnualBook{return b.creditCarry?b:{...b,creditCarry:newCreditCarry()};}
export function prepareInternationalBook(b:AnnualBook):AnnualBook{
if(b.internationalCredits)return b;
const c=newInternationalCredits(),old=b.credits;
@@ -41,6 +51,8 @@ const proofIdentity=(issuer:string,document:string,_date:string)=>JSON.stringify
function store(d:Record<string,unknown>){const s=JSON.parse(String(d.modelo_a_snapshot||'{"version":1,"books":{}}'));if(s.version!==1||!s.books||typeof s.books!=='object'||Array.isArray(s.books))throw Error('Livros fiscais não recuperáveis;originais conservados.');return s;}
function books(d:Record<string,unknown>):Record<string,AnnualBook>{const m=store(d).irpcAnnual;if(m===undefined)return{};if(!m||typeof m!=='object'||Array.isArray(m))throw Error('MapaL8 não recuperável;originais conservados.');return m;}
export function validateAnnual(b:AnnualBook){
if(b?.economicCredits!==undefined)validateEconomic(b.economicCredits);
if(b?.creditCarry!==undefined)validateCreditCarry(b.creditCarry);
if(b?.pecPayments!==undefined)validatePec(b.pecPayments);
if(b?.internationalCredits!==undefined)validateInternational(b.internationalCredits);
if(!b||b.version!==1||['subjectNuit','year','reference','assessmentKey','assessmentReference'].some(k=>typeof b[k as 'year']!=='string')||!['','normal','special'].includes(b.assessment)||!Array.isArray(b.history))throw Error('PreparaçãoL8 não recuperável.');
@@ -48,6 +60,7 @@ export function validateAnnual(b:AnnualBook){
for(const g of[b.pec,b.credits])if(typeof g.amount!=='string')throw Error('CréditoL8 não recuperável.');
const w=['id','rowId','paymentId','sourceKey','subjectNuit','year','amount','incomeIncluded','reference'],p=Object.keys(newAnnualPpc(''));
for(const[rows,keys]of[[b.withholdings.rows,w],[b.ppc.rows,p]]as const)if(!Array.isArray(rows)||new Set(rows.map(r=>r?.id)).size!==rows.length||rows.some(r=>!r||keys.some(k=>typeof(r as unknown as Record<string,unknown>)[k]!=='string')))throw Error('ComprovativosL8 não recuperáveis ou identificador repetido.');
for(const r of[...b.withholdings.rows,...b.ppc.rows])validateProofParcel(r);
if(b.withholdings.rows.some(r=>!['','yes','no'].includes(r.incomeIncluded))||b.ppc.rows.some(r=>!['','yes','no'].includes(r.effective)))throw Error('QualificaçãoL8 não recuperável.');
for(const r of[b.result,...b.history])if(r&&(r.version!==annualSettlementVersion||typeof r.key!=='string'||typeof r.createdAt!=='string'||!r.model||!Array.isArray(r.model.pending)))throw Error('HistóricoL8 não recuperável.');
}
@@ -72,7 +85,7 @@ export function reuseAnnualWithholding(d:Record<string,unknown>,b:AnnualBook,row
if(b.withholdings.rows.some(r=>r.rowId===rowId&&r.paymentId===paymentId))throw Error('Retenção/prova já seleccionada;altere a parcela existente sem duplicar.');
return{...b,withholdings:{...b.withholdings,rows:[...b.withholdings.rows,{id,rowId,paymentId,sourceKey:o.key,subjectNuit:b.subjectNuit,year:o.year,amount:o.amount,incomeIncluded:'',reference:''}]}};
}
function dependencies(d:Record<string,unknown>){let normal:unknown,L5:unknown;try{const a=annualAssessment(d);normal=[a.record,a.current];}catch(e){normal=String(e);}try{const b=irpcBook(d);L5=[b.rows,b.payments,b.result,irpcCurrent(d,b)];}catch(e){L5=String(e);}return[normal,L5,Object.entries(books(d)).filter(([k])=>k!==acquisitionScope(d)).map(([k,b])=>[k,b.subjectNuit,b.year,b.withholdings,b.ppc,...(b.pecPayments?[b.pecPayments]:[]),...(b.internationalCredits?[b.internationalCredits]:[])])];}
function dependencies(d:Record<string,unknown>){let normal:unknown,L5:unknown;try{const a=annualAssessment(d);normal=[a.record,a.current];}catch(e){normal=String(e);}try{const b=irpcBook(d);L5=[b.rows,b.payments,b.result,irpcCurrent(d,b)];}catch(e){L5=String(e);}return[normal,L5,Object.entries(books(d)).filter(([k])=>k!==acquisitionScope(d)).map(([k,b])=>[k,b.subjectNuit,b.year,b.withholdings,b.ppc,...(b.pecPayments?[b.pecPayments]:[]),...(b.internationalCredits?[b.internationalCredits]:[]),...(b.creditCarry?[b.creditCarry]:[]),...(b.economicCredits?[b.economicCredits]:[])])];}
function key(d:Record<string,unknown>,b:AnnualBook){const{result:_,history:__,...input}=b;return closureFingerprint([annualSettlementVersion,acquisitionScope(d),input,dependencies(d)]);}
export function annualCurrent(d:Record<string,unknown>,b:AnnualBook){return !!b.result&&b.result.key===key(d,b);}
export function calculateAnnual(d:Record<string,unknown>,b:AnnualBook){
@@ -89,43 +102,74 @@ export function calculateAnnual(d:Record<string,unknown>,b:AnnualBook){
group(b.withholdings,b.withholdings.rows,'Retenções sofridas por conta');group(b.ppc,b.ppc.rows,'PPC efectuados');
try{if(b.withholdings.state==='absent'&&options.some(o=>o.ready&&o.year===b.year&&cmp(moneyInput(o.amount),zero())>0n))pending.push('Ausência de retenções sofridas contradiz provaL5 efectiva por conta no exercício;reconcilie sem a ignorar.');}catch(e){pending.push('Reconciliação da ausência de retenções: '+String(e));}
for(const[label,e]of[...(b.pecPayments?[]:[['PEC',b.pec]as const]),...(b.internationalCredits?[]:[['Créditos com regras próprias',b.credits]as const])]){try{if(!e.state||!e.reference.trim())throw Error('presença/ausência e suporte em falta');if(e.state==='absent'){if(e.amount.trim())throw Error('ausência contradiz montante preenchido');}else if(cmp(moneyInput(e.amount),zero())!==0n)throw Error('montante positivo fora deste recorte:corresponder ordem,limite e transporte próprios;sem abatimento ou reembolso automático');}catch(err){pending.push(label+': '+String(err));}}
const claims:Array<{id:string;kind:'withholding'|'ppc'|'pec'|'foreign_credit';country?:string;positionId?:string;previouslyUsed?:FiscalFraction;identity:string;proofAmount:FiscalFraction|null;value:FiscalFraction|null;sourceKey:string;allocationAmount:FiscalFraction|null;document:string;issuer:string;date:string;subjectNuit:string;year:string;reason:string}>=[];
const claims:Array<FiscalProofParcel&{id:string;kind:'withholding'|'ppc'|'pec'|'foreign_credit'|'economic_credit';country?:string;positionId?:string;previouslyUsed?:FiscalFraction;identity:string;proofAmount:FiscalFraction|null;value:FiscalFraction|null;sourceKey:string;allocationAmount:FiscalFraction|null;document:string;issuer:string;date:string;subjectNuit:string;year:string;reason:string}>=[];
for(const r of b.withholdings.rows){const o=options.find(o=>o.rowId===r.rowId&&o.paymentId===r.paymentId),issues:string[]=[];let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null;
try{if(!o||!o.ready||r.sourceKey!==o.key)throw Error(o?.reason||'provaL5 ausente ou alterada;reutilize sem duplicar');if(r.subjectNuit!==b.subjectNuit||r.year!==b.year||o.year!==b.year||!o.date.startsWith(b.year+'-'))throw Error('entidade/exercício da retenção não correspondem ao fecho');if(r.incomeIncluded!=='yes'||!r.reference.trim())throw Error('confirme o próprio beneficiário/NUIT e inclusão do rendimento na base do exercício com suporte');value=moneyInput(r.amount);proofAmount=moneyInput(o.proofAmount);if(cmp(value,moneyInput(o.amount))>0n)throw Error('parcela ultrapassa a retenção efectivamente comprovada e afectada emL5');if(b.withholdings.rows.filter(x=>x.rowId===r.rowId&&x.paymentId===r.paymentId).length!==1)throw Error('retenção/prova repetida;uma afectação por linhaL5');if(assessment?.record?.model.special?.cooperative.status==='calculated'&&cmp(value,zero())>0n)throw Error('cooperativa integralmente elegível declara ausência de rendimentos retidos;segregue o casoL7 antes do crédito anual');}catch(e){issues.push(String(e));value=null;}
claims.push({id:r.id,kind:'withholding',identity:o?.identity??'',proofAmount,value,sourceKey:r.sourceKey,allocationAmount:o&&value?moneyInput(o.amount):null,document:o?.document??r.paymentId,issuer:o?.issuer??'',date:o?.date??'',subjectNuit:r.subjectNuit,year:r.year,reason:issues.join(' ')});
try{requireProofParcel(r);if(!o||!o.ready||r.sourceKey!==o.key)throw Error(o?.reason||'provaL5 ausente ou alterada;reutilize sem duplicar');if(r.subjectNuit!==b.subjectNuit||r.year!==b.year||o.year!==b.year||!o.date.startsWith(b.year+'-'))throw Error('entidade/exercício da retenção não correspondem ao fecho');if(r.incomeIncluded!=='yes'||!r.reference.trim())throw Error('confirme o próprio beneficiário/NUIT e inclusão do rendimento na base do exercício com suporte');value=moneyInput(r.amount);proofAmount=moneyInput(o.proofAmount);if(cmp(value,moneyInput(o.amount))>0n)throw Error('parcela ultrapassa a retenção efectivamente comprovada e afectada emL5');if(b.withholdings.rows.filter(x=>x.rowId===r.rowId&&x.paymentId===r.paymentId).length!==1)throw Error('retenção/prova repetida;uma afectação por linhaL5');if(assessment?.record?.model.special?.cooperative.status==='calculated'&&cmp(value,zero())>0n)throw Error('cooperativa integralmente elegível declara ausência de rendimentos retidos;segregue o casoL7 antes do crédito anual');}catch(e){issues.push(String(e));value=null;}
claims.push({...parcelProjection(r),id:r.id,kind:'withholding',identity:o?.identity??'',proofAmount,value,sourceKey:r.sourceKey,allocationAmount:o&&value?moneyInput(o.amount):null,document:o?.document??r.paymentId,issuer:o?.issuer??'',date:o?.date??'',subjectNuit:r.subjectNuit,year:r.year,reason:issues.join(' ')});
}
for(const r of b.ppc.rows){const issues:string[]=[];let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null;
try{if(!r.document.trim()||!r.issuer.trim()||!r.reference.trim()||r.effective!=='yes'||r.currency!=='MZN'||!iso(r.date)||!r.date.startsWith(b.year+'-')||r.subjectNuit!==b.subjectNuit||r.year!==b.year)throw Error('PPC exige comprovativo efectivo,MZN,data,entidade e exercício correspondentes;projecção/tesouraria não é pagamento');value=moneyInput(r.amount);proofAmount=moneyInput(r.proofAmount);if(cmp(value,proofAmount)>0n)throw Error('parcelaPPC ultrapassa o montante comprovado');}catch(e){issues.push(String(e));value=null;}
claims.push({id:r.id,kind:'ppc',identity:proofIdentity(r.issuer,r.document,r.date),proofAmount,value,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason:issues.join(' ')});
try{requireProofParcel(r);if(!r.document.trim()||!r.issuer.trim()||!r.reference.trim()||r.effective!=='yes'||r.currency!=='MZN'||!iso(r.date)||!r.date.startsWith(b.year+'-')||r.subjectNuit!==b.subjectNuit||r.year!==b.year)throw Error('PPC exige comprovativo efectivo,MZN,data,entidade e exercício correspondentes;projecção/tesouraria não é pagamento');value=moneyInput(r.amount);proofAmount=moneyInput(r.proofAmount);if(cmp(value,proofAmount)>0n)throw Error('parcelaPPC ultrapassa o montante comprovado');}catch(e){issues.push(String(e));value=null;}
claims.push({...parcelProjection(r),id:r.id,kind:'ppc',identity:proofIdentity(r.issuer,r.document,r.date),proofAmount,value,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason:issues.join(' ')});
}
if(b.pecPayments){group(b.pecPayments,b.pecPayments.rows,'PEC pagos no próprio exercício');for(const r of b.pecPayments.rows){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,previouslyUsed:FiscalFraction|undefined;let reason='';try{({value,proofAmount,previouslyUsed}=pecPaymentValue(r,b.subjectNuit,b.year));}catch(e){reason=String(e);}claims.push({id:r.id,kind:'pec',identity:proofIdentity(r.issuer,r.document,r.date),value,proofAmount,previouslyUsed,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason});}}
if(b.pecPayments){group(b.pecPayments,b.pecPayments.rows,'PEC pagos no próprio exercício');for(const r of b.pecPayments.rows){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,previouslyUsed:FiscalFraction|undefined;let reason='';try{({value,proofAmount,previouslyUsed}=pecPaymentValue(r,b.subjectNuit,b.year));}catch(e){reason=String(e);}claims.push({...parcelProjection(r),id:r.id,kind:'pec',identity:proofIdentity(r.issuer,r.document,r.date),value,proofAmount,previouslyUsed,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason});}}
if(b.internationalCredits){
pending.push(...internationalGroupPending(b.internationalCredits));
pending.push(...internationalGroupPending(b.internationalCredits,!!b.economicCredits));
const countries=b.internationalCredits.positions.map(p=>p.country);
if(new Set(countries).size!==countries.length)pending.push('Um país/exercício tem várias posições;consolide rendimentos e comprovativos sob uma única fracção nacional,sem repetir o limite.');
for(const p of b.internationalCredits.positions)for(const r of p.payments){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,reason='';try{({value,proofAmount}=internationalProofValue(r,b.subjectNuit,b.year));}catch(e){reason=String(e);}claims.push({id:r.id,kind:'foreign_credit',country:p.country,positionId:p.id,identity:proofIdentity(r.issuer,r.document,r.date),proofAmount,value,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason});}
for(const p of b.internationalCredits.positions)for(const r of p.payments){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,reason='';try{({value,proofAmount}=internationalProofValue(r,b.subjectNuit,b.year));}catch(e){reason=String(e);}claims.push({...parcelProjection(r),id:r.id,kind:'foreign_credit',country:p.country,positionId:p.id,identity:proofIdentity(r.issuer,r.document,r.date),proofAmount,value,sourceKey:'',allocationAmount:null,document:r.document,issuer:r.issuer,date:r.date,subjectNuit:r.subjectNuit,year:r.year,reason});}
}
const elsewhere:Array<{identity:string;subjectNuit:string;year:string;value:FiscalFraction;proofAmount:FiscalFraction;sourceKey:string;kind:'ppc'|'pec'|'withholding'|'foreign_credit';country?:string;previouslyUsed?:FiscalFraction}>=[];
for(const[scope,other]of Object.entries(books(d))){if(scope===acquisitionScope(d))continue;try{validateAnnual(other);for(const p of other.internationalCredits?.positions??[]){if(other.subjectNuit===b.subjectNuit&&other.year===b.year&&b.internationalCredits?.positions.some(x=>x.country===p.country))pending.push('País '+p.country+' já preparado noutro mapa da entidade/exercício;consolide a fracção nacional e usos sem duplicar quotas.');for(const r of p.payments){const v=internationalProofValue(r,other.subjectNuit,other.year);elsewhere.push({identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,...v,sourceKey:'',kind:'foreign_credit',country:p.country});}}for(const r of other.pecPayments?.rows??[]){const p=pecPaymentValue(r,other.subjectNuit,other.year);elsewhere.push({identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,...p,sourceKey:'',kind:'pec'});}for(const r of other.ppc.rows)elsewhere.push({identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,value:moneyInput(r.amount),proofAmount:moneyInput(r.proofAmount),sourceKey:'',kind:'ppc'});for(const r of other.withholdings.rows){const source=(store(d).irpcWithholdings??{})[scope];const row=source?.rows?.find((x:{id:string})=>x.id===r.rowId),p=source?.payments?.find((x:{id:string})=>x.id===r.paymentId);if(row&&p)elsewhere.push({identity:proofIdentity(row.counterparty,p.reference,p.date),subjectNuit:r.subjectNuit,year:r.year,value:moneyInput(r.amount),proofAmount:moneyInput(p.amount),sourceKey:r.sourceKey,kind:'withholding'});}}catch(e){if(other?.subjectNuit===b.subjectNuit)pending.push('Outro mapa da mesma entidade não recuperável para conferir duplicações: '+scope+';'+String(e));}}
for(const c of claims){if(!c.value||!c.proofAmount)continue;const same=claims.filter(x=>x.identity===c.identity&&x.value),other=elsewhere.filter(x=>x.identity===c.identity);let issue='';
if(same.filter(x=>x.kind!=='withholding').length>1||new Set(same.map(x=>x.kind)).size>1)issue='Mesmo comprovativo repetido ou usado com naturezas diferentes (retenção/PPC/PEC/crédito internacional);reconcilie sem dedução dupla.';
if(b.economicCredits){
pending.push(...economicGroupPending(b.economicCredits));
if(!b.internationalCredits)pending.push('Distinguir o detalhe económico do inventário internacional e dos benefícios; use a preparação existente sem apagar o resumo anterior.');
for(const r of b.economicCredits.rows){let value:FiscalFraction|null=null,proofAmount:FiscalFraction|null=null,previouslyUsed:FiscalFraction|undefined,reason='';try{({value,proofAmount,previouslyUsed}=economicTaxProof(r));}catch(e){reason=String(e);}claims.push({id:r.id,kind:'economic_credit',positionId:r.id,identity:proofIdentity(r.taxIssuer,r.taxDocument,r.distributionDate),parcel:r.taxParcel,parcelReference:r.parcelReference,proofAmount,value,previouslyUsed,sourceKey:'',allocationAmount:null,document:r.taxDocument,issuer:r.taxIssuer,date:r.distributionDate,subjectNuit:r.subjectNuit,year:r.year,reason});}
}
const elsewhere:Array<FiscalProofParcel&{identity:string;subjectNuit:string;year:string;value:FiscalFraction;proofAmount:FiscalFraction;sourceKey:string;kind:'ppc'|'pec'|'withholding'|'foreign_credit'|'economic_credit';country?:string;previouslyUsed?:FiscalFraction}>=[];
for(const[scope,other]of Object.entries(books(d))){if(scope===acquisitionScope(d))continue;try{validateAnnual(other);for(const r of other.economicCredits?.rows??[]){
if(b.economicCredits?.rows.some(x=>economicDistributionIdentity(x)===economicDistributionIdentity(r)))pending.push('Parcela de lucros económicos já preparada noutro mapa;consolide sem duplicar o crédito, mesmo com documentos de imposto diferentes.');
const v=economicTaxProof(r);elsewhere.push({identity:proofIdentity(r.taxIssuer,r.taxDocument,r.distributionDate),parcel:r.taxParcel,parcelReference:r.parcelReference,subjectNuit:r.subjectNuit,year:r.year,...v,sourceKey:'',kind:'economic_credit'});
}for(const p of other.internationalCredits?.positions??[]){if(other.subjectNuit===b.subjectNuit&&other.year===b.year&&b.internationalCredits?.positions.some(x=>x.country===p.country))pending.push('País '+p.country+' já preparado noutro mapa da entidade/exercício;consolide a fracção nacional e usos sem duplicar quotas.');for(const r of p.payments){const v=internationalProofValue(r,other.subjectNuit,other.year);elsewhere.push({...parcelProjection(r),identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,...v,sourceKey:'',kind:'foreign_credit',country:p.country});}}for(const r of other.pecPayments?.rows??[]){const p=pecPaymentValue(r,other.subjectNuit,other.year);elsewhere.push({...parcelProjection(r),identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,...p,sourceKey:'',kind:'pec'});}for(const r of other.ppc.rows)elsewhere.push({...parcelProjection(r),identity:proofIdentity(r.issuer,r.document,r.date),subjectNuit:r.subjectNuit,year:r.year,value:moneyInput(r.amount),proofAmount:moneyInput(r.proofAmount),sourceKey:'',kind:'ppc'});for(const r of other.withholdings.rows){const source=(store(d).irpcWithholdings??{})[scope];const row=source?.rows?.find((x:{id:string})=>x.id===r.rowId),p=source?.payments?.find((x:{id:string})=>x.id===r.paymentId);if(row&&p)elsewhere.push({...parcelProjection(r),identity:proofIdentity(row.counterparty,p.reference,p.date),subjectNuit:r.subjectNuit,year:r.year,value:moneyInput(r.amount),proofAmount:moneyInput(p.amount),sourceKey:r.sourceKey,kind:'withholding'});}}catch(e){if(other?.subjectNuit===b.subjectNuit)pending.push('Outro mapa da mesma entidade não recuperável para conferir duplicações: '+scope+';'+String(e));}}
for(const c of claims){if(!c.value||!c.proofAmount)continue;const same=claims.filter(x=>overlappingProofParcels(x,c)&&x.value),other=elsewhere.filter(x=>overlappingProofParcels(x,c));let issue='';
if(same.filter(x=>x.kind!=='withholding').length>1&&!same.every(x=>x.kind==='economic_credit')||new Set(same.map(x=>x.kind)).size>1)issue='Mesmo comprovativo repetido ou usado com naturezas diferentes (retenção/PPC/PEC/crédito internacional);reconcilie sem dedução dupla.';
if(other.some(x=>x.subjectNuit!==b.subjectNuit||x.year!==b.year))issue='Mesmo comprovativo já associado a outra entidade/exercício;reconcilie a titularidade e a afectação.';
if([...same,...other].some(x=>x.proofAmount&&cmp(x.proofAmount,c.proofAmount!)!==0n)||cmp(addFractions([...same.flatMap(x=>x.value?[x.value]:[]),...other.map(x=>x.value)]),c.proofAmount)>0n)issue='Comprovativo utilizado além do montante disponível ou com montantes divergentes neste/outro mapa.';
if(c.kind==='pec'&&c.previouslyUsed){if(other.some(x=>x.kind!=='pec')||other.some(x=>!x.previouslyUsed||cmp(x.previouslyUsed,c.previouslyUsed!)!==0n)||cmp(addFractions([c.previouslyUsed,...same.flatMap(x=>x.value?[x.value]:[]),...other.map(x=>x.value)]),c.proofAmount)>0n)issue='PEC com utilização anterior divergente, natureza incompatível ou parcelas acima do saldo disponível.';}
if((c.kind==='pec'||c.kind==='economic_credit')&&c.previouslyUsed){if(other.some(x=>x.kind!==c.kind)||[...same,...other].some(x=>!x.previouslyUsed||cmp(x.previouslyUsed,c.previouslyUsed!)!==0n)||cmp(addFractions([c.previouslyUsed,...same.flatMap(x=>x.value?[x.value]:[]),...other.map(x=>x.value)]),c.proofAmount)>0n)issue='PEC/IRPC económico com utilização/atribuição anterior divergente, natureza incompatível ou parcelas acima do saldo disponível.';}
if(other.some(x=>x.kind!==c.kind))issue='Comprovativo já afectado a outra natureza (retenção/PPC/PEC/crédito internacional);sem dupla dedução.';
if(c.kind==='foreign_credit'&&other.some(x=>x.country!==c.country))issue='Comprovativo estrangeiro associado a outro país/natureza;reconcilie sem duplicação.';
if(c.kind==='withholding'&&c.sourceKey&&c.allocationAmount&&cmp(addFractions([...same.filter(x=>x.sourceKey===c.sourceKey).flatMap(x=>x.value?[x.value]:[]),...other.filter(x=>x.sourceKey===c.sourceKey).map(x=>x.value)]),c.allocationAmount)>0n)issue='Mesma afectação L5 reutilizada além da parcela disponível, ainda que o comprovativo global seja maior.';
if(c.kind==='withholding'&&c.sourceKey&&c.allocationAmount&&cmp(addFractions([...claims.filter(x=>x.kind==='withholding'&&x.sourceKey===c.sourceKey).flatMap(x=>x.value?[x.value]:[]),...elsewhere.filter(x=>x.kind==='withholding'&&x.sourceKey===c.sourceKey).map(x=>x.value)]),c.allocationAmount)>0n)issue='Mesma afectação L5 reutilizada além da parcela disponível, ainda que o comprovativo global seja maior.';
if(issue)c.reason=[c.reason,issue].filter(Boolean).join(' ');
}
for(const c of claims)if(c.reason)pending.push((c.document||c.id)+': '+c.reason);
const knownWithholdings=addFractions(claims.filter(c=>c.kind==='withholding'&&!c.reason&&c.value).map(c=>c.value!)),knownPpc=addFractions(claims.filter(c=>c.kind==='ppc'&&!c.reason&&c.value).map(c=>c.value!));
const positions=b.internationalCredits?.positions.map(p=>{const own=claims.filter(c=>c.kind==='foreign_credit'&&c.positionId===p.id);const m=internationalPosition(p,addFractions(own.filter(c=>!c.reason&&c.value).map(c=>c.value!)),own.filter(c=>c.reason).map(c=>c.reason),b.subjectNuit,b.year,b.assessmentKey);pending.push(...m.pending.map(e=>'País '+p.country+': '+e));return m;})??[];
const ready=pending.length===0&&colecta!==null,international=b.internationalCredits?internationalDeduction(positions,colecta,ready):null,creditCollecta=international?.afterCredit??colecta;
const pec=b.pecPayments?pecDeduction(addFractions(claims.filter(c=>c.kind==='pec'&&!c.reason&&c.value).map(c=>c.value!)),creditCollecta,ready):null,arithmeticBalance=ready?subtractFractions(subtractFractions(pec?.afterPec??creditCollecta!,knownWithholdings),knownPpc):null;
const economicRows=b.economicCredits?.rows.map(r=>{
const issues=claims.filter(c=>c.kind==='economic_credit'&&c.positionId===r.id&&c.reason).map(c=>c.reason);
const m=economicPosition(r,b.subjectNuit,b.year,b.assessmentKey,colecta,issues);
pending.push(...m.pending.map(e=>'Lucros '+r.distributionDocument+': '+e));return m;
})??[];
if(b.economicCredits){
if(b.economicCredits.rows.length&&assessment?.kind!=='normal')pending.push('Crédito económico delimitado à colecta normal corrente;efeitos L7 exigem correspondência própria.');
}
const economicPreview=b.economicCredits?economicDeduction(economicRows,colecta,true):null;
const remainingForCarry=economicPreview?.afterCredit??colecta;
const pecAvailable=addFractions(claims.filter(c=>c.kind==='pec'&&!c.reason&&c.value).map(c=>c.value!));
const carryDuplicates:string[]=[];
if(b.creditCarry)for(const[scope,other]of Object.entries(books(d))){
if(scope===acquisitionScope(d)||other.subjectNuit!==b.subjectNuit)continue;
try{validateAnnual(other);if(other.creditCarry?.lots.some(r=>b.creditCarry!.lots.some(x=>carryIdentity(x)===carryIdentity(r))))carryDuplicates.push('Saldo anterior já preparado noutro mapa da entidade;consolide a origem e usos sem duplicar: '+scope);}
catch(e){carryDuplicates.push('Outro mapa da entidade não recuperável para conferir saldos anteriores: '+scope+';'+String(e));}
}
const carry=b.creditCarry?carryPlan(b.creditCarry,b.subjectNuit,b.year,b.assessmentKey,addFractions(positions.flatMap(p=>p.available&&!p.pending.length?[p.available]:[])),pecAvailable,remainingForCarry,carryDuplicates):null;
if(carry)pending.push(...carry.pending);
const ready=pending.length===0&&colecta!==null,economic=b.economicCredits?economicDeduction(economicRows,colecta,ready):null,afterEconomic=economic?.afterCredit??colecta;
const international=b.internationalCredits?internationalDeduction(positions,afterEconomic,ready,carry?.international??undefined):null;
const creditCollecta=ready&&carry?subtractFractions(international?.afterCredit??afterEconomic!,carry.priorInternational):international?.afterCredit??afterEconomic;
const pec=b.pecPayments?pecDeduction(pecAvailable,creditCollecta,ready,carry?.pec??undefined):null;
const afterPec=ready&&carry?subtractFractions(pec?.afterPec??creditCollecta!,carry.priorPec):pec?.afterPec??creditCollecta;
const arithmeticBalance=ready?subtractFractions(subtractFractions(afterPec!,knownWithholdings),knownPpc):null;
if(international&&international.insufficientCollecta&&cmp(international.insufficientCollecta,zero())>0n)warn.push('Crédito elegível sem colecta suficiente:sem reembolso,transporte ou escolha automática da afectação por país.');
let payable:FiscalFraction|null=null,recoverable:FiscalFraction|null=null,belowMinimum:FiscalFraction|null=null;let status:'payable'|'recoverable'|'balanced'|'below_minimum'|'indeterminate'='indeterminate';
if(arithmeticBalance){const n=BigInt(arithmeticBalance.numerator),abs=fraction(n<0n?-n:n,BigInt(arithmeticBalance.denominator));payable=zero();recoverable=zero();belowMinimum=zero();if(!n)status='balanced';else if(cmp(abs,fraction(100n))<0n){status='below_minimum';belowMinimum=abs;warn.push('Art27(6):saldo inferior a100MZN,sem cobrança/reembolso neste recorte;aritmética conservada,não é transporte de crédito.');}else if(n>0n){status='payable';payable=abs;}else{status='recoverable';recoverable=abs;}}
return{version:annualSettlementVersion,input:structuredClone(input),subjectNuit:b.subjectNuit,year:b.year,assessment:assessment?.record?{key:b.assessmentKey,kind:b.assessment,version:assessment.record.model.version,createdAt:assessment.record.createdAt,colecta,period:assessment.period,origin:assessment.record.model.origin}:null,claims,internationalCredit:international,pecDeduction:pec,knownWithholdings,knownPpc,arithmeticBalance,payable,recoverable,belowMinimum,status,pending:[...new Set(pending)],warnings:warn,source:annualSource(b),officialBalancesConsumed:false,submitted:false,refundReceived:false,limitations:[...(b.internationalCredits?['Crédito internacional do próprio exercício:fracção nacional,convenção e montantes MZN são documentados;sem cálculo presumido,transporte ou consumo oficial. Créditos económicos/benefícios positivos ficam separados.']:[]),b.internationalCredits?'L8 parcial:créditos económicos/benefícios positivos,transporte/caducidade,obrigações,tributação autónoma,períodos especiais e outras moedas separados. PEC sem reembolso ou transporte automático.':(b.pecPayments?'L8 parcial:transporte/caducidade de PEC, cálculo da obrigação, créditos próprios positivos, tributação autónoma, períodos especiais e outras moedas separados. Excedente PEC não é reembolso nem saldo transportado oficialmente.':'L8 parcial:PEC e créditos positivos,tributação autónoma,períodos especiais e pagamentos noutra moeda exigem regras próprias.'),'PPC aqui é pagamento comprovado;não cálculo automático da obrigação ou calendário.','Retenção sofrida não é retenção entregue pela empresa por conta de terceiros.','Valores racionais exactos;camposM20/M22 e representação não presumidos.','Saldo simulado por colecta projectada;sem pagamento,submissão ou reembolso automático.']};
return{version:annualSettlementVersion,input:structuredClone(input),subjectNuit:b.subjectNuit,year:b.year,assessment:assessment?.record?{key:b.assessmentKey,kind:b.assessment,version:assessment.record.model.version,createdAt:assessment.record.createdAt,colecta,period:assessment.period,origin:assessment.record.model.origin}:null,claims,...(economic?{economicCredit:economic}:{}),internationalCredit:international,pecDeduction:pec,...(carry?{creditCarry:{...carry,afterInternational:ready?creditCollecta:null,afterPec:ready?afterPec:null}}:{}),knownWithholdings,knownPpc,arithmeticBalance,payable,recoverable,belowMinimum,status,pending:[...new Set(pending)],warnings:warn,source:annualSource(b),officialBalancesConsumed:false,submitted:false,refundReceived:false,limitations:[...(b.economicCredits?['Crédito económico ordinário:IRPC correspondente aos lucros,acréscimo53 já incluído e quota proporcional documentados. Sem cálculo automático da inclusão ou da exclusão40;liquidação64(3),associações64(4),benefícios e regras especiais separados. Sem reembolso ou transporte económico presumidos.']:[]),...(b.creditCarry?['Saldos anteriores documentados: escolha explícita das parcelas correntes e anteriores, sem prioridade presumida entre exercícios, reembolso ou criação/consumo de saldos oficiais.']:[]),...(b.internationalCredits?['Crédito internacional do próprio exercício:fracção nacional,convenção e montantes MZN são documentados;sem cálculo presumido,transporte ou consumo oficial. '+(b.economicCredits?'Benefícios positivos ficam separados;crédito económico no detalhe próprio.':'Créditos económicos/benefícios positivos ficam separados.')]:[]),b.economicCredits?'L8 parcial:benefícios próprios,derivação automática de quotas,inclusão/correcção económica na base,liquidação/associações,obrigações,autónomos,períodos especiais,moedas eM20/M22 separados. Saldos anteriores só quando detalhados e documentados.':b.creditCarry?'L8 parcial:créditos económicos/benefícios,obrigações,tributação autónoma,períodos especiais,outras moedas e correspondência M20/M22 separados. Prazos dos saldos anteriores demonstrados apenas para origens anuais ordinárias documentadas;sem criação automática de transporte.':b.internationalCredits?'L8 parcial:créditos económicos/benefícios positivos,transporte/caducidade,obrigações,tributação autónoma,períodos especiais e outras moedas separados. PEC sem reembolso ou transporte automático.':(b.pecPayments?'L8 parcial:transporte/caducidade de PEC, cálculo da obrigação, créditos próprios positivos, tributação autónoma, períodos especiais e outras moedas separados. Excedente PEC não é reembolso nem saldo transportado oficialmente.':'L8 parcial:PEC e créditos positivos,tributação autónoma,períodos especiais e pagamentos noutra moeda exigem regras próprias.'),'PPC aqui é pagamento comprovado;não cálculo automático da obrigação ou calendário.','Retenção sofrida não é retenção entregue pela empresa por conta de terceiros.','Valores racionais exactos;camposM20/M22 e representação não presumidos.','Saldo simulado por colecta projectada;sem pagamento,submissão ou reembolso automático.']};
}
export type AnnualModel=ReturnType<typeof calculateAnnual>;
export function recordAnnual(d:Record<string,unknown>,b:AnnualBook,now=new Date().toISOString()):AnnualBook{return{...b,history:b.result?[...b.history,structuredClone(b.result)]:b.history,result:{version:annualSettlementVersion,key:key(d,b),createdAt:now,model:calculateAnnual(d,b)}};}
@@ -140,13 +184,27 @@ export function annualReportRows(d:Record<string,unknown>):Array<[string,string,
'NUIT: '+m.subjectNuit+'; exercício: '+m.year+'; colecta: '+show(m.assessment?.colecta??null)+'; origem: '+(m.assessment?.kind==='special'?'L7 qualificado':'L6 normal')+'. '+(annualCurrent(d,b)?'Entradas correspondentes.':'Histórico; origem/entradas alteradas: recalcule o saldo corrente.')+' Saldo simulado, não liquidação submetida.',
m.input.reference+'; '+m.input.assessmentReference+'; '+m.source],
...m.claims.map(c=>[
'IRPC — L8',(c.kind==='withholding'?'Retenção sofrida':c.kind==='pec'?'PEC':c.kind==='foreign_credit'?'Imposto estrangeiro':'PPC')+' — '+(c.document||c.id),
'Entidade: '+c.subjectNuit+'; exercício: '+c.year+'; emitente: '+c.issuer+'; data: '+c.date+'; comprovado: '+show(c.proofAmount)+'; parcela: '+(c.reason?'Indeterminado':show(c.value))+'. '+(c.reason||'Reconciliada sem utilização duplicada.'),
c.kind==='withholding'?m.input.withholdings.reference+'; '+(m.input.withholdings.rows.find(r=>r.id===c.id)?.reference??''):c.kind==='foreign_credit'?(m.input.internationalCredits?.reference??'')+'; '+(m.input.internationalCredits?.positions.flatMap(p=>p.payments).find(r=>r.id===c.id)?.reference??'')+'; '+(m.input.internationalCredits?.positions.flatMap(p=>p.payments).find(r=>r.id===c.id)?.exerciseReference??''):c.kind==='pec'?(m.input.pecPayments?.reference??'')+'; '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.reference??'')+'; utilizações anteriores: '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.previouslyUsed??'')+' MZN; '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.priorUseReference??''):m.input.ppc.reference+'; '+(m.input.ppc.rows.find(r=>r.id===c.id)?.reference??'')
'IRPC — L8',(c.kind==='withholding'?'Retenção sofrida':c.kind==='pec'?'PEC':c.kind==='economic_credit'?'IRPC correspondente aos lucros':c.kind==='foreign_credit'?'Imposto estrangeiro':'PPC')+' — '+(c.document||c.id),
'Entidade: '+c.subjectNuit+'; exercício: '+c.year+'; emitente: '+c.issuer+'; data: '+c.date+'; comprovado: '+show(c.proofAmount)+'; parcela: '+(c.reason?'Indeterminado':show(c.value))+(c.parcel?'; parcela documental: '+c.parcel+'; '+(c.parcelReference??''):'')+'. '+(c.reason||'Reconciliada sem utilização duplicada.'),
c.kind==='economic_credit'?(m.input.economicCredits?.reference??'')+'; '+(m.input.economicCredits?.rows.find(r=>r.id===c.id)?.attributionReference??''):c.kind==='withholding'?m.input.withholdings.reference+'; '+(m.input.withholdings.rows.find(r=>r.id===c.id)?.reference??''):c.kind==='foreign_credit'?(m.input.internationalCredits?.reference??'')+'; '+(m.input.internationalCredits?.positions.flatMap(p=>p.payments).find(r=>r.id===c.id)?.reference??'')+'; '+(m.input.internationalCredits?.positions.flatMap(p=>p.payments).find(r=>r.id===c.id)?.exerciseReference??''):c.kind==='pec'?(m.input.pecPayments?.reference??'')+'; '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.reference??'')+'; utilizações anteriores: '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.previouslyUsed??'')+' MZN; '+(m.input.pecPayments?.rows.find(r=>r.id===c.id)?.priorUseReference??''):m.input.ppc.reference+'; '+(m.input.ppc.rows.find(r=>r.id===c.id)?.reference??'')
]as[string,string,string,string]),
...(m.economicCredit?[
...m.economicCredit.rows.map(r=>['IRPC — L8','Crédito económico — '+r.input.distributionDocument,
'Lucros incluídos: '+r.input.income+' MZN;IRPC correspondente: '+r.input.taxAmount+' MZN;crédito nominal60%: '+show(r.nominal)+';acréscimo53 incluído: '+r.input.grossUpIncluded+' MZN;quota proporcional: '+show(r.nationalLimit)+';elegível: '+show(r.eligible)+';uso efectivo anterior: '+show(r.previousUse)+';disponível: '+show(r.available)+';estado: '+r.status+'. '+r.pending.join(' | '),
r.input.qualificationReference+';40(1): '+r.input.article40Reference+';inclusão: '+r.input.incomeReference+';53: '+r.input.grossUpReference+';quota: '+r.input.nationalLimitReference+';uso: '+r.input.previousUse.reference]as[string,string,string,string]),
['IRPC — L8','Crédito económico — antes do internacional','Disponível: '+show(m.economicCredit.available)+';dedução: '+show(m.economicCredit.deducted)+';colecta após crédito económico: '+show(m.economicCredit.afterCredit)+'. Sem reembolso ou criação/consumo de saldo oficial.',m.economicCredit.source+'; '+(m.input.economicCredits?.reference??'')]as[string,string,string,string]
]:[]),
...(m.internationalCredit?[
...m.internationalCredit.positions.map(p=>['IRPC — L8','Crédito internacional — '+p.country,'Imposto pago seleccionado: '+show(p.paid)+'; fracção nacional: '+show(p.nationalLimit)+'; limite CDT: '+(p.input.treaty==='no'?'Não aplicável documentado':show(p.treatyLimit))+'; elegível: '+show(p.eligible)+'; utilização anterior: '+show(p.previousUse)+'; disponível: '+show(p.available)+'; imposto acima dos limites: '+show(p.aboveLimit)+'. '+p.pending.join(' | '),p.input.incomeReference+'; '+p.input.nationalLimitReference+'; '+p.input.treatyReference+'; '+p.input.previousUse.reference]as[string,string,string,string]),
['IRPC — L8','Crédito internacional — antes do PEC','Disponível conhecido: '+show(m.internationalCredit.available)+'; dedução: '+show(m.internationalCredit.deducted)+'; colecta após crédito: '+show(m.internationalCredit.afterCredit)+'; elegível não deduzido por insuficiência de colecta: '+show(m.internationalCredit.insufficientCollecta)+'. Sem reembolso,transporte ou afectação oficial por país. Estado: '+stateLabel(m.input.internationalCredits?.state??'')+'. Créditos económicos/benefícios: '+stateLabel(m.input.internationalCredits?.economic.state??'')+' / '+stateLabel(m.input.internationalCredits?.benefits.state??'')+'.',m.internationalCredit.source+'; '+(m.input.internationalCredits?.reference??'')+'; '+(m.input.internationalCredits?.economic.reference??'')+'; '+(m.input.internationalCredits?.benefits.reference??'')]as[string,string,string,string]
['IRPC — L8','Crédito internacional — antes do PEC','Disponível conhecido: '+show(m.internationalCredit.available)+'; dedução: '+show(m.internationalCredit.deducted)+'; colecta após crédito: '+show(m.internationalCredit.afterCredit)+'; elegível não deduzido por insuficiência de colecta: '+show(m.internationalCredit.insufficientCollecta)+(m.creditCarry?'; crédito corrente não escolhido: '+show(m.internationalCredit.notSelected??null):'')+'. Sem reembolso,transporte ou afectação oficial por país. Estado: '+stateLabel(m.input.internationalCredits?.state??'')+'. Créditos económicos/benefícios: '+stateLabel(m.input.internationalCredits?.economic.state??'')+' / '+stateLabel(m.input.internationalCredits?.benefits.state??'')+'.',m.internationalCredit.source+'; '+(m.input.internationalCredits?.reference??'')+'; '+(m.input.internationalCredits?.economic.reference??'')+'; '+(m.input.internationalCredits?.benefits.reference??'')]as[string,string,string,string]
]:[]),
...(m.creditCarry?[
...m.creditCarry.lots.map(l=>['IRPC — L8','Saldo anterior — '+(l.kind==='pec'?'PEC':'Crédito internacional '+l.country)+' — '+l.year,
'Remanescente da origem: '+show(l.opening)+'; usos efectivos: '+show(l.used)+'; disponível: '+show(l.available)+'; parcela escolhida: '+show(l.selected)+'; saldo aritmético posterior: '+show(l.remaining)+'; último exercício ordinário: '+(l.lastYear??'Indeterminado')+'; prazo terminado: '+(l.expired?'Sim':'Não')+'. '+l.pending.join(' | '),
l.input.originDocument+'; '+l.input.originReference+'; '+l.input.ruleReference+'; '+l.input.usesReference+'; '+l.input.uses.map(u=>u.year+': '+u.amount+' MZN; '+u.document+'; '+u.reference).join(' | ')]as[string,string,string,string]),
['IRPC — L8','Afectação escolhida entre exercícios',
'Corrente internacional: '+show(m.creditCarry.international)+'; anterior internacional: '+show(m.creditCarry.priorInternational)+'; PEC corrente: '+show(m.creditCarry.pec)+'; PEC anterior: '+show(m.creditCarry.priorPec)+'; colecta após créditos internacionais: '+show(m.creditCarry.afterInternational)+'; colecta após todos os PEC: '+show(m.creditCarry.afterPec)+'. Parcelas só deduzidas se o saldo estiver determinado. Sem criação ou consumo de saldo oficial. '+m.creditCarry.pending.join(' | '),
(m.input.creditCarry?.reference??'')+'; '+(m.input.creditCarry?.allocationReference??'')+'; '+m.creditCarry.source]as[string,string,string,string]
]:[]),
...(m.pecDeduction?[[
'IRPC — L8','PEC — dedução limitada à colecta',
+94
View File
@@ -0,0 +1,94 @@
import {countryIsoCodes} from './country-iso-codes.ts';
import {creditCompare, creditMoney, creditLimit} from './irpc-international-credit.ts';
import {addFractions, fraction, subtractFractions, type FiscalFraction} from './fiscal-rational.ts';
export const carryVersion = 'IRPC-credit-carry/1';
export const carrySource = 'CIRPC, Lei 34/2007, art.65(3): crédito internacional elegível não deduzido por insuficiência de colecta, até ao fim dos cinco exercícios seguintes; art.66(1–2): PEC até três exercícios seguintes, depois dos créditos precedentes, sem reembolso. Exemplar BR52, PDF18/p.768-(72). Recorte: fecho2026, mesmo sujeito, exercícios anuais ordinários, montantes comprovados em MZN. A origem e os usos efectivos são documentados; simulações não criam nem consomem saldos oficiais.';
type State = '' | 'known' | 'absent';
export type CarryUse = {id: string; year: string; amount: string; document: string; reference: string};
export type CarryLot = {
id: string; kind: '' | 'international' | 'pec'; country: string; subjectNuit: string; year: string;
currency: string; ordinary: '' | 'yes' | 'no'; originDocument: string; originReference: string;
ruleReference: string; eligible: string; originDeducted: string; insufficient: '' | 'yes' | 'no';
usesState: State; usesReference: string; uses: CarryUse[]; selected: string;
};
export type CreditCarry = {
version: 1; state: State; reference: string; lots: CarryLot[];
currentInternational: string; currentPec: string; allocationReference: string; assessmentKey: string;
};
export const newCreditCarry = (): CreditCarry => ({version: 1, state: '', reference: '', lots: [], currentInternational: '', currentPec: '', allocationReference: '', assessmentKey: ''});
export const newCarryLot = (id: string): CarryLot => ({id, kind: '', country: '', subjectNuit: '', year: '', currency: 'MZN', ordinary: '', originDocument: '', originReference: '', ruleReference: '', eligible: '', originDeducted: '', insufficient: '', usesState: '', usesReference: '', uses: [], selected: ''});
export const newCarryUse = (id: string): CarryUse => ({id, year: '', amount: '', document: '', reference: ''});
const states = ['', 'known', 'absent'];
const zero = () => fraction(0n);
const canonical = (s: string) => s.normalize('NFKC').trim().toLocaleLowerCase('pt').replace(/\s+/g, ' ');
// One consolidated balance per nature/country/origin exercise; changing the document does not create a second quota.
export const carryIdentity = (r: CarryLot) => JSON.stringify([r.subjectNuit, r.kind, r.country, r.year]);
export function validateCreditCarry(c: CreditCarry) {
if (!c || c.version !== 1 || !states.includes(c.state) || ['reference', 'currentInternational', 'currentPec', 'allocationReference', 'assessmentKey'].some(k => typeof (c as unknown as Record<string, unknown>)[k] !== 'string') || !Array.isArray(c.lots)) throw Error('Saldos anteriores não recuperáveis; originais conservados.');
const keys = Object.keys(newCarryLot('')).filter(k => k !== 'uses');
const ids: string[] = [];
for (const r of c.lots) {
if (!r || keys.some(k => typeof (r as unknown as Record<string, unknown>)[k] !== 'string') || !['', 'international', 'pec'].includes(r.kind) || !['', 'yes', 'no'].includes(r.ordinary) || !['', 'yes', 'no'].includes(r.insufficient) || !states.includes(r.usesState) || !Array.isArray(r.uses)) throw Error('Origem do saldo anterior não recuperável.');
ids.push(r.id);
for (const u of r.uses) {
if (!u || Object.keys(newCarryUse('')).some(k => typeof (u as unknown as Record<string, unknown>)[k] !== 'string')) throw Error('Utilização anterior não recuperável.');
ids.push(u.id);
}
}
if (new Set(ids).size !== ids.length || ids.some(id => !id.trim())) throw Error('Identificador de saldo/utilização ausente ou repetido.');
}
export function calculateCarryLot(r: CarryLot, subjectNuit: string, year: string) {
let opening: FiscalFraction | null = null, used: FiscalFraction | null = null, available: FiscalFraction | null = null, selected: FiscalFraction | null = null, remaining: FiscalFraction | null = null;
let lastYear: number | null = null, expired = false;
const pending: string[] = [];
try {
if (!r.kind || r.subjectNuit !== subjectNuit || !/^\d{9}$/.test(r.subjectNuit) || year !== '2026' || !/^20\d{2}$/.test(r.year) || Number(r.year) >= Number(year) || r.ordinary !== 'yes' || r.currency !== 'MZN') throw Error('Origem exige mesmo titular, exercício anterior anual ordinário e montante documentado em MZN.');
if (r.kind === 'international' ? !countryIsoCodes.includes(r.country) || r.country === 'MZ' : r.country !== '') throw Error('País estrangeiro obrigatório para crédito internacional; PEC não tem país estrangeiro.');
if (!r.originDocument.trim() || !r.originReference.trim() || !r.ruleReference.trim()) throw Error('Faltam apuramento original e regra aplicável ao exercício de origem, com suporte.');
if (r.insufficient !== 'yes') throw Error('Falta comprovar que o remanescente resulta de insuficiência de colecta na origem; imposto acima do limite não é saldo transportável.');
lastYear = Number(r.year) + (r.kind === 'international' ? 5 : 3);
expired = Number(year) > lastYear;
const amount = r.kind === 'international' ? creditLimit : creditMoney;
const eligible = amount(r.eligible), originDeducted = amount(r.originDeducted);
if (creditCompare(originDeducted, eligible) > 0n) throw Error('Dedução na origem ultrapassa o montante elegível comprovado.');
opening = subtractFractions(eligible, originDeducted);
if (!r.usesState || !r.usesReference.trim() || r.usesState === 'absent' && r.uses.length || r.usesState === 'known' && !r.uses.length) throw Error('Utilizações efectivas posteriores à origem exigem inventário conhecido ou ausência expressa com suporte.');
const documents = new Set<string>();
const values = r.uses.map(u => {
if (!/^20\d{2}$/.test(u.year) || Number(u.year) <= Number(r.year) || Number(u.year) > Number(year) || Number(u.year) > lastYear! || !u.document.trim() || !u.reference.trim()) throw Error('Uso exige exercício elegível, posterior à origem, documento e suporte; pode incluir uso efectivo já ocorrido no exercício corrente.');
const identity = canonical(u.document);
if (documents.has(identity)) throw Error('Documento de utilização repetido; consolide a dedução efectiva.');
documents.add(identity);
return amount(u.amount);
});
used = addFractions(values);
if (creditCompare(used, opening) > 0n) throw Error('Utilizações efectivas ultrapassam o remanescente da origem.');
const balance = subtractFractions(opening, used);
selected = amount(r.selected);
available = expired ? zero() : balance;
if (creditCompare(selected, available) > 0n) throw Error(expired ? 'Prazo ordinário terminado; saldo conservado no histórico, sem dedução neste exercício.' : 'Parcela seleccionada ultrapassa o saldo documentado disponível.');
remaining = subtractFractions(balance, selected);
} catch (e) { pending.push(String(e)); selected = null; }
return {id: r.id, kind: r.kind, country: r.country, year: r.year, opening, used, available, selected, remaining, lastYear, expired, pending, input: structuredClone(r)};
}
export function carryPlan(c: CreditCarry, subjectNuit: string, year: string, assessmentKey: string, currentInternational: FiscalFraction, currentPec: FiscalFraction, colecta: FiscalFraction | null, duplicates: string[] = []) {
validateCreditCarry(c);
const pending = [...duplicates];
if (!c.state || !c.reference.trim() || c.state === 'absent' && c.lots.length || c.state === 'known' && !c.lots.length) pending.push('Inventário de saldos anteriores em falta ou contraditório; desconhecido não significa ausente.');
const ids = c.lots.map(carryIdentity);
if (new Set(ids).size !== ids.length) pending.push('Saldo de mesma natureza/país/exercício repetido; consolide a origem e os usos.');
const lots = c.lots.map(r => calculateCarryLot(r, subjectNuit, year));
pending.push(...lots.flatMap(r => r.pending.map(p => r.year + '/' + r.kind + ': ' + p)));
let international: FiscalFraction | null = null, pec: FiscalFraction | null = null;
try {
if (c.state !== 'known') return {version: carryVersion, lots, international, pec, priorInternational: zero(), priorPec: zero(), pending, source: carrySource, officialBalancesConsumed: false, carryCreated: false};
if (!c.allocationReference.trim() || !c.assessmentKey || c.assessmentKey !== assessmentKey) throw Error('Confirme a escolha das parcelas correntes e anteriores com suporte na colecta seleccionada; não se presume prioridade entre exercícios.');
international = creditLimit(c.currentInternational); pec = creditMoney(c.currentPec);
if (creditCompare(international, currentInternational) > 0n || creditCompare(pec, currentPec) > 0n) throw Error('Parcela corrente escolhida ultrapassa o respectivo crédito/PEC comprovado disponível.');
} catch (e) {pending.push(String(e));}
const priorInternational = addFractions(lots.filter(r => r.kind === 'international' && !r.pending.length && r.selected).map(r => r.selected!));
const priorPec = addFractions(lots.filter(r => r.kind === 'pec' && !r.pending.length && r.selected).map(r => r.selected!));
if (international && pec && colecta && creditCompare(addFractions([international, pec, priorInternational, priorPec]), colecta) > 0n) pending.push('As parcelas escolhidas ultrapassam a colecta; ajuste a afectação entre exercícios antes de confirmar, sem reduzir valores automaticamente.');
return {version: carryVersion, lots, international, pec, priorInternational, priorPec, pending, source: carrySource, officialBalancesConsumed: false, carryCreated: false};
}
+78
View File
@@ -0,0 +1,78 @@
import {addFractions, fraction, subtractFractions, type FiscalFraction} from './fiscal-rational.ts';
import {creditCompare, creditMoney, creditLimit, type CreditEvidence, type CreditState} from './irpc-international-credit.ts';
import {canonicalParcel} from './fiscal-proof-parcel.ts';
export const economicVersion = 'IRPC-economic-credit/1';
export const economicSource = 'CIRPC64(1–2), Lei34/2007, BR52, PDF18/p768-(72):60% do IRPC correspondente aos lucros distribuídos incluídos na base, limitado à colecta proporcional após acréscimo53(1)a (PDF15/p768-(69)). Distinto de65 e da exclusão40(1), na redacçãoLei20/2009,PDF4/p272-(16). RIRPC21(2/5),PDF6/p121:económico antes do internacional/benefícios/PEC,até à colecta,sem reembolso. Recorte2026,residente geral,ano civil,MZN,lucros ordinários,qualificação e quota proporcional documentadas na colecta corrente. Sem alterar a base por presunção, transporte ou consumo de saldos oficiais.';
type Choice = '' | 'yes' | 'no';
export type EconomicPosition = {
id: string; subjectNuit: string; year: string; assessmentKey: string;
kind: '' | 'ordinary_profit' | 'liquidation' | 'association'; payerNuit: string;
recipientResident: Choice; payerResident: Choice; payerIrpc: Choice; payerExempt: Choice;
article40: Choice; qualificationReference: string; article40Reference: string;
distributionDocument: string; distributionParcel: string; distributionDate: string;
income: string; incomeIncluded: Choice; incomeReference: string;
taxIssuer: string; taxDocument: string; taxParcel: string; parcelReference: string;
currency: string; proofAmount: string; taxAmount: string; attributionReference: string;
previouslyAttributed: string; priorAttributionReference: string;
grossUpIncluded: string; grossUpReference: string; nationalLimit: string; nationalLimitReference: string;
previousUse: CreditEvidence;
};
export type EconomicCredits = {version: 1; state: CreditState; reference: string; rows: EconomicPosition[]};
export const newEconomicCredits = (): EconomicCredits => ({version: 1, state: '', reference: '', rows: []});
export const newEconomicPosition = (id: string): EconomicPosition => ({id, subjectNuit: '', year: '', assessmentKey: '', kind: '', payerNuit: '', recipientResident: '', payerResident: '', payerIrpc: '', payerExempt: '', article40: '', qualificationReference: '', article40Reference: '', distributionDocument: '', distributionParcel: '', distributionDate: '', income: '', incomeIncluded: '', incomeReference: '', taxIssuer: '', taxDocument: '', taxParcel: '', parcelReference: '', currency: 'MZN', proofAmount: '', taxAmount: '', attributionReference: '', previouslyAttributed: '', priorAttributionReference: '', grossUpIncluded: '', grossUpReference: '', nationalLimit: '', nationalLimitReference: '', previousUse: {state: '', amount: '', reference: ''}});
export function validateEconomic(c: EconomicCredits) {
if (!c || c.version !== 1 || !['', 'known', 'absent'].includes(c.state) || typeof c.reference !== 'string' || !Array.isArray(c.rows) || new Set(c.rows.map(r => r?.id)).size !== c.rows.length) throw Error('Crédito económico não recuperável; originais conservados.');
const keys = Object.keys(newEconomicPosition('')).filter(k => k !== 'previousUse');
for (const r of c.rows) if (!r || keys.some(k => typeof (r as unknown as Record<string, unknown>)[k] !== 'string') || !['', 'ordinary_profit', 'liquidation', 'association'].includes(r.kind) || ['recipientResident', 'payerResident', 'payerIrpc', 'payerExempt', 'article40', 'incomeIncluded'].some(k => !['', 'yes', 'no'].includes(r[k as 'payerIrpc'])) || !r.previousUse || !['', 'known', 'absent'].includes(r.previousUse.state) || typeof r.previousUse.amount !== 'string' || typeof r.previousUse.reference !== 'string') throw Error('Posição económica não recuperável; originais conservados.');
}
const zero = () => fraction(0n);
const minimum = (...v: FiscalFraction[]) => v.reduce((a, b) => creditCompare(a, b) < 0n ? a : b);
const validDate = (s: string) => /^20\d{2}-\d{2}-\d{2}$/.test(s) && Number.isFinite(Date.parse(s)) && new Date(s).toISOString().slice(0, 10) === s;
export const economicDistributionIdentity = (r: EconomicPosition) => JSON.stringify([r.payerNuit, canonicalParcel(r.distributionDocument), canonicalParcel(r.distributionParcel)]);
export function economicTaxProof(r: EconomicPosition) {
if (!r.taxIssuer.trim() || !r.taxDocument.trim() || !r.taxParcel.trim() || !r.parcelReference.trim() || !r.attributionReference.trim() || !r.priorAttributionReference.trim() || r.currency !== 'MZN') throw Error('IRPC correspondente exige documento, emitente/parcela, suporte da atribuição aos lucros e montante MZN; não é retenção do beneficiário nem imposto estrangeiro.');
const proofAmount = creditMoney(r.proofAmount), value = creditMoney(r.taxAmount), previouslyUsed = creditMoney(r.previouslyAttributed);
if (creditCompare(addFractions([value, previouslyUsed]), proofAmount) > 0n) throw Error('IRPC atribuído aos lucros mais parcelas já atribuídas ultrapassam o comprovado disponível.');
return {proofAmount, value, previouslyUsed};
}
export function economicGroupPending(c: EconomicCredits) {
const pending: string[] = [];
if (!c.state || !c.reference.trim()) pending.push('Crédito económico: inventário conhecido/ausente e suporte em falta.');
if (c.state === 'absent' && c.rows.length) pending.push('Ausência de crédito económico contradiz lucros registados; conserve e reconcilie.');
if (c.state === 'known' && !c.rows.length) pending.push('Crédito económico conhecido sem lucros/IRPC discriminados; zero não é ausência presumida.');
if (new Set(c.rows.map(economicDistributionIdentity)).size !== c.rows.length) pending.push('Mesma parcela de lucros distribuídos repetida; consolide a origem, mesmo que o documento de imposto ou a data tenham sido alterados.');
return pending;
}
export function economicPosition(r: EconomicPosition, subjectNuit: string, year: string, assessmentKey: string, colecta: FiscalFraction | null, proofIssues: string[]) {
const pending = [...proofIssues];
let nominal: FiscalFraction | null = null, nationalLimit: FiscalFraction | null = null, eligible: FiscalFraction | null = null, previousUse: FiscalFraction | null = null, available: FiscalFraction | null = null, included: FiscalFraction | null = null;
let status: 'qualified' | 'outside_scope' | 'indeterminate' = 'indeterminate';
try {
if (!r.id.trim() || !/^\d{9}$/.test(r.payerNuit) || r.subjectNuit !== subjectNuit || year !== '2026' || r.year !== year || r.currency !== 'MZN') throw Error('Titular, entidade distribuidora, exercício2026 e MZN por corresponder.');
if (r.kind !== 'ordinary_profit') {status = r.kind ? 'outside_scope' : 'indeterminate'; throw Error('Lucros ordinários64(1–2) por identificar; liquidação64(3) e associações64(4) exigem correspondência específica, sem converter a parcela em crédito internacional.');}
if (r.recipientResident !== 'yes' || r.payerResident !== 'yes' || r.payerIrpc !== 'yes' || r.payerExempt !== 'no' || !r.qualificationReference.trim()) throw Error('Exige sede/direcção efectiva em Moçambique de beneficiário e distribuidor, distribuidor sujeito a IRPC e não isento, com suporte.');
if (r.article40 !== 'no' || !r.article40Reference.trim()) {status = r.article40 === 'yes' ? 'outside_scope' : 'indeterminate'; throw Error(r.article40 === 'yes' ? 'Exclusão40(1) identificada: tratar na base; não somar crédito64 à mesma parcela excluída.' : 'Falta corresponder a não aplicação de40(1), incluindo a redacção20/2009; desconhecido não significa não aplicável.');}
if (!validDate(r.distributionDate) || !r.distributionDate.startsWith(year + '-') || !r.distributionDocument.trim() || !r.distributionParcel.trim()) throw Error('Documento/parcela e data da distribuição do exercício por identificar.');
if (!r.assessmentKey || r.assessmentKey !== assessmentKey || r.incomeIncluded !== 'yes' || !r.incomeReference.trim()) throw Error('Confirme a inclusão dos lucros ilíquidos de retenção e a correspondência com a colecta corrente; a origem pode ter mudado.');
const tax = economicTaxProof(r), income = creditMoney(r.income);
nominal = fraction(BigInt(tax.value.numerator) * 3n, BigInt(tax.value.denominator) * 5n);
if (creditCompare(income, zero()) === 0n && creditCompare(nominal, zero()) > 0n) throw Error('Lucros incluídos zero contradizem IRPC correspondente positivo.');
if (!r.grossUpReference.trim() || creditCompare(creditLimit(r.grossUpIncluded), nominal) !== 0n) throw Error('Acréscimo53(1)a incluído na base deve corresponder ao crédito nominal60%; reconcilie L6 sem alterar a colecta ou o histórico automaticamente.');
included = addFractions([income, nominal]);
nationalLimit = creditLimit(r.nationalLimit);
if (!r.nationalLimitReference.trim() || !colecta || creditCompare(nationalLimit, colecta) > 0n || creditCompare(included, zero()) === 0n && creditCompare(nationalLimit, zero()) > 0n) throw Error('Quota proporcional da colecta após acréscimo53 exige suporte e correspondência; não pode exceder a colecta nem ser positiva para rendimento zero.');
if (!r.previousUse.state || !r.previousUse.reference.trim()) throw Error('Utilização anterior efectiva do crédito em falta; simulação não é utilização fiscal.');
if (r.previousUse.state === 'absent') {if (r.previousUse.amount.trim()) throw Error('Ausência de uso anterior contradiz montante'); previousUse = zero();}
else previousUse = creditLimit(r.previousUse.amount);
eligible = minimum(nominal, nationalLimit);
if (creditCompare(previousUse, eligible) > 0n) throw Error('Uso anterior excede o crédito económico elegível.');
if (!pending.length) {available = subtractFractions(eligible, previousUse); status = 'qualified';}
} catch (e) {pending.push(String(e));}
return {id: r.id, nominal, nationalLimit, eligible, previousUse, available, included, status, pending, input: structuredClone(r)};
}
export function economicDeduction(rows: ReturnType<typeof economicPosition>[], colecta: FiscalFraction | null, ready: boolean) {
const available = addFractions(rows.flatMap(r => r.available && !r.pending.length ? [r.available] : []));
const deducted = ready && colecta ? minimum(available, colecta) : null;
return {version: economicVersion, rows, available, deducted, afterCredit: deducted && colecta ? subtractFractions(colecta, deducted) : null, source: economicSource, officialBalancesConsumed: false, carryCreated: false};
}
@@ -1,4 +1,5 @@
import type {AnnualPpc} from './irpc-annual-settlement.ts';
import {validateProofParcel, requireProofParcel} from './fiscal-proof-parcel.ts';
import {countryIsoCodes} from './country-iso-codes.ts';
import {addFractions, subtractFractions, decimalFraction, fraction, type FiscalFraction} from './fiscal-rational.ts';
@@ -32,6 +33,7 @@ export function validateInternational(c: InternationalCredits) {
for (const p of c.positions) {
if (!p || positionKeys.some(k => typeof (p as unknown as Record<string, unknown>)[k] !== 'string') || !yesNo.includes(p.incomeIncluded) || !yesNo.includes(p.treaty) || !evidenceValid(p.previousUse) || !Array.isArray(p.payments)) throw Error('Posição internacional não recuperável; originais conservados.');
for (const r of p.payments) {
validateProofParcel(r);
if (!r || proofKeys.some(k => typeof (r as unknown as Record<string, unknown>)[k] !== 'string') || !yesNo.includes(r.effective) || !yesNo.includes(r.incomeTax)) throw Error('Comprovativo internacional não recuperável.');
proofIds.push(r.id);
}
@@ -43,7 +45,7 @@ export const creditMoney = (raw: string) => {
return decimalFraction(raw);
};
export const creditCompare = (a: FiscalFraction, b: FiscalFraction) => BigInt(a.numerator) * BigInt(b.denominator) - BigInt(b.numerator) * BigInt(a.denominator);
const creditLimit = (raw: string) => {
export const creditLimit = (raw: string) => {
const rational = /^(\d{1,18})\/(\d{1,18})$/.exec(raw);
if (rational) return fraction(BigInt(rational[1]), BigInt(rational[2]));
if (!/^\d{1,18}(\.\d{1,6})?$/.test(raw)) throw Error('Limite documentado em falta/inválido; use decimal ou fracção exacta n/d, sem arredondamento presumido.');
@@ -53,18 +55,19 @@ const zero = () => fraction(0n);
const minimum = (...values: FiscalFraction[]) => values.reduce((a, b) => creditCompare(a, b) < 0n ? a : b);
const isDate = (s: string) => /^20\d{2}-\d{2}-\d{2}$/.test(s) && Number.isFinite(Date.parse(s)) && new Date(s).toISOString().slice(0, 10) === s;
export function internationalProofValue(r: InternationalTaxProof, subjectNuit: string, year: string) {
requireProofParcel(r);
if (!r.id.trim() || !r.document.trim() || !r.issuer.trim() || !r.reference.trim() || !r.taxReference.trim() || r.incomeTax !== 'yes' || r.effective !== 'yes' || r.currency !== 'MZN' || !isDate(r.date) || r.subjectNuit !== subjectNuit || r.year !== year || year !== '2026') throw Error('Crédito internacional: exige imposto sobre o rendimento efectivamente pago, prova/titular/exercício 2026 e MZN; previsões, outras naturezas e conversões não correspondidas ficam separados.');
if (!r.date.startsWith(year + '-') && !r.exerciseReference.trim()) throw Error('Data de pagamento fora do exercício: falta correspondência documental com o rendimento e imposto deste exercício; não é transporte presumido.');
const value = creditMoney(r.amount), proofAmount = creditMoney(r.proofAmount);
if (creditCompare(value, proofAmount) > 0n) throw Error('Parcela estrangeira ultrapassa o montante comprovado.');
return {value, proofAmount};
}
export function internationalGroupPending(c: InternationalCredits) {
export function internationalGroupPending(c: InternationalCredits, economicDetailed = false) {
const pending: string[] = [];
if (!c.state || !c.reference.trim()) pending.push('Crédito internacional: declare pagamentos conhecidos, ausência ou informação em falta, com suporte.');
if (c.state === 'absent' && c.positions.length) pending.push('Ausência de crédito internacional contradiz posições presentes; conserve e reconcilie.');
if (c.state === 'known' && !c.positions.length) pending.push('Crédito internacional conhecido sem posição/comprovativo; zero não é ausência presumida.');
for (const [label, e] of [['Dupla tributação económica', c.economic], ['Benefícios/créditos próprios', c.benefits]] as const) {
for (const [label, e] of [...(economicDetailed ? [] : [['Dupla tributação económica', c.economic] as const]), ['Benefícios/créditos próprios', c.benefits] as const]) {
try {
if (!e.state || !e.reference.trim()) throw Error('estado e suporte em falta');
if (e.state === 'absent') {if (e.amount.trim()) throw Error('ausência contradiz montante');}
@@ -101,8 +104,8 @@ export function internationalPosition(p: InternationalPosition, paid: FiscalFrac
} catch (e) {pending.push(String(e));available = null;}
return {id: p.id, country: p.country, paid, nationalLimit, treatyLimit, previousUse, eligible, available, aboveLimit, pending, input: structuredClone(p)};
}
export function internationalDeduction(positions: ReturnType<typeof internationalPosition>[], colecta: FiscalFraction | null, ready: boolean) {
export function internationalDeduction(positions: ReturnType<typeof internationalPosition>[], colecta: FiscalFraction | null, ready: boolean, selected?: FiscalFraction | null) {
const available = addFractions(positions.flatMap(p => p.available && !p.pending.length ? [p.available] : []));
const deducted = ready && colecta ? minimum(available, colecta) : null;
return {version: internationalCreditVersion, positions, available, deducted, afterCredit: deducted && colecta ? subtractFractions(colecta, deducted) : null, insufficientCollecta: deducted ? subtractFractions(available, deducted) : null, source: internationalCreditSource, countryAllocationCreated: false, carryCreated: false, officialBalancesConsumed: false};
const deducted = ready && colecta ? selected ?? minimum(available, colecta) : null;
return {version: internationalCreditVersion, positions, available, deducted, afterCredit: deducted && colecta ? subtractFractions(colecta, deducted) : null, insufficientCollecta: selected === undefined && deducted ? subtractFractions(available, deducted) : null, ...(selected !== undefined ? {notSelected: deducted ? subtractFractions(available, deducted) : null} : {}), source: internationalCreditSource, countryAllocationCreated: false, carryCreated: false, officialBalancesConsumed: false};
}
+6 -3
View File
@@ -1,8 +1,9 @@
import {subtractFractions, decimalFraction, type FiscalFraction} from './fiscal-rational.ts';
import {validateProofParcel, requireProofParcel, type FiscalProofParcel} from './fiscal-proof-parcel.ts';
export const pecVersion = 'IRPC-PEC/1';
export const pecSource = 'CIRPC, art. 66(1–2), Lei 34/2007, exemplar BR52, p. 768-(72): dedução após créditos anteriores, até à colecta, sem reembolso do PEC. Recorte demonstrado: pagamento efectivo do próprio exercício 2026, residente geral, ano civil, MZN. Não calcula a obrigação PEC, transporte, caducidade ou consumo de saldos oficiais.';
export type PecPayment = {
export type PecPayment = FiscalProofParcel & {
id: string; document: string; issuer: string; date: string; subjectNuit: string;
year: string; currency: string; proofAmount: string; amount: string;
effective: '' | 'yes' | 'no'; reference: string;
@@ -15,6 +16,7 @@ export function validatePec(p: PecPayments) {
if (!p || p.version !== 1 || !['', 'known', 'absent'].includes(p.state) || typeof p.reference !== 'string' || !Array.isArray(p.rows) || new Set(p.rows.map(r => r?.id)).size !== p.rows.length || p.rows.some(r => !r || keys.some(k => typeof (r as unknown as Record<string, unknown>)[k] !== 'string') || !['', 'yes', 'no'].includes(r.effective))) {
throw Error('Comprovativos PEC não recuperáveis; originais conservados.');
}
for (const r of p.rows) validateProofParcel(r);
}
export const pecCompare = (a: FiscalFraction, b: FiscalFraction) => BigInt(a.numerator) * BigInt(b.denominator) - BigInt(b.numerator) * BigInt(a.denominator);
const money = (s: string) => {
@@ -22,6 +24,7 @@ const money = (s: string) => {
return decimalFraction(s);
};
export function pecPaymentValue(r: PecPayment, subjectNuit: string, year: string) {
requireProofParcel(r);
if (!r.id.trim() || !r.document.trim() || !r.issuer.trim() || !r.reference.trim() || !r.priorUseReference.trim() || r.effective !== 'yes' || r.currency !== 'MZN' || !/^20\d{2}-\d{2}-\d{2}$/.test(r.date) || !Number.isFinite(Date.parse(r.date)) || new Date(r.date).toISOString().slice(0, 10) !== r.date || !r.date.startsWith(year + '-') || r.subjectNuit !== subjectNuit || r.year !== year || year !== '2026') {
throw Error('PEC: exige prova efectiva, natureza PEC, titular, exercício 2026, data válida e MZN; saldos anteriores e previsões ficam separados.');
}
@@ -29,7 +32,7 @@ export function pecPaymentValue(r: PecPayment, subjectNuit: string, year: string
if (pecCompare(previouslyUsed, proofAmount) > 0n || pecCompare(value, subtractFractions(proofAmount, previouslyUsed)) > 0n) throw Error('PEC: parcela e utilizações anteriores excedem o comprovativo disponível.');
return {proofAmount, value, previouslyUsed};
}
export function pecDeduction(available: FiscalFraction, colecta: FiscalFraction | null, ready: boolean) {
const deducted = ready && colecta ? (pecCompare(available, colecta) > 0n ? colecta : available) : null;
export function pecDeduction(available: FiscalFraction, colecta: FiscalFraction | null, ready: boolean, selected?: FiscalFraction | null) {
const deducted = ready && colecta ? selected ?? (pecCompare(available, colecta) > 0n ? colecta : available) : null;
return {version: pecVersion, available, deducted, remaining: deducted ? subtractFractions(available, deducted) : null, afterPec: deducted && colecta ? subtractFractions(colecta, deducted) : null, source: pecSource, officialBalancesConsumed: false, carryCreated: false};
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,82 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class IrpcCreditCarryDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_prior_credit_details_round_trip_with_frozen_history_and_preserved_records(): void
{
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('proactive_investment_20261027_test', $target->name);
$this->assertSame(55441, (int) $target->port);
$snapshot = static fn (string $table): array => collect(DB::select('select id::text as id,md5(row_to_json(t)::text) as hash from public."'.$table.'" t order by id'))->pluck('hash', 'id')->all();
$protected = [];
foreach (['opportunities', 'documents', 'opportunity_documents', 'simulation_form_drafts', 'users', 'organizations', 'audit_events'] as $table) {
$protected[$table] = $snapshot($table);
}
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$this->actingAs(User::findOrFail(1021));
$fixture = json_decode(file_get_contents(base_path('tests/frontend/fixtures/irpc-carry-preserved.json')), true, flags: JSON_THROW_ON_ERROR);
$this->assertTrue($fixture['synthetic']);
$this->assertFalse($fixture['actualBalances']);
$id = null;
$etag = null;
foreach ($fixture['cases'] as $name => $draft) {
$personal = ['person_type' => $draft['person_type']];
unset($draft['person_type']);
$payload = ['personal_snapshot' => $personal, 'economic_snapshot' => $draft];
if ($id === null) {
$id = $this->postJson('/api/v1/simulation-drafts', $payload, ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
} else {
$this->putJson('/api/v1/simulation-drafts/'.$id, $payload, ['If-Match' => $etag])->assertOk();
}
$response = $this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk();
$etag = $response->headers->get('ETag');
$back = $response->json('data.economic_snapshot');
$this->assertSame($draft['modelo_a_snapshot'], $back['modelo_a_snapshot']);
$this->assertSame($draft['business_plan_snapshot'], $back['business_plan_snapshot']);
$original = json_decode($draft['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$recovered = json_decode($back['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
foreach (['irpcNormal', 'irpcWithholdings', 'books', 'currencyEvents', 'ispcQuarters'] as $map) {
$this->assertSame($original[$map], $recovered[$map]);
}
$book = $recovered['irpcAnnual'][$draft['context_opportunity']];
$model = $book['result']['model'];
$this->assertSame($original['irpcAnnual'][$draft['context_opportunity']], $book);
$this->assertCount(1, $book['history']);
$this->assertSame('IRPC-credit-carry/1', $model['creditCarry']['version']);
$this->assertFalse($model['creditCarry']['carryCreated']);
$this->assertFalse($model['creditCarry']['officialBalancesConsumed']);
$this->assertFalse($model['submitted']);
if (in_array($name, ['expired', 'missing-use', 'overallocated'], true)) {
$this->assertSame('indeterminate', $model['status']);
$this->assertNull($model['arithmeticBalance']);
$this->assertNull($model['internationalCredit']['deducted']);
$this->assertNull($model['pecDeduction']['deducted']);
} else {
$expected = ['payable' => ['550', '1'], 'fractional' => ['1822', '3'], 'recoverable' => ['-500', '1']][$name];
$this->assertEmpty($model['pending']);
$this->assertSame(['numerator' => $expected[0], 'denominator' => $expected[1]], $model['arithmeticBalance']);
}
if (getenv('INVESTMOZ_CARRY_QA_OUTPUT') === '1') {
file_put_contents(base_path('outputs/irpc-l8-carry-20261028/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
$preserved = [];
foreach ($protected as $table => $before) {
$this->assertSame($before, array_intersect_key($snapshot($table), $before), 'Existing records changed: '.$table);
$preserved[$table] = ['existing_rows' => count($before), 'unchanged' => true];
}
if (getenv('INVESTMOZ_CARRY_QA_OUTPUT') === '1') {
file_put_contents(base_path('outputs/irpc-l8-carry-20261028/existing-records-preservation.json'), json_encode(['database' => $target->name, 'tables' => $preserved, 'transaction_rollback' => true], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
}
}
}
@@ -0,0 +1,83 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class IrpcEconomicCreditDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_economic_credit_and_compatible_carry_round_trip_without_overwriting_accepted_history(): void
{
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('proactive_investment_20261027_test', $target->name);
$this->assertSame(55441, (int) $target->port);
$snapshot = static fn (string $table): array => collect(DB::select('select id::text as id,md5(row_to_json(t)::text) as hash from public."'.$table.'" t order by id'))->pluck('hash', 'id')->all();
$protected = [];
foreach (['opportunities', 'documents', 'opportunity_documents', 'simulation_form_drafts', 'users', 'organizations', 'audit_events'] as $table) {
$protected[$table] = $snapshot($table);
}
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$this->actingAs(User::findOrFail(1021));
$fixture = json_decode(file_get_contents(base_path('tests/frontend/fixtures/irpc-economic-preserved.json')), true, flags: JSON_THROW_ON_ERROR);
$this->assertTrue($fixture['synthetic']);
$this->assertFalse($fixture['actualTaxEvidence']);
$id = null;
$etag = null;
foreach ($fixture['cases'] as $name => $draft) {
$personal = ['person_type' => $draft['person_type']];
unset($draft['person_type']);
$payload = ['personal_snapshot' => $personal, 'economic_snapshot' => $draft];
if ($id === null) {
$id = $this->postJson('/api/v1/simulation-drafts', $payload, ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
} else {
$this->putJson('/api/v1/simulation-drafts/'.$id, $payload, ['If-Match' => $etag])->assertOk();
}
$response = $this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk();
$etag = $response->headers->get('ETag');
$back = $response->json('data.economic_snapshot');
$this->assertSame($draft['modelo_a_snapshot'], $back['modelo_a_snapshot']);
$this->assertSame($draft['business_plan_snapshot'], $back['business_plan_snapshot']);
$original = json_decode($draft['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$recovered = json_decode($back['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
foreach (['irpcNormal', 'irpcWithholdings', 'books', 'currencyEvents', 'ispcQuarters'] as $map) {
$this->assertSame($original[$map], $recovered[$map]);
}
$book = $recovered['irpcAnnual'][$draft['context_opportunity']];
$model = $book['result']['model'];
$this->assertSame($original['irpcAnnual'][$draft['context_opportunity']], $book);
$this->assertCount(1, $book['history']);
$this->assertSame('IRPC-economic-credit/1', $model['economicCredit']['version']);
$this->assertFalse($model['economicCredit']['carryCreated']);
$this->assertFalse($model['economicCredit']['officialBalancesConsumed']);
$this->assertFalse($model['submitted']);
if (in_array($name, ['duplicate', 'missing-gross-up', 'article40', 'partial-parcel'], true)) {
$this->assertSame('indeterminate', $model['status']);
$this->assertNull($model['arithmeticBalance']);
$this->assertNull($model['economicCredit']['deducted']);
$this->assertNull($model['internationalCredit']['deducted']);
$this->assertNull($model['pecDeduction']['deducted']);
} else {
$expected = ['payable' => ['688', '1'], 'combined' => ['538', '1'], 'quota' => ['695', '1'], 'prior-use' => ['691', '1'], 'shared-paper' => ['688', '1'], 'fractional' => ['349997', '500'], 'recoverable' => ['-500', '1']][$name];
$this->assertEmpty($model['pending']);
$this->assertSame(['numerator' => $expected[0], 'denominator' => $expected[1]], $model['arithmeticBalance']);
}
if (getenv('INVESTMOZ_ECONOMIC_QA_OUTPUT') === '1') {
file_put_contents(base_path('outputs/irpc-l8-economic-20261028/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
$preserved = [];
foreach ($protected as $table => $before) {
$this->assertSame($before, array_intersect_key($snapshot($table), $before), 'Existing records changed: '.$table);
$preserved[$table] = ['existing_rows' => count($before), 'unchanged' => true];
}
if (getenv('INVESTMOZ_ECONOMIC_QA_OUTPUT') === '1') {
file_put_contents(base_path('outputs/irpc-l8-economic-20261028/existing-records-preservation.json'), json_encode(['database' => $target->name, 'tables' => $preserved, 'transaction_rollback' => true], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
}
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,28 @@
import {internationalCase} from './irpc-international-case.mjs';
import {prepareCreditCarry} from '../../../resources/js/lib/irpc-annual-settlement.ts';
import {newCarryLot} from '../../../resources/js/lib/irpc-credit-carry.ts';
export function carryCase() {
const c = internationalCase();
c.b = prepareCreditCarry(c.b);
Object.assign(c.b.creditCarry, {
state: 'known', reference: 'SYNTHETIC QA complete prior balance inventory',
currentInternational: '8', currentPec: '200', assessmentKey: c.b.assessmentKey,
allocationReference: 'SYNTHETIC QA explicit allocation: current international8, prior international50, currentPEC200, priorPEC100',
lots: [
{...newCarryLot('international-2021'), kind: 'international', country: 'ZA', subjectNuit: c.b.subjectNuit,
year: '2021', ordinary: 'yes', originDocument: 'SYNTHETIC foreign-credit-assessment2021',
originReference: 'SYNTHETIC QA origin inclusion, eligible tax, national/CDT limits, insufficient collecta',
ruleReference: 'SYNTHETIC QA documented ordinary origin rule art65, no real foreign treaty claim',
eligible: '200', originDeducted: '100', insufficient: 'yes', usesState: 'known',
usesReference: 'SYNTHETIC QA all actual uses reconciled through current exercise',
uses: [{id: 'use-2023', year: '2023', amount: '30', document: 'SYNTHETIC use2023', reference: 'SYNTHETIC QA actual documented use, not simulated'}], selected: '50'},
{...newCarryLot('pec-2023'), kind: 'pec', subjectNuit: c.b.subjectNuit,
year: '2023', ordinary: 'yes', originDocument: 'SYNTHETIC PEC2023 assessment and receipts',
originReference: 'SYNTHETIC QA actual PEC paid, initial deduction and collecta insufficiency',
ruleReference: 'SYNTHETIC QA origin ordinary art66', eligible: '300', originDeducted: '150',
insufficient: 'yes', usesState: 'absent', usesReference: 'SYNTHETIC QA no actual subsequent use', selected: '100'},
],
});
return c;
}
@@ -0,0 +1,25 @@
import {internationalCase} from './irpc-international-case.mjs';
import {carryCase} from './irpc-carry-case.mjs';
import {prepareEconomicBook} from '../../../resources/js/lib/irpc-annual-settlement.ts';
import {newEconomicPosition} from '../../../resources/js/lib/irpc-economic-credit.ts';
export function economicCase(withCarry = false) {
const c = withCarry ? carryCase() : internationalCase();
c.b = prepareEconomicBook(c.b);
Object.assign(c.b.economicCredits, {state: 'known', reference: 'SYNTHETIC QA full ordinary economic-credit inventory', rows: [{
...newEconomicPosition('economic-1'), subjectNuit: c.b.subjectNuit, year: c.b.year, assessmentKey: c.b.assessmentKey,
kind: 'ordinary_profit', payerNuit: '111222333', recipientResident: 'yes', payerResident: 'yes', payerIrpc: 'yes', payerExempt: 'no',
article40: 'no', qualificationReference: 'SYNTHETIC QA entities seated/effectively managed in MZ; payer subject nonexempt IRPC',
article40Reference: 'SYNTHETIC QA explicit nonapplication of40(1), including2009 participation/period/recipient conditions',
distributionDocument: 'SYNTHETIC-DIVIDEND2026', distributionParcel: 'distribution-1', distributionDate: '2026-09-30',
income: '100', incomeIncluded: 'yes', incomeReference: 'SYNTHETIC QA100 gross of beneficiary withholding already included in current L6; no actual dividend assertion',
taxIssuer: 'SYNTHETIC domestic IRPC issuer', taxDocument: 'SYNTHETIC-SOURCE-IRPC2026', taxParcel: 'underlying-tax-1',
parcelReference: 'SYNTHETIC QA underlying domestic IRPC parcel, distinct from recipient withholding or foreign income tax',
proofAmount: '20', taxAmount: '20', attributionReference: 'SYNTHETIC QA documented IRPC20 corresponding to included profits100, not inferred by applying a rate to dividends',
previouslyAttributed: '0', priorAttributionReference: 'SYNTHETIC QA actual previous attribution to other profits known zero',
grossUpIncluded: '12', grossUpReference: 'SYNTHETIC QA53 nominal credit12 already included in reconciled current base4400; no base mutation',
nationalLimit: '32', nationalLimitReference: 'SYNTHETIC QA documented proportional current collecta ceiling32 after credit addition; not an automatic fraction derivation',
previousUse: {state: 'known', amount: '0', reference: 'SYNTHETIC QA actual prior economic-credit use known zero'},
}]});
return c;
}
+124
View File
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {carryCase} from './helpers/irpc-carry-case.mjs';
import {internationalCase} from './helpers/irpc-international-case.mjs';
import {newCarryUse, calculateCarryLot} from '../../resources/js/lib/irpc-credit-carry.ts';
import {calculateAnnual, prepareCreditCarry, recordAnnual, annualBook, annualCurrent, saveAnnualBook, annualHtml, annualReportRows} from '../../resources/js/lib/irpc-annual-settlement.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
const number = v => v ? Number(v.numerator) / Number(v.denominator) : null;
const calc = c => calculateAnnual(c.d, c.b);
const lot = (c, i = 0) => c.b.creditCarry.lots[i];
const pending = c => {const m = calc(c); assert.equal(m.status, 'indeterminate', JSON.stringify(m.pending)); assert.equal(m.arithmeticBalance, null); assert.equal(m.internationalCredit.deducted, null); assert.equal(m.pecDeduction.deducted, null); return m;};
test('2021 international and2023 PEC remain eligible in2026; origin deductions/uses count once:1408-8-50-200-100-500=550', () => {
const m = calc(carryCase()); assert.deepEqual(m.pending, []); assert.equal(number(m.payable), 550);
assert.equal(number(m.creditCarry.lots[0].opening), 100); assert.equal(number(m.creditCarry.lots[0].used), 30);
assert.equal(number(m.creditCarry.lots[0].available), 70); assert.equal(number(m.creditCarry.lots[0].remaining), 20);
assert.equal(m.creditCarry.lots[0].lastYear, 2026); assert.equal(m.creditCarry.lots[1].lastYear, 2026);
assert.equal(number(m.creditCarry.lots[1].remaining), 50); assert.equal(m.creditCarry.carryCreated, false); assert.equal(m.creditCarry.officialBalancesConsumed, false);
});
test('five subsequent exercises differs from PEC three; expired source retained with zero selection', () => {
for (const [i, year] of [[0, '2020'], [1, '2022']]) {
const c = carryCase(); lot(c, i).year = year;
if (i === 0) lot(c).uses[0].year = '2023';
assert.match(pending(c).pending.join(' '), /Prazo ordinário terminado/);
lot(c, i).selected = '0'; const m = calc(c);
assert.deepEqual(m.pending, []); assert.equal(m.creditCarry.lots[i].expired, true);
assert.equal(number(m.creditCarry.lots[i].available), 0); assert.ok(number(m.creditCarry.lots[i].remaining) > 0);
}
});
test('future/current origin, nonordinary periods, currency and wrong subject do not create an eligible carry', () => {
for (const patch of [{year: '2026'}, {year: '2027'}, {year: ''}, {ordinary: ''}, {ordinary: 'no'}, {currency: 'USD'}, {subjectNuit: '999999999'}, {country: 'MZ'}, {country: 'ZZ'}, {kind: ''}]) {
const c = carryCase(); Object.assign(lot(c), patch); pending(c);
}
const c = carryCase(); lot(c, 1).country = 'ZA'; pending(c);
});
test('origin eligibility, insufficient collecta and applicable rule require concrete evidence', () => {
for (const patch of [{originDocument: ''}, {originReference: ''}, {ruleReference: ''}, {insufficient: ''}, {insufficient: 'no'}, {eligible: ''}, {originDeducted: ''}, {originDeducted: '201'}, {selected: ''}, {selected: '70.01'}]) {
const c = carryCase(); Object.assign(lot(c), patch); pending(c);
}
});
test('unknown uses are not zero; every actual use must fit its origin/window and documentary identity', () => {
for (const patch of [{usesState: ''}, {usesReference: ''}, {usesState: 'absent'}, {uses: []}, {uses: [{...newCarryUse('u'), year: '2021', amount: '1', document: 'D', reference: 'R'}]}]) {
const c = carryCase(); Object.assign(lot(c), patch); pending(c);
}
for (const patch of [{year: '2027'}, {amount: '101'}, {document: ''}, {reference: ''}, {amount: ''}]) {
const c = carryCase(); Object.assign(lot(c).uses[0], patch); pending(c);
}
const c = carryCase(); lot(c).uses.push({...lot(c).uses[0], id: 'copy', year: '2024', document: ' synthetic USE2023 '});
assert.match(pending(c).pending.join(' '), /repetido/);
});
test('actual current-year use is subtracted before the proposed new deduction', () => {
const c = carryCase(); lot(c).uses.push({id: 'current-actual', year: '2026', amount: '10', document: 'SYNTHETIC current actual use', reference: 'SYNTHETIC actual assessment, not this simulation'});
const m = calc(c); assert.equal(number(m.creditCarry.lots[0].available), 60); assert.equal(number(m.creditCarry.lots[0].remaining), 10); assert.equal(number(m.payable), 550);
});
test('original country/nature/year cannot be duplicated by changing document or id', () => {
const c = carryCase(); c.b.creditCarry.lots.push({...structuredClone(lot(c)), id: 'other', originDocument: 'OTHER', uses: [] , usesState: 'absent'});
assert.match(pending(c).pending.join(' '), /mesma natureza/);
});
test('cross-context duplicate origin blocks and external edits invalidate saved current result', () => {
const c = carryCase(); c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, c.b));
const b = annualBook(c.d); assert.equal(annualCurrent(c.d, b), true);
const s = JSON.parse(c.d.modelo_a_snapshot), other = structuredClone(c.b);
other.creditCarry.lots = [{...structuredClone(lot(c)), id: 'copied-origin', originDocument: 'OTHER', uses: [], usesState: 'absent'}];
s.irpcAnnual['opportunity:other'] = other; c.d.modelo_a_snapshot = JSON.stringify(s);
assert.equal(annualCurrent(c.d, b), false); assert.match(pending(c).pending.join(' '), /noutro mapa/);
});
test('explicit allocation can favour older balances without automatic reduction or FIFO', () => {
const c = carryCase(); Object.assign(c.b.creditCarry, {currentInternational: '0', currentPec: '100'});
const m = calc(c); assert.equal(number(m.payable), 658); assert.equal(number(m.internationalCredit.deducted), 0);
assert.equal(number(m.internationalCredit.notSelected), 8); assert.equal(m.internationalCredit.insufficientCollecta, null);
assert.equal(number(m.pecDeduction.deducted), 100); assert.equal(number(m.pecDeduction.remaining), 100);
});
test('current selection cannot exceed known availability or total collecta; planned choices are kept on failure', () => {
for (const patch of [{currentInternational: '9'}, {currentPec: '201'}, {currentInternational: ''}, {currentPec: ''}, {allocationReference: ''}, {assessmentKey: 'stale'}]) {
const c = carryCase(); Object.assign(c.b.creditCarry, patch); pending(c);
}
const c = carryCase(); lot(c).eligible = '5000'; lot(c).selected = '1400';
const before = structuredClone(c.b); assert.match(pending(c).pending.join(' '), /ultrapassam a colecta/); assert.deepEqual(c.b, before);
});
test('no credit or PEC reimbursement is generated by old balances; PPC refund stays separate', () => {
const c = carryCase(); Object.assign(c.b.creditCarry, {currentInternational: '8', currentPec: '0'}); lot(c).eligible = '2000'; lot(c).selected = '1300'; lot(c, 1).selected = '100';
const m = calc(c); assert.equal(number(m.recoverable), 500); assert.equal(number(m.pecDeduction.deducted), 0);
assert.equal(m.creditCarry.carryCreated, false); assert.equal(number(m.creditCarry.lots[0].remaining), 570);
});
test('exact foreign-credit fractions are preserved; decimal presentation is never fiscal rounding', () => {
const c = carryCase(); Object.assign(lot(c), {eligible: '2/3', originDeducted: '1/3', selected: '1/3', usesState: 'absent', uses: []});
Object.assign(c.b.creditCarry, {currentInternational: '1/3'});
const m = calc(c); assert.deepEqual(m.pending, []); assert.deepEqual(m.creditCarry.lots[0].available, {numerator: '1', denominator: '3'});
assert.deepEqual(m.payable, {numerator: '1822', denominator: '3'});
lot(c).selected = '1/0'; pending(c);
});
test('missing/absent/known-zero remain distinct; absence does not demand unused allocation fields', () => {
const c = internationalCase(), baseline = calc(c); c.b = prepareCreditCarry(c.b); pending(c);
c.b.creditCarry.state = 'absent'; c.b.creditCarry.reference = 'SYNTHETIC QA documented absence';
let m = calc(c); assert.equal(number(m.payable), number(baseline.payable)); assert.deepEqual(m.internationalCredit, baseline.internationalCredit);
c.b.creditCarry.lots.push({...carryCase().b.creditCarry.lots[0]}); pending(c);
const z = carryCase(); Object.assign(lot(z), {eligible: '0', originDeducted: '0', selected: '0', usesState: 'absent', uses: []});
m = calc(z); assert.deepEqual(m.pending, []); assert.equal(number(m.creditCarry.lots[0].available), 0);
});
test('optional preparation, recording, JSON recovery, HTML and dossier preserve accepted books and frozen history', () => {
const c = internationalCase(); c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, c.b, '2026-10-27T17:00:00+02:00'));
const old = annualBook(c.d), frozen = structuredClone(old.result), existing = JSON.parse(c.d.modelo_a_snapshot), plan = c.d.business_plan_snapshot;
const next = prepareCreditCarry(old); next.creditCarry = carryCase().b.creditCarry;
c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, next, '2026-10-28T12:00:00+02:00'));
const recovered = annualBook(JSON.parse(JSON.stringify(c.d))); assert.deepEqual(recovered.history, [frozen]); assert.equal(number(recovered.result.model.payable), 550);
assert.equal(annualCurrent(c.d, recovered), true); assert.equal(c.d.business_plan_snapshot, plan);
const after = JSON.parse(c.d.modelo_a_snapshot); delete after.irpcAnnual; delete existing.irpcAnnual; assert.deepEqual(after, existing);
assert.match(annualHtml(c.d), /Saldo anterior — Crédito internacional ZA — 2021/);
assert.match(annualHtml(c.d), /550.00/); assert.match(annualHtml(c.d), /2026/);
assert.match(JSON.stringify(createProjectDossierReport(c.d, {selectedSections: new Set(['finance'])})), /Afectação escolhida entre exercícios/);
recovered.creditCarry.lots[0].selected = '49'; c.d.modelo_a_snapshot = saveAnnualBook(c.d, recovered);
assert.equal(annualCurrent(c.d, recovered), false); assert.deepEqual(recovered.result.model, annualBook(c.d).result.model);
assert.throws(() => annualHtml(c.d), /fontes actuais/); assert.match(annualReportRows(c.d).flat().join(' '), /Histórico/);
});
test('malformed detail and duplicate internal ids cannot overwrite original snapshots', () => {
for (const mutate of [c => c.b.creditCarry.lots[0].uses = null, c => c.b.creditCarry.version = 2, c => c.b.creditCarry.lots[0].uses[0].amount = null, c => c.b.creditCarry.lots[1].id = c.b.creditCarry.lots[0].id]) {
const c = carryCase(), before = c.d.modelo_a_snapshot; mutate(c);
assert.throws(() => saveAnnualBook(c.d, c.b), /recuper|repetido/); assert.equal(c.d.modelo_a_snapshot, before);
}
});
test('standalone expired PEC keeps origin and is not silently converted to international five-year window', () => {
const c = carryCase(), r = {...lot(c, 1), year: '2022', selected: '0'};
const m = calculateCarryLot(r, c.b.subjectNuit, c.b.year); assert.equal(m.expired, true); assert.equal(m.lastYear, 2025); assert.equal(number(m.remaining), 150);
});
@@ -0,0 +1,141 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {economicCase} from './helpers/irpc-economic-case.mjs';
import {internationalCase} from './helpers/irpc-international-case.mjs';
import {calculateAnnual, prepareEconomicBook, annualBook, recordAnnual, saveAnnualBook, annualCurrent, annualHtml, annualReportRows} from '../../resources/js/lib/irpc-annual-settlement.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
import {irpcBook, recordIrpc, saveIrpcBook} from '../../resources/js/lib/irpc-withholdings.ts';
const number = v => v ? Number(v.numerator) / Number(v.denominator) : null;
const row = c => c.b.economicCredits.rows[0];
const foreign = c => c.b.internationalCredits.positions[0].payments[0];
const calc = c => calculateAnnual(c.d, c.b);
const pending = c => {const m = calc(c); assert.equal(m.status, 'indeterminate', JSON.stringify(m.pending)); assert.equal(m.arithmeticBalance, null); assert.equal(m.economicCredit.deducted, null); assert.equal(m.internationalCredit.deducted, null); assert.equal(m.pecDeduction.deducted, null); return m;};
test('economic60% of documented sourceIRPC20 yields12 before international8,PEC200 andPPC500:688', () => {
const m = calc(economicCase()); assert.deepEqual(m.pending, []); assert.equal(number(m.economicCredit.rows[0].nominal), 12);
assert.equal(number(m.economicCredit.deducted), 12); assert.equal(number(m.economicCredit.afterCredit), 1396);
assert.equal(number(m.internationalCredit.deducted), 8); assert.equal(number(m.internationalCredit.afterCredit), 1388); assert.equal(number(m.payable), 688);
assert.equal(m.economicCredit.carryCreated, false); assert.equal(m.economicCredit.officialBalancesConsumed, false); assert.equal(m.submitted, false);
});
test('documented proportional ceiling and prior actual use limit economic deduction,not a second tax rate on dividends', () => {
const c = economicCase(); row(c).nationalLimit = '5'; let m = calc(c); assert.equal(number(m.economicCredit.rows[0].nominal), 12); assert.equal(number(m.payable), 695);
row(c).previousUse.amount = '3'; m = calc(c); assert.equal(number(m.economicCredit.deducted), 2); assert.equal(number(m.payable), 698);
row(c).previousUse.amount = '6'; pending(c);
});
test('article40 exclusion, payer exemption/foreign residence and special distributions do not become international credit', () => {
for (const patch of [{article40: ''}, {article40: 'yes'}, {article40Reference: ''}, {payerResident: ''}, {payerResident: 'no'}, {recipientResident: 'no'}, {payerIrpc: 'no'}, {payerExempt: ''}, {payerExempt: 'yes'}, {kind: 'liquidation'}, {kind: 'association'}, {kind: ''}, {qualificationReference: ''}]) {
const c = economicCase(); Object.assign(row(c), patch); const m = pending(c); assert.equal(m.internationalCredit.positions.length, 1); assert.equal(number(m.internationalCredit.positions[0].eligible), 8);
if (patch.article40 === 'yes' || patch.kind === 'liquidation' || patch.kind === 'association') assert.equal(m.economicCredit.rows[0].status, 'outside_scope');
}
});
test('inclusion,credit gross-up and current assessment must be reconciled without silently changing L6', () => {
for (const patch of [{incomeIncluded: ''}, {incomeIncluded: 'no'}, {incomeReference: ''}, {assessmentKey: ''}, {assessmentKey: 'stale'}, {grossUpIncluded: ''}, {grossUpIncluded: '0'}, {grossUpIncluded: '11.99'}, {grossUpReference: ''}, {nationalLimit: ''}, {nationalLimit: '1409'}, {nationalLimitReference: ''}, {income: '0'}]) {
const c = economicCase(), before = c.d.modelo_a_snapshot; Object.assign(row(c), patch); pending(c); assert.equal(c.d.modelo_a_snapshot, before);
}
});
test('dividend/source tax identity,date,year,subject and actual allocated source amount require support', () => {
for (const patch of [{subjectNuit: '999999999'}, {payerNuit: ''}, {year: '2025'}, {distributionDate: '2026-02-30'}, {distributionDate: '2025-12-31'}, {distributionDocument: ''}, {distributionParcel: ''}, {taxIssuer: ''}, {taxDocument: ''}, {taxParcel: ''}, {parcelReference: ''}, {currency: 'USD'}, {proofAmount: ''}, {taxAmount: '21'}, {taxAmount: ''}, {attributionReference: ''}, {previouslyAttributed: ''}, {previouslyAttributed: '1'}, {priorAttributionReference: ''}]) {
const c = economicCase(); Object.assign(row(c), patch); pending(c);
}
});
test('same distributed profit parcel cannot be re-used by changing source-tax document,id or date', () => {
const c = economicCase(); c.b.economicCredits.rows.push({...structuredClone(row(c)), id: 'other', taxDocument: 'OTHER', distributionDate: '2026-10-01', distributionDocument: ' synthetic-dividend2026 ', distributionParcel: ' DISTRIBUTION-1 '});
assert.match(pending(c).pending.join(' '), /Mesma parcela de lucros/);
});
test('one source-tax parcel can support distinct documented distributions only within its actual available amount', () => {
const c = economicCase(), other = {...structuredClone(row(c)), id: 'second', distributionParcel: 'distribution-2'};
c.b.economicCredits.rows.push(other); assert.match(pending(c).pending.join(' '), /disponível/);
for (const r of c.b.economicCredits.rows) {r.taxAmount = '10'; r.grossUpIncluded = '6';}
let m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.economicCredit.deducted), 12);
row(c).previouslyAttributed = '1'; other.previouslyAttributed = '1'; pending(c);
row(c).taxAmount = '9'; other.taxAmount = '9'; row(c).grossUpIncluded = '5.4'; other.grossUpIncluded = '5.4'; m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.economicCredit.deducted), 10.8);
other.previouslyAttributed = '0'; assert.match(pending(c).pending.join(' '), /divergente/);
});
test('economic and international use of the same actual tax parcel is rejected even with changed receipt date', () => {
const c = economicCase(); Object.assign(foreign(c), {issuer: row(c).taxIssuer, document: row(c).taxDocument, parcel: ' UNDERLYING-TAX-1 ', parcelReference: 'SYNTHETIC same parcel', proofAmount: '20', date: '2026-10-01'});
assert.match(pending(c).pending.join(' '), /natureza|naturezas/);
});
test('an old proof with no parcel overlaps the whole document;new names require supported partition on both sides', () => {
const c = economicCase(); Object.assign(foreign(c), {issuer: row(c).taxIssuer, document: row(c).taxDocument, proofAmount: '20'}); pending(c);
foreign(c).parcel = 'foreign-tax-line'; pending(c); foreign(c).parcelReference = 'SYNTHETIC evidence of a distinct foreign-tax line in shared document';
const m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.payable), 688);
});
test('economic source IRPC is not beneficiary withholding,PPC or PEC;distinct supported parcels may share a document', () => {
for (const kind of ['ppc', 'pec']) {
const c = economicCase(), proof = kind === 'ppc' ? c.b.ppc.rows[0] : c.b.pecPayments.rows[0];
Object.assign(row(c), {taxIssuer: proof.issuer, taxDocument: proof.document, proofAmount: proof.proofAmount}); pending(c);
Object.assign(proof, {parcel: 'own-' + kind, parcelReference: 'SYNTHETIC distinct payment parcel'}); assert.deepEqual(calc(c).pending, []);
proof.parcel = row(c).taxParcel; pending(c);
}
});
test('underlying domestic IRPC and beneficiary withholding remain separate even when supported by the same paper', () => {
const c = internationalCase('10', '8', '200', '500', '300'); c.b = prepareEconomicBook(c.b); c.b.economicCredits = economicCase().b.economicCredits;
const withholding = c.b.withholdings.rows[0], proof = calc(c).claims.find(x => x.kind === 'withholding');
Object.assign(row(c), {taxIssuer: proof.issuer, taxDocument: proof.document, proofAmount: '300'}); pending(c);
Object.assign(withholding, {parcel: 'beneficiary-withholding', parcelReference: 'SYNTHETIC separate recipient-tax parcel'});
assert.equal(number(calc(c).payable), 388);
const other = structuredClone(c.b), s = JSON.parse(c.d.modelo_a_snapshot);
other.economicCredits.rows = []; other.economicCredits.state = 'absent'; other.internationalCredits.positions = []; other.internationalCredits.state = 'absent';
other.ppc.rows = []; other.ppc.state = 'absent'; other.pecPayments.rows = []; other.pecPayments.state = 'absent';
other.withholdings.rows[0].parcel = 'relabelled-same-L5-allocation';
s.irpcAnnual = {'opportunity:other': other}; s.irpcWithholdings['opportunity:other'] = structuredClone(Object.values(s.irpcWithholdings)[0]); c.d.modelo_a_snapshot = JSON.stringify(s);
c.d.modelo_a_snapshot = saveIrpcBook(c.d, recordIrpc(c.d, irpcBook(c.d), '2026-10-28T14:00:00+02:00'));
assert.match(pending(c).pending.join(' '), /calculada e reconciliada emL5|afectação L5/);
});
test('documented economic inclusion is not rejected merely because fiscal losses reduce total taxable base below dividends', () => {
const c = economicCase(); row(c).income = '5000';
const m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.payable), 688);
});
test('cross-context source capacity and distributed-income duplication cannot be evaded with new ids/documents', () => {
const c = economicCase(), other = structuredClone(c.b), s = JSON.parse(c.d.modelo_a_snapshot);
other.internationalCredits.positions = []; other.internationalCredits.state = 'absent'; other.ppc.rows = []; other.ppc.state = 'absent'; other.pecPayments.rows = []; other.pecPayments.state = 'absent';
other.economicCredits.rows[0].id = 'other-id'; other.economicCredits.rows[0].taxDocument = 'OTHER';
s.irpcAnnual = {'opportunity:other': other}; c.d.modelo_a_snapshot = JSON.stringify(s); assert.match(pending(c).pending.join(' '), /lucros económicos já/);
other.economicCredits.rows[0].distributionParcel = 'other-distribution'; other.economicCredits.rows[0].taxDocument = row(c).taxDocument; c.d.modelo_a_snapshot = JSON.stringify(s); pending(c);
other.economicCredits.rows[0].taxAmount = '10'; row(c).taxAmount = '10'; row(c).grossUpIncluded = '6'; c.d.modelo_a_snapshot = JSON.stringify(s);
assert.deepEqual(calc(c).pending, []);
});
test('economic and accepted carry increments compose:1408-12-8-50-200-100-500=538', () => {
const m = calc(economicCase(true)); assert.deepEqual(m.pending, []); assert.equal(number(m.payable), 538);
assert.equal(number(m.creditCarry.afterInternational), 1338); assert.equal(number(m.creditCarry.afterPec), 1038);
});
test('economic priority leaves prior explicit allocations intact when remaining collecta becomes insufficient', () => {
const c = economicCase(true); c.b.creditCarry.lots[0].eligible = '2000'; c.b.creditCarry.lots[0].selected = '1300'; c.b.creditCarry.currentPec = '0';
const before = structuredClone(c.b.creditCarry); assert.match(pending(c).pending.join(' '), /ultrapassam a colecta/); assert.deepEqual(c.b.creditCarry, before);
c.b.creditCarry.lots[0].selected = '1288'; const m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.recoverable), 500); assert.equal(m.economicCredit.carryCreated, false);
});
test('zero,absence and missing differ; earlier deliberate economic summary remains frozen and does not block detailed calculation', () => {
const c = economicCase(); c.b.internationalCredits.economic = {state: 'known', amount: '999', reference: 'SYNTHETIC previous deliberate summary'};
assert.equal(number(calc(c).payable), 688); assert.equal(c.b.internationalCredits.economic.amount, '999');
c.b.economicCredits.state = 'absent'; pending(c); c.b.economicCredits.rows = []; assert.equal(number(calc(c).payable), 700);
c.b.economicCredits.state = ''; pending(c);
const z = economicCase(); Object.assign(row(z), {taxAmount: '0', proofAmount: '0', grossUpIncluded: '0', income: '0', nationalLimit: '0'}); assert.equal(number(calc(z).payable), 700);
});
test('exact60% arithmetic and fractional quota never invent fiscal rounding', () => {
const c = economicCase(); Object.assign(row(c), {taxAmount: '0.01', proofAmount: '0.01', grossUpIncluded: '0.006'});
const m = calc(c); assert.deepEqual(m.economicCredit.deducted, {numerator: '3', denominator: '500'}); assert.deepEqual(m.payable, {numerator: '349997', denominator: '500'});
row(c).nationalLimit = '1/1000'; assert.deepEqual(calc(c).economicCredit.deducted, {numerator: '1', denominator: '1000'});
});
test('save/recover/history,HTML and dossier preserve current L6,original snapshots and accepted carry results', () => {
const c = economicCase(true), prior = structuredClone(c.b); delete prior.economicCredits;
c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, prior, '2026-10-28T12:00:00+02:00'));
const old = annualBook(c.d), frozen = structuredClone(old.result), base = JSON.parse(c.d.modelo_a_snapshot), plan = c.d.business_plan_snapshot;
const next = prepareEconomicBook(old); next.economicCredits = c.b.economicCredits;
c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, next, '2026-10-28T14:00:00+02:00'));
const back = annualBook(JSON.parse(JSON.stringify(c.d))); assert.equal(annualCurrent(c.d, back), true); assert.deepEqual(back.history, [frozen]); assert.equal(number(back.result.model.payable), 538);
const after = JSON.parse(c.d.modelo_a_snapshot); delete after.irpcAnnual; delete base.irpcAnnual; assert.deepEqual(after, base); assert.equal(c.d.business_plan_snapshot, plan);
assert.match(annualHtml(c.d), /Crédito económico — antes do internacional/); assert.match(annualHtml(c.d), /538.00/);
assert.match(JSON.stringify(createProjectDossierReport(c.d, {selectedSections: new Set(['finance'])})), /Crédito económico/);
back.economicCredits.rows[0].nationalLimit = '5'; c.d.modelo_a_snapshot = saveAnnualBook(c.d, back); assert.equal(annualCurrent(c.d, back), false); assert.deepEqual(back.result, annualBook(c.d).result); assert.throws(() => annualHtml(c.d), /fontes actuais/); assert.match(annualReportRows(c.d).flat().join(' '), /Histórico/);
});
test('malformed optional evidence and parcels are rejected without resetting snapshots', () => {
for (const mutate of [c => c.b.economicCredits.version = 2, c => row(c).previousUse = null, c => row(c).article40 = null, c => foreign(c).parcel = 1]) {
const c = economicCase(), before = c.d.modelo_a_snapshot; mutate(c); assert.throws(() => saveAnnualBook(c.d, c.b), /recuperável/); assert.equal(c.d.modelo_a_snapshot, before);
}
const c = internationalCase(); const once = prepareEconomicBook(c.b); assert.equal(prepareEconomicBook(once), once);
});
test('a partially identified document parcel remains recoverable and indeterminate rather than acquiring absent fields', () => {
const c = economicCase(); foreign(c).parcel = 'foreign-tax-line';
const model = pending(c); c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, c.b));
const back = annualBook(JSON.parse(JSON.stringify(c.d))); assert.deepEqual(calculateAnnual(c.d, back), back.result.model); assert.equal(back.result.model.status, model.status);
});
+23
View File
@@ -0,0 +1,23 @@
import fs from 'node:fs';
import {carryCase} from '../tests/frontend/helpers/irpc-carry-case.mjs';
import {internationalCase} from '../tests/frontend/helpers/irpc-international-case.mjs';
import {recordAnnual, saveAnnualBook} from '../resources/js/lib/irpc-annual-settlement.ts';
const cases = {};
for (const name of ['payable', 'expired', 'missing-use', 'overallocated', 'fractional', 'recoverable']) {
const c = carryCase(), previous = internationalCase();
const frozen = recordAnnual(previous.d, previous.b, '2026-10-27T17:00:00+02:00').result;
c.b.history = [frozen];
const l = c.b.creditCarry.lots[0];
if (name === 'expired') l.year = '2020';
if (name === 'missing-use') l.usesState = '';
if (name === 'overallocated') {l.eligible = '5000'; l.selected = '1400';}
if (name === 'fractional') {
Object.assign(l, {eligible: '2/3', originDeducted: '1/3', selected: '1/3', usesState: 'absent', uses: []});
c.b.creditCarry.currentInternational = '1/3';
}
if (name === 'recoverable') {l.eligible = '2000'; l.selected = '1300'; c.b.creditCarry.currentPec = '0';}
c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, c.b, '2026-10-28T12:00:00+02:00'));
cases[name] = c.d;
}
fs.writeFileSync(new URL('../tests/frontend/fixtures/irpc-carry-preserved.json', import.meta.url), JSON.stringify({synthetic: true, actualBalances: false, cases}));
console.log('Prepared six synthetic carry API cases with frozen international-credit history.');
+27
View File
@@ -0,0 +1,27 @@
import fs from 'node:fs';
import assert from 'node:assert/strict';
import {annualBook, annualCurrent, calculateAnnual, annualHtml} from '../resources/js/lib/irpc-annual-settlement.ts';
import {createProjectDossierReport} from '../resources/js/lib/project-dossier-report.ts';
const output = new URL('../outputs/irpc-l8-carry-20261028/', import.meta.url);
const receipts = [];
for (const name of ['payable', 'expired', 'missing-use', 'overallocated', 'fractional', 'recoverable']) {
const d = JSON.parse(fs.readFileSync(new URL('recovered-' + name + '.json', output), 'utf8'));
const b = annualBook(d), m = b.result.model, fresh = calculateAnnual(d, b);
assert.equal(annualCurrent(d, b), true);
assert.deepEqual(fresh, m);
assert.equal(b.history.length, 1);
assert.equal(b.history[0].model.payable.numerator, '700');
const html = annualHtml(d);
const dossier = createProjectDossierReport(d, {selectedSections: new Set(['finance']), generatedAt: '2026-10-28T12:00:00+02:00'});
assert.match(html, /Afectação escolhida entre exercícios/);
assert.match(JSON.stringify(dossier), /Saldo anterior — PEC — 2023/);
assert.match(html, /último exercício ordinário/);
if (name === 'payable') assert.match(html, /550.00/);
if (name === 'expired') {assert.equal(m.creditCarry.lots[0].expired, true); assert.equal(m.status, 'indeterminate');}
if (name === 'fractional') assert.deepEqual(m.arithmeticBalance, {numerator: '1822', denominator: '3'});
fs.writeFileSync(new URL('report-' + name + '.html', output), html);
fs.writeFileSync(new URL('dossier-' + name + '.json', output), JSON.stringify(dossier));
receipts.push({name, status: m.status, balance: m.arithmeticBalance, apiRecovered: true, recalculationEqual: true, html: true, dossier: true, frozenHistoryPreserved: true});
}
fs.writeFileSync(new URL('recovered-report-receipt.json', output), JSON.stringify({synthetic: true, activeChanged: false, receipts}, null, 2));
console.log(JSON.stringify(receipts, null, 2));
+24
View File
@@ -0,0 +1,24 @@
import fs from 'node:fs';
import {economicCase} from '../tests/frontend/helpers/irpc-economic-case.mjs';
import {recordAnnual, saveAnnualBook} from '../resources/js/lib/irpc-annual-settlement.ts';
const cases = {};
for (const name of ['payable', 'combined', 'quota', 'prior-use', 'duplicate', 'missing-gross-up', 'article40', 'shared-paper', 'partial-parcel', 'fractional', 'recoverable']) {
const c = economicCase(name === 'combined');
const previous = structuredClone(c.b); delete previous.economicCredits;
c.b.history = [recordAnnual(c.d, previous, '2026-10-28T12:00:00+02:00').result];
const r = c.b.economicCredits.rows[0], p = c.b.internationalCredits.positions[0], f = p.payments[0];
if (name === 'quota') r.nationalLimit = '5';
if (name === 'prior-use') r.previousUse.amount = '3';
if (name === 'duplicate' || name === 'shared-paper') {
Object.assign(f, {issuer: r.taxIssuer, document: r.taxDocument, proofAmount: '20', parcel: name === 'duplicate' ? r.taxParcel : 'foreign-tax-line', parcelReference: 'SYNTHETIC QA documented tax line in shared paper, no actual tax evidence'});
}
if (name === 'missing-gross-up') r.grossUpIncluded = '';
if (name === 'article40') r.article40 = 'yes';
if (name === 'partial-parcel') f.parcel = 'foreign-tax-line';
if (name === 'fractional') Object.assign(r, {proofAmount: '0.01', taxAmount: '0.01', grossUpIncluded: '0.006'});
if (name === 'recoverable') {f.proofAmount = '2000'; f.amount = '2000'; p.nationalLimit = '2000'; p.incomeAmount = '6250';}
c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, c.b, '2026-10-28T14:00:00+02:00'));
cases[name] = c.d;
}
fs.writeFileSync(new URL('../tests/frontend/fixtures/irpc-economic-preserved.json', import.meta.url), JSON.stringify({synthetic: true, actualTaxEvidence: false, cases}));
console.log('Prepared eleven synthetic economic-credit cases with accepted annual/carry history.');
+22
View File
@@ -0,0 +1,22 @@
import fs from 'node:fs';
import assert from 'node:assert/strict';
import {annualBook, annualCurrent, calculateAnnual, annualHtml} from '../resources/js/lib/irpc-annual-settlement.ts';
import {createProjectDossierReport} from '../resources/js/lib/project-dossier-report.ts';
const output = new URL('../outputs/irpc-l8-economic-20261028/', import.meta.url);
const receipts = [];
for (const name of ['payable', 'combined', 'quota', 'prior-use', 'duplicate', 'missing-gross-up', 'article40', 'shared-paper', 'partial-parcel', 'fractional', 'recoverable']) {
const d = JSON.parse(fs.readFileSync(new URL('recovered-' + name + '.json', output), 'utf8'));
const b = annualBook(d), m = b.result.model;
assert.equal(annualCurrent(d, b), true); assert.deepEqual(calculateAnnual(d, b), m);
assert.equal(b.history.length, 1); assert.equal(b.history[0].model.payable.numerator, name === 'combined' ? '550' : '700');
const html = annualHtml(d), dossier = createProjectDossierReport(d, {selectedSections: new Set(['finance']), generatedAt: '2026-10-28T14:00:00+02:00'});
assert.match(html, /Crédito económico — antes do internacional/); assert.match(JSON.stringify(dossier), /Crédito económico/);
if (name === 'combined') {assert.match(html, /538.00/); assert.match(html, /Saldo anterior — PEC — 2023/);}
if (name === 'payable') {assert.match(html, /688.00/); assert.match(html, /1396.00/);}
if (name === 'fractional') assert.deepEqual(m.arithmeticBalance, {numerator: '349997', denominator: '500'});
fs.writeFileSync(new URL('report-' + name + '.html', output), html);
fs.writeFileSync(new URL('dossier-' + name + '.json', output), JSON.stringify(dossier));
receipts.push({name, status: m.status, balance: m.arithmeticBalance, economicDeduction: m.economicCredit.deducted, apiRecovered: true, recalculationEqual: true, html: true, dossier: true, frozenHistoryPreserved: true});
}
fs.writeFileSync(new URL('recovered-report-receipt.json', output), JSON.stringify({synthetic: true, activeChanged: false, receipts}, null, 2));
console.log(JSON.stringify(receipts.map(({name, status, balance}) => ({name, status, balance})), null, 2));