Compare commits
5
Commits
838ad941a2
...
569a1cd750
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
569a1cd750 | ||
|
|
aae67c169d | ||
|
|
6ededb597a | ||
|
|
d134a92d16 | ||
|
|
cf4e0638c1 |
@@ -1561,3 +1561,50 @@ 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`.
|
||||
|
||||
@@ -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,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`.
|
||||
|
||||
@@ -7103,3 +7103,66 @@ 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 — retoma de L8 e preservação antes do novo delta
|
||||
|
||||
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.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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,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>
|
||||
|
||||
@@ -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));
|
||||
@@ -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',
|
||||
|
||||
@@ -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};
|
||||
}
|
||||
@@ -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};
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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.');
|
||||
@@ -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));
|
||||
@@ -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.');
|
||||
@@ -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));
|
||||
Reference in New Issue
Block a user