Compare commits

...
16 changed files with 1039 additions and 9 deletions
@@ -18410,5 +18410,323 @@
},
"base_VAT_separation": "Accepted QA reused:four exclusiontreatments withownconditions;initialnetamount minus onlystillincluded exclusions,alreadyexcluded notsubtractedagain. Judicial/contract/grant/accounts/recipient/packaginginvoice references/scope andimmutableinputs/history/report retained. Base independent of VAT/rate(alwaysnull),no deduction/regularisation inferred. Four installed runtime hashes and16compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
},
"iva_l1_g7h_P103_homologation_20261024": {
"status": "installed_delta_verified_partial_L1",
"candidate": "20871341438c024fa22a82419144734cb95cffbd",
"base_installed": "5d5f3b414866969e4b2d38376402b8f264c6d19c",
"coverage_complete_branches": {
"AUD-SIM-L1-P103": [
"price_comparison",
"referenced_correction"
]
},
"branch_count_complete": 1,
"treatment_count": 2,
"runtime_delta": [
{
"path": "resources/js/lib/iva-value-review.ts",
"sha256_LF": "411aa0506868afd112bac0e27571db1978b21bd8375051dc36abbe55dfad7876"
},
{
"path": "resources/js/components/simulation-value-review.tsx",
"sha256_LF": "ff3fc2ad0e0082a931341ae51b63d6abe2bfee00b90e5891fc4dce742e84a017"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "c7f6a45a8533f6ce4128c912511b7712011fc365b99dfbe675d6cb2b455dfca1"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "89ee4a4abfa36c4d159edd71c936d718e2a6e99c9c8a83be669451fb309c5d2c"
}
],
"counts_before": {
"delivered": 85,
"QA": 1,
"functional_pending": 46,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 86,
"QA": 0,
"functional_pending": 46,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 86,
"QA": 0,
"functional_pending": 46,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g7h-qa-20261024.json"
],
"authorization": "Tempo explicitly deploy20871341 through existingGit,preserve concurrentchanges and check installeddelta only;P103comparison distinct fromreferencedcorrection andconditionalscenario",
"scope": "2026/MZN,P103baseonly;no automaticvaluation/legalcorrection,incidence/rate/VAT/deduction/field11/regularisation/ModeloAtotals oractiveauthorityaction. Referencecontext/scope and equivalentcomposition required. Unknowncorrectionamount notdefaultreference;no inventedfloor/maximum. Projectedcorrection clearlyconditional,notATdecision. Notbelowdoesnotdemonstrate15(7)trigger.",
"meaning": "AT may correct consideration below current/normal factorygate/wholesale/retail/serviceprice,considering natureoftransmission. Comparison doesnot exerciseATpower or automaticallysubstitute referenceprice. Recordedcorrection in effective declareddata or expresslyconditional projectedscenario retains ownamount/ref/date/scope.",
"formula": {
"price_comparison": "compare exactdeclared/reference values;retain declaredbase withoutautomaticcorrection",
"referenced_correction": "if15(7)belowtrigger andscopeconfirmed,use explicitlyreferenced correctedamount;no max/defaultreference"
},
"preservation": "85priorclosures 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-g7h-readonly-rollback-20261024.patch,checked only,not applied;blocks newP103calculations only,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "5d5f3b414866969e4b2d38376402b8f264c6d19c",
"release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"previous_release": "/var/www/investmoz-homologacao/releases/7e5710ebbd235f9478f149f8470a238c9e66ea9e-8bf3c724",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"release_revision": {
"commit": "5d5f3b414866969e4b2d38376402b8f264c6d19c",
"branch": "main",
"built_at": "2026-10-24T21:06:06.620815+00:00",
"manifest_sha256": "640a7390e644ff6efdf891439786a7b1783553d805cf71ccb6e6d488ed7196e8"
},
"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-g7h-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "a61c5e65e681b5d58b514ae910d6a039a6313f9db78f0bfa440248a5d6d04162",
"files_sha256": "18957aa6e1635d99848d4d57248cf6213f0076a2d5c9852d2f1c695b3417c813",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g7h_restore_20261024",
"port": 55441,
"source_dump_sha256": "a61c5e65e681b5d58b514ae910d6a039a6313f9db78f0bfa440248a5d6d04162",
"active_database_writes": 0
}
},
"served_commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"previous_release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"database_migrations": 0,
"content_imports": 0
},
"runtime_files_verified": 4,
"persistent_files_and_env_verified": 369,
"tables_compared": 174,
"changed_tables": {
"cache": {
"before": {
"rows": 106,
"checksum": "7b8d3c22597c8e038d2988b13434f8e7"
},
"after": {
"rows": 106,
"checksum": "54e7a3e15667000170ba51da7a361204"
}
},
"sessions": {
"before": {
"rows": 75,
"checksum": "f3d76a1891ea997f2203be3e4846d2cd"
},
"after": {
"rows": 76,
"checksum": "1907f607e317a43b1157be359c442f5f"
}
}
},
"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": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"branch": "main",
"built_at": "2026-10-24T21:14:42.034149+00:00",
"manifest_sha256": "ba479b580dd012c09e8f4c94e691a75642da781583a21a6fc46c649b59b6d4e1"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"value-review-base/1": [
"assets/project-dossier-BwlKZrlT.js"
],
"price_comparison": [
"assets/project-dossier-BwlKZrlT.js"
],
"referenced_correction": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"valueReviews": [
"assets/project-dossier-BwlKZrlT.js"
],
"referenceCorresponds": [
"assets/project-dossier-BwlKZrlT.js"
],
"priceContext": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"declaredAmount": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"referenceAmount": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"referenceScope": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctedAmount": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctionRef": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctionScope": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctionDate": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctionApplies": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"Cenário condicionado": [
"assets/project-dossier-BwlKZrlT.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-BwlKZrlT.js"
]
},
"assets": [
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-BwlKZrlT.js",
"status": 200,
"sha256": "0c0956f01886a72af19b81daa663cc9c572ed9d16f66ce0d92f6a73a17ec3776"
},
{
"file": "assets/project-dossier-document-CyTqKXcP.js",
"status": 200,
"sha256": "dec458068969e1a8cb9186ff22c882a5c3cb4f2769b32340190f4dbad6d82aff"
},
{
"file": "assets/services-CnR4vnXO.js",
"status": 200,
"sha256": "dcbf2140a4bf353f007c905c9ab25647c1a8f38381743f0d412fd3e33c2046ea"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-DrQ81CqE.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": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"previous_release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"previous_release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"cd530b248bf9dee5a6e7f1e4d710346084a2421f"
],
"finished_at": "2026-10-24T21:14:44.805315+00:00"
},
"log_file": "1792876380762621304.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.73s",
"OK (59 tests, 317 assertions)",
"# tests 374",
"# pass 374",
"# fail 0"
],
"log_bytes": 137846
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted QA reused:comparison retainsdeclaredbase withoutautomaticcorrection;referencedcorrection uses ownamount/ref/date/scope;projectedscenario explicitlyconditional,notATdecision. Context/percourse/origin changesretainvalues andclearconfirmation. Base independent of VAT/rate(alwaysnull),no deduction/regularisation inferred. Four installed runtime hashes and16compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
}
@@ -1,6 +1,6 @@
{
"implementation_commit": "67b8b5814955ebce761b2123969958c9f2c8bf0f",
"status": "QA_complete_not_delivered",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P103": [
"price_comparison",
@@ -154,5 +154,18 @@
"homologation_unchanged": "5d5f3b41",
"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-g7h-value-review-20261024\\source-archive-inventory.json"
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7h-value-review-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"receipt": "l1-g7h-delivery-20261024.json",
"record": "iva_l1_g7h_P103_homologation_20261024",
"counts": {
"delivered": 86,
"QA": 0,
"functional_pending": 46,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,157 @@
{
"implementation_commit": "90b31c677f9f541364a2fdddc98d01280d4371f1",
"status": "QA_complete_not_delivered",
"coverage": {
"AUD-SIM-L1-P089": [
"free_company_service",
"private_company_asset_use",
"exempt_sector_asset_use"
]
},
"branch_count": 1,
"treatment_count": 3,
"source": "CIVA15(2)(c),2016PDF13/p1426(271),4(2)(a)/(b)PDF7/p1426(265),15(4)/(5)/(6)PDF14;2022doesnotamend4,maintains15c/4–6;2025doesnotamend4/15;2017rectificationdoesnotamendtheseprovisions.",
"meaning": "Free services bycompany forprivate/nonbusinesspurpose4(2)(a);useofcompanygoods forprivate/nonbusinesspurpose or in exemptsector4(2)(b). Previous total/partialdeduction ongoods/elements requiredonlyfor4(2)(b),not4(2)(a). Use distinctfrompermanentgoods transferP088.",
"formula": "normalvalue ofservice under15(4),identifiedbasis/scope andcomposition15(5)/(6),netofownVAT",
"technical_choices": "New serviceNormals opportunity-scoped book in existingmodelo_a_snapshot/API/dossier;exactdecimal up to6fractiondigits,no assumedrounding. Treatment change retains amounts/documents/asset/prior deduction references butclears ownconditions,keepingcommonconditions;hiddenvalues notimposed onfree_service. References reused or explicitprojectionassumptions,no newcertificate/appraiser/approver.",
"scope": "2026/MZN,P089baseonly;no automaticnormalvaluation orsubstitution byassetpurchaseprice/cost;no IVA/incidence/rate/deduction/field11/regularisation/ModeloAtotals. Prior deductionfact/reference doesnot calculateorgrant deduction. Unknownconditions/normalvalue indeterminate,explicitno notapplicable notzero. Otherbooks includingP103/102/101/095unchanged.",
"verification": {
"frontend": {
"tests": 4,
"passed": 4,
"failed": 0,
"scope": "Allthree treatments ownconditions unknown/no;free_service no priorDeduction prerequisite;assetuse requiresasset/deduction reference;normalvalue basis/scope/date/currency;exactdecimal/zero;switch preserveshiddenrefs/clearsownconditions;oldbooks/currentkeys/history/report;corruptwriteguard"
},
"privateAPI": {
"tests": 1,
"assertions": 29,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7i-service-normal-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Realcomponent Edge/CUA:missingnormalvaluebasis indeterminate;privateassetuse priorDeductionno notapplicable,unknown indeterminate;switchprivateuse→free hidesasset/deductionrefs andclearsownconditions,free succeedswithoutprior deduction;switchback recoversrefs andrequiresownconditions. Save/recover/report500.25/700.50/900.75,VATnull,3rows+5priorversions. SyntheticQA,notmanualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7i-service-normal-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "33cc971a122be5334b865cb5b3b92c93485f59a0",
"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",
"AUD-SIM-L1-P095",
"AUD-SIM-L1-P100",
"AUD-SIM-L1-P101",
"AUD-SIM-L1-P102",
"AUD-SIM-L1-P103"
],
"confirmed_losses": [],
"accepted_delivery": "cd530b24/33cc971a;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared at delivery",
"frozen": "tests\\frontend\\fixtures\\iva-g7i-preserved-inputs.json",
"sha256": "f563b21e8c75ab7db66bd5c9545f539f304449877796dd71f08c9ded8ee385d0",
"counts_before": {
"delivered": 86,
"QA": 0,
"functional_pending": 46,
"P001": 1,
"total": 133
},
"scope": "P089only;allpreviousbooks immutable including P103/P102/P101/P100/P095/P060/P050/partialP084P085;no active query/write"
},
"runtime_delta": {
"resources/js/lib/iva-service-normal.ts": "e10fa8131534982eae17ce72849fb794a8e0438c85719b872571a33c53e5f019",
"resources/js/components/simulation-service-normal.tsx": "b7838cc7dadd058906a3997e218deb79792d587a6daf67f7f3139ff22a0668a5",
"resources/js/components/simulation-monthly-iva.tsx": "8581d037947c9d764400e99627952524bcf28ed8b5bf865ba4a1cb4b74acd7ac",
"resources/js/lib/project-dossier.ts": "aa15412c46064a9cff6dbe2dba086e1acfe79fe50f313280ccb9ee7c89484c99"
},
"counts_current": {
"delivered": 86,
"QA": 1,
"functional_pending": 45,
"P001": 1,
"total": 133
},
"homologation_unchanged": "cd530b24",
"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-g7i-service-normal-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": "20871341438c024fa22a82419144734cb95cffbd",
"base_installed": "5d5f3b414866969e4b2d38376402b8f264c6d19c",
"coverage_complete_branches": {
@@ -36,8 +36,8 @@
"total": 133
},
"counts_current": {
"delivered": 85,
"QA": 1,
"delivered": 86,
"QA": 0,
"functional_pending": 46,
"documentary": 1,
"total": 133
@@ -127,5 +127,192 @@
"source_dump_sha256": "a61c5e65e681b5d58b514ae910d6a039a6313f9db78f0bfa440248a5d6d04162",
"active_database_writes": 0
}
}
},
"served_commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"previous_release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"database_migrations": 0,
"content_imports": 0
},
"runtime_files_verified": 4,
"persistent_files_and_env_verified": 369,
"tables_compared": 174,
"changed_tables": {
"cache": {
"before": {
"rows": 106,
"checksum": "7b8d3c22597c8e038d2988b13434f8e7"
},
"after": {
"rows": 106,
"checksum": "54e7a3e15667000170ba51da7a361204"
}
},
"sessions": {
"before": {
"rows": 75,
"checksum": "f3d76a1891ea997f2203be3e4846d2cd"
},
"after": {
"rows": 76,
"checksum": "1907f607e317a43b1157be359c442f5f"
}
}
},
"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": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"branch": "main",
"built_at": "2026-10-24T21:14:42.034149+00:00",
"manifest_sha256": "ba479b580dd012c09e8f4c94e691a75642da781583a21a6fc46c649b59b6d4e1"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"value-review-base/1": [
"assets/project-dossier-BwlKZrlT.js"
],
"price_comparison": [
"assets/project-dossier-BwlKZrlT.js"
],
"referenced_correction": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"valueReviews": [
"assets/project-dossier-BwlKZrlT.js"
],
"referenceCorresponds": [
"assets/project-dossier-BwlKZrlT.js"
],
"priceContext": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"declaredAmount": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"referenceAmount": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"referenceScope": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctedAmount": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctionRef": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctionScope": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctionDate": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"correctionApplies": [
"assets/project-dossier-BwlKZrlT.js",
"assets/services-CnR4vnXO.js"
],
"Cenário condicionado": [
"assets/project-dossier-BwlKZrlT.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-BwlKZrlT.js"
]
},
"assets": [
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-BwlKZrlT.js",
"status": 200,
"sha256": "0c0956f01886a72af19b81daa663cc9c572ed9d16f66ce0d92f6a73a17ec3776"
},
{
"file": "assets/project-dossier-document-CyTqKXcP.js",
"status": 200,
"sha256": "dec458068969e1a8cb9186ff22c882a5c3cb4f2769b32340190f4dbad6d82aff"
},
{
"file": "assets/services-CnR4vnXO.js",
"status": 200,
"sha256": "dcbf2140a4bf353f007c905c9ab25647c1a8f38381743f0d412fd3e33c2046ea"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-DrQ81CqE.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": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"previous_release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"previous_release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"cd530b248bf9dee5a6e7f1e4d710346084a2421f"
],
"finished_at": "2026-10-24T21:14:44.805315+00:00"
},
"log_file": "1792876380762621304.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.73s",
"OK (59 tests, 317 assertions)",
"# tests 374",
"# pass 374",
"# fail 0"
],
"log_bytes": 137846
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted QA reused:comparison retainsdeclaredbase withoutautomaticcorrection;referencedcorrection uses ownamount/ref/date/scope;projectedscenario explicitlyconditional,notATdecision. Context/percourse/origin changesretainvalues andclearconfirmation. Base independent of VAT/rate(alwaysnull),no deduction/regularisation inferred. Four installed runtime hashes and16compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,129 @@
{
"status": "ready_after_fresh_authenticated_preflight_and_verified_backup_restore",
"candidate": "a4329bb4bfb44546a5c64b8c4baabf4231a1c3c3",
"base_installed": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"coverage_complete_branches": {
"AUD-SIM-L1-P089": [
"free_company_service",
"private_company_asset_use",
"exempt_sector_asset_use"
]
},
"branch_count_complete": 1,
"treatment_count": 3,
"runtime_delta": [
{
"path": "resources/js/lib/iva-service-normal.ts",
"sha256_LF": "e10fa8131534982eae17ce72849fb794a8e0438c85719b872571a33c53e5f019"
},
{
"path": "resources/js/components/simulation-service-normal.tsx",
"sha256_LF": "b7838cc7dadd058906a3997e218deb79792d587a6daf67f7f3139ff22a0668a5"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "8581d037947c9d764400e99627952524bcf28ed8b5bf865ba4a1cb4b74acd7ac"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "aa15412c46064a9cff6dbe2dba086e1acfe79fe50f313280ccb9ee7c89484c99"
}
],
"counts_before": {
"delivered": 86,
"QA": 1,
"functional_pending": 45,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 86,
"QA": 1,
"functional_pending": 45,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 87,
"QA": 0,
"functional_pending": 45,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g7i-qa-20261024.json"
],
"authorization": "Tempo explicitly deploya4329bb4 through existingGit,preserve concurrentchanges and check installeddelta only;P089three treatments,prior deductioncondition limitedto applicableassetuse paths",
"scope": "2026/MZN,P089baseonly;no automaticnormalvaluation orsubstitution byassetpurchaseprice/cost;no IVA/incidence/rate/deduction/field11/regularisation/ModeloAtotals. Prior deductionfact/reference doesnot calculateorgrant deduction. Unknownconditions/normalvalue indeterminate,explicitno notapplicable notzero. Otherbooks includingP103/102/101/095unchanged.",
"meaning": "Free services bycompany forprivate/nonbusinesspurpose4(2)(a);useofcompanygoods forprivate/nonbusinesspurpose or in exemptsector4(2)(b). Previous total/partialdeduction ongoods/elements requiredonlyfor4(2)(b),not4(2)(a). Use distinctfrompermanentgoods transferP088.",
"formula": "normalvalue ofservice under15(4),identifiedbasis/scope andcomposition15(5)/(6),netofownVAT",
"preservation": "86priorclosures 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-g7i-readonly-rollback-20261024.patch,checked only,not applied;blocks newP089calculations only,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"previous_release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"release_revision": {
"commit": "cd530b248bf9dee5a6e7f1e4d710346084a2421f",
"branch": "main",
"built_at": "2026-10-24T21:14:42.034149+00:00",
"manifest_sha256": "ba479b580dd012c09e8f4c94e691a75642da781583a21a6fc46c649b59b6d4e1"
},
"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-g7i-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "f521bc779cc87c7bc500c37f44d15748961e098d0a420e9514bbb11adf8eefa4",
"files_sha256": "5d26d4d18c8ee9f09c40f9f99c044c9b7c98d3a33db94dc03347b23aa89dc9cf",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g7i_restore_20261024",
"port": 55441,
"source_dump_sha256": "f521bc779cc87c7bc500c37f44d15748961e098d0a420e9514bbb11adf8eefa4",
"active_database_writes": 0
}
}
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-service-normal.ts
+++ b/resources/js/lib/iva-service-normal.ts
@@ -51,6 +51,7 @@
function key(draft:Record<string,unknown>,book:ServiceNormalBook):string{return JSON.stringify({version:serviceNormalVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function serviceNormalCurrent(draft:Record<string,unknown>,book:ServiceNormalBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordServiceNormals(draft:Record<string,unknown>,book:ServiceNormalBook):ServiceNormalBook{
+ throw new Error('Novas bases P089 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:ServiceNormalCalculation={version:serviceNormalVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:serviceNormalSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateServiceNormal(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveServiceNormalBook(draft,next);return next;
@@ -1,6 +1,36 @@
# Rastreabilidade, utilização e formação
## 24/10/2026 — G7I/P089 concluído emQA:valor normal de serviços gratuitos/utilização de bens
Implementação`90b31c67`. **Um ramo,três tratamentos**:`free_company_service`,`private_company_asset_use`,`exempt_sector_asset_use`. FonteCIVA15(2)(c),Lei13/2016PDF13/p1426(271),4(2)(a)/(b)PDF7/p1426(265),15(4)/(5)/(6)PDF14;2022não altera4,mantém15c/4–6 por remissão;2025não altera4/15. Serviço gratuito pela própria empresa para necessidades particulares do titular/pessoal ou fins alheios4(2)a;não exige dedução anterior da alínea b. Utilização de bens da empresa para uso próprio/particular/alheio ou sector isento4(2)b exige dedução total/parcial anterior nesses bens/elementos,com referência;não calcula nem concede dedução/campo11. Uso não é afectação/transmissão permanenteP088.
Base=valor normal do serviço15(4),com fundamento/âmbito e composição15(5)/(6),sem próprioIVA. Não presumir custo/preço aquisição dos bens como valor normal do serviço,nem avaliação automática. Desconhecido não é zero;decimal exacto até6casas,sem arredondamento fiscal presumido. Referências/documentos reutilizáveis ou pressupostos expressos,sem certificados/avaliadores/aprovadores novos. LivroserviceNormals por oportunidade,snapshot/API/dossier existentes,sem schema/permissões novos. Troca de tratamento conserva valores/documentos/bens/dedução anterior ocultos,limpa condições próprias e mantém condições comuns;escolha técnica de integridade. SemIVA/incidência/taxa/dedução/campo11/regularizações/totaisModeloA.
Provas do delta:**4testes frontend**,**APIprivada1teste/29asserções**,guarda`simulator_fiscal_delta_20261021_test:55441` e rollback;tipos/build passaram. Interface real Edge/CUA:fundamento do valor normal desconhecido→indeterminado;uso particular com dedução anterior não→não aplicação,dedução desconhecida→indeterminado;troca uso→serviço gratuito oculta bens/dedução e limpa condições próprias,serviço gratuito aplica sem exigir dedução anterior;regresso recupera referências e exige condições próprias. Gravação recuperada/relatório:500.25/700.50/900.75,IVAindeterminado,3linhas/5versões anteriores. Dados sintéticos,não aceitação manual atribuída à Tempo.86fechos/livros/resultados/históricos intactos,incluindoP103/P102/P101/P100/P095/P094/P091/P060/P050 eP084/P085parciais;provas anteriores reutilizadas. [RegistoQA](../simulations/iva-l1-g7i-qa-20261024.json).
**86entregues +1emQA(P089) +45funcionaispendentes +P001 =133**. Homologação permanece`cd530b24`;falta integração/entrega pelo processoGit,manifesto/backup/restauro e delta instalado. P084/P085 continuam nos45,apenas preparação/simulação condicionada,sem benefícios confirmados. L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.
## 24/10/2026 — preparação G7I/P089,inventário antes de testes
G7H/P103 aceitecd530b24/33cc971a;**86entregues+46funcionaispendentes+P001=133**. Inventariados86fechos,sem perdas confirmadas;provas instaladas código/schema/dados/configuração/permissões174tabelas/369ficheiros/29fichas/28relações/408geometrias reutilizadas. Congelados todos os livros/resultados/históricos,incluindoP103(comparação/correcção),P102/P101/P100/P095/P094/P091/P060/P050/P084/P085parciais. Sem repetir aceitação anterior ou ensaiar no activo.
G7I/P089 executaCIVA15(2)(c),2016PDF13/p1426(271),4(2)(a)/(b)PDF7/p1426(265):base=valor normal do serviço15(4),composição15(5)/(6),PDF14/p1426(272). Três tratamentos no mesmo ramo:serviço gratuito pela própria empresa para necessidades particulares do titular/pessoal ou fins alheios;utilização de bens da empresa para uso próprio/particular/alheio;utilização em sector isento. A dedução anterior total/parcial nos bens/elementos é condição4(2)(b),não condição de4(2)(a);não calcular nem conceder dedução/campo11 por referência a esse facto. Não confundir utilização com afectação/transmissão permanenteP088.2022não altera4,mantém15c/4–6 por remissão;2025não altera4/15;rectificação2017não altera estes trechos. Fontes/exemplares/inventário aceites,cotejo visual com skillPDF. Referências de operação/finalidade/bens/dedução e valor normal reutilizáveis ou pressupostos expressos,sem avaliador/certificado/aprovador novo. Desconhecido não é zero;não usar custo/preço de aquisição de bens como valor normal de serviço presumido. Novo livro incremental,snapshot/API/relatório existentes;sem schema/permissões/IVA/dedução/campo11/regularizações/totaisModeloA. L1aberto;P00105/06;bebidasL2/L3;P084/P085parciais;Estatísticas/IAadiadas.
## 24/10/2026 — G7H/P103 entregue:comparação e correcção referenciada
Homologação **`cd530b24`**,pelo processoGit existente,sobre`5d5f3b41`;candidata`20871341` expressamente aceite pela Tempo. **P103:um ramo,dois tratamentos**:`price_comparison` e`referenced_correction`. Comparação da contraprestação com preços correntes/normais à porta fábrica,grosso,retalho ou serviço,conforme natureza/contexto/âmbito:AT pode corrigir,não automatismo. Comparação conserva a contraprestação declarada. Registo da correcção usa montante/referência/data/âmbito próprios,sem máximo ou preço de referência presumidos;dados efectivos declarados e cenário condicionado de projecção distinguem-se,o cenário não é decisão AT concedida. Mudança de contexto/percurso/origem conserva valores e documentos,limpa confirmações afectadas. Referências/âmbitos/composição equivalente conservados nas entradas imutáveis,versões/histórico/relatório. Desconhecido não é zero/correcção presumida;sem certificados/aprovadores novos. Base separada de incidência/taxa/IVA(IVA/taxa permanecemnull),dedução/campo11/regularizações/totaisModeloA. 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,16marcadores compilados do livro/componente/relatório,comparação/correcção referenciada/cenário condicionado/â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çãoP103 conferida,não aplicada,leitores/históricos e restantes ramos preservados.
[Manifesto/recibo](../simulations/l1-g7h-delivery-20261024.json),registo`iva_l1_g7h_P103_homologation_20261024`. **86entregues +46funcionaispendentes +P001 =133;sem candidatasQA por disponibilizar.** Os85fechos anteriores permanecem encerrados. P084/P085 continuam nos46,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 — G7H/P103 concluído emQA:comparação e correcção referenciada
Implementação`67b8b581`. **Um ramo,dois tratamentos**:`price_comparison` e`referenced_correction`. FonteCIVA15(7),Lei13/2016PDF14/p1426(272),15(1)/(5)/(6);2022PDF3mantém7;2025não altera15. Contraprestação inferior à resultante de preços correntes/normais à porta fábrica,grosso,retalho ou do serviço,considerando natureza das transmissões:AT pode corrigir,não automatismo. Comparação conserva contraprestação declarada;registo de correcção usa montante/referência/data/âmbito próprios,não máximo/referência substitutos. Contexto do preço,referência/âmbito,operação e composição equivalente sem próprioIVA identificados. Na projecção,correcção é cenário condicionado expressamente assumido,não decisão AT concedida;dados efectivos declarados exigem confirmação da correspondência da correcção referenciada. Não se demonstra pressuposto15(7)quando contraprestação não inferior.
File diff suppressed because one or more lines are too long
@@ -14,6 +14,7 @@ import { SimulationNoncashBase } from './simulation-noncash-base';
import { SimulationCompositionBase } from './simulation-composition-base';
import { SimulationExclusionBase } from './simulation-exclusion-base';
import { SimulationValueReview } from './simulation-value-review';
import { SimulationServiceNormal } from './simulation-service-normal';
import { SimulationOfferPreparations } from './simulation-offer-preparations';
import { SimulationOperations } from './simulation-operations';
@@ -106,6 +107,7 @@ export function SimulationMonthlyIva({draft, busy, onCalculate, onChange}: {
<SimulationCompositionBase draft={draft} onChange={onChange} />
<SimulationExclusionBase draft={draft} onChange={onChange} />
<SimulationValueReview draft={draft} onChange={onChange} />
<SimulationServiceNormal draft={draft} onChange={onChange} />
<SimulationOfferPreparations draft={draft} onChange={onChange} />
<SimulationModeloA draft={draft} />
</section>;
@@ -0,0 +1,28 @@
import {useState} from 'react';
import {newServiceNormal,switchServiceTreatment,serviceNormalBook,serviceNormalConditions,ownServiceConditions,serviceNormalCurrent,serviceNormalReportRows,serviceNormalSource,serviceNormalTreatments,recordServiceNormals,saveServiceNormalBook,type ServiceNormalBook,type ServiceNormalRow} from '@/lib/iva-service-normal';
export function SimulationServiceNormal({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:ServiceNormalBook;
try{book=serviceNormalBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:ServiceNormalBook)=>{try{onChange('modelo_a_snapshot',saveServiceNormalBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<ServiceNormalRow>)=>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 — serviços gratuitos e utilização de bens da empresa</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Identifique o serviço e a finalidade abrangida pelo artigo4(2). A base é o valor normal do serviço,com fundamento e âmbito identificados;nenhum custo ou preço de aquisição dos bens é usado como substituto automático.</p>
<p>O serviço gratuito da alínea a)não exige a dedução anterior prevista na alínea b). A utilização de bens exige identificar os bens/elementos e a dedução total/parcial anterior,sem a calcular ou conceder aqui. Utilização não é transmissão permanente de bens. Base e IVA são resultados distintos.</p>
<p>{serviceNormalSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newServiceNormal(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar serviço ou utilização</button>
{book.rows.map(row=><details key={row.id} className="rounded border p-3"><summary>{row.description||'Operação por identificar'} — {row.period||'mês por indicar'}</summary>
<div className="grid gap-3 md:grid-cols-2">
<label>Tratamento do serviço ou utilização<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchServiceTreatment(row,e.target.value))}><option value="">Por indicar</option>{serviceNormalTreatments.map(t=><option key={t.id} value={t.id}>{t.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 ServiceNormalRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Serviço e operação identificados'],['operationRef','Referência da operação / pressuposto'],['purposeRef','Finalidade e destinatário / sector isento'],['documentRef','Documento da operação / referência da previsão'],['documentDate','Data do documento / prevista'],['period','Mês da operação'],['currency','Moeda de origem'],['normalValue','Valor normal do serviço sem IVA (moeda indicada)'],['valuationRef','Fundamento do valor normal / pressuposto'],['valuationScope','Âmbito do valor normal: serviço, estádio, tempo, lugar e condições'],['compositionRef','Referência da composição sem próprio IVA'],['evidence','Fundamento factual / pressupostos']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={field==='documentDate'?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{row.treatment&&row.treatment!=='free_company_service'&&<><label>Bens da empresa / elementos constitutivos identificados<input className="block rounded border p-2" value={row.assetRef} onChange={e=>change(row.id,{assetRef:e.target.value})}/></label><label>Referência da dedução anterior total ou parcial / pressuposto<input className="block rounded border p-2" value={row.deductionRef} onChange={e=>change(row.id,{deductionRef:e.target.value})}/></label></>}
</div>
<p>Mudar o tratamento conserva os valores e documentos,mas exige rever as condições próprias. Os campos sem aplicação ficam ocultos e conservados.</p>
<fieldset><legend>Condições próprias deste percurso</legend>{[...serviceNormalConditions,...ownServiceConditions(row.treatment)].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 as ''|'yes'|'no'}})}><option value="">Por indicar</option><option value="yes">Sim</option><option value="no">Não</option></select></label>)}</fieldset>
</details>)}
{!!book.rows.length&&<button type="button" className="rounded bg-emerald-800 p-2 text-white" onClick={()=>{try{save(recordServiceNormals(draft,book));}catch(cause){setError(String(cause));}}}>Determinar valores normais e guardar versão</button>}
{book.result&&<><p role="status">{serviceNormalCurrent(draft,book)?'Valores normais correspondentes às entradas guardadas.':'Entradas alteradas;valores normais históricos conservados. Reveja e determine novamente.'} {book.history?.length??0} versões anteriores. IVA e campo11 não são preenchidos por estas bases.</p><dl>{serviceNormalReportRows(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>;
}
+61
View File
@@ -0,0 +1,61 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const serviceNormalVersion='assimilated-service-normal/1';
export const serviceNormalSource='CIVA republicado Lei13/2016,15(2)(c),PDF13/p1426(271):operações4(2),base=valor normal do serviço definido15(4),PDF14/p1426(272).4(2)(a),PDF7/p1426(265):serviços gratuitos pela própria empresa para necessidades particulares do titular/pessoal ou fins alheios;4(2)(b):utilização de bens da empresa para uso próprio/titular/pessoal/fins alheios ou sectores isentos,quando houve dedução total/parcial nesses bens ou elementos constitutivos. A condição de dedução anterior é de4(2)(b),não de4(2)(a). Composição15(4)/(5)/(6),sem próprioIVA. Lei22/2022mantém15c/4por remissão,não altera4;Lei10/2025não altera4/15. Recorte2026/MZN;base apenas,sem calcularIVA/dedução/campo11/regularizações/totaisModeloA,nem confundir uso com transmissão permanenteP088.';
export const serviceNormalTreatments=[{id:'free_company_service',label:'Serviço gratuito pela própria empresa para necessidades particulares ou fins alheios'},{id:'private_company_asset_use',label:'Utilização de bens da empresa para uso próprio,particular ou fins alheios'},{id:'exempt_sector_asset_use',label:'Utilização de bens da empresa em sector de actividade isento'}] as const;
export const serviceNormalConditions=[
['domesticOperation','A operação e o âmbito territorial aplicável estão identificados para esta base'],
['normalValueBasis','O valor normal do serviço corresponde15(4):concorrência normal,fornecedor independente,estádio de comercialização,tempo/lugar da operação ou mais próximos,com fundamento e âmbito identificados'],
['netComposition','O montante exclui o próprio IVA e reflecte15(4)/(5)/(6),sem omissões ou dupla contagem'],
] as const;
export const serviceOwnConditions={
free_company_service:[['freeByCompany','A prestação é gratuita e efectuada pela própria empresa'],['nonBusinessPurpose','Destina-se a necessidades particulares do titular/pessoal ou,em geral,a fins alheios à empresa']],
private_company_asset_use:[['companyAssetUse','É utilização de bens da empresa,não afectação/transmissão permanente de bens'],['privatePurpose','Destina-se a uso próprio do titular/pessoal ou,em geral,a fins alheios à empresa'],['priorDeduction','Houve dedução total ou parcial relativamente aos bens ou aos elementos que os constituem']],
exempt_sector_asset_use:[['companyAssetUse','É utilização de bens da empresa,não afectação/transmissão permanente de bens'],['exemptSector','A utilização corresponde a sector de actividade isento identificado'],['priorDeduction','Houve dedução total ou parcial relativamente aos bens ou aos elementos que os constituem']],
} as const;
export function ownServiceConditions(treatment:string):ReadonlyArray<readonly[string,string]>{return serviceOwnConditions[treatment as keyof typeof serviceOwnConditions]??[];}
type Choice=''|'yes'|'no';type Condition=typeof serviceNormalConditions[number][0];
export type ServiceNormalRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';currency:string;operationRef:string;purposeRef:string;assetRef:string;deductionRef:string;documentRef:string;documentDate:string;normalValue:string;valuationRef:string;valuationScope:string;compositionRef:string;evidence:string;conditions:Partial<Record<string,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';baseAmount:string|null;vat:null;rate:null;reason:string};
export type ServiceNormalCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:ServiceNormalRow[];rows:LineResult[]};
export type ServiceNormalBook={rows:ServiceNormalRow[];result?:ServiceNormalCalculation;history?:ServiceNormalCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{serviceNormals?:Record<string,ServiceNormalBook>};
export function newServiceNormal(id:string,currency:string):ServiceNormalRow{return{id,treatment:'',description:'',period:'',origin:'projected',currency,operationRef:'',purposeRef:'',assetRef:'',deductionRef:'',documentRef:'',documentDate:'',normalValue:'',valuationRef:'',valuationScope:'',compositionRef:'',evidence:'',conditions:{}};}
export function switchServiceTreatment(row:ServiceNormalRow,treatment:string):ServiceNormalRow{return{...row,treatment,conditions:Object.fromEntries(serviceNormalConditions.map(([key])=>[key,row.conditions[key]??'']))};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.serviceNormals!==undefined&&(!store.serviceNormals||typeof store.serviceNormals!=='object'||Array.isArray(store.serviceNormals)))throw new Error('Bases de contraprestação não recuperáveis;originais preservados.');
const fields=Object.keys(newServiceNormal('','')).filter(key=>key!=='conditions');
for(const book of Object.values(store.serviceNormals??{}))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 ServiceNormalRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)))throw new Error('Linhas de contraprestação não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function serviceNormalBook(draft:Record<string,unknown>):ServiceNormalBook{return readStore(draft).serviceNormals?.[acquisitionScope(draft)]??{rows:[]};}
export function saveServiceNormalBook(draft:Record<string,unknown>,book:ServiceNormalBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,serviceNormals:{...current.serviceNormals,[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 evaluateServiceNormal(row:ServiceNormalRow,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});
const rule=serviceNormalTreatments.find(t=>t.id===row.treatment);if(!rule)return stop('Identifique serviço gratuito,utilização particular/alheia ou em sector isento;desconhecido não permite presumir aplicaçã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 expressos de projecção.');
const required=[...serviceNormalConditions,...ownServiceConditions(row.treatment)];const failed=required.filter(([key])=>row.conditions[key]==='no');if(failed.length)return stop('Não se aplica esta base4(2)/15(2)(c): '+failed.map(([,label])=>label).join('; ')+'. Não é isenção nem IVA zero.','not_applicable');
if(required.some(([key])=>row.conditions[key]!=='yes'))return stop('Confirme as condições próprias deste percurso;desconhecido não é zero,não aplicável ou dedução presumida.');
if(!row.description.trim()||!row.operationRef.trim()||!row.purposeRef.trim()||!row.documentRef.trim()||!validDate(row.documentDate)||!row.valuationRef.trim()||!row.valuationScope.trim()||!row.compositionRef.trim()||!row.evidence.trim())return stop('Identifique serviço/operação,finalidade,documento/data,fundamento e âmbito do valor normal e composição,ou pressupostos expressos;reutilize dados existentes,sem certificado/avaliador/aprovador novo.');
if(row.treatment!=='free_company_service'&&(!row.assetRef.trim()||!row.deductionRef.trim()))return stop('Identifique os bens/elementos e a referência da dedução anterior total/parcial,ou pressupostos expressos;esta referência não calcula nem concede dedução/campo11.');
const normal=decimal(row.normalValue);if(normal===null)return stop('Indique o valor normal do serviço;desconhecido não é zero nem custo/preço de aquisição dos bens presumido.');
return{...result,status:'determined',baseAmount:money(normal),reason:`Base15(2)(c),${rule.label}:valor normal do serviço ${money(normal)}MZN,${row.origin==='projected'?'nas condições expressamente assumidas na projecção':'nos dados efectivos declarados'}. ${row.treatment==='free_company_service'?'4(2)(a),sem impor a condição de dedução anterior da alínea b).':'4(2)(b),bens/elementos e dedução anterior total/parcial referenciados;uso não é transmissão permanente.'} Valor normal com fundamento/âmbito,sem avaliação automática. Base não é imposto;IVA/taxa,dedução/campo11,regularizações e totaisModeloA não determinados por este cálculo.`};
}
function key(draft:Record<string,unknown>,book:ServiceNormalBook):string{return JSON.stringify({version:serviceNormalVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function serviceNormalCurrent(draft:Record<string,unknown>,book:ServiceNormalBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordServiceNormals(draft:Record<string,unknown>,book:ServiceNormalBook):ServiceNormalBook{
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:ServiceNormalCalculation={version:serviceNormalVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:serviceNormalSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateServiceNormal(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveServiceNormalBook(draft,next);return next;
}
export function serviceNormalReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=serviceNormalBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Base P089 — ${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};${serviceNormalCurrent(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'};${serviceNormalTreatments.find(t=>t.id===row.treatment)?.label??'Percurso por indicar'};operação ${row.operationRef};finalidade ${row.purposeRef};${row.treatment==='free_company_service'?'Dedução anterior não é condição de4(2)(a)':`bens/elementos ${row.assetRef},dedução anterior ${row.deductionRef}`};valor normal ${row.normalValue} ${row.currency};fundamento ${row.valuationRef};âmbito ${row.valuationScope};composição ${row.compositionRef};documento ${row.documentRef},${row.documentDate};condições ${[...serviceNormalConditions,...ownServiceConditions(row.treatment)].map(([key,label])=>label+': '+(row.conditions[key]==='yes'?'Sim':row.conditions[key]==='no'?'Não':'Por indicar')).join('; ')};fundamento factual ${row.evidence};não preenche totaisModeloA ou campo11.`]);}
catch{return[['IVA mensal','Valor normal de serviços assimilados','Dados não recuperáveis','Originais preservados;sem substituir por zero.']];}
}
+2
View File
@@ -13,6 +13,7 @@ import { noncashBaseReportRows } from './iva-noncash-base.ts';
import { compositionReportRows } from './iva-composition-base.ts';
import { exclusionReportRows } from './iva-exclusion-base.ts';
import { valueReviewReportRows } from './iva-value-review.ts';
import { serviceNormalReportRows } from './iva-service-normal.ts';
import { offerPreparationReportRows } from './iva-offer-preparations.ts';
import { salesReportRows } from './iva-operations.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
@@ -636,6 +637,7 @@ export function buildProjectDossierRows(
rows.push(...compositionReportRows(draft));
rows.push(...exclusionReportRows(draft));
rows.push(...valueReviewReportRows(draft));
rows.push(...serviceNormalReportRows(draft));
rows.push(...offerPreparationReportRows(draft));
const operationRows = salesReportRows(draft);
rows.push(...operationRows);
@@ -0,0 +1,56 @@
<?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 IvaServiceNormalDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_service_normals_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-g7i-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:347', $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['serviceNormals']['opportunity:347'];
$this->assertCount(3, $book['rows']);
$this->assertSame(['free_company_service','private_company_asset_use','exempt_sector_asset_use'], array_column($book['rows'], 'treatment'));
$this->assertSame(['500.25','700.50','900.75'], array_column($book['result']['rows'], 'baseAmount'));
$this->assertSame(['determined','determined','determined'], array_column($book['result']['rows'], 'status'));
$this->assertSame([null,null,null], array_column($book['result']['rows'], 'vat'));
$this->assertSame([null,null,null], array_column($book['result']['rows'], 'rate'));
$this->assertArrayNotHasKey('priorDeduction', $book['rows'][0]['conditions']);
$this->assertSame('yes', $book['rows'][1]['conditions']['priorDeduction']);
$this->assertSame('yes', $book['rows'][2]['conditions']['exemptSector']);
$this->assertStringContainsString('bens/elementos A', $book['rows'][1]['assetRef']);
$this->assertStringContainsString('dedução anterior parcial A', $book['rows'][2]['deductionRef']);
$this->assertStringContainsString('finalidade/destinatário', $book['rows'][0]['purposeRef']);
$this->assertStringContainsString('estádio/tempo/lugar', $book['rows'][2]['valuationScope']);
$this->assertStringContainsString('15(2)(c)', $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-g7i-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, ['serviceNormals' => 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-g7i-service-normal-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
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {newServiceNormal,switchServiceTreatment,serviceNormalTreatments,serviceNormalConditions,ownServiceConditions,evaluateServiceNormal,recordServiceNormals,saveServiceNormalBook,serviceNormalBook,serviceNormalCurrent,serviceNormalReportRows} from '../../resources/js/lib/iva-service-normal.ts';
import {valueReviewCurrent} from '../../resources/js/lib/iva-value-review.ts';
import {exclusionCurrent} from '../../resources/js/lib/iva-exclusion-base.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
const frozen=JSON.parse(fs.readFileSync(new URL('./fixtures/iva-g7i-preserved-inputs.json',import.meta.url),'utf8'));
const row=(treatment='free_company_service')=>({...newServiceNormal('g7i-'+treatment,'MZN'),treatment,description:'SYNTHETIC QA serviço A',period:'2026-12',operationRef:'SYNTHETIC QA operação A',purposeRef:'SYNTHETIC QA finalidade/destinatário ou sector isento A',assetRef:'SYNTHETIC QA bens/elementos A',deductionRef:'SYNTHETIC QA referência dedução anterior parcial A',documentRef:'SYNTHETIC QA G7I '+treatment,documentDate:'2026-12-12',normalValue:({free_company_service:'500.25',private_company_asset_use:'700.50',exempt_sector_asset_use:'900.75'})[treatment],valuationRef:'SYNTHETIC QA valor normal serviço A15(4)',valuationScope:'SYNTHETIC QA serviço A,estádio/tempo/lugar/concorrência/fornecedor independente,dezembro2026Manica',compositionRef:'SYNTHETIC QA composição15(4)/(5)/(6),sem próprioIVA',evidence:'SYNTHETIC QA pressupostos expressos,não documento real',conditions:Object.fromEntries([...serviceNormalConditions,...ownServiceConditions(treatment)].map(([key])=>[key,'yes']))});
const draft=()=>({...structuredClone(frozen),context_opportunity:'opportunity:347',project_title:'SYNTHETIC QA — G7I / Valor normal de serviços'});
test('P089 three treatments ownconditions and normalvalue references;prior deduction applies only to assetuse',()=>{
for(const t of serviceNormalTreatments){const input=row(t.id);assert.equal(evaluateServiceNormal(input,'MZN').baseAmount,input.normalValue);assert.equal(evaluateServiceNormal(input,'MZN').vat,null);assert.equal(evaluateServiceNormal(input,'MZN').rate,null);
for(const[key]of [...serviceNormalConditions,...ownServiceConditions(t.id)])for(const value of ['','unknown','no']){const r=evaluateServiceNormal({...input,conditions:{...input.conditions,[key]:value}},'MZN');assert.equal(r.status,value==='no'?'not_applicable':'indeterminate');assert.equal(r.baseAmount,null);}
for(const patch of [{description:''},{operationRef:''},{purposeRef:''},{documentRef:''},{documentDate:'2026-02-30'},{valuationRef:''},{valuationScope:''},{compositionRef:''},{evidence:''},{period:'2025-12'},{currency:'USD'},{treatment:''},{normalValue:''}])assert.equal(evaluateServiceNormal({...input,...patch},'MZN').baseAmount,null);
if(t.id!=='free_company_service')for(const patch of [{assetRef:''},{deductionRef:''}])assert.equal(evaluateServiceNormal({...input,...patch},'MZN').baseAmount,null);
}
const free=row();assert.equal(evaluateServiceNormal({...free,assetRef:'',deductionRef:'',conditions:{...free.conditions,priorDeduction:'no'}},'MZN').baseAmount,'500.25');
});
test('normalvalue only,no assetcost/substitution;exactdecimal/zero and switch preserves hiddenassetrefs but clears ownconditions',()=>{
const input=row('private_company_asset_use');for(const normalValue of ['0','1.000002','999999999999999.999999'])assert.equal(evaluateServiceNormal({...input,normalValue},'MZN').baseAmount,normalValue==='0'?'0.00':normalValue);for(const normalValue of ['-1','NaN','0.0000001'])assert.equal(evaluateServiceNormal({...input,normalValue},'MZN').baseAmount,null);
const changed=switchServiceTreatment(input,'free_company_service');assert.equal(changed.conditions.freeByCompany,undefined);assert.equal(changed.conditions.priorDeduction,undefined);for(const field of ['assetRef','deductionRef','normalValue','valuationRef','valuationScope','purposeRef'])assert.equal(changed[field],input[field]);assert.equal(evaluateServiceNormal(changed,'MZN').baseAmount,null);
assert.equal(evaluateServiceNormal({...changed,conditions:{...changed.conditions,freeByCompany:'yes',nonBusinessPurpose:'yes',priorDeduction:'no'}},'MZN').baseAmount,'700.50');
});
test('save/recovery/history/report preserve all86 delivered books/currentkeys including P103/P102/P101/P095',()=>{
const d=draft(),prior=JSON.parse(d.modelo_a_snapshot);assert.deepEqual(serviceNormalBook(d),{rows:[]});assert.deepEqual(serviceNormalReportRows(d),[]);
let book=recordServiceNormals(d,{rows:serviceNormalTreatments.map(t=>({...row(t.id),conditions:{}}))});book=recordServiceNormals(d,{...book,rows:serviceNormalTreatments.map(t=>({...row(t.id),conditions:{...row(t.id).conditions,domesticOperation:'no'}}))});book=recordServiceNormals(d,{...book,rows:serviceNormalTreatments.map(t=>row(t.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(serviceNormalCurrent(d,book));
for(const field of ['treatment','normalValue','valuationScope','deductionRef','assetRef','purposeRef'])assert.ok(!serviceNormalCurrent(d,{...book,rows:book.rows.map(r=>({...r,[field]:'changed'}))}));for(const patch of [{context_opportunity:'opportunity:348'},{currency:'USD'},{selection_labels:{province_id:'Maputo'}}])assert.ok(!serviceNormalCurrent({...d,...patch},book));
d.modelo_a_snapshot=saveServiceNormalBook(d,book);assert.deepEqual(serviceNormalBook(JSON.parse(JSON.stringify(d))),book);const next=JSON.parse(d.modelo_a_snapshot);const{serviceNormals,...untouched}=next;assert.deepEqual(untouched,prior);for(const[scope,previous]of Object.entries(prior.valueReviews))assert.ok(valueReviewCurrent({...d,context_opportunity:scope},previous));for(const[scope,previous]of Object.entries(prior.considerationExclusions))assert.ok(exclusionCurrent({...d,context_opportunity:scope},previous));
assert.equal(next.valueReviews['opportunity:346'].result.rows[1].baseAmount,'1400.75');assert.equal(next.considerationExclusions['opportunity:345'].result.rows[0].baseAmount,'799.70');assert.equal(next.regulatedFuelBases['opportunity:342'].result.rows[0].baseAmount,'1400.15');assert.equal(next.books['opportunity:329'].result.periods[0].fields['11'],null);
const report=JSON.stringify(createProjectDossierReport(d,{selectedSections:new Set(['finance']),version:'QA G7I'}));for(const token of ['Base P089','500.25','700.50','900.75','IVA: Indeterminado','opportunity:347','Manica','2026-12','15(2)(c)','4(2)(a)','dedução anterior parcial A','campo11'])assert.ok(report.includes(token),token);assert.deepEqual(serviceNormalReportRows({...d,context_opportunity:'opportunity:348'}),[]);
if(process.env.IVA_G7I_CALCULATED)fs.writeFileSync(process.env.IVA_G7I_CALCULATED,JSON.stringify(d));
});
test('corrupt service rows/store cannot overwrite originals;duplicateoperationids cannotbe recorded',()=>{
const d=draft(),original=d.modelo_a_snapshot;for(const patch of [{normalValue:4},{conditions:[]},{deductionRef:null}])assert.throws(()=>saveServiceNormalBook(d,{rows:[{...row(),...patch}]}),/originais preservados/);assert.equal(d.modelo_a_snapshot,original);assert.throws(()=>recordServiceNormals(d,{rows:[row(),row()]}),/distintos/);assert.throws(()=>recordServiceNormals(d,{rows:[]}),/distintos/);assert.throws(()=>serviceNormalBook({...d,modelo_a_snapshot:JSON.stringify({...JSON.parse(original),serviceNormals:[]})}),/originais preservados/);
});