Compare commits

...
4 Commits
13 changed files with 1276 additions and 21 deletions
@@ -10972,5 +10972,629 @@
],
"integration": "Normal Git fast-forward,without force;fetch/ancestor guard repeated immediately before push"
}
},
"iva_l1_g5a_homologation_20261024": {
"status": "installed_delta_verified_partial_L1",
"candidate": "1f7fc13872bd706f583a6f4d29024cd3c22ec265",
"base": "0eb2c485",
"last_known_remote_main": "2e21ca45002b76adcef0347135783c706d37dd42",
"fresh_destination_preflight": "Verified authenticated installed/current-link/build revision2e21ca45;installer inactive;existing authenticated session reused",
"coverage": {
"group": "G5A",
"branches": {
"AUD-SIM-L1-P081": [
"regime_dispatch_goods",
"regime_dispatch_transport"
],
"AUD-SIM-L1-P082": [
"regime_internal_goods",
"regime_internal_services"
],
"AUD-SIM-L1-P083": [
"regime_transit_goods",
"regime_transit_transport"
]
},
"branch_count": 3,
"treatment_count": 6,
"scope": "2026/MZN;CIVA14(1)(b/c/d),19(1)(b)(iv)"
},
"runtime_delta": [
{
"path": "resources/js/components/simulation-operations.tsx",
"sha256_LF": "ef1019201ef546aee7dbd312741ec9653afdd3bb9c94777ea4735682506b6633"
},
{
"path": "resources/js/lib/iva-operations.ts",
"sha256_LF": "e9d2b0d7ed97ef9034f151b88e819e895666048f1d362a81d88855bad8e44f82"
},
{
"path": "resources/js/lib/iva-special-regimes.ts",
"sha256_LF": "76098c658dcaf7bb09c68664001fdd5a2a6e9e2c401d0dd0d1cdca8ae710f4ab"
}
],
"counts_current": {
"delivered": 65,
"QA": 0,
"functional_pending": 67,
"documentary": 1,
"total": 133
},
"counts_after_delivery_only": {
"delivered": 65,
"QA": 0,
"functional_pending": 67,
"documentary": 1,
"total": 133
},
"proofs_reused": {
"frontend_new": 4,
"API_tests": 1,
"API_assertions": 44,
"QA_database": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"types": "passed",
"production_build": "passed; existing plugin timing warnings",
"QA_build": "passed; existing future config/chunk size warnings",
"QA_storage": "save/recover/reject passed in temporary directory",
"UI": {
"actor": "Codex",
"method": "Edge extension/CUA observed actions",
"URL": "http://127.0.0.1:18640/g5a.html",
"observed": [
"six distinct treatments initially visible",
"no-final-use condition unchecked -> indeterminate; price100MZN retained",
"unknown regime -> indeterminate; price/currency/period retained",
"restore regime and explicitly recheck conditions ->600MZN/05",
"Guardar -> Recuperar -> Relatório with context/regime/source and totals",
"three previous results in history;19priorbooks unchanged"
],
"manual_Tempo_reply": null,
"screenshot": "outputs/iva-l1-g5-regimes-20261024/qa-recovered-report.png",
"screenshot_sha256": "ec68a1287ade198f34544fed0e5b1f49a6c15c2e6855fcaf13dc34ceb45c8772"
},
"Word_PDF": "accepted exporter/numeric proofs reused; no new pagination claim"
},
"rollback": "l1-g3-readonly-rollback-20261024.patch checked on G5A candidate,not applied;readers/history/reports retained;fresh backup and previous release must be preserved",
"backup_restore": {
"backup": {
"stage": "/var/backups/investmoz-l1-g5a-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "4568a12444365980c0265429521f7e13df67a03c116103ec18163f8c2feaa9de",
"files_sha256": "2016c081b509c976eda3d809b4481147501468295bcb51f586ea989560ba7c59",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g5a_restore_20261024",
"port": 55441,
"source_dump_sha256": "4568a12444365980c0265429521f7e13df67a03c116103ec18163f8c2feaa9de",
"active_database_writes": 0
}
},
"activation": "Existing Git FF/webhook/installer when delivery is undertaken; no migrations/imports/permission changes or synthetic active tests",
"served_revision_and_delta": "verified",
"limits": "2026/MZN; condição inicial14(1),regime/destino/permanência e ligação directa próprios; preço distinto dos bens/serviços. Sem isenção pelo mapa, certificação de regime, cálculo da própria importação/saída, aquisições14(2),dedução automática ou submissãoAT. P080/P084/P085/P086 continuam pendentes. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas.",
"L1_complete": false,
"P001": "05/06 only",
"beverages": "L2/L3;not closed",
"statistics_AI": "deferred",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "2e21ca45002b76adcef0347135783c706d37dd42",
"release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"previous_release": "/var/www/investmoz-homologacao/releases/686328a0853a1165872b5eb8163f7223600033ea-81b13983",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"release_revision": {
"commit": "2e21ca45002b76adcef0347135783c706d37dd42",
"branch": "main",
"built_at": "2026-10-24T16:27:47.396813+00:00",
"manifest_sha256": "9b28c92c584ad406e17d01ffc3fa982b9299195b371e1c5311626b9025a22615"
},
"service": "ExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"configuration_keys": [
"repository",
"branch",
"target_url",
"legacy_root",
"state_root",
"release_root",
"current_link",
"shared_assets",
"php",
"schema_contract",
"ci_environment",
"postgis_image",
"test_database",
"qa_port",
"retention",
"webhook_secret_file"
],
"safe_paths": {
"repository": "nala/Investidor-V2",
"release_root": "/var/www/investmoz-homologacao/releases",
"postgis_image": "postgis/postgis@sha256:01a6a70e41e6c4467c8f55f6063555ed72db2d6662cd0d571040d42eadaeb6f6"
},
"pipeline_sha256": "adec1c17654f3a8658b83b134f1e75f95391b235738552721906c3236e388604"
},
"authenticated_destination": "Fresh read confirmed2e21ca45;installer inactive",
"new_backup_restore": "Verified fresh backup and real isolated restore;no active restore performed",
"user_instruction": {
"QA_acceptance": "G5A concluído em QA segundo o relatório4e97cd05;seis tratamentos correspondem aos três ramosP081–P083",
"delivery": "Integrar e disponibilizar pelo processoGit existente,preservando alterações concorrentes e conferindo apenas o delta instalado",
"proofs": "Accepted QA proofs reused;no new functional/manual proof requested",
"constraints": "L1open;P00105/06;beveragesL2/L3;StatisticsAIdeferred"
},
"concurrency": {
"fresh_origin_main": "2e21ca45002b76adcef0347135783c706d37dd42",
"fresh_authenticated_destination": "2e21ca45002b76adcef0347135783c706d37dd42",
"incoming_changes_since_G4E": [],
"preserved_local_commits": [
"0eb2c485cc13e0ecbc6fa448c95425a8ab8f05b4",
"1f7fc13872bd706f583a6f4d29024cd3c22ec265",
"4e97cd05ea09e5dd2e74ec3264928a2f1f61858c"
],
"integration": "Normal Git fast-forward,without force;fetch/ancestor guard repeated immediately before push"
},
"beverages_followup": {
"source": "CIVA13(2),20(1)(d)",
"L2": "Dedução do IVA da via13(2),com montante/documento/condições próprios",
"L3": "Restituição da via13(2),conforme procedimento aplicável;pedido não equivale a deferimento",
"closed_by_G5A": false
},
"served_commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"release": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"previous_release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"database_migrations": 0,
"content_imports": 0
},
"runtime_files_verified": 3,
"persistent_files_and_env_verified": 369,
"tables_compared": 174,
"changed_tables": {
"cache": {
"before": {
"rows": 105,
"checksum": "b321ab0f6a8b1ad7ee62098fe598b883"
},
"after": {
"rows": 105,
"checksum": "07a8420630022d972c4c19da59066638"
}
},
"sessions": {
"before": {
"rows": 23,
"checksum": "9573b216049fc4693f4412b041d19015"
},
"after": {
"rows": 24,
"checksum": "9c73aba197fb8ed0448008979941a338"
}
}
},
"preserved_counts": {
"published_fiches": 29,
"relations": 28,
"geometries": 408
},
"migration_count": 0,
"content_imports": 0,
"comparison_role": "postgres_before_and_after;sameexportedsnapshotbaseline;noapplicationRLSvisibilityinference",
"writes_by_verification": 0
},
"public": {
"status": "installed_delta_verified",
"served_revision": {
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"branch": "main",
"built_at": "2026-10-24T16:48:42.080060+00:00",
"manifest_sha256": "84ea021139c585e0c7e7f8ab6933cd1775cd08173d3d0cdfeffad0b5bef46801"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"special-regimes/1": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_dispatch_goods": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_dispatch_transport": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_internal_goods": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_internal_services": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_transit_goods": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_transit_transport": [
"assets/project-dossier-D8_51R3_.js"
],
"specialRegime": [
"assets/project-dossier-D8_51R3_.js",
"assets/services-BJM_v6Xn.js"
]
},
"assets": [
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-D8_51R3_.js",
"status": 200,
"sha256": "71399dba8be4dc38ca0c4fd25742f4ef9281567e1c04f9883a0adb139dbade4c"
},
{
"file": "assets/services-BJM_v6Xn.js",
"status": 200,
"sha256": "6f728b31519a274de615675ae7197d1feb81c5a3e25f75668a2b2aabaf003edd"
},
{
"file": "assets/project-dossier-document-CNrdEqtj.js",
"status": 200,
"sha256": "26ea47eda13fc768227a6221afa225c2d8cc714f8cc769cfd5e430d37faa6274"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-zFlqblFZ.js",
"existing_fiscal_availability": {
"data": {
"enabled": true,
"coverage_start": "2026-01-01",
"coverage_end": "2026-12-31",
"message": "IVA geral sobre base líquida disponível; enquadramento declarado."
}
},
"synthetic_private_writes": 0,
"method": "Read-only installedrevision/manifest/newcompiledcatalogueandreaders/simulatorentry;acceptedQAproofsreused"
},
"installer": {
"service": "ExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"installed": {
"status": "installed",
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"release": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"previous_release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"release": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"previous_release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75"
],
"finished_at": "2026-10-24T16:48:44.469191+00:00"
},
"log_file": "1792860435237937385.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.27s",
"OK (59 tests, 317 assertions)",
"# tests 296",
"# pass 296",
"# fail 0"
],
"log_bytes": 114589
},
"rollback_executed": false
}
},
"iva_l1_g5b_P086_acquisition_continuity_QA_demonstrated_20261024": {
"key": "iva_l1_g5b_P086_acquisition_continuity_QA_demonstrated_20261024",
"status": "demonstrated_QA_not_installed",
"candidate": "689a4c93c33cd737c6fc90823533b34b5219b5d3",
"base": "d3e9f373",
"homologation": "69f2e365/d3e9f373",
"group": "G5B",
"branches": {
"AUD-SIM-L1-P086": "former_exploration_exemption -> explicit normal acquisition continuation"
},
"branch_count": 1,
"scope": "nonapplication and continuation;not a newly active exemption",
"source": {
"rectification": {
"file": "docs\\investmoz\\simulations\\source-archive\\BR-89-I-Serie-2017-06-08.pdf",
"bytes": 9456358,
"sha256": "11f0cab15eb6e51010952203ffa24fdc533a24fd642e19525fe4f46b17a1f5e5",
"pages": 16
},
"page": "PDF1/p569,visual inspected",
"CIVA_original": "14(2)(c),PDF13/p1426(271)",
"2022_2025": "art1 lists checked;no reintroduction14(2)(c)",
"acceptance": "Tempo08/10/2026;no generic provenance/legal revalidation added"
},
"inventory": {
"archive_files": [
{
"file": "docs\\investmoz\\simulations\\source-archive\\BR-16-I-Serie-2008-04-16.pdf",
"bytes": 2267865,
"sha256": "fc373ff5637edf75ec6a9595dec8763a8503d4ee786e3b7d8f1c742eae9d80ee",
"pages": 28
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\BR-248-I-Suplemento-1-2025.pdf",
"bytes": 440018,
"sha256": "ccf2a8deeca820f2dd076b4b2141b1efe3f6a806568c3a587ca59a8e92f4c251",
"pages": 21
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\BR-89-I-Serie-2017-06-08.pdf",
"bytes": 9456358,
"sha256": "11f0cab15eb6e51010952203ffa24fdc533a24fd642e19525fe4f46b17a1f5e5",
"pages": 16
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\BR-95-I-Suplemento-2025-05-21.pdf",
"bytes": 329070,
"sha256": "e0e682e2c027c3cd9c1d46a73a3f48bc5f6bdbf05667fd97314d7a3f6a456358",
"pages": 2
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\Lei-13-2016-CIVA-BR-156-10-suplemento.pdf",
"bytes": 2127554,
"sha256": "b90dc7c14ecea2e378c4a62e8e5a47d54a5644c457baeb8b8053b92fd2a5710b",
"pages": 32
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\Lei-22-2022-IVA-republicada-BR-250-2-suplemento.pdf",
"bytes": 1834284,
"sha256": "ea1b0dc6f5cf6e595f6d9a19e7042f398999e0087caef1785f6e8fac571b5f53",
"pages": 18
}
],
"existing_corpus_references": [
{
"path": "docs/investmoz/document-corpus-inventory-2026-10-06.csv",
"sha256": "3a24442558ad2b9d4ac9b58cc6d281bd0db83b4c93d4696e30a6f8981d9eaa7b",
"usage": "existing corpus/source inventory reused; no claim of newly reviewing every source"
},
{
"path": "docs/investmoz/fiscal-source-references-2026-10-06.csv",
"sha256": "f2fde2257fd481f984e59bdfc62ce209c849b350961111616d2c2927c1421d6f",
"usage": "existing corpus/source inventory reused; no claim of newly reviewing every source"
}
]
},
"preservation": {
"delivered": 65,
"sales_books": 20,
"sales_books_identical_current_without_recalculation": true,
"purchase_books_in_frozen_fixture": 0,
"UI_previous_sales_identical": true,
"new_purchase_context": "opportunity:329",
"UI_history_count": 3,
"confirmed_losses": [],
"active": "Accepted G5A receipt reused;no fresh active query/mutation"
},
"implementation": {
"optional_fields": [
"acquisitionTreatment",
"acquisitionTreatmentOrigin",
"AcquisitionBook.history"
],
"legacy_fields": "No new mandatory keys on previous rows/books;scoped continuity version only on new chosen treatment",
"manual_periods": "calculate only explicit purchase-book months;budget reuse still verifies existing source;no sales month required for direct entries",
"period_change_impact": "Report includes declared purchase months rather than implicit financial-plan months;previous accepted4-month scenarios pass;no frozen result recalculated",
"history": "Previous result snapshots retained when explicitly recalculating;old reference/document/values/answers conserved",
"not_applicable_UI": "Normal deduction controls hidden while former eliminated reference selected;no deleted data"
},
"tests": {
"frontend_new": 4,
"existing_changed_acquisition_suite": 8,
"frontend_total": 12,
"latest_delta": 4,
"API_tests": 1,
"API_assertions": 45,
"QA_database": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"types": "passed",
"production_build": "passed;existing plugin timing warnings",
"QA_build": "passed;existing config/chunk warnings",
"QA_storage": "save/recover/reject passed in temporary directory",
"UI": {
"actor": "Codex",
"method": "Edge/CUA observed",
"URL": "http://127.0.0.1:18641/g5b.html",
"observed": [
"former14(2)(c) selected -> eliminated notice;deduction indeterminate,100/16/116MZN retained",
"normal deduction controls hidden while nonapplicable",
"explicit continue ->normal controls/facts restored;calculate ->16MZN field10 under normal declared conditions",
"Guardar -> Recuperar -> Relatório with document,source,period/context;17/18 remain indeterminate",
"three results in history and20salesbooks unchanged in saved file"
],
"manual_Tempo_reply": null,
"screenshot": "outputs/iva-l1-g5b-acquisitions-20261024/qa-recovered-report.png",
"screenshot_sha256": "e29df1a8daf66f43ab7aaab9f78f472cf331272860aaac0edcde6ff40fd3a9d5"
},
"Word_PDF": "Existing exporter/numeric proofs reused;no new pagination claim"
},
"counts": {
"delivered": 65,
"QA": 1,
"functional_pending": 66,
"documentary": 1,
"total": 133
},
"G5": {
"delivered": 3,
"QA": 1,
"functional_pending": 3
},
"limits": "2026/MZN;P086 é não aplicação da antiga14(2)(c),eliminada pelo Aviso2017,e continuidade deliberada na aquisição normal; não é isenção nova/activa nem cálculo retroactivo. Sem taxa presumida,dedução automática,importação,apuramento integral ou submissãoAT. P080/P084/P085 pendentes. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas."
},
"iva_l1_g5b_delivery_preparation_20261024": {
"status": "ready_after_fresh_authenticated_preflight_and_verified_backup_restore",
"candidate": "689a4c93c33cd737c6fc90823533b34b5219b5d3",
"base": "d3e9f373",
"last_known_remote_main": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"fresh_destination_preflight": "required before installation;not performed in this QA passage",
"coverage": {
"group": "G5B",
"branches": {
"AUD-SIM-L1-P086": "former_exploration_exemption -> explicit normal acquisition continuation"
},
"branch_count": 1,
"scope": "2026/MZN;nonapplication of eliminated14(2)(c) and explicit normal-acquisition continuity;not an active exemption"
},
"runtime_delta": [
{
"path": "resources/js/components/simulation-acquisitions.tsx",
"sha256_LF": "7c4e0a960c361c1fe67e9cb05e249f07ee5710d2dfefa69859e163a9f23118c6"
},
{
"path": "resources/js/lib/iva-acquisition-continuity.ts",
"sha256_LF": "2c40643c8f5ceb79b01fb4cb56d1955beb8bbd1c8a2a0cd080647bbc3db24e74"
},
{
"path": "resources/js/lib/iva-acquisitions.ts",
"sha256_LF": "364661218cdf7769a57b030006818c506a7296057e87333f2d7a1f673ac1a91c"
}
],
"counts_current": {
"delivered": 65,
"QA": 1,
"functional_pending": 66,
"documentary": 1,
"total": 133
},
"counts_after_delivery_only": {
"delivered": 66,
"QA": 0,
"functional_pending": 66,
"documentary": 1,
"total": 133
},
"proofs_reused": {
"frontend_new": 4,
"existing_changed_acquisition_suite": 8,
"frontend_total": 12,
"latest_delta": 4,
"API_tests": 1,
"API_assertions": 45,
"QA_database": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"types": "passed",
"production_build": "passed;existing plugin timing warnings",
"QA_build": "passed;existing config/chunk warnings",
"QA_storage": "save/recover/reject passed in temporary directory",
"UI": {
"actor": "Codex",
"method": "Edge/CUA observed",
"URL": "http://127.0.0.1:18641/g5b.html",
"observed": [
"former14(2)(c) selected -> eliminated notice;deduction indeterminate,100/16/116MZN retained",
"normal deduction controls hidden while nonapplicable",
"explicit continue ->normal controls/facts restored;calculate ->16MZN field10 under normal declared conditions",
"Guardar -> Recuperar -> Relatório with document,source,period/context;17/18 remain indeterminate",
"three results in history and20salesbooks unchanged in saved file"
],
"manual_Tempo_reply": null,
"screenshot": "outputs/iva-l1-g5b-acquisitions-20261024/qa-recovered-report.png",
"screenshot_sha256": "e29df1a8daf66f43ab7aaab9f78f472cf331272860aaac0edcde6ff40fd3a9d5"
},
"Word_PDF": "Existing exporter/numeric proofs reused;no new pagination claim"
},
"rollback": "l1-g3-readonly-rollback-20261024.patch checked on G5B candidate,not applied;readers/history/reports retained;fresh backup and previous release must be preserved",
"backup_restore": {
"backup": {
"stage": "/var/backups/investmoz-l1-g5b-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "d6c09b69fc18aba716554ca4aedded870c861c01c4997a4d29bc5e0f0b5380fe",
"files_sha256": "bd05d701fce9f8c150315791d196289db6036352cfd79341766c7fab031a7501",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g5b_restore_20261024",
"port": 55441,
"source_dump_sha256": "d6c09b69fc18aba716554ca4aedded870c861c01c4997a4d29bc5e0f0b5380fe",
"active_database_writes": 0
}
},
"activation": "Existing Git FF/webhook/installer when delivery is undertaken;no migrations/imports/permission changes or synthetic active tests",
"served_revision_and_delta": "pending installation;homologation remains69f2e365/d3e9f373",
"limits": "2026/MZN;P086 é não aplicação da antiga14(2)(c),eliminada pelo Aviso2017,e continuidade deliberada na aquisição normal; não é isenção nova/activa nem cálculo retroactivo. Sem taxa presumida,dedução automática,importação,apuramento integral ou submissãoAT. P080/P084/P085 pendentes. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas.",
"L1_complete": false,
"P001": "05/06 only",
"beverages": "L2/L3;not closed",
"statistics_AI": "deferred",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"release": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"previous_release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"release_revision": {
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"branch": "main",
"built_at": "2026-10-24T16:48:42.080060+00:00",
"manifest_sha256": "84ea021139c585e0c7e7f8ab6933cd1775cd08173d3d0cdfeffad0b5bef46801"
},
"service": "ExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"configuration_keys": [
"repository",
"branch",
"target_url",
"legacy_root",
"state_root",
"release_root",
"current_link",
"shared_assets",
"php",
"schema_contract",
"ci_environment",
"postgis_image",
"test_database",
"qa_port",
"retention",
"webhook_secret_file"
],
"safe_paths": {
"repository": "nala/Investidor-V2",
"release_root": "/var/www/investmoz-homologacao/releases",
"postgis_image": "postgis/postgis@sha256:01a6a70e41e6c4467c8f55f6063555ed72db2d6662cd0d571040d42eadaeb6f6"
},
"pipeline_sha256": "adec1c17654f3a8658b83b134f1e75f95391b235738552721906c3236e388604"
},
"authenticated_destination": "Fresh read confirmed69f2e365;installer inactive",
"new_backup_restore": "Verified fresh backup and real isolated restore;no active restore performed"
}
}
@@ -1,6 +1,6 @@
{
"key": "iva_l1_g5a_special_regimes_QA_demonstrated_20261024",
"status": "demonstrated_QA_not_installed",
"status": "delivered_with_QA_proofs_preserved",
"candidate": "1f7fc13872bd706f583a6f4d29024cd3c22ec265",
"base": "0eb2c485",
"homologation": "2e21ca45/0eb2c485",
@@ -60,14 +60,15 @@
"Word_PDF": "accepted exporter/numeric proofs reused; no new pagination claim"
},
"counts": {
"delivered": 62,
"QA": 3,
"delivered": 65,
"QA": 0,
"functional_pending": 67,
"documentary": 1,
"total": 133
},
"G5": {
"QA": 3,
"delivered": 3,
"QA": 0,
"functional_pending": 4
},
"limits": "2026/MZN; condição inicial14(1),regime/destino/permanência e ligação directa próprios; preço distinto dos bens/serviços. Sem isenção pelo mapa, certificação de regime, cálculo da própria importação/saída, aquisições14(2),dedução automática ou submissãoAT. P080/P084/P085/P086 continuam pendentes. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas.",
@@ -76,5 +77,18 @@
"P069": "export_diplomatic_mission",
"P070": "export_international_organisation",
"P071": "export_humanitarian_organisation"
},
"qa_acceptance_status": "demonstrated_QA_not_installed",
"qa_acceptance_counts": {
"delivered": 62,
"QA": 3,
"functional_pending": 67,
"documentary": 1,
"total": 133
},
"delivery_followup": {
"served_commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"record": "iva_l1_g5a_homologation_20261024",
"receipt": "l1-g5a-delivery-20261024.json"
}
}
@@ -0,0 +1,143 @@
{
"key": "iva_l1_g5b_P086_acquisition_continuity_QA_demonstrated_20261024",
"status": "demonstrated_QA_not_installed",
"candidate": "689a4c93c33cd737c6fc90823533b34b5219b5d3",
"base": "d3e9f373",
"homologation": "69f2e365/d3e9f373",
"group": "G5B",
"branches": {
"AUD-SIM-L1-P086": "former_exploration_exemption -> explicit normal acquisition continuation"
},
"branch_count": 1,
"scope": "nonapplication and continuation;not a newly active exemption",
"source": {
"rectification": {
"file": "docs\\investmoz\\simulations\\source-archive\\BR-89-I-Serie-2017-06-08.pdf",
"bytes": 9456358,
"sha256": "11f0cab15eb6e51010952203ffa24fdc533a24fd642e19525fe4f46b17a1f5e5",
"pages": 16
},
"page": "PDF1/p569,visual inspected",
"CIVA_original": "14(2)(c),PDF13/p1426(271)",
"2022_2025": "art1 lists checked;no reintroduction14(2)(c)",
"acceptance": "Tempo08/10/2026;no generic provenance/legal revalidation added"
},
"inventory": {
"archive_files": [
{
"file": "docs\\investmoz\\simulations\\source-archive\\BR-16-I-Serie-2008-04-16.pdf",
"bytes": 2267865,
"sha256": "fc373ff5637edf75ec6a9595dec8763a8503d4ee786e3b7d8f1c742eae9d80ee",
"pages": 28
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\BR-248-I-Suplemento-1-2025.pdf",
"bytes": 440018,
"sha256": "ccf2a8deeca820f2dd076b4b2141b1efe3f6a806568c3a587ca59a8e92f4c251",
"pages": 21
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\BR-89-I-Serie-2017-06-08.pdf",
"bytes": 9456358,
"sha256": "11f0cab15eb6e51010952203ffa24fdc533a24fd642e19525fe4f46b17a1f5e5",
"pages": 16
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\BR-95-I-Suplemento-2025-05-21.pdf",
"bytes": 329070,
"sha256": "e0e682e2c027c3cd9c1d46a73a3f48bc5f6bdbf05667fd97314d7a3f6a456358",
"pages": 2
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\Lei-13-2016-CIVA-BR-156-10-suplemento.pdf",
"bytes": 2127554,
"sha256": "b90dc7c14ecea2e378c4a62e8e5a47d54a5644c457baeb8b8053b92fd2a5710b",
"pages": 32
},
{
"file": "docs\\investmoz\\simulations\\source-archive\\Lei-22-2022-IVA-republicada-BR-250-2-suplemento.pdf",
"bytes": 1834284,
"sha256": "ea1b0dc6f5cf6e595f6d9a19e7042f398999e0087caef1785f6e8fac571b5f53",
"pages": 18
}
],
"existing_corpus_references": [
{
"path": "docs/investmoz/document-corpus-inventory-2026-10-06.csv",
"sha256": "3a24442558ad2b9d4ac9b58cc6d281bd0db83b4c93d4696e30a6f8981d9eaa7b",
"usage": "existing corpus/source inventory reused; no claim of newly reviewing every source"
},
{
"path": "docs/investmoz/fiscal-source-references-2026-10-06.csv",
"sha256": "f2fde2257fd481f984e59bdfc62ce209c849b350961111616d2c2927c1421d6f",
"usage": "existing corpus/source inventory reused; no claim of newly reviewing every source"
}
]
},
"preservation": {
"delivered": 65,
"sales_books": 20,
"sales_books_identical_current_without_recalculation": true,
"purchase_books_in_frozen_fixture": 0,
"UI_previous_sales_identical": true,
"new_purchase_context": "opportunity:329",
"UI_history_count": 3,
"confirmed_losses": [],
"active": "Accepted G5A receipt reused;no fresh active query/mutation"
},
"implementation": {
"optional_fields": [
"acquisitionTreatment",
"acquisitionTreatmentOrigin",
"AcquisitionBook.history"
],
"legacy_fields": "No new mandatory keys on previous rows/books;scoped continuity version only on new chosen treatment",
"manual_periods": "calculate only explicit purchase-book months;budget reuse still verifies existing source;no sales month required for direct entries",
"period_change_impact": "Report includes declared purchase months rather than implicit financial-plan months;previous accepted4-month scenarios pass;no frozen result recalculated",
"history": "Previous result snapshots retained when explicitly recalculating;old reference/document/values/answers conserved",
"not_applicable_UI": "Normal deduction controls hidden while former eliminated reference selected;no deleted data"
},
"tests": {
"frontend_new": 4,
"existing_changed_acquisition_suite": 8,
"frontend_total": 12,
"latest_delta": 4,
"API_tests": 1,
"API_assertions": 45,
"QA_database": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"types": "passed",
"production_build": "passed;existing plugin timing warnings",
"QA_build": "passed;existing config/chunk warnings",
"QA_storage": "save/recover/reject passed in temporary directory",
"UI": {
"actor": "Codex",
"method": "Edge/CUA observed",
"URL": "http://127.0.0.1:18641/g5b.html",
"observed": [
"former14(2)(c) selected -> eliminated notice;deduction indeterminate,100/16/116MZN retained",
"normal deduction controls hidden while nonapplicable",
"explicit continue ->normal controls/facts restored;calculate ->16MZN field10 under normal declared conditions",
"Guardar -> Recuperar -> Relatório with document,source,period/context;17/18 remain indeterminate",
"three results in history and20salesbooks unchanged in saved file"
],
"manual_Tempo_reply": null,
"screenshot": "outputs/iva-l1-g5b-acquisitions-20261024/qa-recovered-report.png",
"screenshot_sha256": "e29df1a8daf66f43ab7aaab9f78f472cf331272860aaac0edcde6ff40fd3a9d5"
},
"Word_PDF": "Existing exporter/numeric proofs reused;no new pagination claim"
},
"counts": {
"delivered": 65,
"QA": 1,
"functional_pending": 66,
"documentary": 1,
"total": 133
},
"G5": {
"delivered": 3,
"QA": 1,
"functional_pending": 3
},
"limits": "2026/MZN;P086 é não aplicação da antiga14(2)(c),eliminada pelo Aviso2017,e continuidade deliberada na aquisição normal; não é isenção nova/activa nem cálculo retroactivo. Sem taxa presumida,dedução automática,importação,apuramento integral ou submissãoAT. P080/P084/P085 pendentes. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas."
}
@@ -1,5 +1,5 @@
{
"status": "ready_after_fresh_authenticated_preflight_and_verified_backup_restore",
"status": "installed_delta_verified_partial_L1",
"candidate": "1f7fc13872bd706f583a6f4d29024cd3c22ec265",
"base": "0eb2c485",
"last_known_remote_main": "2e21ca45002b76adcef0347135783c706d37dd42",
@@ -39,8 +39,8 @@
}
],
"counts_current": {
"delivered": 62,
"QA": 3,
"delivered": 65,
"QA": 0,
"functional_pending": 67,
"documentary": 1,
"total": 133
@@ -105,7 +105,7 @@
}
},
"activation": "Existing Git FF/webhook/installer when delivery is undertaken; no migrations/imports/permission changes or synthetic active tests",
"served_revision_and_delta": "pending installation;homologation remains2e21ca45/0eb2c485",
"served_revision_and_delta": "verified",
"limits": "2026/MZN; condição inicial14(1),regime/destino/permanência e ligação directa próprios; preço distinto dos bens/serviços. Sem isenção pelo mapa, certificação de regime, cálculo da própria importação/saída, aquisições14(2),dedução automática ou submissãoAT. P080/P084/P085/P086 continuam pendentes. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas.",
"L1_complete": false,
"P001": "05/06 only",
@@ -171,5 +171,163 @@
"4e97cd05ea09e5dd2e74ec3264928a2f1f61858c"
],
"integration": "Normal Git fast-forward,without force;fetch/ancestor guard repeated immediately before push"
},
"beverages_followup": {
"source": "CIVA13(2),20(1)(d)",
"L2": "Dedução do IVA da via13(2),com montante/documento/condições próprios",
"L3": "Restituição da via13(2),conforme procedimento aplicável;pedido não equivale a deferimento",
"closed_by_G5A": false
},
"served_commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"release": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"previous_release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"database_migrations": 0,
"content_imports": 0
},
"runtime_files_verified": 3,
"persistent_files_and_env_verified": 369,
"tables_compared": 174,
"changed_tables": {
"cache": {
"before": {
"rows": 105,
"checksum": "b321ab0f6a8b1ad7ee62098fe598b883"
},
"after": {
"rows": 105,
"checksum": "07a8420630022d972c4c19da59066638"
}
},
"sessions": {
"before": {
"rows": 23,
"checksum": "9573b216049fc4693f4412b041d19015"
},
"after": {
"rows": 24,
"checksum": "9c73aba197fb8ed0448008979941a338"
}
}
},
"preserved_counts": {
"published_fiches": 29,
"relations": 28,
"geometries": 408
},
"migration_count": 0,
"content_imports": 0,
"comparison_role": "postgres_before_and_after;sameexportedsnapshotbaseline;noapplicationRLSvisibilityinference",
"writes_by_verification": 0
},
"public": {
"status": "installed_delta_verified",
"served_revision": {
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"branch": "main",
"built_at": "2026-10-24T16:48:42.080060+00:00",
"manifest_sha256": "84ea021139c585e0c7e7f8ab6933cd1775cd08173d3d0cdfeffad0b5bef46801"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"special-regimes/1": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_dispatch_goods": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_dispatch_transport": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_internal_goods": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_internal_services": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_transit_goods": [
"assets/project-dossier-D8_51R3_.js"
],
"regime_transit_transport": [
"assets/project-dossier-D8_51R3_.js"
],
"specialRegime": [
"assets/project-dossier-D8_51R3_.js",
"assets/services-BJM_v6Xn.js"
]
},
"assets": [
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-D8_51R3_.js",
"status": 200,
"sha256": "71399dba8be4dc38ca0c4fd25742f4ef9281567e1c04f9883a0adb139dbade4c"
},
{
"file": "assets/services-BJM_v6Xn.js",
"status": 200,
"sha256": "6f728b31519a274de615675ae7197d1feb81c5a3e25f75668a2b2aabaf003edd"
},
{
"file": "assets/project-dossier-document-CNrdEqtj.js",
"status": 200,
"sha256": "26ea47eda13fc768227a6221afa225c2d8cc714f8cc769cfd5e430d37faa6274"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-zFlqblFZ.js",
"existing_fiscal_availability": {
"data": {
"enabled": true,
"coverage_start": "2026-01-01",
"coverage_end": "2026-12-31",
"message": "IVA geral sobre base líquida disponível; enquadramento declarado."
}
},
"synthetic_private_writes": 0,
"method": "Read-only installedrevision/manifest/newcompiledcatalogueandreaders/simulatorentry;acceptedQAproofsreused"
},
"installer": {
"service": "ExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"installed": {
"status": "installed",
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"release": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"previous_release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"release": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"previous_release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75"
],
"finished_at": "2026-10-24T16:48:44.469191+00:00"
},
"log_file": "1792860435237937385.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.27s",
"OK (59 tests, 317 assertions)",
"# tests 296",
"# pass 296",
"# fail 0"
],
"log_bytes": 114589
},
"rollback_executed": false
}
}
@@ -0,0 +1,148 @@
{
"status": "ready_after_fresh_authenticated_preflight_and_verified_backup_restore",
"candidate": "689a4c93c33cd737c6fc90823533b34b5219b5d3",
"base": "d3e9f373",
"last_known_remote_main": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"fresh_destination_preflight": "required before installation;not performed in this QA passage",
"coverage": {
"group": "G5B",
"branches": {
"AUD-SIM-L1-P086": "former_exploration_exemption -> explicit normal acquisition continuation"
},
"branch_count": 1,
"scope": "2026/MZN;nonapplication of eliminated14(2)(c) and explicit normal-acquisition continuity;not an active exemption"
},
"runtime_delta": [
{
"path": "resources/js/components/simulation-acquisitions.tsx",
"sha256_LF": "7c4e0a960c361c1fe67e9cb05e249f07ee5710d2dfefa69859e163a9f23118c6"
},
{
"path": "resources/js/lib/iva-acquisition-continuity.ts",
"sha256_LF": "2c40643c8f5ceb79b01fb4cb56d1955beb8bbd1c8a2a0cd080647bbc3db24e74"
},
{
"path": "resources/js/lib/iva-acquisitions.ts",
"sha256_LF": "364661218cdf7769a57b030006818c506a7296057e87333f2d7a1f673ac1a91c"
}
],
"counts_current": {
"delivered": 65,
"QA": 1,
"functional_pending": 66,
"documentary": 1,
"total": 133
},
"counts_after_delivery_only": {
"delivered": 66,
"QA": 0,
"functional_pending": 66,
"documentary": 1,
"total": 133
},
"proofs_reused": {
"frontend_new": 4,
"existing_changed_acquisition_suite": 8,
"frontend_total": 12,
"latest_delta": 4,
"API_tests": 1,
"API_assertions": 45,
"QA_database": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"types": "passed",
"production_build": "passed;existing plugin timing warnings",
"QA_build": "passed;existing config/chunk warnings",
"QA_storage": "save/recover/reject passed in temporary directory",
"UI": {
"actor": "Codex",
"method": "Edge/CUA observed",
"URL": "http://127.0.0.1:18641/g5b.html",
"observed": [
"former14(2)(c) selected -> eliminated notice;deduction indeterminate,100/16/116MZN retained",
"normal deduction controls hidden while nonapplicable",
"explicit continue ->normal controls/facts restored;calculate ->16MZN field10 under normal declared conditions",
"Guardar -> Recuperar -> Relatório with document,source,period/context;17/18 remain indeterminate",
"three results in history and20salesbooks unchanged in saved file"
],
"manual_Tempo_reply": null,
"screenshot": "outputs/iva-l1-g5b-acquisitions-20261024/qa-recovered-report.png",
"screenshot_sha256": "e29df1a8daf66f43ab7aaab9f78f472cf331272860aaac0edcde6ff40fd3a9d5"
},
"Word_PDF": "Existing exporter/numeric proofs reused;no new pagination claim"
},
"rollback": "l1-g3-readonly-rollback-20261024.patch checked on G5B candidate,not applied;readers/history/reports retained;fresh backup and previous release must be preserved",
"backup_restore": {
"backup": {
"stage": "/var/backups/investmoz-l1-g5b-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "d6c09b69fc18aba716554ca4aedded870c861c01c4997a4d29bc5e0f0b5380fe",
"files_sha256": "bd05d701fce9f8c150315791d196289db6036352cfd79341766c7fab031a7501",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g5b_restore_20261024",
"port": 55441,
"source_dump_sha256": "d6c09b69fc18aba716554ca4aedded870c861c01c4997a4d29bc5e0f0b5380fe",
"active_database_writes": 0
}
},
"activation": "Existing Git FF/webhook/installer when delivery is undertaken;no migrations/imports/permission changes or synthetic active tests",
"served_revision_and_delta": "pending installation;homologation remains69f2e365/d3e9f373",
"limits": "2026/MZN;P086 é não aplicação da antiga14(2)(c),eliminada pelo Aviso2017,e continuidade deliberada na aquisição normal; não é isenção nova/activa nem cálculo retroactivo. Sem taxa presumida,dedução automática,importação,apuramento integral ou submissãoAT. P080/P084/P085 pendentes. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas.",
"L1_complete": false,
"P001": "05/06 only",
"beverages": "L2/L3;not closed",
"statistics_AI": "deferred",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"release": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"previous_release": "/var/www/investmoz-homologacao/releases/2e21ca45002b76adcef0347135783c706d37dd42-a5faea22",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75-ac55d458",
"release_revision": {
"commit": "69f2e365bf4ebd509ec2e080dd0bf1b7717d7a75",
"branch": "main",
"built_at": "2026-10-24T16:48:42.080060+00:00",
"manifest_sha256": "84ea021139c585e0c7e7f8ab6933cd1775cd08173d3d0cdfeffad0b5bef46801"
},
"service": "ExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
"configuration_keys": [
"repository",
"branch",
"target_url",
"legacy_root",
"state_root",
"release_root",
"current_link",
"shared_assets",
"php",
"schema_contract",
"ci_environment",
"postgis_image",
"test_database",
"qa_port",
"retention",
"webhook_secret_file"
],
"safe_paths": {
"repository": "nala/Investidor-V2",
"release_root": "/var/www/investmoz-homologacao/releases",
"postgis_image": "postgis/postgis@sha256:01a6a70e41e6c4467c8f55f6063555ed72db2d6662cd0d571040d42eadaeb6f6"
},
"pipeline_sha256": "adec1c17654f3a8658b83b134f1e75f95391b235738552721906c3236e388604"
},
"authenticated_destination": "Fresh read confirmed69f2e365;installer inactive",
"new_backup_restore": "Verified fresh backup and real isolated restore;no active restore performed"
}
@@ -1,6 +1,39 @@
# Rastreabilidade, utilização e formação
## 24/10/2026 — G5B/P086 demonstrado em QA: referência eliminada e continuidade
**P086 → former_exploration_exemption → continuidade expressa pelo enquadramento normal da aquisição. Umramo**,candidata`689a4c93`,registo`iva_l1_g5b_P086_acquisition_continuity_QA_demonstrated_20261024`. Não é nova isenção,activação da alínea eliminada ou encerramento deP080/P084/P085. AvisoAR/BR89/I08-06-2017,PDF1/p569,página visual conferida,ordena eliminação14(2)(c);originais/hashes e inventário dos seisficheiros preservados. Alterações2022/2025 não reintroduzem14(2)(c) noacervo conferido. DecisãoTempo08/10aceita fonteoficial;sem segundaautenticação ou validaçãojurídicagenérica. Cobertura2026,sem apuramento retroactivo2016/2017. G5A14(1)(b/c/d) preservado.
Editor deaquisições existente explica a nãoaplicação,oculta controlos de dedução normal enquanto seleccionada a referência eliminada,conserva100MZNlíquido/16IVAindicado/116bruto,documento e respostas. Escolhaexpressa decontinuidade repõeoscontrolos eusaapenas ascondições normais existentes;nenhuma taxa,isençãooudedução automática é inferida. Resultadosanteriores guardados emhistory,origem na linhae fonte no relatório. Outras eventuais baseslegais permanecem poridentificar,sem presumir inexistência ou criar bloqueio geral.
Dependência técnica removida: compras directas podem calcularcom mesesexplicitamente declarados nolivro deaquisicões,sem exigir mês devendas. Osresultados incluem osmeses declarados,emvezdegerar mesesimplícitosdoplano;os cenáriosaceitesdequatromeses passam. Reutilização devalores deorçamento mantém conferência deorigem/alterações;nenhuma validaçãoorganizacionalnova. Mantidospreenchimentos,snapshots anteriores,reportes ehistórico;sem alteração ou recálculo dos20livrosanteriores de vendas.
4testesfrontendnovos+8aquisiçõesexistentes;APIprivadaQA1teste/45asserções,rollback eguarda*_test:55441;tipos/produção/QAaprovados,avisosexistentes deplugins/configuração/chunks. UIobservadaCodex/Edge-CUA:seleccionarrefantiga→nãoaplicação/deduçãoindeterminada,dadosconservados;continuar expressamente→condiçõesnormais→16MZN/campo10/Outrosbenseserviços,sem transformarserviço emexistências. Guardar→Recuperar→Relatório comopportunity329/Manica/2026-12,documentoBR89,origem/histórico;3versõesanterioresnahistóriaUI. Totais14–18mantidosindeterminados. Capturaqa-recovered-report.png eDOMemoutputs/iva-l1-g5b-acquisitions-20261024/. ProvasWord/PDFaceitesreutilizadas,semnovaalegaçãodepaginação;semrespostamanualTempoatribuída.
**65entregues+1QA+66funcionaispendentes+P001=133.** G5:3entregues/1QA/3pendentes(P080,P084,P085). Homologação69f2e365/d3e9f373inalterada;G5Bporentregar; [manifesto preparado](../simulations/l1-g5b-delivery-20261024.json),contenção de novos cálculos compatível conferida/não aplicada,leitores/histórico preservados. Destino/main e backup/restauro autenticados frescos continuam necessários antes de alterar o activo;sem push/instalação nesta passagem. 2026/MZN;P086 é não aplicação da antiga14(2)(c),eliminada pelo Aviso2017,e continuidade deliberada na aquisição normal; não é isenção nova/activa nem cálculo retroactivo. Sem taxa presumida,dedução automática,importação,apuramento integral ou submissãoAT. P080/P084/P085 pendentes. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas.
## 24/10/2026 — G5A aceite; inventário prévio e delimitação G5B/P086
Tempo aceitaG5A69f2e365/d3e9f373:65entregues+67funcionaispendentes+P001=133,semQAporentregar. Inventário anterior aos testesG5B:65fechos preservados,nenhuma perda confirmada no delta locald3e9f373 face à revisão servida69f2e365,código/schema/configuração/rotas sem diferenças. ReciboG5A e comparação equivalentePostgreSQL de174tabelas/369ficheiros/29fichas/28relações/408geometrias reutilizados;sem nova leitura/escrita activa alegada. Congelados os livros de vendas/aquisições existentes emiva-g5a-inputs.json;verpreservation-before-tests.json.
G5B avança primeiroP086. O Aviso da Assembleia da República,BR89/I Série08/06/2017,PDF1/p569,ordena eliminação de14(2)(c),com transcrição «c) eliminado». Página visual conferida;original/hash preservados. Lei22/2022art1 eLei10/2025art1 não reintroduzem14(2)(c). Cobertura2026,não cálculo retroactivo2016/2017. A fonteoficial é aceite pela decisãoTempo08/10;as antigas notas genéricas de validação adicional de autenticidade/proveniência no registo histórico não bloqueiam a aplicação deste trecho. Isto aplica a rectificação,não cria nova restrição organizacional. G5A14(1)(b/c/d) não é alterado pela eliminação de14(2)(c).
Implementar a não aplicação explicada no componente de aquisições existente,com escolha expressa de continuidade pelo enquadramento normal,conservando montantes/moeda/período/documento/respostas e resultado anterior. Não criar isenção de venda,zero presumido ou dedução automática;usar os montantes/documentos/condições da aquisição normal já disponíveis. P080/P084/P085 continuam pendências reais noG5;esta tranche não os fecha. SubdivisãoG5B/P086 é escolha técnica incremental,sem nova validação jurídica genérica ou aprovador.
Inventariados os seis ficheiros do arquivo fiscal inteiro emsource-archive-inventory.json antes de seleccionar o Aviso2017;Decreto7/2008 também consultado,sem activar taxa17% ou outra regra histórica por importação/publicação. L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas. Homologação69f2e365 preservada.
## 24/10/2026 — G5A entregue na homologação 69f2e365
**P081 → regime_dispatch_goods / regime_dispatch_transport; P082 → regime_internal_goods / regime_internal_services; P083 → regime_transit_goods / regime_transit_transport. Três ramos/seis tratamentos**, no recorte2026/MZN,14(1)(b/c/d),19(1)(b)(iv). A Tempo aceitouG5A concluído emQA segundo o relatório4e97cd05 e autorizou integração/disponibilização peloGit, preservando alterações concorrentes e conferindo somente o delta instalado. Prova deUICodex/Edge-CUA e provas código/API aceites reutilizadas; não atribuída nova conferência manual àTempo.
Gitfast-forward sobre2e21ca45;main e destino autenticado conferidos antes da entrega,sem alterações concorrentes encontradas;recebimento documentalG4E0eb2c485 eG5A1f7fc138/4e97cd05 preservados. Novo backup/restauro real isolado sem rede verificado em174tabelas/369ficheiros/configuração. Depois da instalação:revisão efectivamente servida,manifesto/hash,oito marcadores compilados,trêsficheiros funcionais e simuladorHTTP200 conferidos;preservados174tabelas/369ficheiros/29fichas/28relações/408geometrias por identidadePostgreSQL equivalente. Somente diferenças operacionais cache/sessões registadas. Zero migrações/importações,alterações de permissões ou ensaios sintéticos noactivo. Release anterior/backup conservados;contenção compatível de novos cálculos conferida,não aplicada,com leitores/histórico/relatórios preservados.19livros anteriores aceites íntegros/actuais,sem recálculo ou repetição das provas.
[Manifesto/recibo](../simulations/l1-g5a-delivery-20261024.json),registo `iva_l1_g5a_homologation_20261024`. **65entregues+67funcionaispendentes+P001=133;sem candidatasQA por disponibilizar.** G5:3ramos entregues/4pendentes(P080,P084–P086). Regime e condições próprios,não inferidos pelo mapa;sem cálculo de importação/saída,aquisições14(2),dedução automática ou certificação de enquadramento. **L1aberto;P001só05/06;bebidasL2/L3;Estatísticas/IAadiadas.** G4E conserva osquatroIDs/tratamentos aceites.
## 24/10/2026 — G5A demonstrado em QA: três IDs/seis tratamentos
**P081 → regime_dispatch_goods / regime_dispatch_transport**: bens expedidos para zona/depósito e transporte directamente conexo,14(1)(b). **P082 → regime_internal_goods / regime_internal_services**: transmissão de bens em regime e serviço directamente conexo,enquanto os bens permanecem nessa situação,14(1)(c). **P083 → regime_transit_goods / regime_transit_transport**: bens em trânsito,draubaque/importação temporária e transporte directamente conexo,enquanto abrangidos,14(1)(d). Direito19(1)(b)(iv); fontes14,p1426(271),19,p1426(273),e alterações2022/2025 conferidas. Não confundir seis tratamentos com seisIDs. Candidata`1f7fc138`,registo`iva_l1_g5a_special_regimes_QA_demonstrated_20261024`.
File diff suppressed because one or more lines are too long
@@ -1,8 +1,10 @@
import { useState } from 'react';
import { acquisitionBook, acquisitionCurrent, acquisitionExcludedFields, acquisitionPlanReferences, acquisitionReportRows, calculateAcquisitions, newAcquisition, reuseAcquisitions, saveAcquisitionBook, type Acquisition, type AcquisitionBook } from '@/lib/iva-acquisitions';
import { acquisitionBook, acquisitionCurrent, acquisitionExcludedFields, acquisitionPlanReferences, acquisitionReportRows, recordAcquisitions, newAcquisition, reuseAcquisitions, saveAcquisitionBook, type Acquisition, type AcquisitionBook } from '@/lib/iva-acquisitions';
import { acquisitionTreatmentIssue, continueWithoutFormerExploration, formerExplorationSource, type AcquisitionTreatment } from '@/lib/iva-acquisition-continuity';
export function SimulationAcquisitions({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}) {
const [error,setError]=useState('');
const [manualPeriod,setManualPeriod]=useState('');
let book:AcquisitionBook;
try {book=acquisitionBook(draft);} catch(cause) {return <p role="alert">{String(cause)}</p>;}
const save=(next:AcquisitionBook)=>{try {onChange('modelo_a_snapshot',saveAcquisitionBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
@@ -21,9 +23,20 @@ export function SimulationAcquisitions({draft,onChange}:{draft:Record<string,unk
<p>Primeiro âmbito: aquisições internas em MZN, afectação exclusiva a operações tributadas, sem exclusões ou dedução parcial, documento e dedução no mesmo período de 2026. Nas projecções, cada confirmação é um pressuposto, sem certificar documento ou declaração efectiva. Indique dois valores entre líquido, IVA e bruto; o terceiro é obtido por diferença ou soma, sem taxa de compra presumida.</p>
<label className="block">Adquirente sujeito passivo de IVA no regime normal (efectivo ou pressuposto da projecção)<select className="block rounded border p-2" value={book.taxpayerRegistered??''} onChange={e=>save({...book,taxpayerRegistered:e.target.value as AcquisitionBook['taxpayerRegistered']})}><option value="">Por confirmar</option><option value="yes">Sim</option><option value="no">Não / outro enquadramento — fora deste lote</option></select></label>
{error&&<p role="alert">{error}</p>}
<details className="rounded border p-2"><summary>Indicar mês da aquisição pelo documento ou pressuposto da projecção</summary>
<p>Para compras introduzidas directamente, indique o mês aplicável sem depender de ter vendas nesse mês. A reutilização de valores do orçamento mantém a conferência da origem.</p>
<label>Mês da aquisição<input type="month" min="2026-01" max="2026-12" value={manualPeriod} onChange={e=>setManualPeriod(e.target.value)}/></label>
<button type="button" onClick={()=>run(()=>{if(!/^2026-(0[1-9]|1[0-2])$/.test(manualPeriod))throw new Error('Indique um mês válido de2026.');if(book.periods.some(p=>p.period===manualPeriod))throw new Error('Esse mês já consta da cobertura; valores conservados.');save({...book,periods:[...book.periods,{period:manualPeriod,complete:false,absent:[]}]});})}>Acrescentar mês indicado</button>
</details>
<button type="button" className="underline" onClick={()=>run(()=>save(reuseAcquisitions(draft,book)))}>Reutilizar compras e períodos existentes</button>
<button type="button" className="ml-3 underline" disabled={!book.periods.length} onClick={()=>save({...book,rows:[...book.rows,newAcquisition(crypto.randomUUID(),book.periods[0]?.period??'',book.currency)]})}>Acrescentar aquisição em falta</button>
{book.rows.map(row=><details key={row.id} className="rounded border p-3"><summary>{row.description||'Aquisição adicional'} — {row.period} — campo{row.field}</summary>
<details className="rounded border p-2"><summary>Enquadramento especial da aquisição / referência anterior</summary>
<label>Tratamento da aquisição<select value={row.acquisitionTreatment??''} onChange={e=>row.acquisitionTreatment==='former_exploration_exemption'&&e.target.value!=='former_exploration_exemption'?run(()=>save({...book,rows:book.rows.map(item=>item.id===row.id?continueWithoutFormerExploration(item):item)})):change(row.id,{acquisitionTreatment:e.target.value as AcquisitionTreatment})}><option value="">Enquadramento normal; sem benefício especial indicado</option><option value="former_exploration_exemption">Antiga isenção de prospecção/pesquisa —14(2)(c),eliminada</option><option value="normal">Continuidade pelo enquadramento normal</option></select></label>
{acquisitionTreatmentIssue(row.acquisitionTreatment)&&<p role="status">{acquisitionTreatmentIssue(row.acquisitionTreatment)}</p>}
{row.acquisitionTreatment==='former_exploration_exemption'&&<><p>{formerExplorationSource}</p><p>A continuidade conserva montantes,moeda,mês,documento e respostas existentes. Não introduz taxa nem altera o IVA declarado; reveja as condições antes de calcular.</p><button type="button" onClick={()=>run(()=>save({...book,rows:book.rows.map(item=>item.id===row.id?continueWithoutFormerExploration(item):item)}))}>Continuar aquisição sem esta isenção e rever condições</button></>}
{row.acquisitionTreatmentOrigin&&<p>Origem conservada: antiga referência14(2)(c),eliminada. {row.acquisitionTreatment==='former_exploration_exemption'?'A continuidade normal foi escolhida numa versão anterior; a referência antiga está agora seleccionada para análise.':'Continuidade normal escolhida expressamente; não é nova concessão de isenção.'}</p>}
</details>
<p>Origem: {row.sourceMonth===null?'Introdução directa':`Plano, mês ${row.sourceMonth} (${row.sourcePeriod??'por indicar'}): ${row.sourceAmount??'sem informação'} ${row.sourceCurrency}`}. O mês da encomenda/orçamento não determina a data do documento ou a dedução. Alterações não substituem o resultado anterior.</p>
<div className="grid gap-3 md:grid-cols-2">
<label>Descrição<input className="block rounded border p-2" value={row.description} onChange={e=>change(row.id,{description:e.target.value})}/></label>
@@ -39,12 +52,14 @@ export function SimulationAcquisitions({draft,onChange}:{draft:Record<string,unk
<label>Data do documento / prevista<input className="block rounded border p-2" type="date" value={row.documentDate} onChange={e=>change(row.id,{documentDate:e.target.value})}/></label>
<label>Fornecedor / previsto<input className="block rounded border p-2" value={row.supplier} onChange={e=>change(row.id,{supplier:e.target.value})}/></label>
{select(row,'domestic','Aquisição interna',yesNo)}
{row.acquisitionTreatment!=='former_exploration_exemption'&&<>
{select(row,'supplierRegistered','Fornecedor inscrito no IVA',yesNo)}
{select(row,'legalDocument','Documento emitido em forma legal',yesNo)}
{select(row,'held','Documento na posse do adquirente / previsto na projecção',yesNo)}
{select(row,'allocation','Afectação',[['taxable_only','Exclusiva a operações tributadas'],['mixed','Mista / parcial — fora deste lote'],['no_right','Operações sem direito à dedução']])}
{select(row,'exclusion','Exclusões de dedução',[['none','Sem exclusões ou casos especiais dos arts.18–20'],['excluded','Despesa excluída'],['special','Veículos, combustível, viagens, alojamento, comunicações, luxo ou outra situação especial — por enquadrar']])}
{select(row,'integrity','Operação real / pressuposto regular, sem simulação, margem de segunda mão ou impedimentos do art.18(3–5)',yesNo)}
</>}
</div>
<p>Fundamento: CIVA arts.18–21, fontes e versão no resultado. Não se calcula dedução parcial, excepção de despesa ou dedução posterior neste lote.</p>
{row.sourceMonth===null && <button type="button" className="mr-3 underline" onClick={()=>save({...book,rows:book.rows.filter(r=>r.id!==row.id)})}>Remover esta aquisição introduzida directamente</button>}
@@ -55,7 +70,7 @@ export function SimulationAcquisitions({draft,onChange}:{draft:Record<string,unk
<p>Campos fora deste lote: assinale apenas quando não existiram as respectivas operações. Uma parcela não assinalada permanece indeterminada.</p>
{acquisitionExcludedFields.map(field=><label className="block" key={field}><input type="checkbox" checked={period.absent.includes(field)} onChange={e=>save({...book,periods:book.periods.map(p=>p.period===period.period?{...p,absent:e.target.checked?[...p.absent,field]:p.absent.filter(f=>f!==field)}:p)})}/> Sem operações no campo{field} — {labels[field]}</label>)}
</details>)}
<button type="button" disabled={!book.periods.length} className="rounded bg-emerald-800 p-2 text-white disabled:opacity-50" onClick={()=>run(()=>save({...book,result:calculateAcquisitions(draft,book)}))}>Calcular e guardar versão do apuramento parcial</button>
<button type="button" disabled={!book.periods.length} className="rounded bg-emerald-800 p-2 text-white disabled:opacity-50" onClick={()=>run(()=>save(recordAcquisitions(draft,book)))}>Calcular e guardar versão do apuramento parcial</button>
<p>O preenchimento e o resultado seguem a gravação privada do simulador. Os campos19–27 e a submissão à AT permanecem fora deste lote; 17/18 são diferenças antes de créditos anteriores, sem ordem de pagamento ou promessa de reembolso.</p>
{book.result&&<><p role="status">{acquisitionCurrent(draft,book)?'Resultado correspondente às entradas guardadas.':'Entradas ou origem alteradas: resultado histórico preservado; actualizar o cálculo.'}</p><dl>{acquisitionReportRows(draft).map(([,label,value,origin],i)=><div key={i}><dt className="font-semibold">{label}</dt><dd>{value}<small className="block">{origin}</small></dd></div>)}</dl></>}
</section>;
@@ -0,0 +1,14 @@
import type { Acquisition } from './iva-acquisitions.ts';
export type AcquisitionTreatment = '' | 'normal' | 'former_exploration_exemption';
export const acquisitionContinuityVersion='acquisition-continuity/1';
export const formerExplorationSource = 'Aviso da Assembleia da República,BR89/I Série,08/06/2017,PDF1/p.569:ordena eliminação de14(2)(c) e transcreve «c) eliminado». CIVA republicado Lei13/2016,PDF13/p.1426(271),continha aquisição de serviços de perfuração,pesquisa e construção de infra-estruturas na actividade mineira/petrolífera em fase de prospecção/pesquisa. Lei22/2022art.1 eLei10/2025art.1 não reintroduzem14(2)(c). Cobertura2026/MZN;sem cálculo retroactivo.';
export const formerExplorationNotice = 'A antiga isenção da aquisição de serviços de perfuração, pesquisa e infra-estruturas de prospecção mineira/petrolífera do artigo14(2)(c) foi eliminada pela rectificação publicada no BR89 de08/06/2017. Não se aplica nesta cobertura2026. Não indique IVA zero nem dedução por esta referência. Valores e documento conservados; escolha expressamente continuar a aquisição sem esta isenção e reveja o enquadramento normal. Outra eventual base legal deve ser identificada, não presumida.';
export function acquisitionTreatmentIssue(treatment:unknown):string|null {
if(treatment===undefined||treatment===''||treatment==='normal')return null;
return treatment==='former_exploration_exemption'?formerExplorationNotice:'Tratamento especial guardado desconhecido; dados conservados, sem isenção ou dedução presumidas. Identifique o enquadramento antes de continuar.';
}
export function continueWithoutFormerExploration(row:Acquisition):Acquisition {
if(row.acquisitionTreatment!=='former_exploration_exemption')throw new Error('A continuidade exige a antiga referência14(2)(c) seleccionada; aquisição conservada.');
return {...row,acquisitionTreatment:'normal',acquisitionTreatmentOrigin:{id:'former_exploration_exemption',source:formerExplorationSource}};
}
+17 -6
View File
@@ -2,6 +2,7 @@ import { modeloAPurchaseReferences } from './iva-modelo-a.ts';
import { monthlyIvaInput, monthlyIvaKey, readMonthlyIvaRecord, readMonthlyIvaSettings } from './monthly-iva.ts';
import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
import { salesBook, salesCurrent as salesOperationsCurrent } from './iva-operations.ts';
import { acquisitionTreatmentIssue, acquisitionContinuityVersion, formerExplorationSource, type AcquisitionTreatment } from './iva-acquisition-continuity.ts';
import { addFractions, decimalFraction, fractionLabel, fractionPresentation, positiveFraction, subtractFractions, type FiscalFraction } from './fiscal-rational.ts';
export const acquisitionVersion = 'modelo-a-internal-acquisitions/1';
@@ -15,10 +16,12 @@ export type Acquisition = {
supplier: string; supplierRegistered: Choice; legalDocument: Choice; held: Choice; domestic: Choice;
allocation: ''|'taxable_only'|'mixed'|'no_right'; exclusion: ''|'none'|'excluded'|'special';
integrity: Choice; description: string;
acquisitionTreatment?: AcquisitionTreatment;
acquisitionTreatmentOrigin?: {id:'former_exploration_exemption';source:string};
};
export type AcquisitionResult = {id:string; net:string|null; vat:string|null; gross:string|null; deductible:string|null; reason:string};
type PeriodInput = {period:string; complete:boolean; absent:string[]};
export type AcquisitionBook = {currency:string; taxpayerRegistered?:Choice; rows:Acquisition[]; periods:PeriodInput[]; result?:AcquisitionCalculation};
export type AcquisitionBook = {currency:string; taxpayerRegistered?:Choice; rows:Acquisition[]; periods:PeriodInput[]; result?:AcquisitionCalculation;history?:AcquisitionCalculation[]};
export type AcquisitionCalculation = {version:string; revision:number; calculatedAt:string; opportunity:string; location:string; currency:string; sourceKey:string; basis:string; sources:string;
declarations?:{taxpayerRegistered:Choice;periods:PeriodInput[]}; rows:AcquisitionResult[]; inputs:Acquisition[]; periods:Array<{period:string; fields:Record<string,string|null>; exactFields?:Record<string,FiscalFraction|null>; reasons:string[]}>};
type Store = {version:1; books:Record<string,AcquisitionBook>};
@@ -36,6 +39,7 @@ export function readAcquisitionStore(raw:unknown):Store {
const value=JSON.parse(String(raw));
if (value?.version!==1 || !value.books || typeof value.books!=='object' || Array.isArray(value.books)) throw new Error('Compras fiscais guardadas não recuperáveis; dados preservados.');
for(const book of Object.values(value.books) as AcquisitionBook[]) {
if(book?.history!==undefined&&!Array.isArray(book.history))throw new Error('Histórico de aquisições não recuperável; originais preservados, sem substituição.');
if(!book || !Array.isArray(book.rows) || !Array.isArray(book.periods) || typeof book.currency!=='string') throw new Error('Formato de compras não recuperável; sem substituição.');
const stringKeys=Object.keys(newAcquisition('','','')).filter(key=>!['sourceMonth','sourceAmount'].includes(key));
if(book.rows.some(row=>!row || stringKeys.some(key=>typeof row[key as keyof Acquisition]!=='string') || !(row.sourceMonth===null || Number.isInteger(row.sourceMonth)) || !(row.sourceAmount===null || typeof row.sourceAmount==='string')) || book.periods.some(p=>!p || typeof p.period!=='string' || typeof p.complete!=='boolean' || !Array.isArray(p.absent) || p.absent.some(f=>typeof f!=='string'))) throw new Error('Linhas ou períodos de compras não recuperáveis; os dados guardados foram preservados.');
@@ -91,6 +95,8 @@ export function evaluateAcquisition(row:Acquisition,currency:string,taxpayerRegi
const stop=(reason:string,deductible:string|null=null)=>({...result,reason,deductible});
if(currency!=='MZN' || row.sourceCurrency!==currency) return stop('Divergência ou moeda fora de MZN; sem conversão.');
if(!/^2026-(0[1-9]|1[0-2])$/.test(row.period)) return stop('Período fora do âmbito 2026 ou em falta.');
const treatmentIssue=acquisitionTreatmentIssue(row.acquisitionTreatment);
if(treatmentIssue)return stop(treatmentIssue);
if(n===null || v===null || g===null || n+v!==g) return stop('Indique dois valores válidos; líquido + IVA deve corresponder ao bruto.');
if(row.sourceMonth!==null && (!row.sourceBasis || amount(row.sourceAmount)!==(row.sourceBasis==='net'?n:g))) return stop('Classifique ou resolva a divergência do valor de origem; não foi reinterpretado.');
if(v===0n) return stop('IVA explicitamente indicado como zero; não existe imposto a deduzir nesta aquisição.','0.00');
@@ -107,7 +113,7 @@ function sourceKey(draft:Record<string,unknown>,book:AcquisitionBook):string {
// Change detection only, never an authorization or authenticity token.
let hash=14695981039346656037n;for(let i=0;i<raw.length;i++)hash=BigInt.asUintN(64,(hash^BigInt(raw.charCodeAt(i)))*1099511628211n);
const operations=(readAcquisitionStore(draft.modelo_a_snapshot) as Store & {salesOperations?:Record<string,unknown>}).salesOperations?.[acquisitionScope(draft)];
return `${raw.length}:${hash.toString(16)}${operations?`:${JSON.stringify(operations)}`:''}`;
return `${raw.length}:${hash.toString(16)}${operations?`:${JSON.stringify(operations)}`:''}${book.rows.some(r=>r.acquisitionTreatment||r.acquisitionTreatmentOrigin)?`:${acquisitionContinuityVersion}`:''}`;
}
function location(draft:Record<string,unknown>):string {
const labels=draft.selection_labels as Record<string,unknown>|undefined;
@@ -115,13 +121,13 @@ function location(draft:Record<string,unknown>):string {
}
export function acquisitionCurrent(draft:Record<string,unknown>,book:AcquisitionBook):boolean {return !!book.result && book.result.version===acquisitionVersion && book.result.opportunity===acquisitionScope(draft) && book.result.sourceKey===sourceKey(draft,book);}
export function calculateAcquisitions(draft:Record<string,unknown>,book:AcquisitionBook,now=new Date().toISOString()):AcquisitionCalculation {
const scope=acquisitionScope(draft),dates=periods(draft);
const scope=acquisitionScope(draft),dates=book.periods.map(p=>p.period);
if(book.currency!=='MZN' || draft.currency!==book.currency) throw new Error('Resolva a moeda de origem das compras; valores preservados sem conversão.');
if(!dates.length) throw new Error('Período de vendas por determinar.');
if(!dates.length||dates.some(period=>!/^2026-(0[1-9]|1[0-2])$/.test(period))||new Set(dates).size!==dates.length) throw new Error('Indique os meses aplicáveis às aquisições em2026,sem períodos duplicados; não inferidos do orçamento ou das vendas.');
if(new Set(book.rows.map(r=>r.id)).size!==book.rows.length) throw new Error('Existem compras com identidade repetida.');
const documents=book.rows.filter(r=>r.documentRef.trim() && r.supplier.trim()).map(r=>JSON.stringify([r.origin,r.supplier.trim().toLowerCase(),r.documentRef.trim().toLowerCase(),r.documentDate,r.documentLine?.trim()??'']));
if(new Set(documents).size!==documents.length) throw new Error('Documento/linha repetido: discrimine linhas distintas ou remova a duplicação antes de deduzir.');
if(book.rows.some(r=>!['08','09','10'].includes(r.field) || !dates.includes(r.period))) throw new Error('Classifique cada aquisição num campo08–10 e num período da projecção.');
if(book.rows.some(r=>!['08','09','10'].includes(r.field) || !dates.includes(r.period))) throw new Error('Classifique cada aquisição num campo08–10 e num mês incluído na cobertura declarada das aquisições.');
const references=acquisitionPlanReferences(draft);
for(const row of book.rows.filter(r=>r.sourceMonth!==null)) {
const current=references.find(p=>p.month===row.sourceMonth && p.kind===(row.sourceField??'inventory'));
@@ -179,7 +185,11 @@ export function calculateAcquisitions(draft:Record<string,unknown>,book:Acquisit
}
return {period,fields,reasons};
});
return {version:acquisitionVersion,revision:(book.result?.revision??0)+1,calculatedAt:now,opportunity:scope,location:location(draft),currency:book.currency,sourceKey:sourceKey(draft,book),basis:acquisitionBasis,sources:acquisitionSources,declarations:{taxpayerRegistered:book.taxpayerRegistered??'',periods:structuredClone(book.periods)},rows,inputs:structuredClone(book.rows),periods:calculated};
return {version:acquisitionVersion,revision:(book.result?.revision??0)+1,calculatedAt:now,opportunity:scope,location:location(draft),currency:book.currency,sourceKey:sourceKey(draft,book),basis:acquisitionBasis,sources:acquisitionSources+(book.rows.some(r=>r.acquisitionTreatment==='former_exploration_exemption'||r.acquisitionTreatmentOrigin)?`; ${formerExplorationSource}`:''),declarations:{taxpayerRegistered:book.taxpayerRegistered??'',periods:structuredClone(book.periods)},rows,inputs:structuredClone(book.rows),periods:calculated};
}
export function recordAcquisitions(draft:Record<string,unknown>,book:AcquisitionBook,now=new Date().toISOString()):AcquisitionBook {
const result=calculateAcquisitions(draft,book,now);
return {...book,...(book.result?{history:[...(book.history??[]),structuredClone(book.result)]}:{}),result};
}
export function acquisitionReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]> {
if(!draft.modelo_a_snapshot) return [];
@@ -193,6 +203,7 @@ export function acquisitionReportRows(draft:Record<string,unknown>):Array<[strin
const source=row.sourceMonth===null?'Introduzido pelo utilizador':`Plano (${row.sourceField==='asset'?'orçamento de activos':row.sourceField==='operating'?'orçamento operacional':'compras/encomendas'}), mês ${row.sourceMonth}, ${row.sourcePeriod??'período de origem não indicado'}, ${row.sourceAmount??'valor em falta'} ${row.sourceCurrency}; ${row.sourceBasis==='net'?'sem IVA':row.sourceBasis==='gross'?'com IVA':'base por classificar'}`;
const allocation={taxable_only:'exclusiva a operações tributadas',mixed:'mista',no_right:'sem direito à dedução','':'por indicar'}[row.allocation];
out.push(['IVA mensal',`Aquisição ${row.id} — campo${row.field} — ${row.period}`,`${row.description}; líquido ${r.net??'Indeterminado'}; IVA ${r.vat??'Indeterminado'}; bruto ${r.gross??'Indeterminado'}; dedutível ${r.deductible??'Indeterminado'}`,`${context}; ${row.origin==='projected'?'Projecção':'Dados efectivos declarados'}; ${source}; ${row.documentType==='invoice'?'Factura':row.documentType==='equivalent'?'Documento equivalente':'Documento por indicar'} ${row.documentRef}, ${row.documentDate}, linha ${row.documentLine||'única'}; fornecedor ${row.supplier}; afectação ${allocation}; ${r.reason}`]);
if(row.acquisitionTreatment==='former_exploration_exemption'||row.acquisitionTreatmentOrigin)out.push(['IVA mensal',`Continuidade14(2)(c) — ${row.id}`,row.acquisitionTreatment==='former_exploration_exemption'?'Antiga isenção eliminada; dedução indeterminada por esta referência':'Continuidade normal expressamente escolhida; montantes e documento conservados; condições de dedução da aquisição, sem aplicar antiga isenção',`${context}; ${formerExplorationSource}; origem conservada ${row.acquisitionTreatmentOrigin?.id??'former_exploration_exemption'}`]);
}
for(const period of result.periods) {
const entries=Object.entries(period.fields).sort(([a],[b])=>Number(a)-Number(b));
@@ -0,0 +1,53 @@
<?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 IvaAcquisitionContinuityDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_acquisition_continuity_recovers_with_document_history_and_previous_sales_books(): void
{
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('simulator_fiscal_delta_20261021_test', $target->name);
$this->assertSame(55441, (int) $target->port);
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$this->actingAs(User::factory()->create(['email_verified_at' => now()]));
$draft = json_decode(file_get_contents(base_path('outputs/iva-l1-g5b-acquisitions-20261024/calculated.json')), true, flags: JSON_THROW_ON_ERROR);
$id = $this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => [], 'economic_snapshot' => $draft], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
$recovered = $this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk()->json('data.economic_snapshot');
$this->assertSame($draft['modelo_a_snapshot'], $recovered['modelo_a_snapshot']);
$this->assertSame('opportunity:329', $recovered['context_opportunity']);
$this->assertSame('Manica', $recovered['selection_labels']['province_id']);
$this->assertArrayNotHasKey('monthly_iva_settings', $recovered);
$store = json_decode($recovered['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$book = $store['books']['opportunity:329'];
$this->assertCount(1, $book['rows']);
$this->assertSame('normal', $book['rows'][0]['acquisitionTreatment']);
$this->assertSame('former_exploration_exemption', $book['rows'][0]['acquisitionTreatmentOrigin']['id']);
$this->assertSame('100', $book['rows'][0]['net']);
$this->assertSame('16', $book['rows'][0]['vat']);
$this->assertSame('116', $book['rows'][0]['gross']);
$this->assertSame('SYNTHETIC QA G5B 001', $book['rows'][0]['documentRef']);
$this->assertSame('2026-12', $book['rows'][0]['period']);
$this->assertSame('MZN', $book['currency']);
$this->assertCount(1, $book['history']);
$this->assertNull($book['history'][0]['rows'][0]['deductible']);
$this->assertSame('former_exploration_exemption', $book['history'][0]['inputs'][0]['acquisitionTreatment']);
$this->assertSame('16.00', $book['result']['rows'][0]['deductible']);
$this->assertSame('16.00', $book['result']['periods'][0]['fields']['10']);
$this->assertNull($book['result']['periods'][0]['fields']['17']);
$this->assertNull($book['result']['periods'][0]['fields']['18']);
$this->assertStringContainsString('BR89', $book['result']['sources']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-g5a-inputs.json')), true, flags: JSON_THROW_ON_ERROR);
foreach (json_decode($frozen['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR)['salesOperations'] as $context => $original) {
$this->assertSame($original, $store['salesOperations'][$context]);
}
file_put_contents(base_path('outputs/iva-l1-g5b-acquisitions-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,41 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { acquisitionTreatmentIssue,continueWithoutFormerExploration,formerExplorationSource } from '../../resources/js/lib/iva-acquisition-continuity.ts';
import { newAcquisition,evaluateAcquisition,recordAcquisitions,acquisitionBook,acquisitionCurrent,saveAcquisitionBook,acquisitionReportRows } from '../../resources/js/lib/iva-acquisitions.ts';
import { salesCurrent } from '../../resources/js/lib/iva-operations.ts';
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
const frozen=JSON.parse(fs.readFileSync(new URL('./fixtures/iva-g5a-inputs.json',import.meta.url),'utf8'));
const row=()=>({...newAcquisition('g5b-0','2026-12','MZN'),field:'10',net:'100',vat:'16',gross:'116',documentType:'invoice',documentRef:'SYNTHETIC QA G5B 001',documentDate:'2026-12-10',supplier:'SYNTHETIC QA fornecedor',supplierRegistered:'yes',legalDocument:'yes',held:'yes',domestic:'yes',allocation:'taxable_only',exclusion:'none',integrity:'yes',description:'SYNTHETIC QA — serviço de pesquisa; antiga referência14(2)(c)',acquisitionTreatment:'former_exploration_exemption'});
function fixture(){
const draft={...structuredClone(frozen),context_opportunity:'opportunity:329',project_title:'SYNTHETIC QA — G5B / Continuidade da aquisição'};
const prior=recordAcquisitions(draft,{currency:'MZN',taxpayerRegistered:'yes',rows:[row()],periods:[{period:'2026-12',complete:true,absent:[]}]});draft.modelo_a_snapshot=saveAcquisitionBook(draft,prior);return{draft,prior};
}
test('2017 rectification prevents former14(2)(c) exemption in2026,including explicit zero;unknown is not a normal treatment',()=>{
assert.match(formerExplorationSource,/BR89/);assert.match(acquisitionTreatmentIssue('former_exploration_exemption'),/eliminada/);
for(const vat of ['16','0','']){const input={...row(),vat,gross:vat==='0'?'100':'116'},result=evaluateAcquisition(input,'MZN','yes');assert.equal(result.deductible,null);assert.match(result.reason,/Não se aplica nesta cobertura2026/);assert.equal(input.net,'100');}
assert.equal(evaluateAcquisition({...row(),acquisitionTreatment:'unknown'},'MZN','yes').deductible,null);
assert.match(evaluateAcquisition({...row(),period:'2016-12'},'MZN','yes').reason,/fora do âmbito/);
});
test('explicit continuation keeps values,document,answers and source;normal deduction requires existing conditions',()=>{
const input=row(),next=continueWithoutFormerExploration(input);for(const key of Object.keys(input).filter(k=>k!=='acquisitionTreatment'))assert.deepEqual(next[key],input[key],key);
assert.equal(input.acquisitionTreatment,'former_exploration_exemption');assert.equal(next.acquisitionTreatment,'normal');assert.equal(next.acquisitionTreatmentOrigin.id,'former_exploration_exemption');
assert.equal(evaluateAcquisition(next,'MZN','yes').deductible,'16.00');
for(const patch of [{held:''},{allocation:'mixed'},{legalDocument:''},{sourceCurrency:'USD'},{vat:'',gross:''},{domestic:'no'},{documentDate:'2026-11-10'}])assert.equal(evaluateAcquisition({...next,...patch},'MZN','yes').deductible,null);
assert.throws(()=>continueWithoutFormerExploration({...input,acquisitionTreatment:'normal'}),/antiga referência/);
});
test('manual purchase month does not require sales;previous classification remains in history and incomplete totals remain unknown',()=>{
const{draft,prior}=fixture();assert.equal(draft.monthly_iva_settings,undefined);assert.equal(prior.result.rows[0].deductible,null);assert.equal(prior.result.periods[0].fields['10'],null);
const next=recordAcquisitions(draft,{...prior,rows:[continueWithoutFormerExploration(prior.rows[0])]});assert.deepEqual(next.history,[prior.result]);assert.equal(next.result.rows[0].deductible,'16.00');assert.equal(next.result.periods[0].fields['10'],'16.00');
for(const f of ['01','02','11','14','15','16','17','18'])assert.equal(next.result.periods[0].fields[f],null,f);
assert.throws(()=>recordAcquisitions(draft,{...next,periods:[]}),/meses aplicáveis/);assert.throws(()=>recordAcquisitions(draft,{...next,periods:[...next.periods,...next.periods]}),/meses aplicáveis/);
assert.throws(()=>recordAcquisitions(draft,{...next,rows:[{...next.rows[0],sourceMonth:1,sourceAmount:'100',sourceBasis:'net'}]}),/orçamentos do plano mudaram/);
});
test('save/recovery/report retain rectification,continuation and history;all20 prior sales books stay identical/current',()=>{
const{draft,prior}=fixture();const book=recordAcquisitions(draft,{...prior,rows:[continueWithoutFormerExploration(prior.rows[0])]});draft.modelo_a_snapshot=saveAcquisitionBook(draft,book);assert.ok(acquisitionCurrent(draft,book));assert.deepEqual(acquisitionBook(JSON.parse(JSON.stringify(draft))),JSON.parse(JSON.stringify(book)));
const before=JSON.parse(frozen.modelo_a_snapshot),after=JSON.parse(draft.modelo_a_snapshot);assert.equal(Object.keys(before.salesOperations).length,20);assert.deepEqual(after.salesOperations,before.salesOperations);assert.deepEqual(Object.keys(after.books),['opportunity:329']);
for(const[context,original]of Object.entries(before.salesOperations))assert.ok(salesCurrent({...draft,context_opportunity:context},original));
const report=JSON.stringify(createProjectDossierReport(draft,{selectedSections:new Set(['finance']),version:'QA G5B'}));for(const token of ['opportunity:329','Manica','2026-12','16.00','BR89','Continuidade14(2)(c)','eliminado','expressamente escolhida'])assert.ok(report.includes(token),token);
assert.match(JSON.stringify(acquisitionReportRows(draft)),/antiga isenção/);
if(process.env.IVA_G5B_CALCULATED)fs.writeFileSync(process.env.IVA_G5B_CALCULATED,JSON.stringify(draft));
});