Compare commits

...
16 changed files with 1020 additions and 9 deletions
@@ -16856,5 +16856,309 @@
},
"base_VAT_separation": "Accepted QA reused:saleprice minuscommission/purchaseprice pluscommission,baseAmount independentfromvat/rate(alwaysnull),immutable references/inputs/version/history/report retained. Exact four installed runtime hashes and compiled ledger/component/report markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
},
"iva_l1_g7c_P094_homologation_20261024": {
"status": "installed_delta_verified_partial_L1",
"candidate": "287f2f8321038dc72ff8f0746526df0761a871d6",
"base_installed": "e62b7dfdc25f7c12425e89cea26f7ccf67b7d177",
"coverage_complete_branches": {
"AUD-SIM-L1-P094": [
"act_sale_amount",
"act_normal_value"
]
},
"branch_count_complete": 1,
"treatment_count": 2,
"runtime_delta": [
{
"path": "resources/js/lib/iva-act-sale-base.ts",
"sha256_LF": "ed555c826427a0964995144c59d4e801bfeebce5219a63a612f31bb977788d00"
},
{
"path": "resources/js/components/simulation-act-sale-base.tsx",
"sha256_LF": "384e17aa18ed5ed9a8c6c47773577e87f211c2bccb3acbe3943269a08de1485a"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "3b2a24fde6db625c350f7366ec789b5aa7e86aa08645409203b5e96d02dc1ff3"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "852ceaf59b95d92ff57d3b711dc2bc13eb4b547e7d9f1516eb543ece83247c09"
}
],
"counts_before": {
"delivered": 80,
"QA": 1,
"functional_pending": 51,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 81,
"QA": 0,
"functional_pending": 51,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 81,
"QA": 0,
"functional_pending": 51,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g7c-qa-20261024.json"
],
"authorization": "Tempo explicitly deploy287f2f83 through existingGit,preserve concurrentchanges and check installeddelta only;two treatments sameP094branch",
"scope": "2026/MZN,P094baseonly;normal value supplied with identified basis/scope,not appraised automatically. No incidence,rate,VAT,deduction/field11/ModeloAtotals or substitution of special auctioncommission15g. Unknown values remain indeterminate,explicit zero distinguished.",
"meaning": "Goods transferred as result of auction,judicial/administrative sale,conciliation or settlement;value at which auction/sale effected or,where applicable,normal value. Five act kinds are contexts,not five branches. No automatic lower value or normal-value fallback.",
"preservation": "80priorclosures and partialP084/P085 preserved;acceptedQA reused;freshbackup/realisolatedrestore beforeinstallation;installeddelta only",
"partial_P084_P085": "Preparation/conditional simulation only,benefits pending;no closure",
"limits": "P084/P085partial,pending;P00105/06;L1open;beveragesL2/L3;Statistics/AIdeferred",
"containment": "l1-g7c-readonly-rollback-20261024.patch,checked only,not applied;blocks newP094calculations only,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "e62b7dfdc25f7c12425e89cea26f7ccf67b7d177",
"release": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"previous_release": "/var/www/investmoz-homologacao/releases/4193056bdd69b48cf61c25a9a7404af4f0957f3c-c2452b39",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"release_revision": {
"commit": "e62b7dfdc25f7c12425e89cea26f7ccf67b7d177",
"branch": "main",
"built_at": "2026-10-24T20:15:27.726611+00:00",
"manifest_sha256": "dccf1e8a2fabf42a877cac166b5821548af5a6e6cfbf2c8578afebb70468c531"
},
"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"
},
"backup_restore": {
"backup": {
"stage": "/var/backups/investmoz-l1-g7c-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "15851ca2ed235382c8acb325b154470e191d95c10d5c2dac8fa9be287132d024",
"files_sha256": "af9076b5993550acd8aa55ac85a1112822f6db26f744247cfcc76d6f03ee7925",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g7c_restore_20261024",
"port": 55441,
"source_dump_sha256": "15851ca2ed235382c8acb325b154470e191d95c10d5c2dac8fa9be287132d024",
"active_database_writes": 0
}
},
"served_commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"previous_release": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"database_migrations": 0,
"content_imports": 0
},
"runtime_files_verified": 4,
"persistent_files_and_env_verified": 369,
"tables_compared": 174,
"changed_tables": {
"cache": {
"before": {
"rows": 105,
"checksum": "4d4e4736806e5d22cd9d595e33c7007b"
},
"after": {
"rows": 105,
"checksum": "d651a6b29d74efd7336b21519b0dfbfa"
}
},
"sessions": {
"before": {
"rows": 59,
"checksum": "05c7fab88f6e1b760d58c9133e156fc0"
},
"after": {
"rows": 60,
"checksum": "f67f94f21e3abaee1b40b2b2fde2f303"
}
}
},
"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": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"branch": "main",
"built_at": "2026-10-24T20:28:33.858560+00:00",
"manifest_sha256": "01f5a06e9be1e2a758de06c51a1c145ab96d83c838b899806f442eec70158e72"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"act-goods-base/1": [
"assets/project-dossier-DYUXbyuH.js"
],
"act_sale_amount": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"act_normal_value": [
"assets/project-dossier-DYUXbyuH.js"
],
"actSaleBases": [
"assets/project-dossier-DYUXbyuH.js"
],
"taxableDomesticGoods": [
"assets/project-dossier-DYUXbyuH.js"
],
"goodsByAct": [
"assets/project-dossier-DYUXbyuH.js"
],
"valuationApplies": [
"assets/project-dossier-DYUXbyuH.js"
],
"notAuctionCommissionRegime": [
"assets/project-dossier-DYUXbyuH.js"
],
"actValue": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"normalValue": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"actRef": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"valuationRef": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"valuationScope": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-DYUXbyuH.js"
]
},
"assets": [
{
"file": "assets/project-dossier-document-B8tRTV0Q.js",
"status": 200,
"sha256": "526b505a0ad7aea611751cadec6efaf47686d9936755698ef6842e62a243fa6e"
},
{
"file": "assets/services-BaH3LfAj.js",
"status": 200,
"sha256": "bb614c00b830d9a4d9b5db82976f341617a23810577ab8f32fe1b674f3ca8dba"
},
{
"file": "assets/project-dossier-DYUXbyuH.js",
"status": 200,
"sha256": "2f41f74e6dc395fd85b2e56d60e6325691478ad89dab9c2f4de4c503da0c7700"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-ClRJoV6g.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": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"previous_release": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"previous_release": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"df7cb7fa47f50ae23f52c1bdf7e48e38489cffef"
],
"finished_at": "2026-10-24T20:28:36.398859+00:00"
},
"log_file": "1792873616425230362.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.93s",
"OK (59 tests, 317 assertions)",
"# tests 354",
"# pass 354",
"# fail 0"
],
"log_bytes": 132224
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted QA reused:act-sale amount or normal value where applicable,identified act/valuation basis/scope/composition retained with immutable inputs/history/report;no automatic minimum/fallback. Base independent of VAT/rate(alwaysnull). Four installed runtime hashes and14compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
}
@@ -1,6 +1,6 @@
{
"implementation_commit": "4672789f2bf1fcce0726936e9e5bec05fb18c448",
"status": "QA_complete_not_delivered",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P094": [
"act_sale_amount",
@@ -145,5 +145,18 @@
"homologation_unchanged": "e62b7dfd",
"remaining": "Integrate/deliver through existingGit withmanifest,freshbackup/real isolatedrestore and installeddelta;no push in QA task",
"limits": "P084/P085partial,pending;P00105/06;L1open;beveragesL2/L3;Statistics/AIdeferred",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7c-act-bases-20261024\\source-archive-inventory.json"
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7c-act-bases-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"receipt": "l1-g7c-delivery-20261024.json",
"record": "iva_l1_g7c_P094_homologation_20261024",
"counts": {
"delivered": 81,
"QA": 0,
"functional_pending": 51,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,154 @@
{
"implementation_commit": "3bcd98e78ee42c3034cee452b8570a72cd89020e",
"status": "QA_complete_not_delivered",
"coverage": {
"AUD-SIM-L1-P095": [
"fuel_tax_included",
"fuel_tax_excluded"
]
},
"branch_count": 1,
"treatment_count": 2,
"source": "CIVA15(2)(i),Lei13/2016PDF13/p1426(271);15(1)/(5)/(6),PDF13–14/p1426(271–272);Lei22/2022PDF3maintains15i/1/5/6 by remissão;Lei10/2025doesnotamend15;2017rectificationdoesnotamend15i.",
"meaning": "Transmissions of fuel with price fixed by public authority,effected by resellers;consideration under15(1)/(5) excludes FuelTax(TC). Two input-composition treatments in one branch,not two legal benefits.",
"formula": {
"fuel_tax_included": "consideration net of own VAT but including TC minus exact TC amount",
"fuel_tax_excluded": "consideration already net of own VAT and TC,unchanged;no second subtraction"
},
"technical_choices": "New regulatedFuelBases opportunity-scoped book in existingmodelo_a_snapshot/API/dossier;no schema/permissions change. Exactdecimal up to6fractiondigits,no assumed fiscalrounding. Explicit reference/scope/interval of price with operation date/month checked;end optional if no fixedterm and temporal correspondence confirmed,not invented mandatory expiry. Source/projection assumptions reused;no certification/approver. Treatment change retains amounts/documents but clears composition confirmation as integrity choice.",
"scope": "2026/MZN,P095baseonly;no automatic price,TC rate/amount,IVA/incidence/rate/deduction/field11/ModeloAtotals. Not general fuel purchases/services or unregulated price. Unknown TC/price parameters indeterminate;zero only explicit. TC exceeding consideration remains indeterminate,not negative/flooredzero.",
"verification": {
"frontend": {
"tests": 4,
"passed": 4,
"failed": 0,
"scope": "Ownconditions missing/no;price/reference/scope/date interval including openend/boundaries;exactdecimal subtractonce/zero/excess;switch retention/clearedconfirmation;corruptwriteguard;oldbooks/currentkeys/history/report"
},
"privateAPI": {
"tests": 1,
"assertions": 30,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7d-fuel-base-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Realcomponent Edge/CUA:TCunknown and operation afterpriceinterval indeterminate;composition switch hidesTC/clearsconfirmation,retains100.10;alreadyexcluded preserves1500.25;pricefixed no yields notapplicable/noIVAzero;finalincluded1400.15/excluded1500.25,VATnull. Save/recover/report2rows+6priorversions. SyntheticQA,not manualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7d-fuel-base-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "960088016944bbdd24e7479a7c08499809cb42fe",
"delivered_ids": [
"AUD-SIM-L1-P003",
"AUD-SIM-L1-P004",
"AUD-SIM-L1-P005",
"AUD-SIM-L1-P006",
"AUD-SIM-L1-P007",
"AUD-SIM-L1-P008",
"AUD-SIM-L1-P009",
"AUD-SIM-L1-P010",
"AUD-SIM-L1-P011",
"AUD-SIM-L1-P012",
"AUD-SIM-L1-P013",
"AUD-SIM-L1-P014",
"AUD-SIM-L1-P015",
"AUD-SIM-L1-P016",
"AUD-SIM-L1-P017",
"AUD-SIM-L1-P018",
"AUD-SIM-L1-P019",
"AUD-SIM-L1-P020",
"AUD-SIM-L1-P021",
"AUD-SIM-L1-P022",
"AUD-SIM-L1-P023",
"AUD-SIM-L1-P024",
"AUD-SIM-L1-P025",
"AUD-SIM-L1-P026",
"AUD-SIM-L1-P027",
"AUD-SIM-L1-P028",
"AUD-SIM-L1-P029",
"AUD-SIM-L1-P030",
"AUD-SIM-L1-P031",
"AUD-SIM-L1-P032",
"AUD-SIM-L1-P033",
"AUD-SIM-L1-P034",
"AUD-SIM-L1-P035",
"AUD-SIM-L1-P036",
"AUD-SIM-L1-P037",
"AUD-SIM-L1-P038",
"AUD-SIM-L1-P039",
"AUD-SIM-L1-P040",
"AUD-SIM-L1-P041",
"AUD-SIM-L1-P042",
"AUD-SIM-L1-P043",
"AUD-SIM-L1-P044",
"AUD-SIM-L1-P045",
"AUD-SIM-L1-P048",
"AUD-SIM-L1-P049",
"AUD-SIM-L1-P050",
"AUD-SIM-L1-P051",
"AUD-SIM-L1-P052",
"AUD-SIM-L1-P053",
"AUD-SIM-L1-P054",
"AUD-SIM-L1-P055",
"AUD-SIM-L1-P056",
"AUD-SIM-L1-P057",
"AUD-SIM-L1-P060",
"AUD-SIM-L1-P061",
"AUD-SIM-L1-P062",
"AUD-SIM-L1-P063",
"AUD-SIM-L1-P064",
"AUD-SIM-L1-P065",
"AUD-SIM-L1-P066",
"AUD-SIM-L1-P067",
"AUD-SIM-L1-P068",
"AUD-SIM-L1-P069",
"AUD-SIM-L1-P070",
"AUD-SIM-L1-P071",
"AUD-SIM-L1-P072",
"AUD-SIM-L1-P073",
"AUD-SIM-L1-P074",
"AUD-SIM-L1-P075",
"AUD-SIM-L1-P076",
"AUD-SIM-L1-P077",
"AUD-SIM-L1-P078",
"AUD-SIM-L1-P079",
"AUD-SIM-L1-P080",
"AUD-SIM-L1-P081",
"AUD-SIM-L1-P082",
"AUD-SIM-L1-P083",
"AUD-SIM-L1-P086",
"AUD-SIM-L1-P090",
"AUD-SIM-L1-P091",
"AUD-SIM-L1-P094"
],
"confirmed_losses": [],
"accepted_delivery": "df7cb7fa/96008801;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared at delivery",
"frozen": "tests\\frontend\\fixtures\\iva-g7d-preserved-inputs.json",
"sha256": "eafc5db6d2b8c0c50f29564eefd2af15fcc77b93d030adae2feb2e75e7a86894",
"counts_before": {
"delivered": 81,
"QA": 0,
"functional_pending": 51,
"P001": 1,
"total": 133
},
"scope": "P095 only;all previousbooks immutable including P094/91/90/P060/P050 and partialP084P085;no active query/write"
},
"runtime_delta": {
"resources/js/lib/iva-fuel-base.ts": "3e00b285b2bfd4e0cdd7106be5f8ebd86dbc17b4dd83e36ccba844b6d6a7a9d2",
"resources/js/components/simulation-fuel-base.tsx": "d55f8ede39ed42114c9eed473684cf1a764420e63cdb0faf2af4906773b8cfd9",
"resources/js/components/simulation-monthly-iva.tsx": "11988f00f562c8d86db442cd7996a6640e8916feea11230f6105521985d83720",
"resources/js/lib/project-dossier.ts": "85ca23ac160e7e06c0e605bfc0dc1a4ed2678df94136eaaa21ccfcba883a7e7c"
},
"counts_current": {
"delivered": 81,
"QA": 1,
"functional_pending": 50,
"P001": 1,
"total": 133
},
"homologation_unchanged": "df7cb7fa",
"remaining": "Integrate/deliver through existingGit withmanifest,freshbackup/real isolatedrestore and installeddelta;no push in QA task",
"limits": "P084/P085partial,pending;P00105/06;L1open;beveragesL2/L3;Statistics/AIdeferred",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7d-fuel-base-20261024\\source-archive-inventory.json"
}
@@ -1,5 +1,5 @@
{
"status": "ready_after_fresh_authenticated_preflight_and_verified_backup_restore",
"status": "installed_delta_verified_partial_L1",
"candidate": "287f2f8321038dc72ff8f0746526df0761a871d6",
"base_installed": "e62b7dfdc25f7c12425e89cea26f7ccf67b7d177",
"coverage_complete_branches": {
@@ -36,8 +36,8 @@
"total": 133
},
"counts_current": {
"delivered": 80,
"QA": 1,
"delivered": 81,
"QA": 0,
"functional_pending": 51,
"documentary": 1,
"total": 133
@@ -123,5 +123,182 @@
"source_dump_sha256": "15851ca2ed235382c8acb325b154470e191d95c10d5c2dac8fa9be287132d024",
"active_database_writes": 0
}
}
},
"served_commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"previous_release": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"database_migrations": 0,
"content_imports": 0
},
"runtime_files_verified": 4,
"persistent_files_and_env_verified": 369,
"tables_compared": 174,
"changed_tables": {
"cache": {
"before": {
"rows": 105,
"checksum": "4d4e4736806e5d22cd9d595e33c7007b"
},
"after": {
"rows": 105,
"checksum": "d651a6b29d74efd7336b21519b0dfbfa"
}
},
"sessions": {
"before": {
"rows": 59,
"checksum": "05c7fab88f6e1b760d58c9133e156fc0"
},
"after": {
"rows": 60,
"checksum": "f67f94f21e3abaee1b40b2b2fde2f303"
}
}
},
"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": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"branch": "main",
"built_at": "2026-10-24T20:28:33.858560+00:00",
"manifest_sha256": "01f5a06e9be1e2a758de06c51a1c145ab96d83c838b899806f442eec70158e72"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"act-goods-base/1": [
"assets/project-dossier-DYUXbyuH.js"
],
"act_sale_amount": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"act_normal_value": [
"assets/project-dossier-DYUXbyuH.js"
],
"actSaleBases": [
"assets/project-dossier-DYUXbyuH.js"
],
"taxableDomesticGoods": [
"assets/project-dossier-DYUXbyuH.js"
],
"goodsByAct": [
"assets/project-dossier-DYUXbyuH.js"
],
"valuationApplies": [
"assets/project-dossier-DYUXbyuH.js"
],
"notAuctionCommissionRegime": [
"assets/project-dossier-DYUXbyuH.js"
],
"actValue": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"normalValue": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"actRef": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"valuationRef": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"valuationScope": [
"assets/services-BaH3LfAj.js",
"assets/project-dossier-DYUXbyuH.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-DYUXbyuH.js"
]
},
"assets": [
{
"file": "assets/project-dossier-document-B8tRTV0Q.js",
"status": 200,
"sha256": "526b505a0ad7aea611751cadec6efaf47686d9936755698ef6842e62a243fa6e"
},
{
"file": "assets/services-BaH3LfAj.js",
"status": 200,
"sha256": "bb614c00b830d9a4d9b5db82976f341617a23810577ab8f32fe1b674f3ca8dba"
},
{
"file": "assets/project-dossier-DYUXbyuH.js",
"status": 200,
"sha256": "2f41f74e6dc395fd85b2e56d60e6325691478ad89dab9c2f4de4c503da0c7700"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-ClRJoV6g.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": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"previous_release": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"previous_release": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"df7cb7fa47f50ae23f52c1bdf7e48e38489cffef"
],
"finished_at": "2026-10-24T20:28:36.398859+00:00"
},
"log_file": "1792873616425230362.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.93s",
"OK (59 tests, 317 assertions)",
"# tests 354",
"# pass 354",
"# fail 0"
],
"log_bytes": 132224
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted QA reused:act-sale amount or normal value where applicable,identified act/valuation basis/scope/composition retained with immutable inputs/history/report;no automatic minimum/fallback. Base independent of VAT/rate(alwaysnull). Four installed runtime hashes and14compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,131 @@
{
"status": "ready_after_fresh_authenticated_preflight_and_verified_backup_restore",
"candidate": "76be72c38c459c09345b57a4d27ccc01edc7052b",
"base_installed": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"coverage_complete_branches": {
"AUD-SIM-L1-P095": [
"fuel_tax_included",
"fuel_tax_excluded"
]
},
"branch_count_complete": 1,
"treatment_count": 2,
"runtime_delta": [
{
"path": "resources/js/lib/iva-fuel-base.ts",
"sha256_LF": "3e00b285b2bfd4e0cdd7106be5f8ebd86dbc17b4dd83e36ccba844b6d6a7a9d2"
},
{
"path": "resources/js/components/simulation-fuel-base.tsx",
"sha256_LF": "d55f8ede39ed42114c9eed473684cf1a764420e63cdb0faf2af4906773b8cfd9"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "11988f00f562c8d86db442cd7996a6640e8916feea11230f6105521985d83720"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "85ca23ac160e7e06c0e605bfc0dc1a4ed2678df94136eaaa21ccfcba883a7e7c"
}
],
"counts_before": {
"delivered": 81,
"QA": 1,
"functional_pending": 50,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 81,
"QA": 1,
"functional_pending": 50,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 82,
"QA": 0,
"functional_pending": 50,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g7d-qa-20261024.json"
],
"authorization": "Tempo explicitly deploy76be72c3 through existingGit,preserve concurrentchanges and check installeddelta only;two input-composition treatments sameP095branch;no double TC subtraction",
"scope": "2026/MZN,P095baseonly;no automatic price,TC rate/amount,IVA/incidence/rate/deduction/field11/ModeloAtotals. Not general fuel purchases/services or unregulated price. Unknown TC/price parameters indeterminate;zero only explicit. TC exceeding consideration remains indeterminate,not negative/flooredzero.",
"meaning": "Transmissions of fuel with price fixed by public authority,effected by resellers;consideration under15(1)/(5) excludes FuelTax(TC). Two input-composition treatments in one branch,not two legal benefits.",
"formula": {
"fuel_tax_included": "consideration net of own VAT but including TC minus exact TC amount",
"fuel_tax_excluded": "consideration already net of own VAT and TC,unchanged;no second subtraction"
},
"preservation": "81priorclosures and partialP084/P085 preserved;acceptedQA reused;freshbackup/realisolatedrestore beforeinstallation;installeddelta only",
"partial_P084_P085": "Preparation/conditional simulation only,benefits pending;no closure",
"limits": "P084/P085partial,pending;P00105/06;L1open;beveragesL2/L3;Statistics/AIdeferred",
"containment": "l1-g7d-readonly-rollback-20261024.patch,checked only,not applied;blocks newP095calculations only,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"previous_release": "/var/www/investmoz-homologacao/releases/e62b7dfdc25f7c12425e89cea26f7ccf67b7d177-c1e20222",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"release_revision": {
"commit": "df7cb7fa47f50ae23f52c1bdf7e48e38489cffef",
"branch": "main",
"built_at": "2026-10-24T20:28:33.858560+00:00",
"manifest_sha256": "01f5a06e9be1e2a758de06c51a1c145ab96d83c838b899806f442eec70158e72"
},
"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"
},
"backup_restore": {
"backup": {
"stage": "/var/backups/investmoz-l1-g7d-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "ad8be21f2b91f0a61c14b3a1df82952710937b44d70bbc45c9add3a8ab215789",
"files_sha256": "63fbe8b63f34ce373eee096d1eba9d5461162c55a2d01bb351e3e68eb3034cae",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g7d_restore_20261024",
"port": 55441,
"source_dump_sha256": "ad8be21f2b91f0a61c14b3a1df82952710937b44d70bbc45c9add3a8ab215789",
"active_database_writes": 0
}
}
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-fuel-base.ts
+++ b/resources/js/lib/iva-fuel-base.ts
@@ -51,6 +51,7 @@
function key(draft:Record<string,unknown>,book:FuelBaseBook):string{return JSON.stringify({version:fuelBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function fuelBaseCurrent(draft:Record<string,unknown>,book:FuelBaseBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordFuelBases(draft:Record<string,unknown>,book:FuelBaseBook):FuelBaseBook{
+ throw new Error('Novas bases P095 temporariamente suspensas; dados, histórico, relatórios e restantes ramos preservados.');
if(!book.rows.length||new Set(book.rows.map(row=>row.id)).size!==book.rows.length)throw new Error('Indique operações com identificadores distintos;originais conservados.');
const result:FuelBaseCalculation={version:fuelBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:fuelBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateFuelBase(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveFuelBaseBook(draft,next);return next;
@@ -1,6 +1,36 @@
# Rastreabilidade, utilização e formação
## 24/10/2026 — G7D/P095 concluído emQA:combustíveis com preço fixado
Implementação`3bcd98e7`. **Um ramo,dois tratamentos de composição**:`fuel_tax_included`(contraprestação semIVA ainda incluiTC→subtrairTCexacta identificada) e`fuel_tax_excluded`(já semTC→conservar,sem segunda subtracção). FonteCIVA15(2)(i),Lei13/2016PDF13/p1426(271),15(1)/(5)/(6),PDF13–14;Lei22/2022PDF3mantémi por remissão;Lei10/2025não altera15. Transmissões por revendedores de combustíveis com preço fixado pela Autoridade Pública,com referência/âmbito/intervalo correspondentes ao combustível,operação,local e data. Na projecção,pressupostos expressos;não presumir preço actual para outro período. Fim do intervalo pode ficar vazio se sem termo fixado,com correspondência temporal confirmada;sem prazo de expiração inventado.
Montantes sem próprioIVA,composição15(1)/(5)/(6)identificada;TC desconhecida não é zero,TC superior ao montante não cria base negativa ou pisozero. Decimal exacto até6casas,sem arredondamento fiscal presumido. Não determina automaticamente preço regulado,taxa/valorTC,incidência/taxa/IVA,dedução/campo11/totaisModeloA. LivroregulatedFuelBases por oportunidade no snapshot/API/dossier existentes,sem schema/permissões novos. Mudar composição conserva montantes/documentos,ocultaTCsem a apagar e limpa confirmação correspondente;escolha técnica de integridade,não regra organizacional. Referências e dados anteriores reutilizáveis,sem novos certificados/aprovadores/revalidação oficial.
Provas do delta:**4testes frontend**,**APIprivada1teste/30asserções**,guarda`simulator_fiscal_delta_20261021_test:55441` e rollback;tipos/build passaram. Interface real Edge/CUA:TC desconhecida e operação fora intervalo do preço→indeterminado;troca composição ocultaTC/limpa confirmação,retém100.10;montante já semTC conserva1500.25;preço não fixado→não aplicação,não isenção/IVAzero. Gravação recuperada/relatório:incluída1500.25−100.10=1400.15;excluída1500.25;IVAindeterminado,2linhas/6versões anteriores. Dados sintéticos,não aceitação manual atribuída à Tempo.81fechos/livros/resultados/históricos intactos,incluindoP094/P091/P090,P060/P056/P050 eP084/P085parciais;provas anteriores reutilizadas. [RegistoQA](../simulations/iva-l1-g7d-qa-20261024.json).
**81entregues +1emQA(P095) +50funcionaispendentes +P001 =133**. Homologação permanece`df7cb7fa`;falta integração/entrega pelo processoGit,manifesto/backup/restauro e delta instalado. P084/P085 continuam nos50,apenas preparação/simulação condicionada,sem benefícios confirmados. L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.
## 24/10/2026 — preparação G7D/P095,inventário antes de testes
G7C/P094 aceitedf7cb7fa/96008801;**81entregues+51funcionaispendentes+P001=133**. Inventariados81fechos,sem perdas confirmadas;provas instaladas código/schema/dados/configuração/permissões174tabelas/369ficheiros/29fichas/28relações/408geometrias reutilizadas. Congelados livros/resultados/históricos,incluindoP094(acto/valorização/âmbito),P091/P090(baseIVA),P060/P056(âmbito),P050(IVAserviço),P084/P085parciais. Sem repetir aceitação anterior ou ensaiar no activo.
G7D/P095 executa CIVA15(2)(i),2016PDF13/p1426(271):combustíveis com preço fixado pela Autoridade Pública,transmitidos por revendedores;contraprestação15(1)/(5)não inclui Taxa sobre Combustíveis.15(5)/(6),PDF14/p1426(272),composição/exclusões,sem próprioIVA;2022PDF3mantémi por remissão;2025não altera15,2017não rectifica15i. Fontes oficiais/exemplares/inventário aceites,cotejo visual com skillPDF. Dois tratamentos de entrada no mesmo ramo:montante semIVA ainda incluiTC(subtrairTCexacta identificada) oumontante já excluiTC(conservar,sem segunda subtracção). Não presumir preço regulado,valorTC,taxaIVA,dedução/campo11/totaisModeloA ou regra de determinação do preço. Referência/âmbito do preço,período e composição associados ao resultado,sem novo certificado/aprovador. Confirmar correspondência após mudança do tratamento,preservando os valores anteriores;escolha técnica de integridade. L1aberto;P00105/06;bebidasL2/L3;P084/P085parciais;Estatísticas/IAadiadas.
## 24/10/2026 — G7C/P094 entregue:valor da arrematação/venda ou normal aplicável
Homologação **`df7cb7fa`**,pelo processoGit existente,sobre`e62b7dfd`;candidata`287f2f83` expressamente aceite pela Tempo. **P094:um ramo,dois tratamentos**,`act_sale_amount` e`act_normal_value`. Acto,bens,fundamento/âmbito da valorização,composição semIVA e referências documentais/pressupostos conservados nas entradas imutáveis,versões/histórico/relatório. Cinco naturezas do acto são contextos,não cinco fechos. Não escolhe o menor valor nem usa valor normal como fallback de montante em falta;sem avaliação automática dos bens. Base separada de incidência/taxa/IVA(IVA/taxa permanecemnull),dedução/campo11/totaisModeloA;leilão especial15g não substituído. Livros anteriores não alterados nem base somada como imposto.
Destino e main conferidos novamente;sem avanço concorrente encontrado. SessãoSSH autenticada existente reutilizada,sem guardar credenciais. Backup novo e restauro real isolado sem rede:**174tabelas e369ficheiros/configuração**. ProvasQA aceites reutilizadas;conferido apenas delta instalado:revisão servida,manifesto/hash,14marcadores compilados do livro/componente/relatório,acto/valorização/âmbito,quatro ficheiros funcionais e simuladorHTTP200. Comparação PostgreSQL pela mesma identidade antes/depois:174tabelas/369ficheiros,29fichas publicadas/28relações/408geometrias preservados;diferenças apenas cache/sessões. Zero migrações/importações/alterações de permissões e zero ensaios sintéticos no activo. Release/backup anteriores preservados;contençãoP094 conferida,não aplicada,leitores/históricos e restantes ramos preservados.
[Manifesto/recibo](../simulations/l1-g7c-delivery-20261024.json),registo`iva_l1_g7c_P094_homologation_20261024`. **81entregues +51funcionaispendentes +P001 =133;sem candidatasQA por disponibilizar.** Os80fechos anteriores permanecem encerrados. P084/P085 continuam nos51,apenas preparação/simulação condicionada,sem benefícios confirmados;rascunhos,decisões,âmbitos e históricos preservados. L1aberto;P001 só05/06;bebidasL2/L3;Estatísticas/IAadiadas. FecharL1 não exige concluirL2/L3 nem todos os impostos.
## 24/10/2026 — G7C/P094 concluído emQA:transmissões por acto
Implementação`4672789f`. **Um ramo,dois tratamentos**:`act_sale_amount`(valor da arrematação/venda efectuada) e`act_normal_value`(valor normal quando aplicável). FonteCIVA15(2)(h),Lei13/2016PDF13/p1426(271),15(4)/(5)/(6)PDF14/p1426(272);Lei22/2022PDF3mantém15h/4–6 por remissão;Lei10/2025não altera15. Arrematação,venda judicial,venda administrativa,conciliação e contrato de transacção são cinco naturezas do acto dentro do ramo,não cinco fechos. Identificar a transmissão dos bens,acto,fundamento e âmbito da valorização,composição semIVA e documentos ou pressupostos expressos;um pagamento/acordo genérico não prova transmissão sujeita.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,29 @@
import {useState} from 'react';
import {newFuelBase,switchFuelTaxTreatment,fuelBaseBook,fuelBaseConditions,fuelBaseCurrent,fuelBaseReportRows,fuelBaseSource,fuelBaseTreatments,recordFuelBases,saveFuelBaseBook,type FuelBaseBook,type FuelBaseRow} from '@/lib/iva-fuel-base';
export function SimulationFuelBase({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:FuelBaseBook;
try{book=fuelBaseBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:FuelBaseBook)=>{try{onChange('modelo_a_snapshot',saveFuelBaseBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<FuelBaseRow>)=>save({...book,rows:book.rows.map(row=>row.id===id?{...row,...patch}:row)});
return<details className="space-y-3 rounded border p-3">
<summary>Base tributável — combustíveis com preço fixado</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Prepare transmissões por revendedores de combustíveis cujo preço é fixado pela Autoridade Pública. Identifique a referência e o âmbito temporal do preço aplicável;na projecção,pode declarar pressupostos expressos. Não se presume um preço actual para outro período.</p>
<p>A base exclui a Taxa sobre Combustíveis (TC). Se o montante já a exclui,não se subtrai novamente. Indique valores sem o próprio IVA e com a composição aplicável identificada. Base e IVA são resultados distintos.</p>
<p>{fuelBaseSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newFuelBase(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar transmissão de combustível</button>
{book.rows.map(row=>{const rule=fuelBaseTreatments.find(item=>item.id===row.treatment);return<details key={row.id} className="rounded border p-3"><summary>{row.description||'Transmissão por identificar'} — {row.period||'mês por indicar'}</summary>
<div className="grid gap-3 md:grid-cols-2">
<label>Composição quanto à TC<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchFuelTaxTreatment(row,e.target.value))}><option value="">Por indicar</option>{fuelBaseTreatments.map(item=><option key={item.id} value={item.id}>{item.label}</option>)}</select></label>
<label>Natureza dos dados<select className="block rounded border p-2" value={row.origin} onChange={e=>change(row.id,{origin:e.target.value as FuelBaseRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Combustível e transmissão identificados'],['operationDate','Data da transmissão / prevista'],['period','Mês da transmissão'],['currency','Moeda de origem'],['priceRef','Referência do preço fixado / pressuposto'],['priceScope','Âmbito do preço: combustível, operação, local e condições'],['priceFrom','Preço aplicável desde / pressuposto'],['priceTo','Preço aplicável até / pressuposto (vazio se sem termo fixado)'],['documentRef','Documento da transmissão / referência da previsão'],['documentDate','Data do documento / prevista'],['compositionRef','Referência da composição sem IVA — inclusões e exclusões aplicáveis'],['evidence','Fundamento factual / pressupostos']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={['operationDate','priceFrom','priceTo','documentDate'].includes(field)?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{rule&&<label>{row.treatment==='fuel_tax_included'?'Contraprestação sem IVA,com TC incluída (moeda indicada)':'Contraprestação sem IVA,já sem TC (moeda indicada)'}<input className="block rounded border p-2" value={row.consideration} onChange={e=>change(row.id,{consideration:e.target.value})}/></label>}
{row.treatment==='fuel_tax_included'&&<><label>TC incluída nesta contraprestação (moeda indicada)<input className="block rounded border p-2" value={row.fuelTax} onChange={e=>change(row.id,{fuelTax:e.target.value})}/></label><label>Referência da TC incluída / pressuposto<input className="block rounded border p-2" value={row.fuelTaxRef} onChange={e=>change(row.id,{fuelTaxRef:e.target.value})}/></label></>}
</div>
<p>Mudar o tratamento conserva os montantes e documentos,mas exige rever se a TC ainda está incluída. Os valores ocultos e as versões anteriores mantêm-se.</p>
{rule?<fieldset><legend>Condições próprias desta transmissão</legend>{fuelBaseConditions.map(([key,label])=><label className="block" key={key}>{label}<select className="block rounded border p-2" value={row.conditions[key]??''} onChange={e=>change(row.id,{conditions:{...row.conditions,[key]:e.target.value}})}><option value="">Por indicar</option><option value="yes">Sim</option><option value="no">Não</option></select></label>)}</fieldset>:<p>Escolha a composição para apresentar os montantes aplicáveis;os valores anteriores conservam-se.</p>}
</details>;})}
{!!book.rows.length&&<button type="button" className="rounded bg-emerald-800 p-2 text-white" onClick={()=>{try{save(recordFuelBases(draft,book));}catch(cause){setError(String(cause));}}}>Determinar bases de combustíveis e guardar versão</button>}
{book.result&&<><p role="status">{fuelBaseCurrent(draft,book)?'Bases de combustíveis correspondentes às entradas guardadas.':'Entradas alteradas;bases de combustíveis históricas conservadas. Reveja e determine novamente.'} {book.history?.length??0} versões anteriores. IVA e campo11 não são preenchidos por estas bases.</p><dl>{fuelBaseReportRows(draft).map(([,label,value,origin],index)=><div key={index}><dt className="font-semibold">{label}</dt><dd>{value}<small className="block">{origin}</small></dd></div>)}</dl></>}
</details>;
}
@@ -9,6 +9,7 @@ import { SimulationImportExemptions } from './simulation-import-exemptions';
import { SimulationPublicAuthorityBase } from './simulation-public-authority-base';
import { SimulationCommissionBase } from './simulation-commission-base';
import { SimulationActSaleBase } from './simulation-act-sale-base';
import { SimulationFuelBase } from './simulation-fuel-base';
import { SimulationOfferPreparations } from './simulation-offer-preparations';
import { SimulationOperations } from './simulation-operations';
@@ -96,6 +97,7 @@ export function SimulationMonthlyIva({draft, busy, onCalculate, onChange}: {
<SimulationPublicAuthorityBase draft={draft} onChange={onChange} />
<SimulationCommissionBase draft={draft} onChange={onChange} />
<SimulationActSaleBase draft={draft} onChange={onChange} />
<SimulationFuelBase draft={draft} onChange={onChange} />
<SimulationOfferPreparations draft={draft} onChange={onChange} />
<SimulationModeloA draft={draft} />
</section>;
+61
View File
@@ -0,0 +1,61 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const fuelBaseVersion='regulated-fuel-base/1';
export const fuelBaseSource='CIVA republicado Lei13/2016,15(2)(i),PDF13/p1426(271): nas transmissões de combustíveis cujo preço é fixado por Autoridade Pública,efectuadas por revendedores,o valor da contraprestação determinado nos termos dos números1 e5 não inclui a Taxa sobre os Combustíveis. Art15(5)/(6),PDF14/p1426(272),composição/exclusões,sem próprioIVA. Lei22/2022PDF3mantém15(2)(i)/(1)/(5)/(6)por remissão;Lei10/2025não altera15. Recorte2026/MZN;base apenas,sem presumir preço regulado,valorTC,incidência,taxaIVA,IVA,dedução/campo11 ou totaisModeloA.';
export const fuelBaseTreatments=[{id:'fuel_tax_included',label:'Montante sem IVA ainda inclui a Taxa sobre Combustíveis'},{id:'fuel_tax_excluded',label:'Montante sem IVA já exclui a Taxa sobre Combustíveis'}] as const;
export const fuelBaseConditions=[
['taxableFuelResale','Está identificada uma transmissão de combustíveis sujeita a IVA,efectuada por revendedor; não é qualquer aquisição ou prestação de serviços'],
['publicFixedPrice','O preço deste combustível é fixado pela Autoridade Pública identificada na referência aplicável'],
['priceScopeMatches','A referência do preço e o respectivo âmbito abrangem este combustível,operação,local e data; não se presume um preço actual para outro período'],
['netComposition','O montante indicado exclui o próprio IVA e reflecte a composição aplicável do artigo15(1)/(5)/(6),sem omissões ou duplicações'],
['fuelTaxTreatment','O tratamento escolhido corresponde à composição do montante:TC ainda incluída ou já excluída; a mesma TC não será subtraída duas vezes'],
] as const;
type Choice=''|'yes'|'no';type Condition=typeof fuelBaseConditions[number][0];
export type FuelBaseRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';currency:string;operationDate:string;priceRef:string;priceScope:string;priceFrom:string;priceTo:string;documentRef:string;documentDate:string;consideration:string;fuelTax:string;fuelTaxRef:string;compositionRef:string;evidence:string;conditions:Partial<Record<Condition,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';baseAmount:string|null;vat:null;rate:null;reason:string};
export type FuelBaseCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:FuelBaseRow[];rows:LineResult[]};
export type FuelBaseBook={rows:FuelBaseRow[];result?:FuelBaseCalculation;history?:FuelBaseCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{regulatedFuelBases?:Record<string,FuelBaseBook>};
export function newFuelBase(id:string,currency:string):FuelBaseRow{return{id,treatment:'',description:'',period:'',origin:'projected',currency,operationDate:'',priceRef:'',priceScope:'',priceFrom:'',priceTo:'',documentRef:'',documentDate:'',consideration:'',fuelTax:'',fuelTaxRef:'',compositionRef:'',evidence:'',conditions:{}};}
export function switchFuelTaxTreatment(row:FuelBaseRow,treatment:string):FuelBaseRow{return{...row,treatment,conditions:{...row.conditions,fuelTaxTreatment:''}};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.regulatedFuelBases!==undefined&&(!store.regulatedFuelBases||typeof store.regulatedFuelBases!=='object'||Array.isArray(store.regulatedFuelBases)))throw new Error('Bases de combustíveis não recuperáveis;originais preservados.');
const fields=Object.keys(newFuelBase('','')).filter(key=>key!=='conditions');
for(const book of Object.values(store.regulatedFuelBases??{}))if(!book||!Array.isArray(book.rows)||(book.history!==undefined&&!Array.isArray(book.history))||book.rows.some(row=>!row||fields.some(key=>typeof row[key as keyof FuelBaseRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)))throw new Error('Linhas de combustíveis não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function fuelBaseBook(draft:Record<string,unknown>):FuelBaseBook{return readStore(draft).regulatedFuelBases?.[acquisitionScope(draft)]??{rows:[]};}
export function saveFuelBaseBook(draft:Record<string,unknown>,book:FuelBaseBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,regulatedFuelBases:{...current.regulatedFuelBases,[acquisitionScope(draft)]:book}});readStore({...draft,modelo_a_snapshot:encoded});return encoded;}
function decimal(raw:unknown):bigint|null{if(typeof raw!=='string'||!/^\d{1,15}(\.\d{1,6})?$/.test(raw.trim()))return null;const[whole,fraction='']=raw.trim().split('.');return BigInt(whole)*1000000n+BigInt(fraction.padEnd(6,'0'));}
function money(n:bigint):string{return`${n/1000000n}.${(n%1000000n).toString().padStart(6,'0').replace(/0+$/,'').padEnd(2,'0')}`;}
function validDate(value:string):boolean{const d=new Date(value+'T00:00:00Z');return /^\d{4}-\d{2}-\d{2}$/.test(value)&&Number.isFinite(d.getTime())&&d.toISOString().slice(0,10)===value;}
export function evaluateFuelBase(row:FuelBaseRow,currency:unknown):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',baseAmount:null,vat:null,rate:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,reason});
if(!fuelBaseTreatments.some(item=>item.id===row.treatment))return stop('Indique se o montante sem IVA ainda inclui a TC ou já a exclui;não se presume a composição.');
if(currency!=='MZN'||row.currency!==currency)return stop('Moeda fora do âmbito MZN ou divergente do projecto;sem conversão silenciosa.');
if(!/^2026-(0[1-9]|1[0-2])$/.test(row.period)||!['projected','effective'].includes(row.origin))return stop('Indique mês em2026 e dados efectivos declarados ou pressupostos de projecção;sem inferir do orçamento.');
const failed=fuelBaseConditions.filter(([key])=>row.conditions[key]==='no');if(failed.length)return stop('Não se aplica esta base especial de combustíveis: '+failed.map(([,label])=>label).join('; ')+'. Não é isenção nem IVA zero.','not_applicable');
const missing=fuelBaseConditions.filter(([key])=>row.conditions[key]!=='yes');if(missing.length)return stop('Condições por indicar: '+missing.map(([,label])=>label).join('; ')+'. Desconhecido não significa não aplicável ou zero.');
if(!row.description.trim()||!row.priceRef.trim()||!row.priceScope.trim()||!row.documentRef.trim()||!row.compositionRef.trim()||!row.evidence.trim()||!validDate(row.documentDate))return stop('Identifique combustível/transmissão,referência e âmbito do preço,documento/data,composição e fundamento ou pressupostos expressos;reutilize referências existentes,sem novo certificado/aprovador.');
if(!validDate(row.operationDate)||row.operationDate.slice(0,7)!==row.period||!validDate(row.priceFrom)||row.operationDate<row.priceFrom||(row.priceTo!==''&&(!validDate(row.priceTo)||row.priceFrom>row.priceTo||row.operationDate>row.priceTo)))return stop('Identifique a data da transmissão no mês escolhido e o intervalo aplicável do preço que a abrange. Sem aplicar preço de outro período;na projecção indique pressupostos temporais expressos. O fim pode ficar vazio quando não existe termo fixado,com a correspondência temporal confirmada.');
const amount=decimal(row.consideration);if(amount===null)return stop('Indique o montante da contraprestação sem IVA;valor desconhecido ou inválido não é zero.');
let base=amount,formula='montante já sem TC,sem nova subtracção';
if(row.treatment==='fuel_tax_included'){
const tc=decimal(row.fuelTax);if(tc===null||!row.fuelTaxRef.trim())return stop('Identifique o montante exacto e a referência da TC incluída nesta contraprestação,ou pressuposto expresso;sem taxa TC presumida ou valor desconhecido igual a zero.');
if(tc>amount)return stop('A TC indicada excede a contraprestação sem IVA;reveja a composição e os montantes,sem base negativa ou zero substituto.');
base=amount-tc;formula=`${money(amount)} − ${money(tc)} de TC`;
}
return{...result,status:'determined',baseAmount:money(base),reason:`Base15(2)(i): ${formula} = ${money(base)}MZN,${row.origin==='projected'?'nas condições expressamente assumidas na projecção':'nos dados efectivos declarados'}. Preço/âmbito/período e composição identificados;sem determinar automaticamente preço ou taxaTC. Base não é imposto;IVA/taxa,dedução/campo11 e totaisModeloA não são determinados por este cálculo.`};
}
function key(draft:Record<string,unknown>,book:FuelBaseBook):string{return JSON.stringify({version:fuelBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function fuelBaseCurrent(draft:Record<string,unknown>,book:FuelBaseBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordFuelBases(draft:Record<string,unknown>,book:FuelBaseBook):FuelBaseBook{
if(!book.rows.length||new Set(book.rows.map(row=>row.id)).size!==book.rows.length)throw new Error('Indique operações com identificadores distintos;originais conservados.');
const result:FuelBaseCalculation={version:fuelBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:fuelBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateFuelBase(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveFuelBaseBook(draft,next);return next;
}
export function fuelBaseReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=fuelBaseBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Base P095 — ${row.period} — ${row.id}`,`${row.description};base tributável: ${result.rows[index].baseAmount??'Indeterminada'} ${row.currency};IVA: Indeterminado;${result.rows[index].reason}`,`${result.opportunity};${result.location};${fuelBaseCurrent(draft,book)?'Resultado actual':'Entradas alteradas;resultado histórico conservado'};versão${result.revision};${result.calculatedAt};${result.source};${row.origin==='projected'?'Projecção':'Dados efectivos declarados'};transmissão ${row.operationDate};preço ${row.priceRef};âmbito ${row.priceScope};intervalo ${row.priceFrom} a ${row.priceTo||'sem termo fixado,correspondência temporal confirmada'};${fuelBaseTreatments.find(item=>item.id===row.treatment)?.label??'Composição por indicar'};contraprestação ${row.consideration} ${row.currency};${row.treatment==='fuel_tax_included'?`TC incluída ${row.fuelTax} ${row.currency},referência ${row.fuelTaxRef}`:'TC já excluída,sem segunda subtracção'};composição ${row.compositionRef};documento ${row.documentRef},${row.documentDate};condições ${fuelBaseConditions.map(([key,label])=>label+': '+(row.conditions[key]==='yes'?'Sim':row.conditions[key]==='no'?'Não':'Por indicar')).join('; ')};fundamento ${row.evidence};não preenche totaisModeloA ou campo11.`]);}
catch{return[['IVA mensal','Base de combustíveis','Dados não recuperáveis','Originais preservados;sem substituir por zero.']];}
}
+2
View File
@@ -8,6 +8,7 @@ import { importExemptionReportRows } from './iva-import-exemptions.ts';
import { publicBaseReportRows } from './iva-public-authority-base.ts';
import { commissionBaseReportRows } from './iva-commission-base.ts';
import { actSaleReportRows } from './iva-act-sale-base.ts';
import { fuelBaseReportRows } from './iva-fuel-base.ts';
import { offerPreparationReportRows } from './iva-offer-preparations.ts';
import { salesReportRows } from './iva-operations.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
@@ -626,6 +627,7 @@ export function buildProjectDossierRows(
rows.push(...publicBaseReportRows(draft));
rows.push(...commissionBaseReportRows(draft));
rows.push(...actSaleReportRows(draft));
rows.push(...fuelBaseReportRows(draft));
rows.push(...offerPreparationReportRows(draft));
const operationRows = salesReportRows(draft);
rows.push(...operationRows);
+57
View File
@@ -0,0 +1,57 @@
<?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 IvaFuelBaseDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_fuel_bases_recover_privately_preserving_all_delivered_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('tests/frontend/fixtures/iva-g7d-bases.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:342', $recovered['context_opportunity']);
$this->assertSame('Manica', $recovered['selection_labels']['province_id']);
$store = json_decode($recovered['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$book = $store['regulatedFuelBases']['opportunity:342'];
$this->assertCount(2, $book['rows']);
$this->assertSame(['fuel_tax_included','fuel_tax_excluded'], array_column($book['rows'], 'treatment'));
$this->assertSame(['1400.15','1500.25'], array_column($book['result']['rows'], 'baseAmount'));
$this->assertSame(['determined','determined'], array_column($book['result']['rows'], 'status'));
$this->assertSame([null,null], array_column($book['result']['rows'], 'vat'));
$this->assertSame([null,null], array_column($book['result']['rows'], 'rate'));
$this->assertSame('1500.25', $book['rows'][0]['consideration']);
$this->assertSame('100.10', $book['rows'][0]['fuelTax']);
$this->assertStringContainsString('TC desta operação', $book['rows'][0]['fuelTaxRef']);
$this->assertStringContainsString('preço A', $book['rows'][0]['priceRef']);
$this->assertStringContainsString('Manica', $book['rows'][0]['priceScope']);
$this->assertSame('2026-12-12', $book['rows'][0]['operationDate']);
$this->assertSame('2026-12-01', $book['rows'][0]['priceFrom']);
$this->assertSame('2026-12-31', $book['rows'][0]['priceTo']);
$this->assertStringContainsString('15(2)(i)', $book['result']['source']);
$this->assertSame($book['rows'], $book['result']['inputs']);
$this->assertCount(2, $book['history']);
$this->assertNull($book['history'][0]['rows'][0]['baseAmount']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-g7d-preserved-inputs.json')), true, flags: JSON_THROW_ON_ERROR);
$prior = json_decode($frozen['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$this->assertSame($prior, array_diff_key($store, ['regulatedFuelBases' => true]));
$this->assertSame('1250.30', $store['publicAuthorityBases']['opportunity:339']['result']['rows'][1]['baseAmount']);
$this->assertNull($store['publicAuthorityBases']['opportunity:339']['result']['rows'][1]['vat']);
$this->assertSame('400.00', $store['importExemptions']['opportunity:338']['result']['rows'][1]['importVat']);
$this->assertNull($store['books']['opportunity:329']['result']['periods'][0]['fields']['11']);
file_put_contents(base_path('outputs/iva-l1-g7d-fuel-base-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+39
View File
@@ -0,0 +1,39 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {newFuelBase,switchFuelTaxTreatment,fuelBaseTreatments,fuelBaseConditions,evaluateFuelBase,recordFuelBases,saveFuelBaseBook,fuelBaseBook,fuelBaseCurrent,fuelBaseReportRows} from '../../resources/js/lib/iva-fuel-base.ts';
import {actSaleCurrent} from '../../resources/js/lib/iva-act-sale-base.ts';
import {commissionBaseCurrent} from '../../resources/js/lib/iva-commission-base.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
const frozen=JSON.parse(fs.readFileSync(new URL('./fixtures/iva-g7d-preserved-inputs.json',import.meta.url),'utf8'));
const row=(treatment=fuelBaseTreatments[0].id)=>({...newFuelBase('g7d-'+treatment,'MZN'),treatment,description:'SYNTHETIC QA revenda de combustível A',period:'2026-12',operationDate:'2026-12-12',priceRef:'SYNTHETIC QA referência preço A / Autoridade Pública',priceScope:'SYNTHETIC QA combustível A, revenda A, Manica, dezembro2026, pressupostos',priceFrom:'2026-12-01',priceTo:'2026-12-31',documentRef:'SYNTHETIC QA G7D '+treatment,documentDate:'2026-12-12',consideration:'1500.25',fuelTax:'100.10',fuelTaxRef:'SYNTHETIC QA TC desta operação sem estimar taxa',compositionRef:'SYNTHETIC QA composição15(1)/(5)/(6),líquida de IVA',evidence:'SYNTHETIC QA pressupostos expressos,não documento real',conditions:Object.fromEntries(fuelBaseConditions.map(([key])=>[key,'yes']))});
const draft=()=>({...structuredClone(frozen),context_opportunity:'opportunity:342',project_title:'SYNTHETIC QA — G7D / Bases de combustíveis'});
test('P095 own resale/price/scope/composition conditions; missing references and wrong date never become zero',()=>{
for(const rule of fuelBaseTreatments){const input=row(rule.id),ok=evaluateFuelBase(input,'MZN');assert.equal(ok.status,'determined');assert.equal(ok.baseAmount,rule.id==='fuel_tax_included'?'1400.15':'1500.25');assert.equal(ok.vat,null);assert.equal(ok.rate,null);
for(const[key]of fuelBaseConditions)for(const value of ['','unknown','no']){const r=evaluateFuelBase({...input,conditions:{...input.conditions,[key]:value}},'MZN');assert.equal(r.status,value==='no'?'not_applicable':'indeterminate');assert.equal(r.baseAmount,null);assert.equal(r.vat,null);}
for(const patch of [{description:''},{priceRef:''},{priceScope:''},{documentRef:''},{documentDate:'2026-02-30'},{compositionRef:''},{evidence:''},{period:'2025-12'},{currency:'USD'},{treatment:'unknown'},{operationDate:'2026-11-12'},{operationDate:'2026-02-30'},{priceFrom:''},{priceTo:'invalid'},{priceFrom:'2026-12-20'},{priceTo:'2026-12-11'},{priceFrom:'2026-12-31',priceTo:'2026-12-01'}])assert.equal(evaluateFuelBase({...input,...patch},'MZN').baseAmount,null);
assert.equal(evaluateFuelBase({...input,priceTo:''},'MZN').status,'determined');
for(const operationDate of ['2026-12-01','2026-12-31'])assert.equal(evaluateFuelBase({...input,operationDate},'MZN').status,'determined');
}
});
test('TC subtracted exactly once only when included; zero,precision,excess and treatment changes preserve inputs',()=>{
const input=row();for(const[patch,expected]of [[{consideration:'0',fuelTax:'0'},'0.00'],[{consideration:'1.000002',fuelTax:'0.000001'},'1.000001'],[{consideration:'999999999999999.999999',fuelTax:'0.000001'},'999999999999999.999998'],[{treatment:'fuel_tax_excluded',fuelTax:'invalid',fuelTaxRef:''},'1500.25']])assert.equal(evaluateFuelBase({...input,...patch},'MZN').baseAmount,expected);
for(const patch of [{consideration:''},{fuelTax:''},{fuelTaxRef:''},{consideration:'-1'},{fuelTax:'NaN'},{fuelTax:'0.0000001'},{fuelTax:'1500.26'}])assert.equal(evaluateFuelBase({...input,...patch},'MZN').baseAmount,null);
const switched=switchFuelTaxTreatment(input,'fuel_tax_excluded');assert.equal(switched.conditions.fuelTaxTreatment,'');for(const field of ['consideration','fuelTax','fuelTaxRef','priceRef','priceScope','priceFrom','priceTo','documentRef'])assert.equal(switched[field],input[field]);assert.equal(evaluateFuelBase(switched,'MZN').baseAmount,null);assert.equal(evaluateFuelBase({...switched,conditions:{...switched.conditions,fuelTaxTreatment:'yes'}},'MZN').baseAmount,'1500.25');
});
test('save/recovery/history/report preserve all81 delivered books including P094/P091 and currentkeys',()=>{
const d=draft(),prior=JSON.parse(d.modelo_a_snapshot);assert.deepEqual(fuelBaseBook(d),{rows:[]});assert.deepEqual(fuelBaseReportRows(d),[]);
let book=recordFuelBases(d,{rows:fuelBaseTreatments.map(rule=>({...row(rule.id),conditions:{}}))});book=recordFuelBases(d,{...book,rows:fuelBaseTreatments.map(rule=>({...row(rule.id),conditions:{...row(rule.id).conditions,publicFixedPrice:'no'}}))});book=recordFuelBases(d,{...book,rows:fuelBaseTreatments.map(rule=>row(rule.id))});assert.equal(book.history.length,2);assert.ok(book.history.every(h=>h.rows.every(r=>r.baseAmount===null&&r.vat===null)));assert.ok(fuelBaseCurrent(d,book));
for(const field of ['treatment','consideration','fuelTax','fuelTaxRef','priceRef','priceScope','priceFrom','priceTo','operationDate'])assert.ok(!fuelBaseCurrent(d,{...book,rows:book.rows.map(r=>({...r,[field]:'changed'}))}));for(const patch of [{context_opportunity:'opportunity:343'},{currency:'USD'},{selection_labels:{province_id:'Maputo'}}])assert.ok(!fuelBaseCurrent({...d,...patch},book));
d.modelo_a_snapshot=saveFuelBaseBook(d,book);assert.deepEqual(fuelBaseBook(JSON.parse(JSON.stringify(d))),book);const next=JSON.parse(d.modelo_a_snapshot);const{regulatedFuelBases,...untouched}=next;assert.deepEqual(untouched,prior);for(const[scope,previous]of Object.entries(prior.actSaleBases))assert.ok(actSaleCurrent({...d,context_opportunity:scope},previous));for(const[scope,previous]of Object.entries(prior.commissionBases))assert.ok(commissionBaseCurrent({...d,context_opportunity:scope},previous));
assert.equal(next.actSaleBases['opportunity:341'].result.rows[1].baseAmount,'2200.50');assert.equal(next.commissionBases['opportunity:340'].result.rows[0].baseAmount,'900.15');assert.equal(next.publicAuthorityBases['opportunity:339'].result.rows[0].vat,null);assert.equal(next.importExemptions['opportunity:338'].result.rows[1].importVat,'400.00');assert.equal(next.books['opportunity:329'].result.periods[0].fields['11'],null);
const report=JSON.stringify(createProjectDossierReport(d,{selectedSections:new Set(['finance']),version:'QA G7D'}));for(const token of ['Base P095','1400.15','1500.25','IVA: Indeterminado','opportunity:342','Manica','2026-12-12','preço A','15(2)(i)','100.10','2026-12-01','2026-12-31','campo11'])assert.ok(report.includes(token),token);assert.deepEqual(fuelBaseReportRows({...d,context_opportunity:'opportunity:343'}),[]);
if(process.env.IVA_G7D_CALCULATED)fs.writeFileSync(process.env.IVA_G7D_CALCULATED,JSON.stringify(d));
});
test('corrupt fuel rows/store cannot overwrite originals; duplicate operation identifiers cannot be recorded',()=>{
const d=draft(),original=d.modelo_a_snapshot;for(const patch of [{fuelTax:4},{conditions:[]},{priceRef:null}])assert.throws(()=>saveFuelBaseBook(d,{rows:[{...row(),...patch}]}),/originais preservados/);assert.equal(d.modelo_a_snapshot,original);assert.throws(()=>recordFuelBases(d,{rows:[row(),row()]}),/distintos/);assert.throws(()=>recordFuelBases(d,{rows:[]}),/distintos/);assert.throws(()=>fuelBaseBook({...d,modelo_a_snapshot:JSON.stringify({...JSON.parse(original),regulatedFuelBases:[]})}),/originais preservados/);
});