Compare commits

..
Author SHA1 Message Date
nala 019bcbad6c docs(iva): prepare joint P092 P093 P125 delivery after isolated restore
tests / ci (push) Canceled after 0s
2026-10-25 00:30:43 +02:00
nala 0ebb20c86a docs(iva): record grouped QA P092 P093 P125 and preserve 111 deliveries 2026-10-25 00:28:41 +02:00
nala b0818c0163 Implement P092 P093 P125 individual secondhand bases in QA 2026-10-25 00:27:37 +02:00
nala ec786f4ae2 docs(iva): receipt P088-P124 delivery with deduction history preserved 2026-10-25 00:19:44 +02:00
nala 6c12aabb3a docs(iva): prepare joint P088-P124 delivery after backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-25 00:17:11 +02:00
nala cd259623ae docs(iva): record P088-P124 QA with historical deduction separate from new deduction 2026-10-25 00:15:24 +02:00
nala 9b95e5e7a8 feat(iva): prepare goods allocation classification and current acquisition-cost bases in QA 2026-10-25 00:15:19 +02:00
nala 1b67fa85ff docs(iva): receipt joint P122-P128 delivery preserving P091 and prior closures 2026-10-25 00:10:37 +02:00
nala 63cc336787 docs(iva): prepare joint P122-P128 delivery after backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-25 00:08:02 +02:00
nala af7d250320 docs(iva): record P122-P128 QA preserving 107 delivered branches 2026-10-25 00:06:28 +02:00
nala 2b592ded66 feat(iva): prepare own-name goods and service chains together in QA 2026-10-25 00:06:24 +02:00
nala 5837f34a2c docs(iva): receipt joint P096-P099 delivery with deduction outside scope 2026-10-25 00:02:07 +02:00
nala 2fdca86367 docs(iva): prepare joint P096-P099 delivery after backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 23:59:51 +02:00
nala 833b4e5cef docs(iva): record four proportional bases in QA preserving 103 deliveries 2026-10-24 23:58:10 +02:00
nala 67a96085c8 feat(iva): prepare four proportional tax bases in one QA set 2026-10-24 23:58:06 +02:00
nala b0e01ef737 docs(iva): receipt joint G9A-G9J delivery preserving 93 closures 2026-10-24 23:53:30 +02:00
nala 2a7254406d docs(iva): prepare one G9A-G9J delivery after backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 23:49:58 +02:00
nala 4601bf64a0 docs(iva): record P111-P120 QA with separate territoriality and obligations 2026-10-24 23:48:12 +02:00
nala 6cffa1188f feat(iva): prepare P111-P120 listed services as one compatible QA set 2026-10-24 23:48:08 +02:00
nala 4853bc7284 docs(iva): receipt one joint G8B-G8F delivery preserving 88 closures 2026-10-24 23:43:03 +02:00
nala 03c26d6613 docs(iva): prepare one G8B-G8F delivery after backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 23:40:32 +02:00
nala 3f4e71c3f3 docs(iva): record five G8 branches in QA for one compatible delivery 2026-10-24 23:38:44 +02:00
nala ec33fb5be2 feat(iva): prepare five G8 service territoriality branches together in QA 2026-10-24 23:38:14 +02:00
nala aac3f46306 docs(iva): receipt G8A installation and adopt grouped future deliveries 2026-10-24 23:33:35 +02:00
nala 8f14f5dde2 docs(iva): prepare G8A delivery after verified backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 23:31:08 +02:00
nala fb7248661d docs(iva): record G8A P105 QA and preserve 87 delivered branches 2026-10-24 23:29:12 +02:00
nala 0682ef74e2 feat(iva): classify goods territoriality for L1 P105 in QA 2026-10-24 23:29:03 +02:00
nala 21ce03f65c docs(iva): record installed G7I P089 and distinct prior deduction scope 2026-10-24 23:23:49 +02:00
nala 6f1cf7b7a0 docs(iva): prepare G7I delivery after verified backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 23:21:33 +02:00
nala a4329bb4bf docs(iva): record G7I P089 QA and preserve 86 deliveries 2026-10-24 23:19:43 +02:00
nala 90b31c677f feat(iva): prepare P089 service normal values with distinct own conditions in QA 2026-10-24 23:19:00 +02:00
nala 33cc971a12 docs(iva): record installed G7H P103 and referenced correction scope 2026-10-24 23:15:02 +02:00
nala cd530b248b docs(iva): prepare G7H delivery after verified backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 23:12:48 +02:00
nala 2087134143 docs(iva): record G7H P103 QA and preserve 85 deliveries 2026-10-24 23:10:58 +02:00
nala 67b8b58149 feat(iva): prepare P103 price comparison and referenced correction in QA 2026-10-24 23:10:11 +02:00
nala adb849d4fc docs(iva): record installed G7G P102 and four exclusion scopes 2026-10-24 23:06:42 +02:00
nala 5d5f3b4148 docs(iva): prepare G7G delivery after verified backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 23:04:14 +02:00
nala 9c2b2c6560 docs(iva): record G7G P102 QA and preserve 84 deliveries 2026-10-24 23:00:49 +02:00
nala acc633bf08 feat(iva): prepare four P102 exclusions with own conditions in QA 2026-10-24 22:59:39 +02:00
nala a89f9eca8c docs(iva): record installed G7F P101 and single operation base 2026-10-24 22:55:06 +02:00
nala 7e5710ebbd docs(iva): prepare G7F delivery after verified backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 22:52:59 +02:00
nala 6f90fcb9d4 docs(iva): record G7F P101 QA and preserve 83 deliveries 2026-10-24 22:50:04 +02:00
nala e3caf55361 feat(iva): prepare P101 consideration composition without doublecounting in QA 2026-10-24 22:49:56 +02:00
nala 0bef805ede docs(iva): record installed G7E P100 and preserved valuation scope 2026-10-24 22:45:45 +02:00
nala 70b4a640ee docs(iva): prepare G7E delivery after verified backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 22:43:24 +02:00
nala 0460c85330 docs(iva): record G7E P100 QA and preserve 82 deliveries 2026-10-24 22:41:41 +02:00
nala 9f053ac9d3 feat(iva): prepare P100 noncash consideration bases in QA 2026-10-24 22:41:33 +02:00
nala 6234d34392 docs(iva): record installed G7D P095 and TC excluded once 2026-10-24 22:38:04 +02:00
nala 92a7418cb6 docs(iva): prepare G7D delivery after verified backup and isolated restore
tests / ci (push) Canceled after 0s
2026-10-24 22:35:57 +02:00
nala 76be72c38c docs(iva): record G7D P095 QA and preserve 81 deliveries 2026-10-24 22:34:04 +02:00
nala 3bcd98e78e feat(iva): prepare P095 regulated fuel base excluding TC in QA 2026-10-24 22:33:57 +02:00
nala 9600880169 docs(iva): record installed G7C P094 and preserved valuation scope 2026-10-24 22:29:08 +02:00
124 changed files with 14194 additions and 41 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,191 @@
{
"implementation_commit": "2b592ded669f400e2322c183947a045bb3790c73",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P122": [
"goods_sale_commission",
"goods_purchase_commission"
],
"AUD-SIM-L1-P128": [
"service_sale_mandate",
"service_purchase_mandate"
]
},
"branch_count": 2,
"treatment_count": 4,
"source": "CIVA3(3)c,Lei13/2016PDF6/p1426(264);4(3),PDF7/p1426(265). Lei22/2022não altera3/4;Lei10/2025PDF12mantém3(3)c e não altera4. Base15(2)e/P091já entregue permanece independente;sem nova aplicação da base neste incremento.",
"meaning": {
"P122": "Transferências de bens em execução de contrato de comissão,incluindo consignação;na venda comissário considerado comprador,na compra comitente considerado comprador. Venda:comitente→comissário→terceiro;compra:terceiro→comissário→comitente. Contraprestações e referências das duas relações separadas.",
"P128": "Serviço efectuado por intervenção de mandatário emnome próprio:mandatário considerado adquirente eprestador sucessivamente4(3). Venda/prestação:mandante→mandatário→terceiro;compra/aquisição:terceiro→mandatário→mandante. Não é mera intermediação emnome de outrem ou base15(2)e de bens."
},
"formula": "Classifytwo successive relations bykind/direction;keep eachoriginalconsideration separate;no monetaryaggregation or taxcalculation.",
"scope": "2026,circuitos emnome próprio,partes/contratos/objectos econtraprestações originais das duas relações. Sem soma/compensação automática,base tributável nova,localização,isenção,taxa,IVA,dedução/campo11 ou totaisModeloA. Sem conversão cambial;moeda original identificada e coerente com contexto. P091preservado,sem repetir aceitação/cálculo.",
"technical_choices": "NewownNames opportunity-scoped book in existingmodelo_a snapshot/API/dossier,no schema/permissions. Switchretainsallhiddenrefs/values andclearsownconfirmations,keepscommon. Originaldecimalstrings up to15integer/6fractiondigits retained;no rounding/conversion. References or explicitassumptions reused,no certificates/approvers invented. OptionalexistingBaseRef notprerequisite;doesnotmodifyP091.",
"verification": {
"frontend": {
"tests": 6,
"passed": 6,
"failed": 0,
"by_treatment": "Four circuits:ownconditions unknown/no,direction/parties,separate originals,dates/refs/currency,zero vsunknown",
"additional": "Switchretainsvalues/refs andclearsownconfirmations;nonmonetarytaxfields remainnull;allpriorbooks includingP091 unchanged,history/report/currentkey/corruptwriteguards"
},
"privateAPI": {
"tests": 1,
"assertions": 37,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g10-own-name-20261025\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Edge/CUArealcomponent:ownNameunknown makescircuitindeterminate;restoredconfirmation andsave/recover/report4circuitswith2relations each and1000.25/1100.75MZN keptseparate,no totals,newbase/VAT/ratenull,3previousversions. SyntheticQA,notmanualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g10-own-name-20261025\\qa-recovered-report.png"
},
"preservation": {
"base": "5837f34a2cc64a94f91f038ffcb0c62f5fb5ba6a",
"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-P089",
"AUD-SIM-L1-P090",
"AUD-SIM-L1-P091",
"AUD-SIM-L1-P094",
"AUD-SIM-L1-P095",
"AUD-SIM-L1-P096",
"AUD-SIM-L1-P097",
"AUD-SIM-L1-P098",
"AUD-SIM-L1-P099",
"AUD-SIM-L1-P100",
"AUD-SIM-L1-P101",
"AUD-SIM-L1-P102",
"AUD-SIM-L1-P103",
"AUD-SIM-L1-P105",
"AUD-SIM-L1-P106",
"AUD-SIM-L1-P107",
"AUD-SIM-L1-P108",
"AUD-SIM-L1-P109",
"AUD-SIM-L1-P110",
"AUD-SIM-L1-P111",
"AUD-SIM-L1-P112",
"AUD-SIM-L1-P113",
"AUD-SIM-L1-P114",
"AUD-SIM-L1-P115",
"AUD-SIM-L1-P116",
"AUD-SIM-L1-P117",
"AUD-SIM-L1-P118",
"AUD-SIM-L1-P119",
"AUD-SIM-L1-P120"
],
"confirmed_losses": [],
"accepted_delivery": "2fdca863/5837f34a;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared",
"frozen": "tests\\frontend\\fixtures\\iva-g10-own-name-preserved.json",
"sha256": "03defa4a680af33e1bcd05770d619343704d448d295142263b21c40e516b2a5d",
"scope": "P122/P128QA;all priorbooks/history includingP105–110 andpartialP084/P085 immutable;no activewrites"
},
"runtime_delta": {
"resources/js/lib/iva-own-name.ts": "c36509de24d31d747d91630a31ce7d72baa749e9928b718a944556348fc54f85",
"resources/js/components/simulation-own-name.tsx": "6e142242aa29ae07e36b4d8d0be7d78f770d701e0a92e1a6e9832fcb794c17cf",
"resources/js/components/simulation-monthly-iva.tsx": "9718dc440aa98497011775d8bd03049d7857fa3badf27f4467d6d434f642defd",
"resources/js/lib/project-dossier.ts": "099dc307a86c763a9509516f6d59cc5c454b1f81189cc04b919d8d6045baf9dc"
},
"counts_current": {
"delivered": 107,
"QA": 2,
"functional_pending": 23,
"P001": 1,
"total": 133
},
"homologation_unchanged": "2fdca863",
"remaining": "OnejointGit delivery forP122/P128,freshbackup/realisolatedrestore,acceptedQA reused,installeddeltaonly. No individualbranch deployment.",
"limits": "L1open;deductionoutsideincrement;P00105/06;P121digital/P084/P085pending;beveragesL2/L3;Statistics/AIdeferred",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g10-own-name-20261025\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"receipt": "l1-g10-own-name-delivery-20261025.json",
"record": "iva_l1_g10_own_name_P122_P128_homologation_20261025",
"counts": {
"delivered": 109,
"QA": 0,
"functional_pending": 23,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,214 @@
{
"implementation_commit": "67a96085c8828231bb7e44ca26a4acb7b915ecee",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P096": [
"regulated_energy"
],
"AUD-SIM-L1-P097": [
"aeronautical_fees"
],
"AUD-SIM-L1-P098": [
"public_works"
],
"AUD-SIM-L1-P099": [
"public_water"
]
},
"branch_count": 4,
"treatment_count": 4,
"source": "CIVA15(2)j/k/l/m,15(1)/(5)/(6)/(9),Lei13/2016PDF13–14/p1426(271–272);Lei22/2022PDF3mantém15(2)j–m;Lei10/2025não altera15,adita18(6),PDF13:dedução do imposto suportado relativo a essas operações na mesma proporção da base reduzida.",
"meaning": {
"P096": {
"treatment": "regulated_energy",
"formula": "contraprestação total antes redução,sempróprioIVA ×62%",
"conditions": "Transmissão de energia com preço fixado porAutoridadePública,referência/âmbito/intervalo aplicáveis."
},
"P097": {
"treatment": "aeronautical_fees",
"formula": "contraprestação total antes redução,sempróprioIVA ×85%",
"conditions": "Preço doserviço fixado através de taxas aeronáuticas. Não aplicar a comunicações/saneamento/telecomunicações genericamente pelo título histórico da matriz;é necessário demonstrar o preço fixado através de taxa aeronáutica15(2)k."
},
"P098": {
"treatment": "public_works",
"formula": "contraprestação total antes redução,sempróprioIVA ×40%(redução60%,não base60%)",
"conditions": "Construção/reabilitação de obras públicas abrangidas15(2)l/15(9),projecto/contrato/categoria/âmbito identificados;estradas,pontes,infraestrutura água/saneamento,electrificação rural emprojectos públicos e hidráulicaagrícola noâmbito definido. Não exigir preço regulado a esta alínea."
},
"P099": {
"treatment": "public_water",
"formula": "contraprestação total antes redução,sempróprioIVA ×75%",
"conditions": "Água potável através derede pública,preço fixado porAutoridadePública comreferência/âmbito/intervalo aplicáveis."
}
},
"formula": "Base=fullconsideration before reduction excludingownVAT ×branchpercentage once;exactdecimal retained,no fiscalrounding assumed.",
"scope": "2026/MZN,base apenas. Percentagens62/85/40/75 são de base,não taxasIVA. Proporção18(6)registada sem calcular/conceder dedução/campo11;dedução permanece nas condições/lotes próprios. Sem taxaIVA,IVA,isenção ou totaisModeloA. Não dividir bruto comIVA sem composição esclarecida,nem reduzir montante já reduzido.",
"technical_choices": "NewregulatedReducedBases opportunity-scoped book in existingmodelo_a snapshot/API/dossier,no schema/permissions. Switchretainshiddenprice/projectrefs andclearsownconditions;sharedconditions retained. Inputs15integer/6fractiondigits,BigInt×percentage,outputupto8fractiondigits. Existingrefs or explicitassumptions,no certificates/approvers invented.",
"verification": {
"frontend": {
"tests": 6,
"passed": 6,
"failed": 0,
"by_branch": {
"AUD-SIM-L1-P096": "Ownconditions unknown/no,source/scope/date/currency,exactpercentage/base,zero vsunknown passed",
"AUD-SIM-L1-P097": "Ownconditions unknown/no,source/scope/date/currency,exactpercentage/base,zero vsunknown passed",
"AUD-SIM-L1-P098": "Ownconditions unknown/no,source/scope/date/currency,exactpercentage/base,zero vsunknown passed",
"AUD-SIM-L1-P099": "Ownconditions unknown/no,source/scope/date/currency,exactpercentage/base,zero vsunknown passed"
},
"additional": "Eightfractiondigit exactresults from6fractioninput,no float/fiscalrounding;works40not60,pricefields irrelevanttoworks,project/categories guard,switchhiddenretention,allpreviousbooks/history/report/corruptwriteguards"
},
"privateAPI": {
"tests": 1,
"assertions": 27,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7-reduced-bases-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Edge/CUArealcomponent:unknown full-before-reduction composition makesenergybaseindeterminate;unknown workscategory makesworksbaseindeterminate;restore confirms620.155/850.2125/400.10/750.1875MZN,proportion62/85/40/75%,VAT/ratenull. Save/recover/report4rows+3previousversions. SyntheticQA,notmanualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7-reduced-bases-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "b0e01ef737d26a991474e7fcc5d77cd330f20815",
"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-P089",
"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",
"AUD-SIM-L1-P105",
"AUD-SIM-L1-P106",
"AUD-SIM-L1-P107",
"AUD-SIM-L1-P108",
"AUD-SIM-L1-P109",
"AUD-SIM-L1-P110",
"AUD-SIM-L1-P111",
"AUD-SIM-L1-P112",
"AUD-SIM-L1-P113",
"AUD-SIM-L1-P114",
"AUD-SIM-L1-P115",
"AUD-SIM-L1-P116",
"AUD-SIM-L1-P117",
"AUD-SIM-L1-P118",
"AUD-SIM-L1-P119",
"AUD-SIM-L1-P120"
],
"confirmed_losses": [],
"accepted_delivery": "2a725440/b0e01ef7;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared",
"frozen": "tests\\frontend\\fixtures\\iva-g7-reduced-preserved.json",
"sha256": "0f106010eb54921462d64f42bf44ac551ef2ab614f6fe0eb063908d858529b01",
"scope": "P096–P099QA;all priorbooks/history includingP111–P120 andpartialP084/P085 immutable;no activewrites"
},
"runtime_delta": {
"resources/js/lib/iva-reduced-bases.ts": "4fc79388066a4d012b9af279ef53212ee963ae43d858307155e9ae8a140b5285",
"resources/js/components/simulation-reduced-bases.tsx": "00f1e0f1490240f578401c3a6e10b6812ee5b7978bbf7d7e5c9c1a81124bc6d1",
"resources/js/components/simulation-monthly-iva.tsx": "6032b9605703e7e29d5fb45cc158e8da57b9af4980d312f3326ddf18ee1e8814",
"resources/js/lib/project-dossier.ts": "ab044a0952cc4753925768f5ba7fd422637cfb9d826c1e8c26d21d7616b6dacf"
},
"counts_current": {
"delivered": 103,
"QA": 4,
"functional_pending": 25,
"P001": 1,
"total": 133
},
"homologation_unchanged": "2a725440",
"remaining": "OnejointGit delivery forfourcompatiblebranches,onebackup/realisolatedrestore,perbranchQAproofsreused,installeddeltaonly. No individualbranch deployment.",
"limits": "P121digital/P084/P085pending;L1open;P00105/06;beveragesL2/L3;Statistics/AIdeferred",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7-reduced-bases-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"receipt": "l1-g7-reduced-delivery-20261024.json",
"record": "iva_l1_g7_reduced_P096_P099_homologation_20261024",
"counts": {
"delivered": 107,
"QA": 0,
"functional_pending": 25,
"documentary": 1,
"total": 133
}
}
}
@@ -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,167 @@
{
"implementation_commit": "3bcd98e78ee42c3034cee452b8570a72cd89020e",
"status": "delivered_with_QA_proofs_preserved",
"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",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"receipt": "l1-g7d-delivery-20261024.json",
"record": "iva_l1_g7d_P095_homologation_20261024",
"counts": {
"delivered": 82,
"QA": 0,
"functional_pending": 50,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,168 @@
{
"implementation_commit": "9f053ac9d3f332c432420fd5b5d31cdfb7936071",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P100": [
"noncash_only",
"cash_and_noncash"
]
},
"branch_count": 1,
"treatment_count": 2,
"source": "CIVA15(3)/(4),Lei13/2016PDF14/p1426(272);composition15(5)/(6);Lei22/2022PDF3maintains15(3–6)byremissão;Lei10/2025doesnotamend15;2017rectificationdoesnotamend15(3)/(4).",
"meaning": "Consideration not wholly or partly defined in money:money received/receivable plus normalvalue of goods/services given in exchange as consideration for identified operation. Entirely noncash only with express composition confirmation,not inferred from emptycash field.",
"formula": {
"noncash_only": "normalvalue,absence of monetary consideration explicitly confirmed",
"cash_and_noncash": "cashamount received/receivable + normalvalue of goods/services given in exchange"
},
"technical_choices": "New noncashBases opportunity-scoped book in existingmodelo_a_snapshot/API/dossier;no schema/permissionschange. Exactdecimal up to6fractiondigits,no assumed fiscalrounding. Composition change retains cash/reference/normalvalue/documents but clears corresponding confirmation as integrity choice. Hidden cash is preserved but not summed in noncash_only. Normalvalue supplied with15(4)basis/scope,composition15(5)/(6)netofownVAT;no automatic appraisal/certificate/appraiser/approver.",
"scope": "2026/MZN,baseonly;no currencyconversion,automatic normalvaluation,incidence/rate/VAT/deduction/field11/ModeloAtotals. Unknown monetary share not inferredzero;explicitzero differentiated. Otherbranches and prior normalvalue contexts unchanged.",
"verification": {
"frontend": {
"tests": 4,
"passed": 4,
"failed": 0,
"scope": "Ownconditions missing/no;exchange/agreement/normalvalue basis/scope/references;exactadditiononce/zero/largefractionalamounts;switchretention;hidden cash excluded;corruptwriteguard;alloldbooks/currentkeys/history/report"
},
"privateAPI": {
"tests": 1,
"assertions": 29,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7e-noncash-base-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Realcomponent Edge/CUA:normalvalue basis/moneyunknown indeterminate;switch mixed→noncash hidescash/clearsconfirmation;confirmed noncash uses2200.50 despite retained500.25;switchback recovers500.25;finalnoncash2200.50/mixed2700.75,VATnull;save/recover/report2rows+5priorversions. SyntheticQA,not manualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7e-noncash-base-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "6234d3439285f0251af90694c9347f1936cb4f7f",
"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"
],
"confirmed_losses": [],
"accepted_delivery": "92a7418c/6234d343;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared at delivery",
"frozen": "tests\\frontend\\fixtures\\iva-g7e-preserved-inputs.json",
"sha256": "825dd90f48540c83bd7c9ca8b234e0dd558a12aca19d394cfa91b32a17d0edb7",
"counts_before": {
"delivered": 82,
"QA": 0,
"functional_pending": 50,
"P001": 1,
"total": 133
},
"scope": "P100 only;allpreviousbooks immutable including P095TC/P094valuation/P091/P090/P060/P050/partialP084P085;no active query/write"
},
"runtime_delta": {
"resources/js/lib/iva-noncash-base.ts": "d07cbefec4d54cffe41626093832972b31b8eacf0021a146655c79b189f25434",
"resources/js/components/simulation-noncash-base.tsx": "e8d5dd905d9c6b75ed7589e4ecf7b708bb288ba59285d409f444e799f9f09c35",
"resources/js/components/simulation-monthly-iva.tsx": "bc1005d31306c859dfa325f8d63e8bac98073b38f6d65ab22f736537629d4752",
"resources/js/lib/project-dossier.ts": "84d3c968dfa0a644f1767c09dd266fbe32b086117da0416564681e4a51e8d7f6"
},
"counts_current": {
"delivered": 82,
"QA": 1,
"functional_pending": 49,
"P001": 1,
"total": 133
},
"homologation_unchanged": "92a7418c",
"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-g7e-noncash-base-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"receipt": "l1-g7e-delivery-20261024.json",
"record": "iva_l1_g7e_P100_homologation_20261024",
"counts": {
"delivered": 83,
"QA": 0,
"functional_pending": 49,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,166 @@
{
"implementation_commit": "e3caf553616da59222dbc2bd2327dfae602ad3db",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P101": [
"tax_component",
"accessory_component"
]
},
"branch_count": 1,
"treatment_count": 2,
"source": "CIVA15(5)(a)/(b),Lei13/2016PDF14/p1426(272);15(1)/(2)/(6);Lei22/2022PDF3maintains15(5)byremissão;Lei10/2025doesnotamend15;2017rectificationdoesnotamend15(5).",
"meaning": "Include taxes,duties,fees/otherimpositions excludingownVAT;accessory expenses charged forcommissions,packaging,transport/insurance onclientaccount. Both component treatments form one base peroperation,not parallelbases.",
"formula": "initial amount netofownVAT/applicableexclusions + sum of applicable components notalreadyincluded;alreadyincluded components retained without secondsum",
"technical_choices": "New considerationCompositions opportunity-scoped book in existingmodelo_a_snapshot/API/dossier;operations with nested components,ids and immutableinput/history/report. No schema/permissionschange. Exactdecimal up to6fractiondigits,no assumed fiscalrounding. Componenttreatmentchange preservesamount/reference/inclusion but clearsnatureconfirmation as integritychoice. Idduplicates/malformednestedwrite guarded. References reuse documents/projectionassumptions,no newcertificates/approvers.",
"scope": "2026/MZN,P101compositiononly;no incidence/taxrates/IVA/deduction/field11/ModeloAtotals. Initialamount explicitlynetofownIVA and applicable15(6)exclusions;specialbases15(2)respected includingP095TCexclusion. DetailedP102exclusions notclosed by thisrecorte. Unknowncomponentamount/inclusion notassumedzero or missing;ownIVA not added ascomponent.",
"verification": {
"frontend": {
"tests": 4,
"passed": 4,
"failed": 0,
"scope": "Ownoperationandcomponentconditions unknown/no;tax/accessory separately andtogether;ownIVA;references;addmissingonly/alreadyincluded unchanged;exactdecimal/zero;switchretention;duplicateparts/malformednestedwrite;oldbooks/currentkeys/history/report"
},
"privateAPI": {
"tests": 1,
"assertions": 31,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7f-composition-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Realcomponent Edge/CUA:unknown inclusion indeterminate;tax100.10alreadyincluded plusaccessory50.25 produces1050.50 from1000.25;ownIVAcondition no yields notapplicable/noIVAzero;finalbothnotincluded1150.60,VATnull;save/recover/report1operation/2components/6priorversions. SyntheticQA,not manualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7f-composition-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "0bef805ede26c9878f5e040aafbd65186ddb56f2",
"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"
],
"confirmed_losses": [],
"accepted_delivery": "70b4a640/0bef805e;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared at delivery",
"frozen": "tests\\frontend\\fixtures\\iva-g7f-preserved-inputs.json",
"sha256": "6f22015f78ed08c36234b5a19ad574fbc2662d6854c1f85112e1c2bd635ec325",
"counts_before": {
"delivered": 83,
"QA": 0,
"functional_pending": 49,
"P001": 1,
"total": 133
},
"scope": "P101 only;allpreviousbooks immutable including P100normalvalue/P095TC/P094/P091/P060/P050/partialP084P085;no active query/write"
},
"runtime_delta": {
"resources/js/lib/iva-composition-base.ts": "557d6b4b5ed2c534b69e5edf43c9e4014cdfb7362bf164829cd16e4deeabbf73",
"resources/js/components/simulation-composition-base.tsx": "3507c14f15e40bf018089520a46b7e22002ddbd9bffa64d179f085b0d933ae0e",
"resources/js/components/simulation-monthly-iva.tsx": "82694be2d0a5ac097b64d68dceeda1df239bb2bf2bce193e8112d3dadad79a95",
"resources/js/lib/project-dossier.ts": "c640883680629049ea851a63e28e967a70297257a55e5d885df8e32f4b81e871"
},
"counts_current": {
"delivered": 83,
"QA": 1,
"functional_pending": 48,
"P001": 1,
"total": 133
},
"homologation_unchanged": "70b4a640",
"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-g7f-composition-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"receipt": "l1-g7f-delivery-20261024.json",
"record": "iva_l1_g7f_P101_homologation_20261024",
"counts": {
"delivered": 84,
"QA": 0,
"functional_pending": 48,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,169 @@
{
"implementation_commit": "acc633bf088c66042a8442d356076bdbb508ac53",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P102": [
"judicial_indemnity",
"granted_discount",
"third_party_payment",
"returnable_packaging"
]
},
"branch_count": 1,
"treatment_count": 4,
"source": "CIVA15(6)(a–d),2016PDF14/p1426(272);27(5)(b),PDF17/p1426(275);2022PDF3maintains15(6);2025PDF14maintains27(5)(b),amends27(10),not15;2017rectificationdoesnotamendtheseprovisions.",
"meaning": "Four exclusions:judicial indemnity for total/partial contractbreach;granteddiscount/abatement/bonus;payment inname/onaccount of purchaser/recipient recorded inappropriate thirdpartyaccounts;packaging notactuallytransacted withseparateinvoiceindication/express agreedreturnmention.",
"formula": "initialamount netofownVAT with15(5)inclusions minus only exclusions stillincluded;alreadyexcluded retained without secondsubtraction",
"technical_choices": "New considerationExclusions opportunity-scoped book,operations with nestedparts and ownconditions/references/scope. Exactdecimal up to6fractiondigits,no assumedrounding. Typechange preservesamount/reference/scope/hiddenaccounts/invoiceexcerpt butclears ownconditions. No newcertificates/approvers. References identify judicialdeclaration/contract,discountgrant,thirdpartyaccounts/recipient,invoicepackagingmention or explicit projectionassumptions.",
"scope": "2026/MZN,P102baseonly;no IVA/incidence/rate/deduction/field11/regularisations/ModeloAtotals. No automaticlegaldecision orpriorperiodposting. Packagingrequiresagreedreturnmention,notactualreturn. Unknownconditions/amount/inclusion indeterminate;failedcondition yields notapplicable,notzero;exclusionsexceedinginitialamount notnegative/flooredzero.",
"verification": {
"frontend": {
"tests": 4,
"passed": 4,
"failed": 0,
"scope": "Allfour treatments ownconditions unknown/no;judicial/contract/grant/account/recipient/invoice/scope references;subtractincludedonly/alreadyexcluded;exactdecimal/zero/excess;typechange retains hiddenvalues andclears ownconditions;corruptnestedguard;allpreviousbooks/currentkeys/history/report"
},
"privateAPI": {
"tests": 1,
"assertions": 34,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7g-exclusions-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Realcomponent Edge/CUA:judicialdeclarationunknown;discountnotgranted;thirdpartyaccountconditionunknown;packagingreturnmentionunknown allpreventexclusion. Alreadyexcluded indemnity100.10notresubtracted=>899.80. Finalallincluded:1000.25−200.55=799.70,VATnull;save/recover/report1operation/4parts/8priorversions. SyntheticQA,notmanualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7g-exclusions-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "a89f9eca8cb388512d97aebf5e2e1ff267756dd6",
"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"
],
"confirmed_losses": [],
"accepted_delivery": "7e5710eb/a89f9eca;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared at delivery",
"frozen": "tests\\frontend\\fixtures\\iva-g7g-preserved-inputs.json",
"sha256": "7bc9a3a0b2a37dbb6f342dde26c6463e2f5ce62228796e44fc0e0e213a03dfa0",
"counts_before": {
"delivered": 84,
"QA": 0,
"functional_pending": 48,
"P001": 1,
"total": 133
},
"scope": "P102only;allpreviousbooks immutable including P101/P100/P095/P094/P091/P060/P050/partialP084P085;no active query/write"
},
"runtime_delta": {
"resources/js/lib/iva-exclusion-base.ts": "2d4d2f607eb4e24e617a5640b239d14ab4958e364cc6f3cda36a407b8b1d782f",
"resources/js/components/simulation-exclusion-base.tsx": "4c69345d9e49c96756727cbf909bf1d5949fa9db14c346157413dd1885258520",
"resources/js/components/simulation-monthly-iva.tsx": "81be9e69aeab5d544a2fb8aadcf487bb6f04ae0ab06861759709912afe9c82bf",
"resources/js/lib/project-dossier.ts": "af10643db841e08f14a9ef534ccf7367fe5b05e20c58b770e3a4cf51aa0192e8"
},
"counts_current": {
"delivered": 84,
"QA": 1,
"functional_pending": 47,
"P001": 1,
"total": 133
},
"homologation_unchanged": "7e5710eb",
"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-g7g-exclusions-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "5d5f3b414866969e4b2d38376402b8f264c6d19c",
"receipt": "l1-g7g-delivery-20261024.json",
"record": "iva_l1_g7g_P102_homologation_20261024",
"counts": {
"delivered": 85,
"QA": 0,
"functional_pending": 47,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,171 @@
{
"implementation_commit": "67b8b5814955ebce761b2123969958c9f2c8bf0f",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P103": [
"price_comparison",
"referenced_correction"
]
},
"branch_count": 1,
"treatment_count": 2,
"source": "CIVA15(7),2016PDF14/p1426(272),15(1)/(5)/(6);2022PDF3maintains15(7);2025doesnotamend15;2017rectificationdoesnotamend15(7).",
"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"
},
"technical_choices": "New valueReviews opportunity-scoped book in existingmodelo_a_snapshot/API/dossier;exactdecimal up to6fractiondigits,no assumedrounding. Context/percourse/origin changes preserve values/references butclear affected confirmation;projected→effective cannotreuse assumedcorrectionconfirmation. No newcertificates/appraisers/approvers. Currentkeys/history/immutableinputs/report retained.",
"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.",
"verification": {
"frontend": {
"tests": 4,
"passed": 4,
"failed": 0,
"scope": "Allfourpricecontexts;ownconditions/references;below/equal/above;no automaticreference substitution;correctionamount/ref/date/scope/application;projected/effective distinction;exactdecimal/zero;context/percourse/originswitch retention/clearedconfirmation;oldbooks/currentkeys/history/report;corruptwriteguard"
},
"privateAPI": {
"tests": 1,
"assertions": 33,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7h-value-review-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Realcomponent Edge/CUA:pricereference/missingcorrectedamount indeterminate;comparisonbelow retains1000.25 against1500.50;projected→effective clearsapplicationconfirmation;outofscope no preventsapplication;returnprojected/confirmed producesconditional1400.75,not1500.50. Save/recover/report2rows+5priorversions,VATnull. SyntheticQA,notmanualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g7h-value-review-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "adb849d4fc6d840eec1123e8fc90c4c34a008da4",
"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"
],
"confirmed_losses": [],
"accepted_delivery": "5d5f3b41/adb849d4;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared at delivery",
"frozen": "tests\\frontend\\fixtures\\iva-g7h-preserved-inputs.json",
"sha256": "d2e25976ee432238fa90791db01c124f24c0cfb805e213af73d4c7dab4f25f31",
"counts_before": {
"delivered": 85,
"QA": 0,
"functional_pending": 47,
"P001": 1,
"total": 133
},
"scope": "P103only;allpreviousbooks immutable including P102/P101/P100/P095/P060/P050/partialP084P085;no active query/write"
},
"runtime_delta": {
"resources/js/lib/iva-value-review.ts": "411aa0506868afd112bac0e27571db1978b21bd8375051dc36abbe55dfad7876",
"resources/js/components/simulation-value-review.tsx": "ff3fc2ad0e0082a931341ae51b63d6abe2bfee00b90e5891fc4dce742e84a017",
"resources/js/components/simulation-monthly-iva.tsx": "c7f6a45a8533f6ce4128c912511b7712011fc365b99dfbe675d6cb2b455dfca1",
"resources/js/lib/project-dossier.ts": "89ee4a4abfa36c4d159edd71c936d718e2a6e99c9c8a83be669451fb309c5d2c"
},
"counts_current": {
"delivered": 85,
"QA": 1,
"functional_pending": 46,
"P001": 1,
"total": 133
},
"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",
"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,170 @@
{
"implementation_commit": "90b31c677f9f541364a2fdddc98d01280d4371f1",
"status": "delivered_with_QA_proofs_preserved",
"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",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"receipt": "l1-g7i-delivery-20261024.json",
"record": "iva_l1_g7i_P089_homologation_20261024",
"counts": {
"delivered": 87,
"QA": 0,
"functional_pending": 45,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,189 @@
{
"implementation_commit": "ec33fb5be2934f34d06349b84bf8e5316f90960e",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P106": [
"general_service"
],
"AUD-SIM-L1-P107": [
"immovable_service"
],
"AUD-SIM-L1-P108": [
"movable_work"
],
"AUD-SIM-L1-P109": [
"activity_service"
],
"AUD-SIM-L1-P110": [
"transport_service"
]
},
"branch_count": 5,
"treatment_count": 5,
"QA_example_count": 10,
"source": "CIVA6(3),6(4)/(5)a–d,6(6),Lei13/2016 PDF7–8/p1426(265–266);Aviso BR89-I,de08/06/2017,PDF1,rectifica expressamente6(5)c/d:actividades nacionais e transporte pela distância nacional;Lei10/2025 PDF12mantém6(3–6),altera7–9digitais.",
"meaning": {
"P106": "Sede/EP/domicílio do prestador a partir do qual o serviço é prestado,sem regras especiais aplicáveis. Não usar endereço/nacionalidade do cliente.",
"P107": "Local do imóvel e relação do serviço,incluindo preparação/coordenação de trabalhos imobiliários,peritos/agentes. Independente da sede do prestador.",
"P108": "Execução total ou essencial dos trabalhos/peritagens em bens móveis corpóreos. Independente da sede do prestador.",
"P109": "Local material de actividades artísticas,científicas,desportivas,recreativas,ensino/similares,organizadores e serviços acessórios;6(5)c rectificado2017.",
"P110": "Distância nacional6(5)d rectificada2017;partida/chegada nacionais incluem percurso fora do país6(6);ida/volta são dois trajectos. Identificar distância total/nacional na mesma unidade,sem apuramento monetário."
},
"formula": "Territorial classification only;P110 exact distances retained as numerator/denominator with6(6)deemednational override,no monetaryapportionment/rounding.",
"scope": "Recorte2026,classificação territorial de serviços por factos próprios;sem base,taxa,IVA,isenção,dedução/campo11 ou totaisModeloA. Digital/outros6(7)/(8)exigem percursos próprios,não classificados automaticamente. P002transversal não encerrado.",
"technical_choices": "NewserviceLocations opportunity-scoped book in existingmodelo_a snapshot/API/dossier;no schema/permissions. Switch preserveshiddenrefs/locations/routes but clearsownconditions,keepscommon. Decimaldistance up to18integer/6fractiondigits,BigInt comparison,no float/no assumedzero. References or explicitprojectedassumptions reused,no certificates/approvers invented.",
"verification": {
"frontend": {
"tests": 7,
"passed": 7,
"failed": 0,
"by_branch": {
"AUD-SIM-L1-P106": "own conditions unknown/no,dates/references,domestic/foreign cases passed",
"AUD-SIM-L1-P107": "own conditions unknown/no,dates/references,domestic/foreign cases passed",
"AUD-SIM-L1-P108": "own conditions unknown/no,dates/references,domestic/foreign cases passed",
"AUD-SIM-L1-P109": "own conditions unknown/no,dates/references,domestic/foreign cases passed",
"AUD-SIM-L1-P110": "own conditions unknown/no,dates/references,domestic/foreign cases passed"
},
"additional": "Preservation of all oldbooks includingP105 and partialP084/P085;switch hiddenretention/ownconditions reset;scope/history/report;transport mixed route,deemed national route,zero vs unknown,invalid/decimal exact distances."
},
"privateAPI": {
"tests": 1,
"assertions": 48,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g8-services-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Realcomponent Edge/CUA:unknown providercountry makesP106 indeterminate;restoration producesnational. P110 departureMZ/arrivalforeign yieldsnationalportion80.25of100.50. Saved/recovered/report10rows+3previousversions across5branches;VAT/base/rate alwaysnull. SyntheticQA,notmanualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g8-services-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "aac3f463067e9178e15219262027fcb976566a2a",
"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-P089",
"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",
"AUD-SIM-L1-P105"
],
"confirmed_losses": [],
"accepted_delivery": "8f14f5dd/aac3f463;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared",
"frozen": "tests\\frontend\\fixtures\\iva-g8-services-preserved.json",
"sha256": "bed8a17fc6bf961dc15eccc46a8c336270752728470cf196cb2c2c901085c186",
"scope": "P106–109 QA only;P105 and all previous books/history immutable;no active writes"
},
"runtime_delta": {
"resources/js/lib/iva-service-location.ts": "abf13bd0f6f8aed209b38f3fd8d5906b96572de2d13f87b0d742ee3f31095a19",
"resources/js/components/simulation-service-location.tsx": "ede4923dc4343949821cdd1c540837261cf816afee3069d031053cac73da5339",
"resources/js/components/simulation-monthly-iva.tsx": "dd102e122a243f58c85db0dcde889877066c5aac9c873eb0f8f93905a6d0d848",
"resources/js/lib/project-dossier.ts": "03bfad1ac2a443ee4fd0a7c0091f5b3e34e17a9c8b2b75d1249ac0c96729d643"
},
"counts_current": {
"delivered": 88,
"QA": 5,
"functional_pending": 39,
"P001": 1,
"total": 133
},
"homologation_unchanged": "8f14f5dd",
"remaining": "One jointGit integration/delivery forfivecompatiblebranches,one backup/realrestore,individualQAproofsreused,installeddelta only. No individualbranch deployment.",
"limits": "P084/P085partial,pending;L1open;P00105/06;beveragesL2/L3;Statistics/AIdeferred",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g8-services-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"receipt": "l1-g8-services-delivery-20261024.json",
"record": "iva_l1_g8_services_P106_P110_homologation_20261024",
"counts": {
"delivered": 93,
"QA": 0,
"functional_pending": 39,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,171 @@
{
"implementation_commit": "0682ef74e2e1523d5a424b92989de39122677898",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P105": [
"goods_with_transport",
"goods_without_transport",
"goods_before_import"
]
},
"branch_count": 1,
"treatment_count": 3,
"source": "CIVA6(1)/(2),Lei13/2016 PDF7/p1426(265);Lei10/2025 PDF12 mantém1/2 e altera7–9 digitais.",
"meaning": "Local dos bens no início transporte/expedição ou,sem transporte,quando postos à disposição;regra especial do importador/transmissões subsequentes antes da importação nacional. Fora do território não equivale a isenção ou IVA zero.",
"formula": "Classificação territorial pelos factos6(1)/(2),sem cálculo monetário.",
"scope": "2026,bens corpóreos;classificação territorial apenas,sem base,taxa,IVA,isenção,dedução/campo11,direitos ou totaisModeloA. Não abrange digitais/serviços por esta regra.",
"technical_choices": "Livro goodsLocations por oportunidade no snapshot/API/dossier existente;sem schema/permissões. Troca conserva locais/referências ocultos e limpa condições próprias;dados e documentos reutilizáveis ou pressupostos expressos,sem certificados/aprovadores inventados.",
"verification": {
"frontend": {
"tests": 4,
"passed": 4,
"failed": 0,
"scope": "Três percursos,condições desconhecidas/não,referências/datas,local físico e regra6(2),endereço/moeda não determinam território,troca conserva dados ocultos/limpa condições próprias,gravação/histórico/relatório e livros anteriores preservados."
},
"privateAPI": {
"tests": 1,
"assertions": 30,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g8a-goods-location-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Edge/CUA componente real:local desconhecido produz indeterminado;restauradoMZ,gravação/recuperação/relatório confirmam national/outside/national,IVA/base/taxa null,3linhas e4versões anteriores. Dados sintéticos,não aceitação manualTempo.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g8a-goods-location-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "21ce03f65ced0047ae7143e47c76f250b20029d6",
"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-P089",
"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": "6f1cf7b7/21ce03f6;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared at delivery",
"frozen": "tests\\frontend\\fixtures\\iva-g8a-preserved-inputs.json",
"sha256": "7b0b553abaeb83d891064cedb65ccddc730caac27a227ae2046aa3e4f5d75538",
"counts_before": {
"delivered": 87,
"QA": 0,
"functional_pending": 45,
"P001": 1,
"total": 133
},
"scope": "P105only;allpreviousbooks immutable including P089/P103/P102/P101/P095/P060/P050/partialP084P085;no active query/write"
},
"runtime_delta": {
"resources/js/lib/iva-goods-location.ts": "c187bbaf13d408461e787786dc8cc81504fef6ed60a848f62ebffe31cfa86e6d",
"resources/js/components/simulation-goods-location.tsx": "e4440c1315a1b1009d9b51ced99d7e6a2fc65a3ebac05d6b5bde1d41a796784f",
"resources/js/components/simulation-monthly-iva.tsx": "ca7c2185d9fcf8ffc8374be4a99d3102c7e1326372859ac678603da90b3de913",
"resources/js/lib/project-dossier.ts": "c95bbd7e307ab2c7dcec42fc9d280709f0ecb7c9be174977ae571cc4447bf5b9"
},
"counts_current": {
"delivered": 87,
"QA": 1,
"functional_pending": 44,
"P001": 1,
"total": 133
},
"homologation_unchanged": "6f1cf7b7",
"remaining": "Integrar/disponibilizar pelo processoGit existente com manifesto,backup/restauro e delta instalado;sem push nesta tarefaQA.",
"limits": "P084/P085 parciais e pendentes;L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g8a-goods-location-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"receipt": "l1-g8a-delivery-20261024.json",
"record": "iva_l1_g8a_P105_homologation_20261024",
"counts": {
"delivered": 88,
"QA": 0,
"functional_pending": 44,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,264 @@
{
"implementation_commit": "6cffa1188f8f0f43d8d161cf97b7a08a885055f6",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P111": [
"rights_service"
],
"AUD-SIM-L1-P112": [
"advertising_service"
],
"AUD-SIM-L1-P113": [
"telecom_service"
],
"AUD-SIM-L1-P114": [
"consulting_service"
],
"AUD-SIM-L1-P115": [
"data_service"
],
"AUD-SIM-L1-P116": [
"finance_service"
],
"AUD-SIM-L1-P117": [
"staff_service"
],
"AUD-SIM-L1-P118": [
"intermediation_service"
],
"AUD-SIM-L1-P119": [
"abstention_service"
],
"AUD-SIM-L1-P120": [
"movable_lease_service"
]
},
"branch_count": 10,
"treatment_count": 10,
"QA_example_count": 30,
"source": "CIVA2(1)a/b,2(2),6(3),6(7)a–j e6(8),Lei13/2016PDF6–8/p1426(264–266);23(1)/(2),25(4),26(1–3),PDF16–17. Lei22/2022não altera estes artigos. Lei10/2025PDF12mantém alíneasa–j ealtera6(7–9);PDF13art23(2)excluik e remete declaração33(2);PDF14mantém26(1–3),adita26(4)digital ealtera33(2).",
"meaning": {
"P111": {
"clause": "6(7)a",
"treatment": "rights_service",
"nature": "Cessão/autorização de direitos de autor,licenças,marcas e análogos"
},
"P112": {
"clause": "6(7)b",
"treatment": "advertising_service",
"nature": "Publicidade"
},
"P113": {
"clause": "6(7)c",
"treatment": "telecom_service",
"nature": "Telecomunicações"
},
"P114": {
"clause": "6(7)d",
"treatment": "consulting_service",
"nature": "Consultores,engenheiros,advogados,economistas,contabilistas/gabinetes de estudos,organização,investigação/desenvolvimento e similares"
},
"P115": {
"clause": "6(7)e",
"treatment": "data_service",
"nature": "Tratamento de dados/fornecimento de informações"
},
"P116": {
"clause": "6(7)f",
"treatment": "finance_service",
"nature": "Operações bancárias,financeiras,seguro/resseguro;eventual isenção independente"
},
"P117": {
"clause": "6(7)g",
"treatment": "staff_service",
"nature": "Colocação de pessoal"
},
"P118": {
"clause": "6(7)h",
"treatment": "intermediation_service",
"nature": "Intermediação em nome epor conta de outrem no fornecimento de serviço enumerado,subjacente identificado"
},
"P119": {
"clause": "6(7)i",
"treatment": "abstention_service",
"nature": "Obrigação de não exercer,mesmo parcialmente,actividade/direito enumerado,subjacente identificado"
},
"P120": {
"clause": "6(7)j",
"treatment": "movable_lease_service",
"nature": "Locação de bens móveis corpóreos,incluindo financeira,bens/contrato identificados"
}
},
"routes": {
"inbound": "Prestador semsede/EP/domicílio nacional a partir do qual presta;adquirente2(1)a/b comEP/domicílio nacional,incluindo exclusivamente isentos semdedução:territórionacional6(7),responsáveladquirente2(2)/23(2),declaração33(2)nos termosa regulamentar;sem pressupor montante/imposto devido.",
"outbound": "Adquirente estabelecido/domiciliado noestrangeiro:6(8)forado âmbitonacional,ainda que prestadortenha sede/EP/domicílio nacional;não isenção/IVAzero nem imposto estrangeiro presumido. Qualidadea/b oculta/conservada,não imposta aestepercurso.",
"domestic": "Prestador nacional apartirdo qualpresta eadquirentenacional,sem regraspróprias:6(3);qualidade prestadorSP/regimegeral ereferência permite identificarprestador23(1),casocontrário responsávelindeterminado sem apagarclassificaçãoterritorial."
},
"formula": "Territorial classification and responsible party only,no monetarycalculation. No righttodeduction prerequisite for6(7);nondigital23(2)excludedigital26(4)/32(1)c routing.",
"scope": "2026,serviços enumerados não digitais;localização e identificação do responsável pelas obrigações. Sem isenção confirmada,base,taxa,IVA,montante a pagar,dedução/campo11 ou totaisModeloA. P121/P130digitais eP002transversal não fechados;outros6(4)/(5)encaminhados para percursos próprios. Não automatiza declaração,pagamento,retenção ou prazo digital32(1)c.",
"technical_choices": "NewlistedServices opportunity-scoped book in existingmodelo_a snapshot/API/dossier;no schema/permissions. Switchpreserveshiddenparty/quality/targetrefs andclearsownconditions,keepscommon. References or explicitprojectedassumptions reused,no certificates/approvers invented. Requiredfactualrefs explainruleapplication,not provenance revalidation.",
"verification": {
"frontend": {
"tests": 12,
"passed": 12,
"failed": 0,
"by_branch": {
"AUD-SIM-L1-P111": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P112": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P113": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P114": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P115": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P116": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P117": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P118": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P119": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed",
"AUD-SIM-L1-P120": "Ownnature,unknown/no,three routes,quality a/b/other,exemptwithoutdeduction allowed,dates/references and separate responsible passed"
},
"additional": "P118/P119 underlyingclauses/refs,selfreference/digitaltarget guard;switchretains hiddenrefs andclearsownconditions;alloldbooks immutable,currentkeys/history/report/corruptwrites."
},
"privateAPI": {
"tests": 1,
"assertions": 109,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g9-nondigital-20261024\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Realcomponent Edge/CUA:recipientqualityunknown andP118underlyingclauseunknown make resultsindeterminate;switch buyerforeign applies6(8)andhidesquality,returnMZ restoresunknown qualityandoriginalref;restorea/subjclause then save/recover/report30rows+4previousversions. VAT/base/ratealwaysnull,responsible acquirer/outside/provider. SyntheticQA,notmanualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g9-nondigital-20261024\\qa-recovered-report.png"
},
"preservation": {
"base": "4853bc7284d3ed3b1fbafa403fd8406705ac3165",
"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-P089",
"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",
"AUD-SIM-L1-P105",
"AUD-SIM-L1-P106",
"AUD-SIM-L1-P107",
"AUD-SIM-L1-P108",
"AUD-SIM-L1-P109",
"AUD-SIM-L1-P110"
],
"confirmed_losses": [],
"accepted_delivery": "03c26d66/4853bc72;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared",
"frozen": "tests\\frontend\\fixtures\\iva-g9-nondigital-preserved.json",
"sha256": "3132adfbbbcde4b2d8c7c7c657dfb38f743d7994650b78bab4931c443eaab628",
"scope": "P111–P120QA;all priorbooks/history includingP105–110 andpartialP084/P085 immutable;no activewrites"
},
"runtime_delta": {
"resources/js/lib/iva-listed-services.ts": "fdc05407576a6c68f8158bc797331380c09e84282609a06ae2a7aa2966c54db6",
"resources/js/components/simulation-listed-services.tsx": "77badfa54c3bb6e25fe5153bb852cebc48262b64b4aabc9348a2b1838094917a",
"resources/js/components/simulation-monthly-iva.tsx": "43446ed6a23b0e101d72ea50f73cdbae0242ace92af12d836a0955cc85800d82",
"resources/js/lib/project-dossier.ts": "fea39f530bf7786778dbdadbb6b08678f2a4071bcccc264e3d026155477517c8"
},
"counts_current": {
"delivered": 93,
"QA": 10,
"functional_pending": 29,
"P001": 1,
"total": 133
},
"homologation_unchanged": "03c26d66",
"remaining": "OnejointGit integration/delivery for tencompatiblebranches,onebackup/realisolatedrestore,individualQAproofsreused,installeddeltaonly. No individualbranch deployment.",
"limits": "P084/P085partial,pending;L1open;P00105/06;beveragesL2/L3;Statistics/AIdeferred",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-g9-nondigital-20261024\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"receipt": "l1-g9-nondigital-delivery-20261024.json",
"record": "iva_l1_g9_nondigital_P111_P120_homologation_20261024",
"counts": {
"delivered": 103,
"QA": 0,
"functional_pending": 29,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,198 @@
{
"implementation_commit": "9b95e5e7a8d129d6256f8df1b62423b8a94c4477",
"status": "delivered_with_QA_proofs_preserved",
"coverage": {
"AUD-SIM-L1-P088": [
"permanent_private_goods",
"free_goods_transfer",
"exempt_sector_goods",
"fixed_asset_20a"
],
"AUD-SIM-L1-P124": [
"permanent_private_goods",
"free_goods_transfer",
"exempt_sector_goods",
"fixed_asset_20a"
]
},
"branch_count": 2,
"treatment_count": 4,
"shared_operations_not_double_counted": true,
"source": "CIVA3(3)e/f,Lei13/2016PDF6–7/p1426(264–265);15(2)b,PDF13/p1426(271);20(1)a,PDF15/p1426(273). Lei22/2022PDF3mantém15(2)b e20(1)a;Lei10/2025PDF12mantém3(3)e/f e não altera15/20.",
"meaning": {
"P124": "Classificação da afectação permanente de bens a uso próprio/particular/alheio,transmissão gratuita,afectação a sector isento ou aoactivo imobilizado de bens20(1)a. Exige dedução anterior total/parcial nos bens/elementos;em3e conferir excepção de amostras/ofertas depequeno valor,sem limiar inventado. Facto histórico de dedução,não nova dedução.",
"P088": "Base15(2)b:preço aquisição ou,na sua falta demonstrada,preço custo,reportados ao momento da operação. ClassificaçãoP124 pode estar identificada ebaseP088 indeterminada;sem custo por defeito para preço aquisição desconhecido."
},
"formula": "15(2)b:current acquisitionprice;only if absent,currentcost.No automaticvaluation/update/depreciation/deduction.",
"scope": "2026/MZN,quatro tratamentos partilhados entre dois requisitos sobre a mesma operação,registada uma vez. Distinto de uso temporário de bens como serviçoP089. Sem nova dedução/campo11,regularização,taxaIVA,IVA ou totaisModeloA;dedução anterior apenas facto histórico. Excepçãoamostras/ofertas fica fora deste percurso quando aplicável;desconhecido permanece indeterminado.",
"technical_choices": "NewregulatedGoodsAllocations opportunity-scoped book in existingmodelo_a snapshot/API/dossier;oneoperation jointlycoversP124facts/P088base,no duplicatedentry/aggregation. Switchretains hiddenprices/refs andrequiresreviewownfacts/valuation. Money15integer/6fractiondigits,BigInt,no float/rounding. Existingrefs or explicitassumptions,no certificates/approvers/newthresholds. valuationDate meansmomenttowhichpriceisreported,not compulsorynewdocumentissue date.",
"verification": {
"frontend": {
"tests": 7,
"passed": 7,
"failed": 0,
"by_treatment": "Four ownfact paths,priorDeduction unknown/no,scope/refs/date,exactcurrent acquisition/cost and no VAT",
"additional": "P124classification separatedfromP088missingbase;costfallback requires explicitabsence ofacquisitionprice,currentmoment,date/scope;switchretains hiddenprices/refs andclearsconfirmations;zero vsunknown;allpreviousbooks/history/report/corruptwriteguards"
},
"privateAPI": {
"tests": 1,
"assertions": 27,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-goods-allocation-20261025\\api-tests.xml"
},
"types": "passed",
"build": "passed,existing plugin timing warnings",
"UI": "Edge/CUArealcomponent:acquisitionabsenceunknown retainsassimilatedclassification butcostbaseindeterminate;priorDeductionunknown makesclassificationindeterminate;restorefacts,saved/recovered/report4operations1000.25/800.15/1000.25/800.15MZN and4previousversions,VAT/ratenull. SyntheticQA,notmanualTempoacceptance.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-goods-allocation-20261025\\qa-recovered-report.png"
},
"preservation": {
"base": "1b67fa85ff91174a45c171a6cf6af821727acca5",
"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-P089",
"AUD-SIM-L1-P090",
"AUD-SIM-L1-P091",
"AUD-SIM-L1-P094",
"AUD-SIM-L1-P095",
"AUD-SIM-L1-P096",
"AUD-SIM-L1-P097",
"AUD-SIM-L1-P098",
"AUD-SIM-L1-P099",
"AUD-SIM-L1-P100",
"AUD-SIM-L1-P101",
"AUD-SIM-L1-P102",
"AUD-SIM-L1-P103",
"AUD-SIM-L1-P105",
"AUD-SIM-L1-P106",
"AUD-SIM-L1-P107",
"AUD-SIM-L1-P108",
"AUD-SIM-L1-P109",
"AUD-SIM-L1-P110",
"AUD-SIM-L1-P111",
"AUD-SIM-L1-P112",
"AUD-SIM-L1-P113",
"AUD-SIM-L1-P114",
"AUD-SIM-L1-P115",
"AUD-SIM-L1-P116",
"AUD-SIM-L1-P117",
"AUD-SIM-L1-P118",
"AUD-SIM-L1-P119",
"AUD-SIM-L1-P120",
"AUD-SIM-L1-P122",
"AUD-SIM-L1-P128"
],
"confirmed_losses": [],
"accepted_delivery": "63cc3367/1b67fa85;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared",
"frozen": "tests\\frontend\\fixtures\\iva-goods-allocation-preserved.json",
"sha256": "724929bfda23475531c373f2bf5a88951c192e7ecb930e1d38249d6e2cbefd14",
"scope": "P088/P124QA;all priorbooks/history includingP105–110 andpartialP084/P085 immutable;no activewrites"
},
"runtime_delta": {
"resources/js/lib/iva-goods-allocation.ts": "6646a2054ebd4e6731b60719d36ce922ed50f2e062e0f980190eb20ce8c23d20",
"resources/js/components/simulation-goods-allocation.tsx": "08c84f4b9af21e46cd9d5af6f6bee9e12c14b111438f1649a694a27f36d14180",
"resources/js/components/simulation-monthly-iva.tsx": "1b27e8d3a6c79c6f8769bf5158ed8be45718f655b13cdf23b517bdb44c5a6951",
"resources/js/lib/project-dossier.ts": "c5de565ff7ded1fcf4d1f3a025694d3e2af4ff75e55266463758e8c1c5fcc314"
},
"counts_current": {
"delivered": 109,
"QA": 2,
"functional_pending": 21,
"P001": 1,
"total": 133
},
"homologation_unchanged": "63cc3367",
"remaining": "OnejointGit delivery forP088/P124,freshbackup/realisolatedrestore,acceptedQA reused,installeddeltaonly. No individualbranch deployment.",
"limits": "L1open;newdeduction/regularisationoutsideincrement;P00105/06;P121digital/P084/P085pending;beveragesL2/L3;Statistics/AIdeferred",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-goods-allocation-20261025\\source-archive-inventory.json",
"qa_status_preserved": "QA_complete_not_delivered",
"delivery_followup": {
"served_commit": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"receipt": "l1-goods-allocation-delivery-20261025.json",
"record": "iva_l1_goods_allocation_P088_P124_homologation_20261025",
"counts": {
"delivered": 111,
"QA": 0,
"functional_pending": 21,
"documentary": 1,
"total": 133
}
}
}
@@ -0,0 +1,188 @@
{
"implementation_commit": "b0818c01633ed7eab7240fcec5fa4a0a87c15104",
"status": "QA_complete_not_delivered",
"coverage": {
"AUD-SIM-L1-P092": [
"reseller_margin"
],
"AUD-SIM-L1-P093": [
"auction_margin"
],
"AUD-SIM-L1-P125": [
"used_goods",
"art",
"collection",
"antique"
]
},
"branch_count": 3,
"treatment_count": 2,
"category_count": 4,
"QA_example_count": 8,
"shared_operations_not_double_counted": true,
"source": "CIVA Lei13/2016:3(3)g/3(6),PDF7,p1426(265);15(2)f/g,PDF13,p1426(271). RIVA Decreto7/2008,BR16-I de16/04/2008,arts47–49,PDF8–9,p106–107. Lei22/2022 PDF3 mantém15f/g e fixa17(1)16%. Lei10/2025 não altera15/17 e revoga regimes35/42;referência antiga não os reactiva. Rectificação2017 sem alteração destas disposições.",
"meaning": {
"P092": "Revendedor: margem individual positiva da contraprestação total com IVA menos preço de compra justificado; dividir por 1.16 e arredondar a base à unidade. Perda conservada no bem, sem compensação entre transmissões. Opção pelo regime normal fica separada.",
"P093": "Organizador em nome próprio por conta do comitente, contrato de comissão e venda em leilão: base = facturado ao comprador menos líquido do comitente menos IVA próprio identificado. Líquido = adjudicação menos comissão. IVA desconhecido não é zero.",
"P125": "Classificação própria: bem usado reutilizável, arte, colecção ou antiguidade superior a 100 anos; critérios de 3(6) conservados. Categoria identificada não activa automaticamente a margem. Tiragem limitada a 200 exemplares e cerâmica única executada/assinada pelo artista nos percursos respectivos."
},
"scope": "2026/MZN,transmissões internas tributáveis e aquisição nacional com qualidade do fornecedor/comitente demonstrada. Duas fórmulas, quatro categorias, oito exemplos e três ramos; uma operação individual, sem dupla contagem. Apenas classificação/base:sem IVA calculado,nova dedução,campo11,regularização ou totaisModeloA. IVA identificado no leilão é componente referenciada. Exportação isenta e opção normal separadas; origens legadas35/42 permanecem indeterminadas.",
"technical_choices": "regulatedSecondhands por oportunidade no snapshot/API/dossier existentes;BigInt com6casas,sem float;arredondamento à unidade mais próxima,empate para cima como escolha técnica explícita;troca conserva campos/referências e exige rever confirmações.Nenhum certificado/aprovador inventado. Prazo49(6)/(7) de5dias úteis identificado,sem calendário de feriados presumido.",
"verification": {
"frontend": {
"tests": 11,
"passed": 11,
"failed": 0,
"coverage": "8 combinações regime/categoria;ausência de factos/referências;opção normal;origem nacional/elegibilidade;limites de tiragem/idade;perdas/arredondamento;trocadecategoria;persistência,histórico,relatório e preservação integral"
},
"privateAPI": {
"tests": 1,
"assertions": 35,
"target": "simulator_fiscal_delta_20261021_test:55441",
"transaction_rollback": true,
"xml": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-secondhand-20261025\\phpunit.xml"
},
"types": "passed",
"build": "passed;existing plugin timing warnings",
"UI": "Edge/CUA,componente real:preço compra vazio mantém classificação mas base indeterminada;venda900/compra1000 conserva perda100 ebase0semcompensaroutrosbens;restauro1160/1000base138;gravação/recuperação/relatório8operações,4versõesanteriores,bases138.00x4/344.83x4,IVA/taxanull. Dados sintéticos,não aceitação manual da Tempo.",
"UI_screenshot": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-secondhand-20261025\\qa-recovered-report.png"
},
"preservation": {
"base": "ec786f4ae2eb25d9a21cdc46dc883efcf8fb8c02",
"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-P088",
"AUD-SIM-L1-P089",
"AUD-SIM-L1-P090",
"AUD-SIM-L1-P091",
"AUD-SIM-L1-P094",
"AUD-SIM-L1-P095",
"AUD-SIM-L1-P096",
"AUD-SIM-L1-P097",
"AUD-SIM-L1-P098",
"AUD-SIM-L1-P099",
"AUD-SIM-L1-P100",
"AUD-SIM-L1-P101",
"AUD-SIM-L1-P102",
"AUD-SIM-L1-P103",
"AUD-SIM-L1-P105",
"AUD-SIM-L1-P106",
"AUD-SIM-L1-P107",
"AUD-SIM-L1-P108",
"AUD-SIM-L1-P109",
"AUD-SIM-L1-P110",
"AUD-SIM-L1-P111",
"AUD-SIM-L1-P112",
"AUD-SIM-L1-P113",
"AUD-SIM-L1-P114",
"AUD-SIM-L1-P115",
"AUD-SIM-L1-P116",
"AUD-SIM-L1-P117",
"AUD-SIM-L1-P118",
"AUD-SIM-L1-P119",
"AUD-SIM-L1-P120",
"AUD-SIM-L1-P122",
"AUD-SIM-L1-P124",
"AUD-SIM-L1-P128"
],
"confirmed_losses": [],
"accepted_delivery": "6c12aabb/ec786f4a;174tables/369files;29published/28relations/408geometries;code/schema/data/config/permissions compared",
"frozen": "tests\\frontend\\fixtures\\iva-secondhand-preserved.json",
"sha256": "f3616dc0b3a333128d08679e0e0949fa3cc425290db8e46bd4f563198f7f8e07",
"scope": "P092/P093/P125QA;all priorbooks/history includingP105–110 andpartialP084/P085 immutable;no activewrites"
},
"runtime_delta": {
"resources/js/lib/iva-secondhand.ts": "de9cab0f8685c0be1072ce0b8b5ae98865383fa52f4487ecb62514ddb28d6fdc",
"resources/js/components/simulation-secondhand.tsx": "7a715a05635137d3b7b8a1eb3d554646c4553430904613235199fc6a254cec20",
"resources/js/components/simulation-monthly-iva.tsx": "338d5c4b9b60b2be6b3f059c543c92127222f621424854cba9a19651d86d2967",
"resources/js/lib/project-dossier.ts": "fe0b12b2acc5d1a59c862abf6c96e2e09c51193fc2e090e475dc0ec8673e23c9"
},
"counts_current": {
"delivered": 111,
"QA": 3,
"functional_pending": 18,
"P001": 1,
"total": 133
},
"homologation_unchanged": "6c12aabb",
"remaining": "Uma entrega conjunta P092/P093/P125 pelo processoGit;backup/restauro isolado fresco e conferência apenas do delta instalado,reutilizando estas provas.",
"limits": "L1aberto;P00105/06;P121digital/P084/P085pendentes;bebidasL2/L3;Estatísticas/IAadiadas",
"sources_inventory": "C:\\laragon\\www\\portal-investidor\\outputs\\iva-l1-secondhand-20261025\\source-archive-inventory.json"
}
@@ -0,0 +1,323 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "af7d2503207c8744cdbb6d96b8cca89fa367384e",
"base_installed": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"coverage_complete_branches": {
"AUD-SIM-L1-P122": [
"goods_sale_commission",
"goods_purchase_commission"
],
"AUD-SIM-L1-P128": [
"service_sale_mandate",
"service_purchase_mandate"
]
},
"branch_count_complete": 2,
"treatment_count": 4,
"runtime_delta": [
{
"path": "resources/js/lib/iva-own-name.ts",
"sha256_LF": "c36509de24d31d747d91630a31ce7d72baa749e9928b718a944556348fc54f85"
},
{
"path": "resources/js/components/simulation-own-name.tsx",
"sha256_LF": "6e142242aa29ae07e36b4d8d0be7d78f770d701e0a92e1a6e9832fcb794c17cf"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "9718dc440aa98497011775d8bd03049d7857fa3badf27f4467d6d434f642defd"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "099dc307a86c763a9509516f6d59cc5c454b1f81189cc04b919d8d6045baf9dc"
}
],
"counts_before": {
"delivered": 107,
"QA": 2,
"functional_pending": 23,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 109,
"QA": 0,
"functional_pending": 23,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 109,
"QA": 0,
"functional_pending": 23,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g10-own-name-qa-20261025.json"
],
"authorization": "Tempo explicitly requests one joint delivery ofaf7d2503,P122/P128,main compatibility/concurrent changes preserved,installeddelta only",
"scope": "2026,circuitos emnome próprio,partes/contratos/objectos econtraprestações originais das duas relações. Sem soma/compensação automática,base tributável nova,localização,isenção,taxa,IVA,dedução/campo11 ou totaisModeloA. Sem conversão cambial;moeda original identificada e coerente com contexto. P091preservado,sem repetir aceitação/cálculo.",
"source": "CIVA3(3)c,Lei13/2016PDF6/p1426(264);4(3),PDF7/p1426(265). Lei22/2022não altera3/4;Lei10/2025PDF12mantém3(3)c e não altera4. Base15(2)e/P091já entregue permanece independente;sem nova aplicação da base neste incremento.",
"meaning": {
"P122": "Transferências de bens em execução de contrato de comissão,incluindo consignação;na venda comissário considerado comprador,na compra comitente considerado comprador. Venda:comitente→comissário→terceiro;compra:terceiro→comissário→comitente. Contraprestações e referências das duas relações separadas.",
"P128": "Serviço efectuado por intervenção de mandatário emnome próprio:mandatário considerado adquirente eprestador sucessivamente4(3). Venda/prestação:mandante→mandatário→terceiro;compra/aquisição:terceiro→mandatário→mandante. Não é mera intermediação emnome de outrem ou base15(2)e de bens."
},
"formula": "Classifytwo successive relations bykind/direction;keep eachoriginalconsideration separate;no monetaryaggregation or taxcalculation.",
"preservation": "107prior closures and partialP084/P085 preserved;accepted perbranchQA reused;one integration/backup/real isolatedrestore/check for whole set",
"partial_P084_P085": "Preparation/conditional simulation only,benefits pending;no closure",
"limits": "L1open;deductionoutsideincrement;P00105/06;P121digital/P084/P085pending;beveragesL2/L3;Statistics/AIdeferred",
"containment": "l1-g10-own-name-readonly-rollback-20261025.patch,checked only,not applied;blocks newP096–099classifications,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"release": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"previous_release": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"release_revision": {
"commit": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"branch": "main",
"built_at": "2026-10-24T22:01:48.219730+00:00",
"manifest_sha256": "d45edd81644fa6b659aece95804fd9c5e8e99c599ef82bf078ee2ba39e700f12"
},
"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-g10-own-name-delivery-20261025/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "85e90033b54a7eb7fed1bf0de466b984f5c03cc3b4938b5d8db20b7bf0abf954",
"files_sha256": "291e2c871d94c3b642252f8daa8a9d7557278f13028e68df78b5f6edec5b1234",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g10_own_name_restore_20261024",
"port": 55441,
"source_dump_sha256": "85e90033b54a7eb7fed1bf0de466b984f5c03cc3b4938b5d8db20b7bf0abf954",
"active_database_writes": 0
}
},
"delivery_local_date": "2026-10-25",
"delivery_timezone": "Africa/Johannesburg",
"served_commit": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"release": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"previous_release": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"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": "0533965406197091e01442f39b006a04"
},
"after": {
"rows": 106,
"checksum": "690fff122d6fc745c2e2ab9bd28732aa"
}
},
"sessions": {
"before": {
"rows": 93,
"checksum": "d97f35b74199225940dea7078a712474"
},
"after": {
"rows": 94,
"checksum": "def210abad7e8e9b838f9490594fb787"
}
}
},
"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": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"branch": "main",
"built_at": "2026-10-24T22:09:58.694541+00:00",
"manifest_sha256": "40f4377487ec290e47d1bee92146172fa4e2a316fa4a072dcc82300fea3cc6c1"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"own-name-chains/1": [
"assets/project-dossier-Ct_yYLqe.js"
],
"goods_sale_commission": [
"assets/project-dossier-Ct_yYLqe.js"
],
"goods_purchase_commission": [
"assets/project-dossier-Ct_yYLqe.js"
],
"service_sale_mandate": [
"assets/project-dossier-Ct_yYLqe.js"
],
"service_purchase_mandate": [
"assets/project-dossier-Ct_yYLqe.js"
],
"ownNames": [
"assets/project-dossier-Ct_yYLqe.js"
],
"ownName": [
"assets/project-dossier-Ct_yYLqe.js"
],
"forAnother": [
"assets/project-dossier-Ct_yYLqe.js"
],
"commissionContract": [
"assets/project-dossier-Ct_yYLqe.js"
],
"successiveService": [
"assets/project-dossier-Ct_yYLqe.js"
],
"directionConfirmed": [
"assets/project-dossier-Ct_yYLqe.js"
],
"firstAmount": [
"assets/services-BoK-jPgg.js",
"assets/project-dossier-Ct_yYLqe.js"
],
"secondAmount": [
"assets/services-BoK-jPgg.js",
"assets/project-dossier-Ct_yYLqe.js"
],
"firstLegRef": [
"assets/services-BoK-jPgg.js",
"assets/project-dossier-Ct_yYLqe.js"
],
"secondLegRef": [
"assets/services-BoK-jPgg.js",
"assets/project-dossier-Ct_yYLqe.js"
],
"existingBaseRef": [
"assets/services-BoK-jPgg.js",
"assets/project-dossier-Ct_yYLqe.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-Ct_yYLqe.js"
]
},
"assets": [
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/services-BoK-jPgg.js",
"status": 200,
"sha256": "df86ebec3aad6060cc563343ddc3010d330fcd8b89e21db9861c042dbadb3317"
},
{
"file": "assets/project-dossier-document-DTNvmcJB.js",
"status": 200,
"sha256": "e961e77528e9c18681f133dd6e332202f48783bb0f9373117aac8aa83a0653b3"
},
{
"file": "assets/project-dossier-Ct_yYLqe.js",
"status": 200,
"sha256": "db9b14435dccf65e83555e2517b939e0bc05a31782996abffe6d7b29b901ea47"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-dGCxtIbq.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": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"release": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"previous_release": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"release": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"previous_release": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"63cc336787cade92fb7ee5b2b2d407308a0cf66b"
],
"finished_at": "2026-10-24T22:10:01.647328+00:00"
},
"log_file": "1792879692780810651.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 27.93s",
"OK (59 tests, 317 assertions)",
"# tests 413",
"# pass 413",
"# fail 0"
],
"log_bytes": 146997
},
"rollback_executed": false
},
"base_VAT_separation": "AcceptedQA reused:P122goods sale/purchasecommission3(3)c andP128services sale/purchasemandate4(3). Agent ownname andforanother,parties/contract/object/period/two relations explicit. Originalconsiderations separated,never summed/netted/converted or usedasautomaticbase. P091anditsbooks/history preserved,not recalculated. No territoriality/exemption/base/rate/VAT/deductionfield11 or ModeloAtotals activated. Four installedruntimehashes/17compiledmarkers;107previousclosures preserved;no syntheticactivewrites.",
"activation": "OnejointGit fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-own-name.ts
+++ b/resources/js/lib/iva-own-name.ts
@@ -45,6 +45,7 @@
function key(draft:Record<string,unknown>,book:OwnNameBook):string{return JSON.stringify({version:ownNameVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function ownNameCurrent(draft:Record<string,unknown>,book:OwnNameBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordOwnNames(draft:Record<string,unknown>,book:OwnNameBook):OwnNameBook{
+ throw new Error('Novas classificações P122/P128 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:OwnNameCalculation={version:ownNameVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:ownNameSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateOwnName(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveOwnNameBook(draft,next);return next;
@@ -0,0 +1,343 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "833b4e5cef4334220fd3f27843d520113e9ba0cd",
"base_installed": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"coverage_complete_branches": {
"AUD-SIM-L1-P096": [
"regulated_energy"
],
"AUD-SIM-L1-P097": [
"aeronautical_fees"
],
"AUD-SIM-L1-P098": [
"public_works"
],
"AUD-SIM-L1-P099": [
"public_water"
]
},
"branch_count_complete": 4,
"treatment_count": 4,
"runtime_delta": [
{
"path": "resources/js/lib/iva-reduced-bases.ts",
"sha256_LF": "4fc79388066a4d012b9af279ef53212ee963ae43d858307155e9ae8a140b5285"
},
{
"path": "resources/js/components/simulation-reduced-bases.tsx",
"sha256_LF": "00f1e0f1490240f578401c3a6e10b6812ee5b7978bbf7d7e5c9c1a81124bc6d1"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "6032b9605703e7e29d5fb45cc158e8da57b9af4980d312f3326ddf18ee1e8814"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "ab044a0952cc4753925768f5ba7fd422637cfb9d826c1e8c26d21d7616b6dacf"
}
],
"counts_before": {
"delivered": 103,
"QA": 4,
"functional_pending": 25,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 107,
"QA": 0,
"functional_pending": 25,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 107,
"QA": 0,
"functional_pending": 25,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g7-reduced-bases-qa-20261024.json"
],
"authorization": "Tempo explicitly requests one joint delivery of833b4e5c,P096–P099,main compatibility/concurrent changes preserved,installeddelta only",
"scope": "2026/MZN,base apenas. Percentagens62/85/40/75 são de base,não taxasIVA. Proporção18(6)registada sem calcular/conceder dedução/campo11;dedução permanece nas condições/lotes próprios. Sem taxaIVA,IVA,isenção ou totaisModeloA. Não dividir bruto comIVA sem composição esclarecida,nem reduzir montante já reduzido.",
"source": "CIVA15(2)j/k/l/m,15(1)/(5)/(6)/(9),Lei13/2016PDF13–14/p1426(271–272);Lei22/2022PDF3mantém15(2)j–m;Lei10/2025não altera15,adita18(6),PDF13:dedução do imposto suportado relativo a essas operações na mesma proporção da base reduzida.",
"meaning": {
"P096": {
"treatment": "regulated_energy",
"formula": "contraprestação total antes redução,sempróprioIVA ×62%",
"conditions": "Transmissão de energia com preço fixado porAutoridadePública,referência/âmbito/intervalo aplicáveis."
},
"P097": {
"treatment": "aeronautical_fees",
"formula": "contraprestação total antes redução,sempróprioIVA ×85%",
"conditions": "Preço doserviço fixado através de taxas aeronáuticas. Não aplicar a comunicações/saneamento/telecomunicações genericamente pelo título histórico da matriz;é necessário demonstrar o preço fixado através de taxa aeronáutica15(2)k."
},
"P098": {
"treatment": "public_works",
"formula": "contraprestação total antes redução,sempróprioIVA ×40%(redução60%,não base60%)",
"conditions": "Construção/reabilitação de obras públicas abrangidas15(2)l/15(9),projecto/contrato/categoria/âmbito identificados;estradas,pontes,infraestrutura água/saneamento,electrificação rural emprojectos públicos e hidráulicaagrícola noâmbito definido. Não exigir preço regulado a esta alínea."
},
"P099": {
"treatment": "public_water",
"formula": "contraprestação total antes redução,sempróprioIVA ×75%",
"conditions": "Água potável através derede pública,preço fixado porAutoridadePública comreferência/âmbito/intervalo aplicáveis."
}
},
"formula": "Base=fullconsideration before reduction excludingownVAT ×branchpercentage once;exactdecimal retained,no fiscalrounding assumed.",
"preservation": "103prior closures and partialP084/P085 preserved;accepted perbranchQA reused;one integration/backup/real isolatedrestore/check for whole set",
"partial_P084_P085": "Preparation/conditional simulation only,benefits pending;no closure",
"limits": "P121digital/P084/P085pending;L1open;P00105/06;beveragesL2/L3;Statistics/AIdeferred",
"containment": "l1-g7-reduced-readonly-rollback-20261024.patch,checked only,not applied;blocks newP096–099classifications,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"release": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"previous_release": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"release_revision": {
"commit": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"branch": "main",
"built_at": "2026-10-24T21:51:55.419637+00:00",
"manifest_sha256": "a04bb2c3e527c027aa263827b37e1566b67b372c479904112cfef79de9bcf2fb"
},
"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-g7-reduced-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "844803edd3a18d94ebd1cc75f942cce73b113111c92342ff32acf178b27f210d",
"files_sha256": "0b8a20760cdb89e2d7ac03e4b00881a882946370b9d7fa5a428355111e5ace4c",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g7_reduced_restore_20261024",
"port": 55441,
"source_dump_sha256": "844803edd3a18d94ebd1cc75f942cce73b113111c92342ff32acf178b27f210d",
"active_database_writes": 0
}
},
"delivery_local_date": "2026-10-25",
"delivery_timezone": "Africa/Johannesburg",
"batch_identifier_date_preserved": "20261024",
"served_commit": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"release": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"previous_release": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"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": "fc22bd1093218afa1777652f5fffb28c"
},
"after": {
"rows": 106,
"checksum": "60c94ff2cef9ca39b64d2c8035070dff"
}
},
"sessions": {
"before": {
"rows": 90,
"checksum": "242150536cdc201c41ae0e40414c384d"
},
"after": {
"rows": 91,
"checksum": "8c3ccd96b9dc1fa7897ce7976df83f6b"
}
}
},
"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": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"branch": "main",
"built_at": "2026-10-24T22:01:48.219730+00:00",
"manifest_sha256": "d45edd81644fa6b659aece95804fd9c5e8e99c599ef82bf078ee2ba39e700f12"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"proportional-bases/1": [
"assets/project-dossier-DNLCPaVL.js"
],
"regulated_energy": [
"assets/project-dossier-DNLCPaVL.js"
],
"aeronautical_fees": [
"assets/project-dossier-DNLCPaVL.js"
],
"public_works": [
"assets/services-C-RxFM34.js",
"assets/project-dossier-DNLCPaVL.js"
],
"public_water": [
"assets/project-dossier-DNLCPaVL.js"
],
"regulatedReducedBases": [
"assets/project-dossier-DNLCPaVL.js"
],
"fullNetInvoice": [
"assets/project-dossier-DNLCPaVL.js"
],
"scopeMatches": [
"assets/project-dossier-DNLCPaVL.js"
],
"publicFixedPrice": [
"assets/project-dossier-DNLCPaVL.js"
],
"workCategoryMatches": [
"assets/project-dossier-DNLCPaVL.js"
],
"deductionProportion": [
"assets/project-dossier-DNLCPaVL.js"
],
"consideration": [
"assets/services-C-RxFM34.js",
"assets/project-dossier-DNLCPaVL.js"
],
"compositionRef": [
"assets/services-C-RxFM34.js",
"assets/project-dossier-DNLCPaVL.js"
],
"projectRef": [
"assets/services-C-RxFM34.js",
"assets/project-dossier-DNLCPaVL.js"
],
"workCategory": [
"assets/services-C-RxFM34.js",
"assets/project-dossier-DNLCPaVL.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-DNLCPaVL.js"
]
},
"assets": [
{
"file": "assets/services-C-RxFM34.js",
"status": 200,
"sha256": "10b075f5e0e73b50ca8c50bc3b78b6a985064b04db20964880e02eb1d4b54463"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-DNLCPaVL.js",
"status": 200,
"sha256": "e92f51bbe03990bb075096fd4036f903c47a13b55be7d41ae33462ae392e553a"
},
{
"file": "assets/project-dossier-document-CMVlVhKB.js",
"status": 200,
"sha256": "d707cab4744f123b860cd9b6da836d88f1ac83eba2cdc6c96fa5c6d4eccd7131"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-D3qtybUs.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": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"release": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"previous_release": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "2fdca86367d8bad524113b4cf6c49a0110130be9",
"release": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"previous_release": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"2fdca86367d8bad524113b4cf6c49a0110130be9"
],
"finished_at": "2026-10-24T22:01:51.055662+00:00"
},
"log_file": "1792879201936459656.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 28.30s",
"OK (59 tests, 317 assertions)",
"# tests 407",
"# pass 407",
"# fail 0"
],
"log_bytes": 145227
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted perbranchQA reused:P096energy62%,P097aeronautical85%,P098publicworks40%(reduction60%),P099publicwater75%. These percentages apply to taxableBASE,not VATrates. Exactdecimal base applied once to fullconsideration before reduction excludingownVAT. Art18(6)deductionproportion notedonly;deduction/field11 outsideincrement,no VAT/deductioncalculated. Four installedruntimehashes/16compiledmarkers,103priorclosures preserved,no syntheticactivewrites.",
"activation": "OnejointGit fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-reduced-bases.ts
+++ b/resources/js/lib/iva-reduced-bases.ts
@@ -53,6 +53,7 @@
function key(draft:Record<string,unknown>,book:ReducedBaseBook):string{return JSON.stringify({version:reducedBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function reducedBaseCurrent(draft:Record<string,unknown>,book:ReducedBaseBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordReducedBases(draft:Record<string,unknown>,book:ReducedBaseBook):ReducedBaseBook{
+ throw new Error('Novas classificações P096–P099 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:ReducedBaseCalculation={version:reducedBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:reducedBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateReducedBase(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveReducedBaseBook(draft,next);return next;
@@ -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,312 @@
{
"status": "installed_delta_verified_partial_L1",
"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": 82,
"QA": 0,
"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
}
},
"served_commit": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"release": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"previous_release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"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": "9753319afae2b48c6603174611c29a44"
},
"after": {
"rows": 105,
"checksum": "0952fbca996676b2672ef9e20bc6f3b4"
}
},
"sessions": {
"before": {
"rows": 62,
"checksum": "3cad129ac66a652cdd459999598f14ce"
},
"after": {
"rows": 63,
"checksum": "157ddd76903db6ec5dd9176ac8f58bef"
}
}
},
"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": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"branch": "main",
"built_at": "2026-10-24T20:37:45.995677+00:00",
"manifest_sha256": "bac69b18e37c76367dbcdd4caee54122f088dfafdc344ebd8a7e31f66617cfc8"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"regulated-fuel-base/1": [
"assets/project-dossier-Cz-1HWwj.js"
],
"fuel_tax_included": [
"assets/project-dossier-Cz-1HWwj.js",
"assets/services-DYdBDJDo.js"
],
"fuel_tax_excluded": [
"assets/project-dossier-Cz-1HWwj.js"
],
"regulatedFuelBases": [
"assets/project-dossier-Cz-1HWwj.js"
],
"taxableFuelResale": [
"assets/project-dossier-Cz-1HWwj.js"
],
"publicFixedPrice": [
"assets/project-dossier-Cz-1HWwj.js"
],
"priceScopeMatches": [
"assets/project-dossier-Cz-1HWwj.js"
],
"fuelTaxTreatment": [
"assets/project-dossier-Cz-1HWwj.js"
],
"consideration": [
"assets/project-dossier-Cz-1HWwj.js",
"assets/services-DYdBDJDo.js"
],
"fuelTaxRef": [
"assets/project-dossier-Cz-1HWwj.js",
"assets/services-DYdBDJDo.js"
],
"priceRef": [
"assets/project-dossier-Cz-1HWwj.js",
"assets/services-DYdBDJDo.js"
],
"priceScope": [
"assets/project-dossier-Cz-1HWwj.js",
"assets/services-DYdBDJDo.js"
],
"priceFrom": [
"assets/project-dossier-Cz-1HWwj.js",
"assets/services-DYdBDJDo.js"
],
"priceTo": [
"assets/project-dossier-Cz-1HWwj.js",
"assets/services-DYdBDJDo.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-Cz-1HWwj.js"
]
},
"assets": [
{
"file": "assets/project-dossier-Cz-1HWwj.js",
"status": 200,
"sha256": "5d3889631817dce24a1d5117adfedb857f82b7904661f2542fe1e8bec9b175db"
},
{
"file": "assets/project-dossier-document-CD6rt2wY.js",
"status": 200,
"sha256": "1d3d83cc19a332bf7b4a2f3bd53ded192944990da4c670da66894ca2bd5dd0d1"
},
{
"file": "assets/services-DYdBDJDo.js",
"status": 200,
"sha256": "9963e8e963cc91d4ed93e49f855f72d2354353e13bd65329064875fca34584c7"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-DVpJlD3c.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": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"release": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"previous_release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"release": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"previous_release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"92a7418cb6b080916a4d02d3c1db4be94d3d96f1"
],
"finished_at": "2026-10-24T20:37:48.666648+00:00"
},
"log_file": "1792874168886523454.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.42s",
"OK (59 tests, 317 assertions)",
"# tests 358",
"# pass 358",
"# fail 0"
],
"log_bytes": 133280
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted QA reused:TC included is subtracted once;alreadyexcluded unchanged. Price reference/scope/period and immutable inputs/history/report retained;no presumed price/TC or double subtraction. Base independent of VAT/rate(alwaysnull). Four installed runtime hashes and15compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
@@ -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;
@@ -0,0 +1,316 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "0460c85330557b8074c14c04c74cd890e6cab97a",
"base_installed": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"coverage_complete_branches": {
"AUD-SIM-L1-P100": [
"noncash_only",
"cash_and_noncash"
]
},
"branch_count_complete": 1,
"treatment_count": 2,
"runtime_delta": [
{
"path": "resources/js/lib/iva-noncash-base.ts",
"sha256_LF": "d07cbefec4d54cffe41626093832972b31b8eacf0021a146655c79b189f25434"
},
{
"path": "resources/js/components/simulation-noncash-base.tsx",
"sha256_LF": "e8d5dd905d9c6b75ed7589e4ecf7b708bb288ba59285d409f444e799f9f09c35"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "bc1005d31306c859dfa325f8d63e8bac98073b38f6d65ab22f736537629d4752"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "84d3c968dfa0a644f1767c09dd266fbe32b086117da0416564681e4a51e8d7f6"
}
],
"counts_before": {
"delivered": 82,
"QA": 1,
"functional_pending": 49,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 83,
"QA": 0,
"functional_pending": 49,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 83,
"QA": 0,
"functional_pending": 49,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g7e-qa-20261024.json"
],
"authorization": "Tempo explicitly deploy0460c853 through existingGit,preserve concurrentchanges and check installeddelta only;two treatments sameP100branch",
"scope": "2026/MZN,baseonly;no currencyconversion,automatic normalvaluation,incidence/rate/VAT/deduction/field11/ModeloAtotals. Unknown monetary share not inferredzero;explicitzero differentiated. Otherbranches and prior normalvalue contexts unchanged.",
"meaning": "Consideration not wholly or partly defined in money:money received/receivable plus normalvalue of goods/services given in exchange as consideration for identified operation. Entirely noncash only with express composition confirmation,not inferred from emptycash field.",
"formula": {
"noncash_only": "normalvalue,absence of monetary consideration explicitly confirmed",
"cash_and_noncash": "cashamount received/receivable + normalvalue of goods/services given in exchange"
},
"preservation": "82priorclosures 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-g7e-readonly-rollback-20261024.patch,checked only,not applied;blocks newP100calculations only,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"release": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"previous_release": "/var/www/investmoz-homologacao/releases/df7cb7fa47f50ae23f52c1bdf7e48e38489cffef-be472ead",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"release_revision": {
"commit": "92a7418cb6b080916a4d02d3c1db4be94d3d96f1",
"branch": "main",
"built_at": "2026-10-24T20:37:45.995677+00:00",
"manifest_sha256": "bac69b18e37c76367dbcdd4caee54122f088dfafdc344ebd8a7e31f66617cfc8"
},
"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-g7e-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "dcc4d9b15c0a62b065742f976dc4478c560674f40e6fd7c2017492dee433a27e",
"files_sha256": "59804ad31f7c6a6055aed0020b7b8d30f23e0ad8b43e75d6280fba977d0e4a4e",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g7e_restore_20261024",
"port": 55441,
"source_dump_sha256": "dcc4d9b15c0a62b065742f976dc4478c560674f40e6fd7c2017492dee433a27e",
"active_database_writes": 0
}
},
"served_commit": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"release": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"previous_release": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"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": "ed216cb11fffaa2b61c114570c78a17b"
},
"after": {
"rows": 105,
"checksum": "ff9165ae0fd40844ce207770858bf0d1"
}
},
"sessions": {
"before": {
"rows": 65,
"checksum": "8aee0965c2b1e3d8f0a01c8d0d7d5ec1"
},
"after": {
"rows": 66,
"checksum": "13e05ea1a9dc6cd7c07205bfe491b4c7"
}
}
},
"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": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"branch": "main",
"built_at": "2026-10-24T20:45:12.326319+00:00",
"manifest_sha256": "c141928a91011ced381e72b1e616469bb9fe061a2a9e9d7b43dcf8ec37ccd068"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"noncash-consideration-base/1": [
"assets/project-dossier-BG2KqrE6.js"
],
"noncash_only": [
"assets/project-dossier-BG2KqrE6.js"
],
"cash_and_noncash": [
"assets/project-dossier-BG2KqrE6.js",
"assets/services-B-L_nC4P.js"
],
"noncashBases": [
"assets/project-dossier-BG2KqrE6.js"
],
"taxableOperation": [
"assets/project-dossier-BG2KqrE6.js"
],
"exchangeIdentified": [
"assets/project-dossier-BG2KqrE6.js"
],
"cashComposition": [
"assets/project-dossier-BG2KqrE6.js"
],
"normalValueBasis": [
"assets/project-dossier-BG2KqrE6.js"
],
"cashAmount": [
"assets/project-dossier-BG2KqrE6.js",
"assets/services-B-L_nC4P.js"
],
"cashRef": [
"assets/project-dossier-BG2KqrE6.js",
"assets/services-B-L_nC4P.js"
],
"normalValue": [
"assets/project-dossier-BG2KqrE6.js",
"assets/services-B-L_nC4P.js"
],
"exchangeDescription": [
"assets/project-dossier-BG2KqrE6.js",
"assets/services-B-L_nC4P.js"
],
"agreementRef": [
"assets/project-dossier-BG2KqrE6.js",
"assets/services-B-L_nC4P.js"
],
"valuationRef": [
"assets/project-dossier-BG2KqrE6.js",
"assets/services-B-L_nC4P.js"
],
"valuationScope": [
"assets/project-dossier-BG2KqrE6.js",
"assets/services-B-L_nC4P.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-BG2KqrE6.js"
]
},
"assets": [
{
"file": "assets/project-dossier-BG2KqrE6.js",
"status": 200,
"sha256": "372b30385b0d0ead940a585e0eb90517e0b03bf8e04eff78aa368d52ba882a81"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/services-B-L_nC4P.js",
"status": 200,
"sha256": "4272f5a7705350dbb2e46dc328a73447e814f9280614077a9c902c32e4f32063"
},
{
"file": "assets/project-dossier-document-CbKgC_ZS.js",
"status": 200,
"sha256": "68a73417854b38b1cb93434f10762323ad3dfed97b9bddbce0e3f2ca0f5af7d2"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-BKEVCVJE.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": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"release": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"previous_release": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"release": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"previous_release": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"70b4a640ee5f790f8e6a089d157456ff437e336d"
],
"finished_at": "2026-10-24T20:45:15.438182+00:00"
},
"log_file": "1792874615285322105.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.36s",
"OK (59 tests, 317 assertions)",
"# tests 362",
"# pass 362",
"# fail 0"
],
"log_bytes": 134422
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted QA reused:normalvalue of goods/services given in exchange plus monetary share if present;absence expressly confirmed,hidden monetary inputs preserved but not summed in noncash_only. Normalvalue basis/scope and immutable inputs/history/report retained. Base independent of VAT/rate(alwaysnull). Four installed runtime hashes and16compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-noncash-base.ts
+++ b/resources/js/lib/iva-noncash-base.ts
@@ -49,6 +49,7 @@
function key(draft:Record<string,unknown>,book:NoncashBaseBook):string{return JSON.stringify({version:noncashBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function noncashBaseCurrent(draft:Record<string,unknown>,book:NoncashBaseBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordNoncashBases(draft:Record<string,unknown>,book:NoncashBaseBook):NoncashBaseBook{
+ throw new Error('Novas bases P100 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:NoncashBaseCalculation={version:noncashBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:noncashBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateNoncashBase(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveNoncashBaseBook(draft,next);return next;
@@ -0,0 +1,309 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "6f90fcb9d4ea6e93b13291e65fa6cb7406ca98c9",
"base_installed": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"coverage_complete_branches": {
"AUD-SIM-L1-P101": [
"tax_component",
"accessory_component"
]
},
"branch_count_complete": 1,
"treatment_count": 2,
"runtime_delta": [
{
"path": "resources/js/lib/iva-composition-base.ts",
"sha256_LF": "557d6b4b5ed2c534b69e5edf43c9e4014cdfb7362bf164829cd16e4deeabbf73"
},
{
"path": "resources/js/components/simulation-composition-base.tsx",
"sha256_LF": "3507c14f15e40bf018089520a46b7e22002ddbd9bffa64d179f085b0d933ae0e"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "82694be2d0a5ac097b64d68dceeda1df239bb2bf2bce193e8112d3dadad79a95"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "c640883680629049ea851a63e28e967a70297257a55e5d885df8e32f4b81e871"
}
],
"counts_before": {
"delivered": 83,
"QA": 1,
"functional_pending": 48,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 84,
"QA": 0,
"functional_pending": 48,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 84,
"QA": 0,
"functional_pending": 48,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g7f-qa-20261024.json"
],
"authorization": "Tempo explicitly deploy6f90fcb9 through existingGit,preserve concurrentchanges and check installeddelta only;onebase peroperation,withoutdoublecounting or ownVAT;two componenttreatments sameP101branch",
"scope": "2026/MZN,P101compositiononly;no incidence/taxrates/IVA/deduction/field11/ModeloAtotals. Initialamount explicitlynetofownIVA and applicable15(6)exclusions;specialbases15(2)respected includingP095TCexclusion. DetailedP102exclusions notclosed by thisrecorte. Unknowncomponentamount/inclusion notassumedzero or missing;ownIVA not added ascomponent.",
"meaning": "Include taxes,duties,fees/otherimpositions excludingownVAT;accessory expenses charged forcommissions,packaging,transport/insurance onclientaccount. Both component treatments form one base peroperation,not parallelbases.",
"formula": "initial amount netofownVAT/applicableexclusions + sum of applicable components notalreadyincluded;alreadyincluded components retained without secondsum",
"preservation": "83priorclosures 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-g7f-readonly-rollback-20261024.patch,checked only,not applied;blocks newP101calculations only,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"release": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"previous_release": "/var/www/investmoz-homologacao/releases/92a7418cb6b080916a4d02d3c1db4be94d3d96f1-ebe3dcb6",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"release_revision": {
"commit": "70b4a640ee5f790f8e6a089d157456ff437e336d",
"branch": "main",
"built_at": "2026-10-24T20:45:12.326319+00:00",
"manifest_sha256": "c141928a91011ced381e72b1e616469bb9fe061a2a9e9d7b43dcf8ec37ccd068"
},
"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-g7f-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "18729e57928183ae4a59eb2e34566a1e87ec4a1fa9e8d3a97177ab9623ae272a",
"files_sha256": "13142a0558b2a84ae6fd142789fe313f09ef3a0f3b201c6421a274e4105f7f23",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g7f_restore_20261024",
"port": 55441,
"source_dump_sha256": "18729e57928183ae4a59eb2e34566a1e87ec4a1fa9e8d3a97177ab9623ae272a",
"active_database_writes": 0
}
},
"served_commit": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"release": "/var/www/investmoz-homologacao/releases/7e5710ebbd235f9478f149f8470a238c9e66ea9e-8bf3c724",
"previous_release": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"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": "5019a5447b0c93535079b73e9c088755"
},
"after": {
"rows": 105,
"checksum": "9d9ac5701d82e434ce40ad346398071d"
}
},
"sessions": {
"before": {
"rows": 68,
"checksum": "6d9856e21f1e09b08fb17ec81d0cb6b6"
},
"after": {
"rows": 69,
"checksum": "1f8d81747e4a1f9ac7416bb0c6cd6b88"
}
}
},
"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": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"branch": "main",
"built_at": "2026-10-24T20:54:47.716763+00:00",
"manifest_sha256": "bb782ee252ff461e8c53287876736b77f7851f7a5f23c7f12ff84aa8a23dd611"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"consideration-composition-base/1": [
"assets/project-dossier-D2E5WlN9.js"
],
"tax_component": [
"assets/services-CY5shkop.js",
"assets/project-dossier-D2E5WlN9.js"
],
"accessory_component": [
"assets/project-dossier-D2E5WlN9.js"
],
"considerationCompositions": [
"assets/project-dossier-D2E5WlN9.js"
],
"taxableOperation": [
"assets/project-dossier-D2E5WlN9.js"
],
"initialNet": [
"assets/project-dossier-D2E5WlN9.js"
],
"completeComposition": [
"assets/project-dossier-D2E5WlN9.js"
],
"specialRules": [
"assets/project-dossier-D2E5WlN9.js"
],
"initialAmount": [
"assets/services-CY5shkop.js",
"assets/project-dossier-D2E5WlN9.js"
],
"initialRef": [
"assets/services-CY5shkop.js",
"assets/project-dossier-D2E5WlN9.js"
],
"operationRef": [
"assets/services-CY5shkop.js",
"assets/project-dossier-D2E5WlN9.js"
],
"natureConfirmed": [
"assets/services-CY5shkop.js",
"assets/project-dossier-D2E5WlN9.js"
],
"ownVatExcluded": [
"assets/services-CY5shkop.js",
"assets/project-dossier-D2E5WlN9.js"
],
"included": [
"assets/services-CY5shkop.js",
"assets/project-dossier-D2E5WlN9.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-D2E5WlN9.js"
]
},
"assets": [
{
"file": "assets/services-CY5shkop.js",
"status": 200,
"sha256": "fab469e821906d7c3f53403a2c7dabd9daf0374c98582f2c5250028534e4e919"
},
{
"file": "assets/project-dossier-document-CYmMav6B.js",
"status": 200,
"sha256": "5c905f45fdb879c0315e78f4283fd0427010d7ddd7b15eaebabdd1ca635a0054"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-D2E5WlN9.js",
"status": 200,
"sha256": "fddc0c2b79528fd9e8993ad98daeeff67f76c0f05d0ab38adda087b1547cf40b"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-D5CFqFe4.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": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"release": "/var/www/investmoz-homologacao/releases/7e5710ebbd235f9478f149f8470a238c9e66ea9e-8bf3c724",
"previous_release": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"release": "/var/www/investmoz-homologacao/releases/7e5710ebbd235f9478f149f8470a238c9e66ea9e-8bf3c724",
"previous_release": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"7e5710ebbd235f9478f149f8470a238c9e66ea9e"
],
"finished_at": "2026-10-24T20:54:50.708939+00:00"
},
"log_file": "1792875189810569987.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 25.63s",
"OK (59 tests, 317 assertions)",
"# tests 366",
"# pass 366",
"# fail 0"
],
"log_bytes": 135617
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted QA reused:initial netamount plus onlynotalreadyincluded tax/accessorycomponents;onebase peroperation,no doublecounting or ownVAT. Nestedcomponentnature/amount/inclusion/references,immutableinputs/history/report retained;specialbases and exclusions respected. Base independent of VAT/rate(alwaysnull). Four installed runtime hashes and15compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-composition-base.ts
+++ b/resources/js/lib/iva-composition-base.ts
@@ -55,6 +55,7 @@
function key(draft:Record<string,unknown>,book:CompositionBook):string{return JSON.stringify({version:compositionBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function compositionCurrent(draft:Record<string,unknown>,book:CompositionBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordCompositions(draft:Record<string,unknown>,book:CompositionBook):CompositionBook{
+ throw new Error('Novas bases P101 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:CompositionCalculation={version:compositionBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:compositionBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateComposition(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveCompositionBook(draft,next);return next;
@@ -0,0 +1,313 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "9c2b2c6560062fcc261b27731cf9726276510d47",
"base_installed": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"coverage_complete_branches": {
"AUD-SIM-L1-P102": [
"judicial_indemnity",
"granted_discount",
"third_party_payment",
"returnable_packaging"
]
},
"branch_count_complete": 1,
"treatment_count": 4,
"runtime_delta": [
{
"path": "resources/js/lib/iva-exclusion-base.ts",
"sha256_LF": "2d4d2f607eb4e24e617a5640b239d14ab4958e364cc6f3cda36a407b8b1d782f"
},
{
"path": "resources/js/components/simulation-exclusion-base.tsx",
"sha256_LF": "4c69345d9e49c96756727cbf909bf1d5949fa9db14c346157413dd1885258520"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "81be9e69aeab5d544a2fb8aadcf487bb6f04ae0ab06861759709912afe9c82bf"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "af10643db841e08f14a9ef534ccf7367fe5b05e20c58b770e3a4cf51aa0192e8"
}
],
"counts_before": {
"delivered": 84,
"QA": 1,
"functional_pending": 47,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 85,
"QA": 0,
"functional_pending": 47,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 85,
"QA": 0,
"functional_pending": 47,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g7g-qa-20261024.json"
],
"authorization": "Tempo explicitly deploy9c2b2c65 through existingGit,preserve concurrentchanges and check installeddelta only;four treatments sameP102branch,ownconditions and no double subtraction",
"scope": "2026/MZN,P102baseonly;no IVA/incidence/rate/deduction/field11/regularisations/ModeloAtotals. No automaticlegaldecision orpriorperiodposting. Packagingrequiresagreedreturnmention,notactualreturn. Unknownconditions/amount/inclusion indeterminate;failedcondition yields notapplicable,notzero;exclusionsexceedinginitialamount notnegative/flooredzero.",
"meaning": "Four exclusions:judicial indemnity for total/partial contractbreach;granteddiscount/abatement/bonus;payment inname/onaccount of purchaser/recipient recorded inappropriate thirdpartyaccounts;packaging notactuallytransacted withseparateinvoiceindication/express agreedreturnmention.",
"formula": "initialamount netofownVAT with15(5)inclusions minus only exclusions stillincluded;alreadyexcluded retained without secondsubtraction",
"preservation": "84priorclosures 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-g7g-readonly-rollback-20261024.patch,checked only,not applied;blocks newP102calculations only,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"release": "/var/www/investmoz-homologacao/releases/7e5710ebbd235f9478f149f8470a238c9e66ea9e-8bf3c724",
"previous_release": "/var/www/investmoz-homologacao/releases/70b4a640ee5f790f8e6a089d157456ff437e336d-c95636fc",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/7e5710ebbd235f9478f149f8470a238c9e66ea9e-8bf3c724",
"release_revision": {
"commit": "7e5710ebbd235f9478f149f8470a238c9e66ea9e",
"branch": "main",
"built_at": "2026-10-24T20:54:47.716763+00:00",
"manifest_sha256": "bb782ee252ff461e8c53287876736b77f7851f7a5f23c7f12ff84aa8a23dd611"
},
"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-g7g-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "4eafcef8350b4a486b4306b675bc71ed89961f43ab56aa49a9751982d7a8d9b5",
"files_sha256": "abc18ef93cfbd7b266b08cb8c7fcc5f048eae33c74e5bce0fa19c3e9ba25469e",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g7g_restore_20261024",
"port": 55441,
"source_dump_sha256": "4eafcef8350b4a486b4306b675bc71ed89961f43ab56aa49a9751982d7a8d9b5",
"active_database_writes": 0
}
},
"served_commit": "5d5f3b414866969e4b2d38376402b8f264c6d19c",
"installation": {
"protected": {
"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
},
"runtime_files_verified": 4,
"persistent_files_and_env_verified": 369,
"tables_compared": 174,
"changed_tables": {
"cache": {
"before": {
"rows": 105,
"checksum": "1d5e3ec2a5dba626144c3527b18e0e65"
},
"after": {
"rows": 106,
"checksum": "3b79bad8f86095c2b11c82425ce8a63c"
}
},
"sessions": {
"before": {
"rows": 71,
"checksum": "3738e4ce15d39c7ac152c3045dc1c11f"
},
"after": {
"rows": 73,
"checksum": "901a2e2d485d58ea01f02b2e1887cf0e"
}
}
},
"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": "5d5f3b414866969e4b2d38376402b8f264c6d19c",
"branch": "main",
"built_at": "2026-10-24T21:06:06.620815+00:00",
"manifest_sha256": "640a7390e644ff6efdf891439786a7b1783553d805cf71ccb6e6d488ed7196e8"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"consideration-exclusions-base/1": [
"assets/project-dossier-N7veALmJ.js"
],
"judicial_indemnity": [
"assets/project-dossier-N7veALmJ.js"
],
"granted_discount": [
"assets/project-dossier-N7veALmJ.js"
],
"third_party_payment": [
"assets/services-Bum8CrDQ.js",
"assets/project-dossier-N7veALmJ.js"
],
"returnable_packaging": [
"assets/services-Bum8CrDQ.js",
"assets/project-dossier-N7veALmJ.js"
],
"considerationExclusions": [
"assets/project-dossier-N7veALmJ.js"
],
"judicialDeclaration": [
"assets/project-dossier-N7veALmJ.js"
],
"contractBreach": [
"assets/project-dossier-N7veALmJ.js"
],
"thirdPartyAccounts": [
"assets/project-dossier-N7veALmJ.js"
],
"returnMention": [
"assets/project-dossier-N7veALmJ.js"
],
"separateIndication": [
"assets/project-dossier-N7veALmJ.js"
],
"accountRef": [
"assets/services-Bum8CrDQ.js",
"assets/project-dossier-N7veALmJ.js"
],
"beneficiaryRef": [
"assets/services-Bum8CrDQ.js",
"assets/project-dossier-N7veALmJ.js"
],
"documentExcerpt": [
"assets/services-Bum8CrDQ.js",
"assets/project-dossier-N7veALmJ.js"
],
"included": [
"assets/services-Bum8CrDQ.js",
"assets/project-dossier-N7veALmJ.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-N7veALmJ.js"
]
},
"assets": [
{
"file": "assets/services-Bum8CrDQ.js",
"status": 200,
"sha256": "2333ebe00e8e446bc3721eb76a5b7a34c80bc3e64789bbaf0e488f16f13adb1e"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-document-CJyannat.js",
"status": 200,
"sha256": "cece8886f730ac17191b912bc840bde193d0ea377a056c5adb5476a16a66c88e"
},
{
"file": "assets/project-dossier-N7veALmJ.js",
"status": 200,
"sha256": "77a3cd4693091ea6979bf10129036e592f7e26eaf9edc573081f9f3e6240c4c5"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-DjGpWTrb.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": "5d5f3b414866969e4b2d38376402b8f264c6d19c",
"release": "/var/www/investmoz-homologacao/releases/5d5f3b414866969e4b2d38376402b8f264c6d19c-7453aad9",
"previous_release": "/var/www/investmoz-homologacao/releases/7e5710ebbd235f9478f149f8470a238c9e66ea9e-8bf3c724",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"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,
"requested_commits": [
"5d5f3b414866969e4b2d38376402b8f264c6d19c"
],
"finished_at": "2026-10-24T21:06:09.473849+00:00"
},
"log_file": "1792875866291395065.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 26.50s",
"OK (59 tests, 317 assertions)",
"# tests 370",
"# pass 370",
"# fail 0"
],
"log_bytes": 136776
},
"rollback_executed": false
},
"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"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-exclusion-base.ts
+++ b/resources/js/lib/iva-exclusion-base.ts
@@ -67,6 +67,7 @@
function key(draft:Record<string,unknown>,book:ExclusionBook):string{return JSON.stringify({version:exclusionBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function exclusionCurrent(draft:Record<string,unknown>,book:ExclusionBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordExclusions(draft:Record<string,unknown>,book:ExclusionBook):ExclusionBook{
+ throw new Error('Novas bases P102 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:ExclusionCalculation={version:exclusionBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:exclusionBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateExclusion(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveExclusionBook(draft,next);return next;
@@ -0,0 +1,318 @@
{
"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"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-value-review.ts
+++ b/resources/js/lib/iva-value-review.ts
@@ -54,6 +54,7 @@
function key(draft:Record<string,unknown>,book:ValueReviewBook):string{return JSON.stringify({version:valueReviewVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function valueReviewCurrent(draft:Record<string,unknown>,book:ValueReviewBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordValueReviews(draft:Record<string,unknown>,book:ValueReviewBook):ValueReviewBook{
+ throw new Error('Novas bases P103 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:ValueReviewCalculation={version:valueReviewVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:valueReviewSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateValueReview(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveValueReviewBook(draft,next);return next;
@@ -0,0 +1,315 @@
{
"status": "installed_delta_verified_partial_L1",
"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": 87,
"QA": 0,
"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
}
},
"served_commit": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"release": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"previous_release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"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": "45610a4958896515bb8c40336788ed14"
},
"after": {
"rows": 106,
"checksum": "fbe7bcd9ed9fb14cd53e72323e65123b"
}
},
"sessions": {
"before": {
"rows": 78,
"checksum": "f2d2cc72e918fa3281aa63d3f1694643"
},
"after": {
"rows": 79,
"checksum": "cd50f4e02a9922517e5d427d5dd2473c"
}
}
},
"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": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"branch": "main",
"built_at": "2026-10-24T21:23:28.102878+00:00",
"manifest_sha256": "329dea28609b9850332b63a730576a539077489d9e085235be7f344c3428f39c"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"assimilated-service-normal/1": [
"assets/project-dossier-_Ly_4ECn.js"
],
"free_company_service": [
"assets/services-QCmLUqU2.js",
"assets/project-dossier-_Ly_4ECn.js"
],
"private_company_asset_use": [
"assets/project-dossier-_Ly_4ECn.js"
],
"exempt_sector_asset_use": [
"assets/project-dossier-_Ly_4ECn.js"
],
"serviceNormals": [
"assets/project-dossier-_Ly_4ECn.js"
],
"freeByCompany": [
"assets/project-dossier-_Ly_4ECn.js"
],
"nonBusinessPurpose": [
"assets/project-dossier-_Ly_4ECn.js"
],
"companyAssetUse": [
"assets/project-dossier-_Ly_4ECn.js"
],
"privatePurpose": [
"assets/project-dossier-_Ly_4ECn.js"
],
"exemptSector": [
"assets/project-dossier-_Ly_4ECn.js"
],
"priorDeduction": [
"assets/project-dossier-_Ly_4ECn.js"
],
"assetRef": [
"assets/services-QCmLUqU2.js",
"assets/project-dossier-_Ly_4ECn.js"
],
"deductionRef": [
"assets/services-QCmLUqU2.js",
"assets/project-dossier-_Ly_4ECn.js"
],
"purposeRef": [
"assets/services-QCmLUqU2.js",
"assets/project-dossier-_Ly_4ECn.js"
],
"normalValue": [
"assets/services-QCmLUqU2.js",
"assets/project-dossier-_Ly_4ECn.js"
],
"valuationScope": [
"assets/services-QCmLUqU2.js",
"assets/project-dossier-_Ly_4ECn.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-_Ly_4ECn.js"
]
},
"assets": [
{
"file": "assets/services-QCmLUqU2.js",
"status": 200,
"sha256": "43e0f5cc440aac01075a66a6cde5cf2b8124f9ae2ce1937d742a38867f4f1c26"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-_Ly_4ECn.js",
"status": 200,
"sha256": "9db3d0991381c45f9ef4e73ee285f90b6e39736709459cbe992d59644008ed0c"
},
{
"file": "assets/project-dossier-document-CdgtDyQM.js",
"status": 200,
"sha256": "d319ea9cc9113ed0dc5ebe2f931b9e445578cea9d0e35a6f4d9feab4a0476d85"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-BEW2fH9O.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": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"release": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"previous_release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"release": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"previous_release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"6f1cf7b7a09796b3964b39f0b1e778f978ae60fb"
],
"finished_at": "2026-10-24T21:23:30.754896+00:00"
},
"log_file": "1792876907186052463.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 26.07s",
"OK (59 tests, 317 assertions)",
"# tests 378",
"# pass 378",
"# fail 0"
],
"log_bytes": 139074
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted QA reused:normalvalueofservice15c/4(2),three ownconditionpaths;prior total/partialdeduction ongoods/elements requiredonlyassetuse4(2)b,notfreecompanyservice4(2)a. References/purpose/normalvaluebasis/scope/immutableinputs/history/report preserved. Base independent of VAT/rate(alwaysnull),prior deductionreference doesnotcalculateorgrantfield11. Four installed runtime hashes and17compiled markers verified;no synthetic activewrite.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
@@ -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;
@@ -0,0 +1,338 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "3f4e71c3f360505dcb53c12376d14ee91643f3cd",
"base_installed": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"coverage_complete_branches": {
"AUD-SIM-L1-P106": [
"general_service"
],
"AUD-SIM-L1-P107": [
"immovable_service"
],
"AUD-SIM-L1-P108": [
"movable_work"
],
"AUD-SIM-L1-P109": [
"activity_service"
],
"AUD-SIM-L1-P110": [
"transport_service"
]
},
"branch_count_complete": 5,
"treatment_count": 5,
"runtime_delta": [
{
"path": "resources/js/lib/iva-service-location.ts",
"sha256_LF": "abf13bd0f6f8aed209b38f3fd8d5906b96572de2d13f87b0d742ee3f31095a19"
},
{
"path": "resources/js/components/simulation-service-location.tsx",
"sha256_LF": "ede4923dc4343949821cdd1c540837261cf816afee3069d031053cac73da5339"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "dd102e122a243f58c85db0dcde889877066c5aac9c873eb0f8f93905a6d0d848"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "03bfad1ac2a443ee4fd0a7c0091f5b3e34e17a9c8b2b75d1249ac0c96729d643"
}
],
"counts_before": {
"delivered": 88,
"QA": 5,
"functional_pending": 39,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 93,
"QA": 0,
"functional_pending": 39,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 93,
"QA": 0,
"functional_pending": 39,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g8-services-qa-20261024.json"
],
"authorization": "Tempo explicitly requests one joint delivery of3f4e71c3,P106–P110,main compatibility/concurrent changes preserved,installeddelta only",
"scope": "Recorte2026,classificação territorial de serviços por factos próprios;sem base,taxa,IVA,isenção,dedução/campo11 ou totaisModeloA. Digital/outros6(7)/(8)exigem percursos próprios,não classificados automaticamente. P002transversal não encerrado.",
"source": "CIVA6(3),6(4)/(5)a–d,6(6),Lei13/2016 PDF7–8/p1426(265–266);Aviso BR89-I,de08/06/2017,PDF1,rectifica expressamente6(5)c/d:actividades nacionais e transporte pela distância nacional;Lei10/2025 PDF12mantém6(3–6),altera7–9digitais.",
"meaning": {
"P106": "Sede/EP/domicílio do prestador a partir do qual o serviço é prestado,sem regras especiais aplicáveis. Não usar endereço/nacionalidade do cliente.",
"P107": "Local do imóvel e relação do serviço,incluindo preparação/coordenação de trabalhos imobiliários,peritos/agentes. Independente da sede do prestador.",
"P108": "Execução total ou essencial dos trabalhos/peritagens em bens móveis corpóreos. Independente da sede do prestador.",
"P109": "Local material de actividades artísticas,científicas,desportivas,recreativas,ensino/similares,organizadores e serviços acessórios;6(5)c rectificado2017.",
"P110": "Distância nacional6(5)d rectificada2017;partida/chegada nacionais incluem percurso fora do país6(6);ida/volta são dois trajectos. Identificar distância total/nacional na mesma unidade,sem apuramento monetário."
},
"formula": "Territorial classification only;P110 exact distances retained as numerator/denominator with6(6)deemednational override,no monetaryapportionment/rounding.",
"preservation": "88prior closures and partialP084/P085 preserved;accepted perbranchQA reused;one integration/backup/real isolatedrestore/check for whole set",
"partial_P084_P085": "Preparation/conditional simulation only,benefits pending;no closure",
"limits": "P084/P085partial,pending;L1open;P00105/06;beveragesL2/L3;Statistics/AIdeferred",
"containment": "l1-g8-services-readonly-rollback-20261024.patch,checked only,not applied;blocks newP106–110classifications,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"release": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"previous_release": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"release_revision": {
"commit": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"branch": "main",
"built_at": "2026-10-24T21:33:02.101616+00:00",
"manifest_sha256": "0a967a74dd5163728a082b24a62b22b9fae00a3ac428b5bcaa2082340c62ac00"
},
"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-g8-services-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "1188dd6c559ba60472c26a9332765b5157bd2b25ba66655b0311d5584c18b919",
"files_sha256": "252a84497714170faac6088de5e2f343a046092023c52c676f60628039d30f83",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g8_services_restore_20261024",
"port": 55441,
"source_dump_sha256": "1188dd6c559ba60472c26a9332765b5157bd2b25ba66655b0311d5584c18b919",
"active_database_writes": 0
}
},
"served_commit": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"release": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"previous_release": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"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": "555fd286e63d7efbd8080a4539536e17"
},
"after": {
"rows": 106,
"checksum": "1549defd5f3415c655fef9d5c1eacec9"
}
},
"sessions": {
"before": {
"rows": 84,
"checksum": "4a8cb0e5713004dc915ae58634691888"
},
"after": {
"rows": 85,
"checksum": "2dc4aeb9fab2ea3553e91d84f14e9b98"
}
}
},
"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": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"branch": "main",
"built_at": "2026-10-24T21:42:26.795541+00:00",
"manifest_sha256": "7deb424f38c7361d0a8df4d0be22464ab066a01e5aa38ece15fa62115c15f8c4"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"service-territoriality/1": [
"assets/project-dossier-CyMPKo3h.js"
],
"general_service": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
],
"immovable_service": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
],
"movable_work": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
],
"activity_service": [
"assets/project-dossier-CyMPKo3h.js"
],
"transport_service": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
],
"serviceLocations": [
"assets/project-dossier-CyMPKo3h.js"
],
"providerEstablishment": [
"assets/project-dossier-CyMPKo3h.js"
],
"propertyRelation": [
"assets/project-dossier-CyMPKo3h.js"
],
"totalEssential": [
"assets/project-dossier-CyMPKo3h.js"
],
"materialActivity": [
"assets/project-dossier-CyMPKo3h.js"
],
"routeCorresponds": [
"assets/project-dossier-CyMPKo3h.js"
],
"totalDistance": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
],
"nationalDistance": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
],
"providerCountry": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
],
"subjectRef": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-CyMPKo3h.js"
],
"08/06/2017": [
"assets/project-dossier-CyMPKo3h.js",
"assets/services-CZ5pQbhW.js"
]
},
"assets": [
{
"file": "assets/project-dossier-CyMPKo3h.js",
"status": 200,
"sha256": "2b4728486975e76e77f8f343dcd6c4f82d32385f9b70af212e204b4bb500bb69"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-document-ESDgCIR1.js",
"status": 200,
"sha256": "731071c47247f46f2f693f51dbad7e2ad7fd3f122c873b7525c844788ccedb2c"
},
{
"file": "assets/services-CZ5pQbhW.js",
"status": 200,
"sha256": "23ee3e239b2b0b3aa977486aee55212babc601b7599e42943d3298d6f4affe43"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-D23Ij5K_.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": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"release": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"previous_release": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"release": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"previous_release": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"03c26d66139f36573cf58362a5076b4d5f98eca2"
],
"finished_at": "2026-10-24T21:42:30.119032+00:00"
},
"log_file": "1792878042157298229.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 27.76s",
"OK (59 tests, 317 assertions)",
"# tests 389",
"# pass 389",
"# fail 0"
],
"log_bytes": 141421
},
"rollback_executed": false
},
"base_VAT_separation": "Accepted perbranchQA reused:P106general providerestablishment,P107propertylocation,P108total/essential movablework,P109materialactivities,P110national/deemednational/mixedroute. AvisoBR89-I08/06/2017PDF1rectification6(5)c/d maintained. Territorial classification independentof exemption/base/rate/VAT/deductionfield11. Four installedruntime hashes/18compiledmarkers;88previousclosures preserved;no syntheticactivewrite.",
"activation": "OnejointGit fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-service-location.ts
+++ b/resources/js/lib/iva-service-location.ts
@@ -56,6 +56,7 @@
function key(draft:Record<string,unknown>,book:ServiceLocationBook):string{return JSON.stringify({version:serviceLocationVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},rows:book.rows});}
export function serviceLocationCurrent(draft:Record<string,unknown>,book:ServiceLocationBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordServiceLocations(draft:Record<string,unknown>,book:ServiceLocationBook):ServiceLocationBook{
+ throw new Error('Novas classificações P106–P110 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:ServiceLocationCalculation={version:serviceLocationVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:serviceLocationSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateServiceLocation(row))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveServiceLocationBook(draft,next);return next;
@@ -0,0 +1,311 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "fb7248661dce64def0b809479b2b30fbb099ea42",
"base_installed": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"coverage_complete_branches": {
"AUD-SIM-L1-P105": [
"goods_with_transport",
"goods_without_transport",
"goods_before_import"
]
},
"branch_count_complete": 1,
"treatment_count": 3,
"runtime_delta": [
{
"path": "resources/js/lib/iva-goods-location.ts",
"sha256_LF": "c187bbaf13d408461e787786dc8cc81504fef6ed60a848f62ebffe31cfa86e6d"
},
{
"path": "resources/js/components/simulation-goods-location.tsx",
"sha256_LF": "e4440c1315a1b1009d9b51ced99d7e6a2fc65a3ebac05d6b5bde1d41a796784f"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "ca7c2185d9fcf8ffc8374be4a99d3102c7e1326372859ac678603da90b3de913"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "c95bbd7e307ab2c7dcec42fc9d280709f0ecb7c9be174977ae571cc4447bf5b9"
}
],
"counts_before": {
"delivered": 87,
"QA": 1,
"functional_pending": 44,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 88,
"QA": 0,
"functional_pending": 44,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 88,
"QA": 0,
"functional_pending": 44,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g8a-qa-20261024.json"
],
"authorization": "Tempo explicitly deployfb724866 through existingGit,preserve concurrentchanges and check installeddelta only",
"scope": "2026,bens corpóreos;classificação territorial apenas,sem base,taxa,IVA,isenção,dedução/campo11,direitos ou totaisModeloA. Não abrange digitais/serviços por esta regra.",
"meaning": "Local dos bens no início transporte/expedição ou,sem transporte,quando postos à disposição;regra especial do importador/transmissões subsequentes antes da importação nacional. Fora do território não equivale a isenção ou IVA zero.",
"formula": "Classificação territorial pelos factos6(1)/(2),sem cálculo monetário.",
"preservation": "87prior closures and partialP084/P085 preserved;acceptedQA reused;fresh backup/real isolated restore;installed delta only",
"partial_P084_P085": "Preparation/conditional simulation only,benefits pending;no closure",
"limits": "P084/P085 parciais e pendentes;L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.",
"containment": "l1-g8a-readonly-rollback-20261024.patch,checked only,not applied;blocks newP105classifications,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"release": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"previous_release": "/var/www/investmoz-homologacao/releases/cd530b248bf9dee5a6e7f1e4d710346084a2421f-0b68e7a9",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"release_revision": {
"commit": "6f1cf7b7a09796b3964b39f0b1e778f978ae60fb",
"branch": "main",
"built_at": "2026-10-24T21:23:28.102878+00:00",
"manifest_sha256": "329dea28609b9850332b63a730576a539077489d9e085235be7f344c3428f39c"
},
"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-g8a-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "8d776d1a8fe3383bf7a02b8539256ef5c9c12a8d9a07ef5e310ee70dd30de38d",
"files_sha256": "b90f41cd34fac9e2aea698e7d95eeb55893a6e1cca1c08e26d3f7ef00ca7aec3",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g8a_restore_20261024",
"port": 55441,
"source_dump_sha256": "8d776d1a8fe3383bf7a02b8539256ef5c9c12a8d9a07ef5e310ee70dd30de38d",
"active_database_writes": 0
}
},
"served_commit": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"release": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"previous_release": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"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": "b71bbd418f434e4cd252de9c8db2767f"
},
"after": {
"rows": 106,
"checksum": "430d9fb2707a97bf11f20da3f69721ae"
}
},
"sessions": {
"before": {
"rows": 81,
"checksum": "23894ba9a97f87ef8fade6cce1a1b6b9"
},
"after": {
"rows": 82,
"checksum": "f52ae0d14e4c0bd31543756d83305bb9"
}
}
},
"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": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"branch": "main",
"built_at": "2026-10-24T21:33:02.101616+00:00",
"manifest_sha256": "0a967a74dd5163728a082b24a62b22b9fae00a3ac428b5bcaa2082340c62ac00"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"goods-territoriality/1": [
"assets/project-dossier-l0g-w_hy.js"
],
"goods_with_transport": [
"assets/services-BYGK7w_P.js",
"assets/project-dossier-l0g-w_hy.js"
],
"goods_without_transport": [
"assets/project-dossier-l0g-w_hy.js"
],
"goods_before_import": [
"assets/services-BYGK7w_P.js",
"assets/project-dossier-l0g-w_hy.js"
],
"goodsLocations": [
"assets/project-dossier-l0g-w_hy.js"
],
"notBeforeImport": [
"assets/project-dossier-l0g-w_hy.js"
],
"transportToBuyer": [
"assets/project-dossier-l0g-w_hy.js"
],
"noTransport": [
"assets/project-dossier-l0g-w_hy.js"
],
"fromAbroad": [
"assets/project-dossier-l0g-w_hy.js"
],
"nationalImport": [
"assets/project-dossier-l0g-w_hy.js"
],
"importerChain": [
"assets/project-dossier-l0g-w_hy.js"
],
"beforeImport": [
"assets/project-dossier-l0g-w_hy.js"
],
"placeCountry": [
"assets/services-BYGK7w_P.js",
"assets/project-dossier-l0g-w_hy.js"
],
"placeRef": [
"assets/services-BYGK7w_P.js",
"assets/project-dossier-l0g-w_hy.js"
],
"chainRef": [
"assets/services-BYGK7w_P.js",
"assets/project-dossier-l0g-w_hy.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-l0g-w_hy.js"
]
},
"assets": [
{
"file": "assets/services-BYGK7w_P.js",
"status": 200,
"sha256": "8101fcf81fd55ca5de974667767336fe8199927e4107880c61c89ad4f1e4062d"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-l0g-w_hy.js",
"status": 200,
"sha256": "c00cf64236adbbc7a8467488e6519dba629861972cd8bff06db72b252837c16e"
},
{
"file": "assets/project-dossier-document-cHoELYnH.js",
"status": 200,
"sha256": "13303e6e5b3e96851a9f48d372ae4c763f755f97df4833293b92053094fd1934"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-BF7zA-aZ.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": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"release": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"previous_release": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "8f14f5dde24819fce062dc316ed21dfbe033ebf8",
"release": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"previous_release": "/var/www/investmoz-homologacao/releases/6f1cf7b7a09796b3964b39f0b1e778f978ae60fb-e919f615",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"8f14f5dde24819fce062dc316ed21dfbe033ebf8"
],
"finished_at": "2026-10-24T21:33:05.003586+00:00"
},
"log_file": "1792877479675740742.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 26.44s",
"OK (59 tests, 317 assertions)",
"# tests 382",
"# pass 382",
"# fail 0"
],
"log_bytes": 140139
},
"rollback_executed": false
},
"base_VAT_separation": "AcceptedQA reused:P105goods territoriality6(1)/(2),three distinct owncondition paths;physical place/time for transport or availability,preimport importer/subsequentchain override with references/scope. Outside territory not exemption/zeroVAT;classification doesnotcalculatebase/rate/VAT/deductionfield11. Inputs/history/report and87priorclosures preserved;four installedruntime hashes and16compiled markers;no syntheticactivewrites.",
"activation": "Normal Git fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-goods-location.ts
+++ b/resources/js/lib/iva-goods-location.ts
@@ -51,6 +51,7 @@
function key(draft:Record<string,unknown>,book:GoodsLocationBook):string{return JSON.stringify({version:goodsLocationVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},rows:book.rows});}
export function goodsLocationCurrent(draft:Record<string,unknown>,book:GoodsLocationBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordGoodsLocations(draft:Record<string,unknown>,book:GoodsLocationBook):GoodsLocationBook{
+ throw new Error('Novas classificações P105 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:GoodsLocationCalculation={version:goodsLocationVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:goodsLocationSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateGoodsLocation(row))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveGoodsLocationBook(draft,next);return next;
@@ -0,0 +1,402 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "4601bf64a03a02254cbf2e247374996cb36b6a49",
"base_installed": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"coverage_complete_branches": {
"AUD-SIM-L1-P111": [
"rights_service"
],
"AUD-SIM-L1-P112": [
"advertising_service"
],
"AUD-SIM-L1-P113": [
"telecom_service"
],
"AUD-SIM-L1-P114": [
"consulting_service"
],
"AUD-SIM-L1-P115": [
"data_service"
],
"AUD-SIM-L1-P116": [
"finance_service"
],
"AUD-SIM-L1-P117": [
"staff_service"
],
"AUD-SIM-L1-P118": [
"intermediation_service"
],
"AUD-SIM-L1-P119": [
"abstention_service"
],
"AUD-SIM-L1-P120": [
"movable_lease_service"
]
},
"branch_count_complete": 10,
"treatment_count": 10,
"runtime_delta": [
{
"path": "resources/js/lib/iva-listed-services.ts",
"sha256_LF": "fdc05407576a6c68f8158bc797331380c09e84282609a06ae2a7aa2966c54db6"
},
{
"path": "resources/js/components/simulation-listed-services.tsx",
"sha256_LF": "77badfa54c3bb6e25fe5153bb852cebc48262b64b4aabc9348a2b1838094917a"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "43446ed6a23b0e101d72ea50f73cdbae0242ace92af12d836a0955cc85800d82"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "fea39f530bf7786778dbdadbb6b08678f2a4071bcccc264e3d026155477517c8"
}
],
"counts_before": {
"delivered": 93,
"QA": 10,
"functional_pending": 29,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 103,
"QA": 0,
"functional_pending": 29,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 103,
"QA": 0,
"functional_pending": 29,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-g9-nondigital-qa-20261024.json"
],
"authorization": "Tempo explicitly requests one joint delivery of4601bf64,P111–P120,main compatibility/concurrent changes preserved,installeddelta only",
"scope": "2026,serviços enumerados não digitais;localização e identificação do responsável pelas obrigações. Sem isenção confirmada,base,taxa,IVA,montante a pagar,dedução/campo11 ou totaisModeloA. P121/P130digitais eP002transversal não fechados;outros6(4)/(5)encaminhados para percursos próprios. Não automatiza declaração,pagamento,retenção ou prazo digital32(1)c.",
"source": "CIVA2(1)a/b,2(2),6(3),6(7)a–j e6(8),Lei13/2016PDF6–8/p1426(264–266);23(1)/(2),25(4),26(1–3),PDF16–17. Lei22/2022não altera estes artigos. Lei10/2025PDF12mantém alíneasa–j ealtera6(7–9);PDF13art23(2)excluik e remete declaração33(2);PDF14mantém26(1–3),adita26(4)digital ealtera33(2).",
"meaning": {
"P111": {
"clause": "6(7)a",
"treatment": "rights_service",
"nature": "Cessão/autorização de direitos de autor,licenças,marcas e análogos"
},
"P112": {
"clause": "6(7)b",
"treatment": "advertising_service",
"nature": "Publicidade"
},
"P113": {
"clause": "6(7)c",
"treatment": "telecom_service",
"nature": "Telecomunicações"
},
"P114": {
"clause": "6(7)d",
"treatment": "consulting_service",
"nature": "Consultores,engenheiros,advogados,economistas,contabilistas/gabinetes de estudos,organização,investigação/desenvolvimento e similares"
},
"P115": {
"clause": "6(7)e",
"treatment": "data_service",
"nature": "Tratamento de dados/fornecimento de informações"
},
"P116": {
"clause": "6(7)f",
"treatment": "finance_service",
"nature": "Operações bancárias,financeiras,seguro/resseguro;eventual isenção independente"
},
"P117": {
"clause": "6(7)g",
"treatment": "staff_service",
"nature": "Colocação de pessoal"
},
"P118": {
"clause": "6(7)h",
"treatment": "intermediation_service",
"nature": "Intermediação em nome epor conta de outrem no fornecimento de serviço enumerado,subjacente identificado"
},
"P119": {
"clause": "6(7)i",
"treatment": "abstention_service",
"nature": "Obrigação de não exercer,mesmo parcialmente,actividade/direito enumerado,subjacente identificado"
},
"P120": {
"clause": "6(7)j",
"treatment": "movable_lease_service",
"nature": "Locação de bens móveis corpóreos,incluindo financeira,bens/contrato identificados"
}
},
"formula": "Territorial classification and responsible party only,no monetarycalculation. No righttodeduction prerequisite for6(7);nondigital23(2)excludedigital26(4)/32(1)c routing.",
"preservation": "93prior closures and partialP084/P085 preserved;accepted perbranchQA reused;one integration/backup/real isolatedrestore/check for whole set",
"partial_P084_P085": "Preparation/conditional simulation only,benefits pending;no closure",
"limits": "P084/P085partial,pending;L1open;P00105/06;beveragesL2/L3;Statistics/AIdeferred",
"containment": "l1-g9-nondigital-readonly-rollback-20261024.patch,checked only,not applied;blocks newP111–120classifications,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"release": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"previous_release": "/var/www/investmoz-homologacao/releases/8f14f5dde24819fce062dc316ed21dfbe033ebf8-6abb42c2",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"release_revision": {
"commit": "03c26d66139f36573cf58362a5076b4d5f98eca2",
"branch": "main",
"built_at": "2026-10-24T21:42:26.795541+00:00",
"manifest_sha256": "7deb424f38c7361d0a8df4d0be22464ab066a01e5aa38ece15fa62115c15f8c4"
},
"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-g9-nondigital-delivery-20261024/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "8d783acaa134d37d4d5d7da2842f3a4a2ca159cab444b10b127fc1baf7113ac2",
"files_sha256": "195de1b12e33ce73510143f009a10cae42f622093e6049d36389e2849e3a117b",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_g9_nondigital_restore_20261024",
"port": 55441,
"source_dump_sha256": "8d783acaa134d37d4d5d7da2842f3a4a2ca159cab444b10b127fc1baf7113ac2",
"active_database_writes": 0
}
},
"served_commit": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"release": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"previous_release": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"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": "38b2f9e034cc821c5c1b47b85fcf4cf2"
},
"after": {
"rows": 106,
"checksum": "fc22bd1093218afa1777652f5fffb28c"
}
},
"sessions": {
"before": {
"rows": 87,
"checksum": "104d8807ca3446d84e590d48138eb3bc"
},
"after": {
"rows": 90,
"checksum": "242150536cdc201c41ae0e40414c384d"
}
}
},
"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": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"branch": "main",
"built_at": "2026-10-24T21:51:55.419637+00:00",
"manifest_sha256": "a04bb2c3e527c027aa263827b37e1566b67b372c479904112cfef79de9bcf2fb"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"listed-nondigital-services/1": [
"assets/project-dossier-DBVXbPWM.js"
],
"rights_service": [
"assets/project-dossier-DBVXbPWM.js"
],
"advertising_service": [
"assets/project-dossier-DBVXbPWM.js"
],
"telecom_service": [
"assets/project-dossier-DBVXbPWM.js"
],
"consulting_service": [
"assets/project-dossier-DBVXbPWM.js"
],
"data_service": [
"assets/project-dossier-DBVXbPWM.js"
],
"finance_service": [
"assets/project-dossier-DBVXbPWM.js"
],
"staff_service": [
"assets/project-dossier-DBVXbPWM.js"
],
"intermediation_service": [
"assets/services-D1gOx3Gd.js",
"assets/project-dossier-DBVXbPWM.js"
],
"abstention_service": [
"assets/services-D1gOx3Gd.js",
"assets/project-dossier-DBVXbPWM.js"
],
"movable_lease_service": [
"assets/project-dossier-DBVXbPWM.js"
],
"listedServices": [
"assets/project-dossier-DBVXbPWM.js"
],
"recipientType": [
"assets/services-D1gOx3Gd.js",
"assets/project-dossier-DBVXbPWM.js"
],
"recipientRef": [
"assets/services-D1gOx3Gd.js",
"assets/project-dossier-DBVXbPWM.js"
],
"targetClause": [
"assets/services-D1gOx3Gd.js",
"assets/project-dossier-DBVXbPWM.js"
],
"targetRef": [
"assets/services-D1gOx3Gd.js",
"assets/project-dossier-DBVXbPWM.js"
],
"providerTaxable": [
"assets/services-D1gOx3Gd.js",
"assets/project-dossier-DBVXbPWM.js"
],
"responsible": [
"assets/project-dossier-DBVXbPWM.js"
],
"obligationReason": [
"assets/project-dossier-DBVXbPWM.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-DBVXbPWM.js"
]
},
"assets": [
{
"file": "assets/services-D1gOx3Gd.js",
"status": 200,
"sha256": "76f46314d8d000351ccb43a22737352bd8455e6db4db3954dab0949fdc9f7176"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-DBVXbPWM.js",
"status": 200,
"sha256": "64051d89dabde0c3c23f22396a2d13a3b10413ca1bae4d9f80c65fff2d56ace6"
},
{
"file": "assets/project-dossier-document-CafLZ1EI.js",
"status": 200,
"sha256": "93c06e2dd413c6309f1d4af50c300924764589afe7ee57ff06e4b960043c2a5b"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-qriXxj5i.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": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"release": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"previous_release": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "2a7254406db3aa6e8c71bfbaf56bbcda1f139d19",
"release": "/var/www/investmoz-homologacao/releases/2a7254406db3aa6e8c71bfbaf56bbcda1f139d19-ae306e0a",
"previous_release": "/var/www/investmoz-homologacao/releases/03c26d66139f36573cf58362a5076b4d5f98eca2-ac76aca8",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"2a7254406db3aa6e8c71bfbaf56bbcda1f139d19"
],
"finished_at": "2026-10-24T21:51:58.085449+00:00"
},
"log_file": "1792878609052376699.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 28.19s",
"OK (59 tests, 317 assertions)",
"# tests 401",
"# pass 401",
"# fail 0"
],
"log_bytes": 143948
},
"rollback_executed": false
},
"base_VAT_separation": "AcceptedQA reused for10branches/30examples:nondigital6(7)a–j inbound,6(8)outbound and6(3)domestic;acquirerquality2(1)a/b including exclusivelyexemptwithoutdeduction;responsible2(2)/23(2)/33(2)separatefromterritory/exemption/base/rate/VAT/deductionfield11. No digital26(4)/32(1)c automaticroute. Inputs/history/report and93priorclosures preserved;4installedruntimehashes/20compiledmarkers;no syntheticactivewrites.",
"activation": "OnejointGit fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-listed-services.ts
+++ b/resources/js/lib/iva-listed-services.ts
@@ -71,6 +71,7 @@
function key(draft:Record<string,unknown>,book:ListedServiceBook):string{return JSON.stringify({version:listedServiceVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},rows:book.rows});}
export function listedServiceCurrent(draft:Record<string,unknown>,book:ListedServiceBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordListedServices(draft:Record<string,unknown>,book:ListedServiceBook):ListedServiceBook{
+ throw new Error('Novas classificações P111–P120 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:ListedServiceCalculation={version:listedServiceVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:listedServiceSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateListedService(row))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveListedServiceBook(draft,next);return next;
@@ -0,0 +1,346 @@
{
"status": "installed_delta_verified_partial_L1",
"candidate": "cd259623aed6e8831091866de02d5e5db4ef1818",
"base_installed": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"coverage_complete_branches": {
"AUD-SIM-L1-P088": [
"permanent_private_goods",
"free_goods_transfer",
"exempt_sector_goods",
"fixed_asset_20a"
],
"AUD-SIM-L1-P124": [
"permanent_private_goods",
"free_goods_transfer",
"exempt_sector_goods",
"fixed_asset_20a"
]
},
"branch_count_complete": 2,
"treatment_count": 4,
"runtime_delta": [
{
"path": "resources/js/lib/iva-goods-allocation.ts",
"sha256_LF": "6646a2054ebd4e6731b60719d36ce922ed50f2e062e0f980190eb20ce8c23d20"
},
{
"path": "resources/js/components/simulation-goods-allocation.tsx",
"sha256_LF": "08c84f4b9af21e46cd9d5af6f6bee9e12c14b111438f1649a694a27f36d14180"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "1b27e8d3a6c79c6f8769bf5158ed8be45718f655b13cdf23b517bdb44c5a6951"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "c5de565ff7ded1fcf4d1f3a025694d3e2af4ff75e55266463758e8c1c5fcc314"
}
],
"counts_before": {
"delivered": 109,
"QA": 2,
"functional_pending": 21,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 111,
"QA": 0,
"functional_pending": 21,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 111,
"QA": 0,
"functional_pending": 21,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-goods-allocation-qa-20261025.json"
],
"authorization": "Tempo explicitly requests one joint delivery ofcd259623,P088/P124,main compatibility/concurrent changes preserved,installeddelta only",
"scope": "2026/MZN,quatro tratamentos partilhados entre dois requisitos sobre a mesma operação,registada uma vez. Distinto de uso temporário de bens como serviçoP089. Sem nova dedução/campo11,regularização,taxaIVA,IVA ou totaisModeloA;dedução anterior apenas facto histórico. Excepçãoamostras/ofertas fica fora deste percurso quando aplicável;desconhecido permanece indeterminado.",
"source": "CIVA3(3)e/f,Lei13/2016PDF6–7/p1426(264–265);15(2)b,PDF13/p1426(271);20(1)a,PDF15/p1426(273). Lei22/2022PDF3mantém15(2)b e20(1)a;Lei10/2025PDF12mantém3(3)e/f e não altera15/20.",
"meaning": {
"P124": "Classificação da afectação permanente de bens a uso próprio/particular/alheio,transmissão gratuita,afectação a sector isento ou aoactivo imobilizado de bens20(1)a. Exige dedução anterior total/parcial nos bens/elementos;em3e conferir excepção de amostras/ofertas depequeno valor,sem limiar inventado. Facto histórico de dedução,não nova dedução.",
"P088": "Base15(2)b:preço aquisição ou,na sua falta demonstrada,preço custo,reportados ao momento da operação. ClassificaçãoP124 pode estar identificada ebaseP088 indeterminada;sem custo por defeito para preço aquisição desconhecido."
},
"formula": "15(2)b:current acquisitionprice;only if absent,currentcost.No automaticvaluation/update/depreciation/deduction.",
"preservation": "109prior closures and partialP084/P085 preserved;accepted perbranchQA reused;one integration/backup/real isolatedrestore/check for whole set",
"partial_P084_P085": "Preparation/conditional simulation only,benefits pending;no closure",
"limits": "L1open;newdeduction/regularisationoutsideincrement;P00105/06;P121digital/P084/P085pending;beveragesL2/L3;Statistics/AIdeferred",
"containment": "l1-goods-allocation-readonly-rollback-20261025.patch,checked only,not applied;blocks newP096–099classifications,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"release": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"previous_release": "/var/www/investmoz-homologacao/releases/2fdca86367d8bad524113b4cf6c49a0110130be9-c65ebbad",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"release_revision": {
"commit": "63cc336787cade92fb7ee5b2b2d407308a0cf66b",
"branch": "main",
"built_at": "2026-10-24T22:09:58.694541+00:00",
"manifest_sha256": "40f4377487ec290e47d1bee92146172fa4e2a316fa4a072dcc82300fea3cc6c1"
},
"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-goods-allocation-delivery-20261025/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "a78973a94e05f58ab4cea4bebedca4603d7f68aa4a0d8a46b889d27751514e64",
"files_sha256": "9302d0e283a5ea2619de1fbe5853d4c2e563d455d7aafb7e88203eafc6ef85e1",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_goods_allocation_restore_20261024",
"port": 55441,
"source_dump_sha256": "a78973a94e05f58ab4cea4bebedca4603d7f68aa4a0d8a46b889d27751514e64",
"active_database_writes": 0
}
},
"delivery_local_date": "2026-10-25",
"delivery_timezone": "Africa/Johannesburg",
"served_commit": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"installation": {
"protected": {
"installed": {
"status": "installed",
"commit": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"release": "/var/www/investmoz-homologacao/releases/6c12aabb3ac7f8296025a2af0408390bfe292bdb-4c33615a",
"previous_release": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"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": "09d3d422c9a8be947a5b477dbee30bb4"
},
"after": {
"rows": 106,
"checksum": "898f63b7cbe166244f5a4ea6d0803cb2"
}
},
"sessions": {
"before": {
"rows": 96,
"checksum": "375984b4326c2b632b66fba47946b8c8"
},
"after": {
"rows": 97,
"checksum": "acfde110c5f28d239ee13f14da01e6b7"
}
}
},
"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": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"branch": "main",
"built_at": "2026-10-24T22:19:07.102372+00:00",
"manifest_sha256": "91a95647c3666b2dc9a322fbf7534e055c616872c791920d2cc004234c1b0d25"
},
"manifest_hash_matches": true,
"compiled_delta_markers": {
"goods-allocation-base/1": [
"assets/project-dossier-Dnh3xPdC.js"
],
"permanent_private_goods": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"free_goods_transfer": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"exempt_sector_goods": [
"assets/project-dossier-Dnh3xPdC.js"
],
"fixed_asset_20a": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"regulatedGoodsAllocations": [
"assets/project-dossier-Dnh3xPdC.js"
],
"priorDeduction": [
"assets/project-dossier-Dnh3xPdC.js"
],
"deductionRef": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"acquisitionPrice": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"acquisitionRef": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"currentCost": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"costRef": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"valuationMode": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"valuationConfirmed": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"acquisitionUnavailable": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"valuationScope": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"valuationDate": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"asset20aRef": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"exceptionRef": [
"assets/services-B0mFnttq.js",
"assets/project-dossier-Dnh3xPdC.js"
],
"IVA: Indeterminado": [
"assets/project-dossier-Dnh3xPdC.js"
]
},
"assets": [
{
"file": "assets/services-B0mFnttq.js",
"status": 200,
"sha256": "8e586f10c4efa6ad9805ed75ba0c21f68b1550d9a697959b5f51c966b40ace45"
},
{
"file": "assets/project-dossier-Dnh3xPdC.js",
"status": 200,
"sha256": "a02b40fbbafa16651af80f74b6d0486b8fb086b404151bcf1a25690252138d40"
},
{
"file": "assets/simulation-form-CPZAFZU3.js",
"status": 200,
"sha256": "c6bcf64e60a5eeac0cafe3dc055dc5544162f21942ee08b34d51bc6d52947567"
},
{
"file": "assets/project-dossier-document-Cb9azkcP.js",
"status": 200,
"sha256": "08aa7a6c7f2b78ddfdd69b51c355f186b6811171bd702275bf76fe3369aa87d9"
}
],
"simulator_status": 200,
"simulator_entry": "assets/app-Cy6kCwzN.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": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"release": "/var/www/investmoz-homologacao/releases/6c12aabb3ac7f8296025a2af0408390bfe292bdb-4c33615a",
"previous_release": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"database_migrations": 0,
"content_imports": 0
},
"latest_report": {
"status": "installed",
"commit": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"release": "/var/www/investmoz-homologacao/releases/6c12aabb3ac7f8296025a2af0408390bfe292bdb-4c33615a",
"previous_release": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"database_migrations": 0,
"content_imports": 0,
"requested_commits": [
"6c12aabb3ac7f8296025a2af0408390bfe292bdb"
],
"finished_at": "2026-10-24T22:19:10.041371+00:00"
},
"log_file": "1792880241239958545.log",
"summaries": [
"OK (1 test, 3106 assertions)",
"built in 26.70s",
"OK (59 tests, 317 assertions)",
"# tests 420",
"# pass 420",
"# fail 0"
],
"log_bytes": 148552
},
"rollback_executed": false
},
"base_VAT_separation": "AcceptedQA reused:P124assimilatedgoods classification3(3)e/f andP088base15(2)b,four sharedtreatments,one operationidentity. Prior total/partialdeduction is historicalfact ongoods/elements,not newdeduction/field11 orregularisation. Base=currentacquisitionprice;currentcostonlyin demonstratedabsence ofacquisitionprice. Unknownfallback retainsclassification withindeterminatebase;unknownhistoricaldeduction leavesclassificationindeterminate. No tax/IVA/regularisationcalculated. Fourinstalledruntimehashes/20compiledmarkers;109priorclosures preserved;no syntheticactivewrites.",
"activation": "OnejointGit fast-forward/webhook/installer;zero migrations/imports"
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-goods-allocation.ts
+++ b/resources/js/lib/iva-goods-allocation.ts
@@ -55,6 +55,7 @@
function key(draft:Record<string,unknown>,book:GoodsAllocationBook):string{return JSON.stringify({version:goodsAllocationVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function goodsAllocationCurrent(draft:Record<string,unknown>,book:GoodsAllocationBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordGoodsAllocations(draft:Record<string,unknown>,book:GoodsAllocationBook):GoodsAllocationBook{
+ throw new Error('Novas classificações P088/P124 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:GoodsAllocationCalculation={version:goodsAllocationVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:goodsAllocationSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateGoodsAllocation(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveGoodsAllocationBook(draft,next);return next;
@@ -0,0 +1,143 @@
{
"status": "ready_after_fresh_authenticated_preflight_and_verified_backup_restore",
"candidate": "0ebb20c86a8cfcee9fae56c38f6bfdc6b2ab80ab",
"base_installed": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"coverage_complete_branches": {
"AUD-SIM-L1-P092": [
"reseller_margin"
],
"AUD-SIM-L1-P093": [
"auction_margin"
],
"AUD-SIM-L1-P125": [
"used_goods",
"art",
"collection",
"antique"
]
},
"branch_count_complete": 3,
"treatment_count": 2,
"category_count": 4,
"QA_example_count": 8,
"runtime_delta": [
{
"path": "resources/js/lib/iva-secondhand.ts",
"sha256_LF": "de9cab0f8685c0be1072ce0b8b5ae98865383fa52f4487ecb62514ddb28d6fdc"
},
{
"path": "resources/js/components/simulation-secondhand.tsx",
"sha256_LF": "7a715a05635137d3b7b8a1eb3d554646c4553430904613235199fc6a254cec20"
},
{
"path": "resources/js/components/simulation-monthly-iva.tsx",
"sha256_LF": "338d5c4b9b60b2be6b3f059c543c92127222f621424854cba9a19651d86d2967"
},
{
"path": "resources/js/lib/project-dossier.ts",
"sha256_LF": "fe0b12b2acc5d1a59c862abf6c96e2e09c51193fc2e090e475dc0ec8673e23c9"
}
],
"counts_before": {
"delivered": 111,
"QA": 3,
"functional_pending": 18,
"documentary": 1,
"total": 133
},
"counts_current": {
"delivered": 111,
"QA": 3,
"functional_pending": 18,
"documentary": 1,
"total": 133
},
"counts_after_delivery": {
"delivered": 114,
"QA": 0,
"functional_pending": 18,
"documentary": 1,
"total": 133
},
"QA_proofs_reused": [
"iva-l1-secondhand-qa-20261025.json"
],
"authorization": "Tempo explicitly requests one joint delivery of0ebb20c8,P092/P093/P125,preserving concurrent changes and installeddelta only",
"scope": "2026/MZN,transmissões internas tributáveis e aquisição nacional com qualidade do fornecedor/comitente demonstrada. Duas fórmulas, quatro categorias, oito exemplos e três ramos; uma operação individual, sem dupla contagem. Apenas classificação/base:sem IVA calculado,nova dedução,campo11,regularização ou totaisModeloA. IVA identificado no leilão é componente referenciada. Exportação isenta e opção normal separadas; origens legadas35/42 permanecem indeterminadas.",
"source": "CIVA Lei13/2016:3(3)g/3(6),PDF7,p1426(265);15(2)f/g,PDF13,p1426(271). RIVA Decreto7/2008,BR16-I de16/04/2008,arts47–49,PDF8–9,p106–107. Lei22/2022 PDF3 mantém15f/g e fixa17(1)16%. Lei10/2025 não altera15/17 e revoga regimes35/42;referência antiga não os reactiva. Rectificação2017 sem alteração destas disposições.",
"meaning": {
"P092": "Revendedor: margem individual positiva da contraprestação total com IVA menos preço de compra justificado; dividir por 1.16 e arredondar a base à unidade. Perda conservada no bem, sem compensação entre transmissões. Opção pelo regime normal fica separada.",
"P093": "Organizador em nome próprio por conta do comitente, contrato de comissão e venda em leilão: base = facturado ao comprador menos líquido do comitente menos IVA próprio identificado. Líquido = adjudicação menos comissão. IVA desconhecido não é zero.",
"P125": "Classificação própria: bem usado reutilizável, arte, colecção ou antiguidade superior a 100 anos; critérios de 3(6) conservados. Categoria identificada não activa automaticamente a margem. Tiragem limitada a 200 exemplares e cerâmica única executada/assinada pelo artista nos percursos respectivos."
},
"classification_margin_separation": "P125 classifies goods;P092/P093 independently require eligible supplier/principal,territorial and regimeconditions;no automaticmargineligibility",
"preservation": "111priorclosures andpartialP084/P085 preserved;acceptedperbranchQA reused;one integration/backup/realisolatedrestore/check forwhole set",
"partial_P084_P085": "Preparation/conditional simulation only;benefits pending;no closure",
"limits": "L1aberto;P00105/06;P121digital/P084/P085pendentes;bebidasL2/L3;Estatísticas/IAadiadas",
"containment": "l1-secondhand-readonly-rollback-20261025.patch,checked only,not applied;blocks newP092/P093/P125calculations,preserves readers/history/otherbranches",
"authenticated_preflight": {
"installed": {
"status": "installed",
"commit": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"release": "/var/www/investmoz-homologacao/releases/6c12aabb3ac7f8296025a2af0408390bfe292bdb-4c33615a",
"previous_release": "/var/www/investmoz-homologacao/releases/63cc336787cade92fb7ee5b2b2d407308a0cf66b-a32af166",
"database_migrations": 0,
"content_imports": 0
},
"current_link": "/var/www/investmoz-homologacao/releases/6c12aabb3ac7f8296025a2af0408390bfe292bdb-4c33615a",
"release_revision": {
"commit": "6c12aabb3ac7f8296025a2af0408390bfe292bdb",
"branch": "main",
"built_at": "2026-10-24T22:19:07.102372+00:00",
"manifest_sha256": "91a95647c3666b2dc9a322fbf7534e055c616872c791920d2cc004234c1b0d25"
},
"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-secondhand-delivery-20261025/backup",
"target": {
"database": "teste_investidor",
"port": 5432
},
"tables": 174,
"files_verified": 369,
"dump_sha256": "d7c0767888ce08fcb078020cefe7a83634849939c6d436911475d6779a640c01",
"files_sha256": "e3b297c870dd26676004c495c1893cebf68be0ccbc013b2c073b93f63a4643e6",
"restore_verified": false
},
"restore": {
"restore_verified": true,
"tables_verified": 174,
"container_network": "none",
"database": "l1_secondhand_restore_20261024",
"port": 55441,
"source_dump_sha256": "d7c0767888ce08fcb078020cefe7a83634849939c6d436911475d6779a640c01",
"active_database_writes": 0
}
}
}
@@ -0,0 +1,10 @@
--- a/resources/js/lib/iva-secondhand.ts
+++ b/resources/js/lib/iva-secondhand.ts
@@ -74,6 +74,7 @@
function key(draft:Record<string,unknown>,book:SecondhandBook):string{return JSON.stringify({version:secondhandVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function secondhandCurrent(draft:Record<string,unknown>,book:SecondhandBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordSecondhands(draft:Record<string,unknown>,book:SecondhandBook):SecondhandBook{
+ throw new Error('Novos cálculos P092/P093/P125 temporariamente suspensos;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:SecondhandCalculation={version:secondhandVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:secondhandSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateSecondhand(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveSecondhandBook(draft,next);return next;
@@ -1,5 +1,437 @@
# Rastreabilidade, utilização e formação
## 25/10/2026 — P092/P093/P125 concluídos em QA: segunda mão e leilões
Implementação `b0818c01`. Três ramos, duas fórmulas de base e quatro categorias, conferidos em oito exemplos. A classificação P125 partilha a mesma operação com P092 ou P093; não soma uma segunda base. CIVA Lei13/2016:3(3)g/3(6),PDF7,p1426(265);15(2)f/g,PDF13,p1426(271). RIVA Decreto7/2008,BR16-I de16/04/2008,arts47–49,PDF8–9,p106–107. Lei22/2022 PDF3 mantém15f/g e fixa17(1)16%. Lei10/2025 não altera15/17 e revoga regimes35/42;referência antiga não os reactiva. Rectificação2017 sem alteração destas disposições.
- **P092**: Revendedor: margem individual positiva da contraprestação total com IVA menos preço de compra justificado; dividir por 1.16 e arredondar a base à unidade. Perda conservada no bem, sem compensação entre transmissões. Opção pelo regime normal fica separada.
- **P093**: Organizador em nome próprio por conta do comitente, contrato de comissão e venda em leilão: base = facturado ao comprador menos líquido do comitente menos IVA próprio identificado. Líquido = adjudicação menos comissão. IVA desconhecido não é zero.
- **P125**: Classificação própria: bem usado reutilizável, arte, colecção ou antiguidade superior a 100 anos; critérios de 3(6) conservados. Categoria identificada não activa automaticamente a margem. Tiragem limitada a 200 exemplares e cerâmica única executada/assinada pelo artista nos percursos respectivos.
2026/MZN,transmissões internas tributáveis e aquisição nacional com qualidade do fornecedor/comitente demonstrada. Duas fórmulas, quatro categorias, oito exemplos e três ramos; uma operação individual, sem dupla contagem. Apenas classificação/base:sem IVA calculado,nova dedução,campo11,regularização ou totaisModeloA. IVA identificado no leilão é componente referenciada. Exportação isenta e opção normal separadas; origens legadas35/42 permanecem indeterminadas.
Reutilizar dados/documentos e registar referências ou pressupostos expressos. O livro regulatedSecondhands conserva entradas/resultados/histórico por oportunidade, integra a gravação/recuperação privada e o relatório existente. Trocar percurso/categoria conserva campos ocultos e obriga a rever apenas as confirmações afectadas. Arredondamento da base de revenda à unidade mais próxima por48(6)b;empate para cima é escolha técnica explícita. Montantes com seis casas e BigInt. Prazo do relatório ao comitente de cinco dias úteis identificado, sem inventar calendário. Não emitir factura fiscal nem relatório legal ao comitente por esta simulação.
Verificação:11testesfrontend,APIprivada1teste/35asserções comrollback emQAisolada55441,tipos ebuild aprovados. Edge/CUA:compra desconhecida deixa base indeterminada;perda individual mantémbasezero sem compensar outros bens;restauro dos valores,gravação,recuperação e relatório oito operações,bases138.00x4/344.83x4MZN,quatro versões anteriores,IVA/taxanull. Todos os livros anteriores comparados com congelamento;111fechos preservados,sem perdas confirmadas,provas6c12aabb/ec786f4a reutilizadas. Relatório `docs\investmoz\simulations\iva-l1-secondhand-qa-20261025.json`,prova `C:\laragon\www\portal-investidor\outputs\iva-l1-secondhand-20261025/verification.json`,imagem `qa-recovered-report.png`. Sem escrita no activo.
**111entregues +3QA +18funcionaispendentes +P001=133**. Homologação `6c12aabb`;entrega conjunta pendente,sem entrega individual por ramo. L1aberto;P00105/06;P121digital/P084/P085pendentes;bebidasL2/L3;Estatísticas/IAadiadas.
## 25/10/2026 — preparação conjunta P092/P093/P125
Inventariados111fechos antes dos testes,sem perdas confirmadas;provas6c12aabb/ec786f4a reutilizadas.Congelados livros/resultados/históricos incluindoP088/P124/P091/P122/P128 eP084/P085parciais.QAporramo eentrega conjunta futura,sem alterações noactivo.CIVA3(3)g/3(6),15(2)f/g,2016PDF7/13;RIVADecreto7/2008arts47–49,acervoBR16-I16/04/2008PDF8–9;2022mantém15f/g;2025revoga regimes35/42,não os reactivar por referência antiga.Regularização/dedução fora.Revenda:margem individual sem compensação entrebens;base de margem positiva comdivisor1.16 e arredondamento à unidade47/48.Leilão:facturado−líquidocomitente−IVApróprio identificado,sem IVAzero presumido.
## 25/10/2026 — G7N/G10C/P088/P124 entregues numa operação conjunta
Homologação **`6c12aabb`**,sobre`63cc3367`;candidata`cd259623` expressamente aceite pela Tempo. Dois ramos,quatro tratamentos,uma integração/backup/restauro/instalação/conferência,provas individuaisQA reutilizadas.
- **P124**: Classificação da afectação permanente de bens a uso próprio/particular/alheio,transmissão gratuita,afectação a sector isento ou aoactivo imobilizado de bens20(1)a. Exige dedução anterior total/parcial nos bens/elementos;em3e conferir excepção de amostras/ofertas depequeno valor,sem limiar inventado. Facto histórico de dedução,não nova dedução.
- **P088**: Base15(2)b:preço aquisição ou,na sua falta demonstrada,preço custo,reportados ao momento da operação. ClassificaçãoP124 pode estar identificada ebaseP088 indeterminada;sem custo por defeito para preço aquisição desconhecido.
CIVA3(3)e/f,Lei13/2016PDF6–7/p1426(264–265);15(2)b,PDF13/p1426(271);20(1)a,PDF15/p1426(273). Lei22/2022PDF3mantém15(2)b e20(1)a;Lei10/2025PDF12mantém3(3)e/f e não altera15/20. 2026/MZN,quatro tratamentos partilhados entre dois requisitos sobre a mesma operação,registada uma vez. Distinto de uso temporário de bens como serviçoP089. Sem nova dedução/campo11,regularização,taxaIVA,IVA ou totaisModeloA;dedução anterior apenas facto histórico. Excepçãoamostras/ofertas fica fora deste percurso quando aplicável;desconhecido permanece indeterminado. Uma operação partilhada entreP124classificação eP088base,sem dupla entrada/soma. Dedução anterior apenas facto histórico exigido pela fonte,não nova dedução ou regularização. Base pelo preço aquisição ou,na sua falta demonstrada,custo reportado ao momento da operação. Sem preenchimento do campo11.Factos/referências/datas/âmbito,entradas imutáveis/histórico/relatório preservados. Desconhecido não é zero;fora do território não é isenção/IVAzero;sem certificados/aprovadores novos.
Compatibilidade com main e destino conferida,sem avanço concorrente encontrado;fast-forward normal,sem sobrescrever alterações. SessãoSSH existente autenticada reutilizada,sem guardar credenciais. Backup novo e restauro real isolado sem rede:174tabelas/369ficheiros/configuração. Conferido apenas delta instalado:revisão servida,manifesto/hash,20marcadores compilados,quatro hashes funcionais e simuladorHTTP200. PostgreSQL pela mesma identidade antes/depois:174tabelas/369ficheiros e29fichas publicadas/28relações/408geometrias preservados;diferenças apenascache/sessões. Zero migrações/importações/alterações de permissões ou ensaios sintéticos no activo. Contenção de novas classificações conferida,não aplicada;leitores/histórico/outrosramos preservados. Release/backup anteriores conservados.
[Manifesto/recibo](../simulations/l1-goods-allocation-delivery-20261025.json),registo`iva_l1_goods_allocation_P088_P124_homologation_20261025`. **111entregues +21funcionaispendentes +P001=133**,sem candidatasQApor disponibilizar. Os109fechos anteriores preservados. P084/P085 continuam incluídos nos21,apenas preparação/simulação condicionada;P002transversal eL1abertos;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. ManterQAporramo eentregasconjuntas compatíveis.
## 25/10/2026 — P088/P124 concluídos emQA,classificação de afectações ebase aquisição/custo
Implementação`9b95e5e7`. Dois ramos,quatro tratamentos partilhados:afectação permanente privada,transmissão gratuita,sector isento,activo imobilizado20(1)a.Uma operação registada uma vez,coberturaP124/P088 distinta,não oito tratamentos nem dupla base. CIVA3(3)e/f,Lei13/2016PDF6–7/p1426(264–265);15(2)b,PDF13/p1426(271);20(1)a,PDF15/p1426(273). Lei22/2022PDF3mantém15(2)b e20(1)a;Lei10/2025PDF12mantém3(3)e/f e não altera15/20.
- **P124**: Classificação da afectação permanente de bens a uso próprio/particular/alheio,transmissão gratuita,afectação a sector isento ou aoactivo imobilizado de bens20(1)a. Exige dedução anterior total/parcial nos bens/elementos;em3e conferir excepção de amostras/ofertas depequeno valor,sem limiar inventado. Facto histórico de dedução,não nova dedução.
- **P088**: Base15(2)b:preço aquisição ou,na sua falta demonstrada,preço custo,reportados ao momento da operação. ClassificaçãoP124 pode estar identificada ebaseP088 indeterminada;sem custo por defeito para preço aquisição desconhecido.
2026/MZN,quatro tratamentos partilhados entre dois requisitos sobre a mesma operação,registada uma vez. Distinto de uso temporário de bens como serviçoP089. Sem nova dedução/campo11,regularização,taxaIVA,IVA ou totaisModeloA;dedução anterior apenas facto histórico. Excepçãoamostras/ofertas fica fora deste percurso quando aplicável;desconhecido permanece indeterminado. Preço/custo reportado ao momento da operação,comdata/âmbito;esse campo temporal não impõe novo documento emitido na mesma data.Reutilizar referências epressupostos expressos,sem certificado/aprovador/limiar inventado.Custo não é alternativa automática para aquisição desconhecida.Sem actualização automática de custos/depreciações.regulatedGoodsAllocations poroportunidade nosnapshot/API/dossier existentes;troca conserva valores ocultos e exige rever factos/avaliação,escolha técnica de integridade.
Sete testes funcionais:quatro tratamentos+P124factos/P088base separados+subsidiariedade custo/precisão/troca+preservação/persistência/histórico/relatório.APIprivada1teste/27asserções comrollback emQAisolada55441;tipos/build aprovados.Edge/CUA:falta aquisição por esclarecer conserva classificação masbase indeterminada;dedução histórica desconhecida torna classificação indeterminada;restaurados factos egravação/recuperação/relatório4operações1000.25/800.15/1000.25/800.15MZN,4versõesanteriores,IVA/taxanull.Comparados todos oslivros anteriores comcongelamento,incluindoP091/P089/P122/P128/P096–P099/P111–P120 eP084/P085parciais;109fechos preservados,provas anteriores reutilizadas.Relatório`docs\investmoz\simulations\iva-l1-goods-allocation-qa-20261025.json`;evidência`C:\laragon\www\portal-investidor\outputs\iva-l1-goods-allocation-20261025/verification.json` eimagem`qa-recovered-report.png`.Sem escrita noactivo.
**109entregues +2QA +21funcionaispendentes +P001=133**.Homologação`63cc3367`;entrega conjunta pendente.L1aberto;nova dedução/regularização fora;P121digital/P084/P085pendentes;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.Uma integração/backup/restauro/conferência paraoconjunto,reutilizando provas porramo.
## 25/10/2026 — preparação conjunta G7N/G10C,P088/P124
Inventariados109fechos antes dos testes,sem perdas confirmadas;provas63cc3367/1b67fa85 reutilizadas. Congelados livros/resultados/históricos incluindoP091/P122/P128 eP084/P085parciais. QAporramo eentrega conjunta futura;sem alterações noactivo. CIVA3(3)e/f,2016PDF6–7;15(2)b,PDF13:preço aquisição ou,nasua falta,preço custo,reportados aomomento daoperação. Dedução anterior total/parcial é facto histórico de3e/f,não nova dedução/campo11. Não confundir uso temporário de serviçosP089 comafectação/transmissão permanente de bens.
## 25/10/2026 — G10A–G10B/P122/P128 entregues numa operação conjunta
Homologação **`63cc3367`**,sobre`2fdca863`;candidata`af7d2503` expressamente aceite pela Tempo. Dois ramos,quatro tratamentos,uma integração/backup/restauro/instalação/conferência,provas individuaisQA reutilizadas.
- **P122**: Transferências de bens em execução de contrato de comissão,incluindo consignação;na venda comissário considerado comprador,na compra comitente considerado comprador. Venda:comitente→comissário→terceiro;compra:terceiro→comissário→comitente. Contraprestações e referências das duas relações separadas.
- **P128**: Serviço efectuado por intervenção de mandatário emnome próprio:mandatário considerado adquirente eprestador sucessivamente4(3). Venda/prestação:mandante→mandatário→terceiro;compra/aquisição:terceiro→mandatário→mandante. Não é mera intermediação emnome de outrem ou base15(2)e de bens.
CIVA3(3)c,Lei13/2016PDF6/p1426(264);4(3),PDF7/p1426(265). Lei22/2022não altera3/4;Lei10/2025PDF12mantém3(3)c e não altera4. Base15(2)e/P091já entregue permanece independente;sem nova aplicação da base neste incremento. 2026,circuitos emnome próprio,partes/contratos/objectos econtraprestações originais das duas relações. Sem soma/compensação automática,base tributável nova,localização,isenção,taxa,IVA,dedução/campo11 ou totaisModeloA. Sem conversão cambial;moeda original identificada e coerente com contexto. P091preservado,sem repetir aceitação/cálculo. Contraprestações das duas relações mantidas separadas,sem dupla soma.P091 e seus cálculos/históricos preservados,sem recalcular.Dedução fora deste incremento.Factos/referências/datas/âmbito,entradas imutáveis/histórico/relatório preservados. Desconhecido não é zero;fora do território não é isenção/IVAzero;sem certificados/aprovadores novos.
Compatibilidade com main e destino conferida,sem avanço concorrente encontrado;fast-forward normal,sem sobrescrever alterações. SessãoSSH existente autenticada reutilizada,sem guardar credenciais. Backup novo e restauro real isolado sem rede:174tabelas/369ficheiros/configuração. Conferido apenas delta instalado:revisão servida,manifesto/hash,17marcadores compilados,quatro hashes funcionais e simuladorHTTP200. PostgreSQL pela mesma identidade antes/depois:174tabelas/369ficheiros e29fichas publicadas/28relações/408geometrias preservados;diferenças apenascache/sessões. Zero migrações/importações/alterações de permissões ou ensaios sintéticos no activo. Contenção de novas classificações conferida,não aplicada;leitores/histórico/outrosramos preservados. Release/backup anteriores conservados.
[Manifesto/recibo](../simulations/l1-g10-own-name-delivery-20261025.json),registo`iva_l1_g10_own_name_P122_P128_homologation_20261025`. **109entregues +23funcionaispendentes +P001=133**,sem candidatasQApor disponibilizar. Os107fechos anteriores preservados. P084/P085 continuam incluídos nos23,apenas preparação/simulação condicionada;P002transversal eL1abertos;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. ManterQAporramo eentregasconjuntas compatíveis.
## 25/10/2026 — G10A–G10B/P122/P128 concluídos emQA,circuitos emnome próprio
Implementação`2b592ded`. Dois ramos,quatro tratamentos comtestes próprios,uma candidata conjunta. CIVA3(3)c,Lei13/2016PDF6/p1426(264);4(3),PDF7/p1426(265). Lei22/2022não altera3/4;Lei10/2025PDF12mantém3(3)c e não altera4. Base15(2)e/P091já entregue permanece independente;sem nova aplicação da base neste incremento.
- **P122**: Transferências de bens em execução de contrato de comissão,incluindo consignação;na venda comissário considerado comprador,na compra comitente considerado comprador. Venda:comitente→comissário→terceiro;compra:terceiro→comissário→comitente. Contraprestações e referências das duas relações separadas.
- **P128**: Serviço efectuado por intervenção de mandatário emnome próprio:mandatário considerado adquirente eprestador sucessivamente4(3). Venda/prestação:mandante→mandatário→terceiro;compra/aquisição:terceiro→mandatário→mandante. Não é mera intermediação emnome de outrem ou base15(2)e de bens.
2026,circuitos emnome próprio,partes/contratos/objectos econtraprestações originais das duas relações. Sem soma/compensação automática,base tributável nova,localização,isenção,taxa,IVA,dedução/campo11 ou totaisModeloA. Sem conversão cambial;moeda original identificada e coerente com contexto. P091preservado,sem repetir aceitação/cálculo. Reutilizar referências/partes/contratos/documentos oupressupostos expressos,sem certificado/aprovador novo. ownNames poroportunidade nosnapshot/API/dossier existentes;troca conserva dados ocultos e limpa confirmações próprias,escolha técnica de integridade. ReferênciaP091opcional,reutilizável,sem obrigar a repetir prova ou cálculo aceite.
Seis testes funcionais:quatro circuitos+troca de sentido/natureza+preservação/gravação/histórico/relatório.APIprivada1teste/37asserções comrollback emQAisolada55441;tipos/build aprovados;Edge/CUAactuação emnome próprio desconhecida,restauro da confirmação,gravação/recuperação/relatório4circuitos,2relações porcada,1000.25/1100.75MZNseparados e3versõesanteriores. Base/IVA/taxanull;sem soma das relações. Comparados todos oslivros anteriores comcongelamento,incluindoP091/P096–P099/P111–P120 eP084/P085parciais;107fechos preservados,provas anteriores reutilizadas. Relatório`docs\investmoz\simulations\iva-l1-g10-own-name-qa-20261025.json`;evidência`C:\laragon\www\portal-investidor\outputs\iva-l1-g10-own-name-20261025/verification.json` eimagem`qa-recovered-report.png`. Sem escrita noactivo.
**107entregues +2QA +23funcionaispendentes +P001=133**. Homologação`2fdca863`;entrega conjunta pendente. L1aberto,dedução fora deste incremento;P121digital/P084/P085pendentes;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. Uma integração/backup/restauro/conferência paraoconjunto,reutilizando provas porramo.
## 25/10/2026 — preparação conjunta G10A–G10B/P122/P128
Inventariados107fechos antes dos testes,sem perdas confirmadas;provas2fdca863/5837f34a reutilizadas. Congelados livros/resultados/históricos incluindoP091/P096–P099/P111–P120 eP084/P085parciais. QAporramo eentrega conjunta futura;sem alterações noactivo. CIVA3(3)c,4(3),2016PDF6–7/p1426(264–265);2025mantém3(3)c e nãoaltera4. Comissões de bens:comissário comprador na venda,comitente comprador na compra;mandatário de serviços emnome próprio é adquirente eprestador sucessivamente. Duas relações econtraprestações separadas,não dupla soma ou comissão autónoma presumida. BaseP091já entregue preservada,sem recalcular;dedução/campo11 fora.
## 25/10/2026 — G7J–G7M/P096–P099 entregues numa operação conjunta
Homologação **`2fdca863`**,sobre`2a725440`;candidata`833b4e5c` expressamente aceite pela Tempo. Quatro ramos,uma integração/backup/restauro/instalação/conferência,provas individuaisQA reutilizadas.
- **P096**: contraprestação total antes redução,sempróprioIVA ×62%. Transmissão de energia com preço fixado porAutoridadePública,referência/âmbito/intervalo aplicáveis.
- **P097**: contraprestação total antes redução,sempróprioIVA ×85%. Preço doserviço fixado através de taxas aeronáuticas. Não aplicar a comunicações/saneamento/telecomunicações genericamente pelo título histórico da matriz;é necessário demonstrar o preço fixado através de taxa aeronáutica15(2)k.
- **P098**: contraprestação total antes redução,sempróprioIVA ×40%(redução60%,não base60%). Construção/reabilitação de obras públicas abrangidas15(2)l/15(9),projecto/contrato/categoria/âmbito identificados;estradas,pontes,infraestrutura água/saneamento,electrificação rural emprojectos públicos e hidráulicaagrícola noâmbito definido. Não exigir preço regulado a esta alínea.
- **P099**: contraprestação total antes redução,sempróprioIVA ×75%. Água potável através derede pública,preço fixado porAutoridadePública comreferência/âmbito/intervalo aplicáveis.
CIVA15(2)j/k/l/m,15(1)/(5)/(6)/(9),Lei13/2016PDF13–14/p1426(271–272);Lei22/2022PDF3mantém15(2)j–m;Lei10/2025não altera15,adita18(6),PDF13:dedução do imposto suportado relativo a essas operações na mesma proporção da base reduzida. 2026/MZN,base apenas. Percentagens62/85/40/75 são de base,não taxasIVA. Proporção18(6)registada sem calcular/conceder dedução/campo11;dedução permanece nas condições/lotes próprios. Sem taxaIVA,IVA,isenção ou totaisModeloA. Não dividir bruto comIVA sem composição esclarecida,nem reduzir montante já reduzido. As percentagens62/85/40/75 incidem sobre a base tributável,não são taxasIVA. Dedução fora deste incremento;18(6)apenas indica a proporção aplicável,sem cálculo ou preenchimento do campo11. Factos/referências/datas/âmbito,entradas imutáveis/histórico/relatório preservados. Desconhecido não é zero;fora do território não é isenção/IVAzero;sem certificados/aprovadores novos.
Compatibilidade com main e destino conferida,sem avanço concorrente encontrado;fast-forward normal,sem sobrescrever alterações. SessãoSSH existente autenticada reutilizada,sem guardar credenciais. Backup novo e restauro real isolado sem rede:174tabelas/369ficheiros/configuração. Conferido apenas delta instalado:revisão servida,manifesto/hash,16marcadores compilados,quatro hashes funcionais e simuladorHTTP200. PostgreSQL pela mesma identidade antes/depois:174tabelas/369ficheiros e29fichas publicadas/28relações/408geometrias preservados;diferenças apenascache/sessões. Zero migrações/importações/alterações de permissões ou ensaios sintéticos no activo. Contenção de novas classificações conferida,não aplicada;leitores/histórico/outrosramos preservados. Release/backup anteriores conservados.
[Manifesto/recibo](../simulations/l1-g7-reduced-delivery-20261024.json),registo`iva_l1_g7_reduced_P096_P099_homologation_20261024`. **107entregues +25funcionaispendentes +P001=133**,sem candidatasQApor disponibilizar. Os103fechos anteriores preservados. P084/P085 continuam incluídos nos25,apenas preparação/simulação condicionada;P002transversal eL1abertos;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. ManterQAporramo eentregasconjuntas compatíveis.
## 24/10/2026 — G7J–G7M/P096–P099 concluídos emQA,conjunto de bases reduzidas
Implementação`67a96085`. Quatro ramos comtestes/rastreabilidade próprios,uma candidata conjunta. CIVA15(2)j/k/l/m,15(1)/(5)/(6)/(9),Lei13/2016PDF13–14/p1426(271–272);Lei22/2022PDF3mantém15(2)j–m;Lei10/2025não altera15,adita18(6),PDF13:dedução do imposto suportado relativo a essas operações na mesma proporção da base reduzida.
- **P096**: contraprestação total antes redução,sempróprioIVA ×62%. Transmissão de energia com preço fixado porAutoridadePública,referência/âmbito/intervalo aplicáveis.
- **P097**: contraprestação total antes redução,sempróprioIVA ×85%. Preço doserviço fixado através de taxas aeronáuticas. Não aplicar a comunicações/saneamento/telecomunicações genericamente pelo título histórico da matriz;é necessário demonstrar o preço fixado através de taxa aeronáutica15(2)k.
- **P098**: contraprestação total antes redução,sempróprioIVA ×40%(redução60%,não base60%). Construção/reabilitação de obras públicas abrangidas15(2)l/15(9),projecto/contrato/categoria/âmbito identificados;estradas,pontes,infraestrutura água/saneamento,electrificação rural emprojectos públicos e hidráulicaagrícola noâmbito definido. Não exigir preço regulado a esta alínea.
- **P099**: contraprestação total antes redução,sempróprioIVA ×75%. Água potável através derede pública,preço fixado porAutoridadePública comreferência/âmbito/intervalo aplicáveis.
2026/MZN,base apenas. Percentagens62/85/40/75 são de base,não taxasIVA. Proporção18(6)registada sem calcular/conceder dedução/campo11;dedução permanece nas condições/lotes próprios. Sem taxaIVA,IVA,isenção ou totaisModeloA. Não dividir bruto comIVA sem composição esclarecida,nem reduzir montante já reduzido. Composição e referências existentes reutilizáveis oupressupostos expressos,sem certificados/aprovadores novos. Obraspúblicas usam projecto/categoria/âmbito,sem impor condição de preço regulado deoutras alíneas. A descrição históricaP097na matriz não estende15(2)k aqualquer telecomunicação/saneamento;conferido o alcance do texto,sem percentagem presumida por título. Novo livroregulatedReducedBases poroportunidade nosnapshot/API/dossier existentes;troca conserva campos ocultos e limpa condições próprias,escolha técnica de integridade. Decimal exacto até8casasde resultado,sem arredondamento fiscal presumido.
Seis testes funcionais:um porramo+precisão/obras40%não60/sem dupla redução+preservação/gravação/histórico/relatório.APIprivada1teste/27asserções comrollback emQAisolada55441;tipos/build aprovados;Edge/CUAcomposição/categoria desconhecidas,restauro deentradas,gravação/recuperação/relatório4linhas+3versõesanteriores. Bases620.155/850.2125/400.10/750.1875MZN para1000.25MZNantesredução. Proporções18(6)62/85/40/75%,sem dedução calculada;IVA/taxanull. Comparados todos oslivros anteriores comcongelamento,incluindoP111–P120 eP084/P085parciais;103fechos preservados,provas anteriores reutilizadas. Relatório`docs\investmoz\simulations\iva-l1-g7-reduced-bases-qa-20261024.json`;evidência`C:\laragon\www\portal-investidor\outputs\iva-l1-g7-reduced-bases-20261024/verification.json` eimagem`qa-recovered-report.png`. Sem escrita noactivo.
**103entregues +4QA +25funcionaispendentes +P001=133**. Homologação`2a725440`;entrega conjunta pendente. P121digital/P084/P085 eL1abertos;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. Uma integração/backup/restauro/conferência paraoconjunto,reutilizando provas porramo.
## 24/10/2026 — preparação conjunta G7J–G7M/P096–P099
Inventariados103fechos antes dos testes,sem perdas confirmadas;provas2a725440/b0e01ef7 reutilizadas. Congelados livros/resultados/históricos incluindoP111–P120 eP084/P085parciais. QAporramo eentrega conjunta futura;sem alterações noactivo. CIVA15(2)j–m,15(1)/(5)/(6)/(9),2016PDF13–14;Lei22/2022PDF3mantém15(2)j–m;Lei10/2025PDF13adita18(6):dedução proporcional,sem activar campo11. Base62%energia,85%aeronáutica,40%obras(redução60%),75%água. Não aplicar redução duasvezes ou a todos osserviços de telecomunicações por descrição.
## 24/10/2026 — G9A–G9J/P111–P120 entregues numa operação conjunta
Homologação **`2a725440`**,sobre`03c26d66`;candidata`4601bf64` expressamente aceite pela Tempo. Dez ramos,uma integração/backup/restauro/instalação/conferência,provas individuaisQA reutilizadas.
- **P111 — 6(7)a**: Cessão/autorização de direitos de autor,licenças,marcas e análogos
- **P112 — 6(7)b**: Publicidade
- **P113 — 6(7)c**: Telecomunicações
- **P114 — 6(7)d**: Consultores,engenheiros,advogados,economistas,contabilistas/gabinetes de estudos,organização,investigação/desenvolvimento e similares
- **P115 — 6(7)e**: Tratamento de dados/fornecimento de informações
- **P116 — 6(7)f**: Operações bancárias,financeiras,seguro/resseguro;eventual isenção independente
- **P117 — 6(7)g**: Colocação de pessoal
- **P118 — 6(7)h**: Intermediação em nome epor conta de outrem no fornecimento de serviço enumerado,subjacente identificado
- **P119 — 6(7)i**: Obrigação de não exercer,mesmo parcialmente,actividade/direito enumerado,subjacente identificado
- **P120 — 6(7)j**: Locação de bens móveis corpóreos,incluindo financeira,bens/contrato identificados
CIVA2(1)a/b,2(2),6(3),6(7)a–j e6(8),Lei13/2016PDF6–8/p1426(264–266);23(1)/(2),25(4),26(1–3),PDF16–17. Lei22/2022não altera estes artigos. Lei10/2025PDF12mantém alíneasa–j ealtera6(7–9);PDF13art23(2)excluik e remete declaração33(2);PDF14mantém26(1–3),adita26(4)digital ealtera33(2). 2026,serviços enumerados não digitais;localização e identificação do responsável pelas obrigações. Sem isenção confirmada,base,taxa,IVA,montante a pagar,dedução/campo11 ou totaisModeloA. P121/P130digitais eP002transversal não fechados;outros6(4)/(5)encaminhados para percursos próprios. Não automatiza declaração,pagamento,retenção ou prazo digital32(1)c. Factos/referências/datas/âmbito,entradas imutáveis/histórico/relatório preservados. Desconhecido não é zero;fora do território não é isenção/IVAzero;sem certificados/aprovadores novos.
Compatibilidade com main e destino conferida,sem avanço concorrente encontrado;fast-forward normal,sem sobrescrever alterações. SessãoSSH autenticada inicial reutilizada no backup/restauro;expirou durante a instalação e foi restabelecida pelo responsável para leituras finais,sem guardar credenciais. A revisão pública foi conferida antes dessa retoma;nenhuma instalação repetida. Backup novo e restauro real isolado sem rede:174tabelas/369ficheiros/configuração. Conferido apenas delta instalado:revisão servida,manifesto/hash,20marcadores compilados,quatro hashes funcionais e simuladorHTTP200. PostgreSQL pela mesma identidade antes/depois:174tabelas/369ficheiros e29fichas publicadas/28relações/408geometrias preservados;diferenças apenascache/sessões. Zero migrações/importações/alterações de permissões ou ensaios sintéticos no activo. Contenção de novas classificações conferida,não aplicada;leitores/histórico/outrosramos preservados. Release/backup anteriores conservados.
[Manifesto/recibo](../simulations/l1-g9-nondigital-delivery-20261024.json),registo`iva_l1_g9_nondigital_P111_P120_homologation_20261024`. **103entregues +29funcionaispendentes +P001=133**,sem candidatasQApor disponibilizar. Os93fechos anteriores preservados. P084/P085 continuam incluídos nos29,apenas preparação/simulação condicionada;P121digital/P130digital/P002transversal eL1abertos;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. ManterQAporramo eentregasconjuntas compatíveis.
## 24/10/2026 — G9A–G9J/P111–P120 concluídos emQA,conjunto compatível não digital
Implementação`6cffa118`. Dez ramos com rastreabilidade/testes próprios,uma candidata conjunta. CIVA2(1)a/b,2(2),6(3),6(7)a–j e6(8),Lei13/2016PDF6–8/p1426(264–266);23(1)/(2),25(4),26(1–3),PDF16–17. Lei22/2022não altera estes artigos. Lei10/2025PDF12mantém alíneasa–j ealtera6(7–9);PDF13art23(2)excluik e remete declaração33(2);PDF14mantém26(1–3),adita26(4)digital ealtera33(2).
- **P111 — 6(7)a**: Cessão/autorização de direitos de autor,licenças,marcas e análogos.
- **P112 — 6(7)b**: Publicidade.
- **P113 — 6(7)c**: Telecomunicações.
- **P114 — 6(7)d**: Consultores,engenheiros,advogados,economistas,contabilistas/gabinetes de estudos,organização,investigação/desenvolvimento e similares.
- **P115 — 6(7)e**: Tratamento de dados/fornecimento de informações.
- **P116 — 6(7)f**: Operações bancárias,financeiras,seguro/resseguro;eventual isenção independente.
- **P117 — 6(7)g**: Colocação de pessoal.
- **P118 — 6(7)h**: Intermediação em nome epor conta de outrem no fornecimento de serviço enumerado,subjacente identificado.
- **P119 — 6(7)i**: Obrigação de não exercer,mesmo parcialmente,actividade/direito enumerado,subjacente identificado.
- **P120 — 6(7)j**: Locação de bens móveis corpóreos,incluindo financeira,bens/contrato identificados.
Prestador estrangeiro semsede/EP/domicílio nacional apartirdoqualpresta+adquirente2(1)a/b comEP/domicílio nacional:6(7),incluindo quem pratique exclusivamente operações isentas sem direitoàdedução;responsáveladquirente2(2)/23(2),declaração33(2)nos termosa regulamentar. Não exigir dedução para localizar. Adquirente estabelecido/domiciliado estrangeiro:6(8),ainda queprestador nacional,sem imposto estrangeiro presumido. Percurso doméstico6(3),sem regras especiais:qualidade prestadorSP/regimegeral+referência identifica prestador23(1);se desconhecida,conservarlocalização e responsávelindeterminado. P118/P119exigem subjacente identificado,sem auto-referência ou enquadramento digital presumido. 2026,serviços enumerados não digitais;localização e identificação do responsável pelas obrigações. Sem isenção confirmada,base,taxa,IVA,montante a pagar,dedução/campo11 ou totaisModeloA. P121/P130digitais eP002transversal não fechados;outros6(4)/(5)encaminhados para percursos próprios. Não automatiza declaração,pagamento,retenção ou prazo digital32(1)c.
Localização/isenção/dedução/obrigação/montante independentes. Referências e pressupostos expressos reutilizáveis,sem certificado/aprovador novo;troca conserva dados ocultos e limpa condições próprias,escolhatécnicadeintegridade. listedServices poroportunidade nosnapshot/API/dossier existentes,sem schema/permissões.
Doze testes funcionais:um porramo comtrêspercursos+subjacentes/troca+persistência/histórico/preservação.APIprivada1teste/109asserções comrollback emQAisolada55441;tipos/build aprovados;Edge/CUAqualidade/subjacente desconhecidos,adquirente estrangeiro/retorno conserva referências,gravação/recuperação/relatório30exemplos+4versõesanteriores. Comparação de todos oslivros anteriores,incluindoP105–110/P084/P085parciais,comcongelamento;93fechos preservados,provas anteriores reutilizadas. Relatório`docs\investmoz\simulations\iva-l1-g9-nondigital-qa-20261024.json`;evidência`C:\laragon\www\portal-investidor\outputs\iva-l1-g9-nondigital-20261024/verification.json` eimagem`qa-recovered-report.png`. Sem escrita noactivo.
**93entregues +10QA +29funcionaispendentes +P001=133**. Homologação`03c26d66`;entrega conjunta pendente. P121/P130digitais/P002transversal/P084/P085 eL1abertos;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. Uma integração/backup/restauro/conferência paraesteconjunto,reutilizando provas porramo.
## 24/10/2026 — preparação conjunta G9A–G9J/P111–P120
Inventariados93fechos antes dos testes,sem perdas confirmadas;provas03c26d66/4853bc72 reutilizadas. Congelados livros/resultados/históricos incluindoP105–110 eP084/P085parciais. QAporramo eentrega conjunta futura;sem alterações no activo. CIVA6(7)a–j/6(8),2(1)a/b e2(2),2016PDF6/8;Lei10/2025PDF12–14 para6(7–9),23(2),26/33. P121digital é percurso próprio,não classificar pelo recorte não digital. Localização,isenção e dedução independentes;qualidade SP do adquirente inclui quem realiza operações isentas sem direito à dedução.
## 24/10/2026 — G8B–G8F/P106–P110 entregues numa operação conjunta
Homologação **`03c26d66`**,sobre`8f14f5dd`;candidata`3f4e71c3` expressamente aceite pela Tempo. Cinco ramos,uma integração/backup/restauro/instalação/conferência,provas individuaisQA reutilizadas.
- **P106**: Sede/EP/domicílio do prestador a partir do qual o serviço é prestado,sem regras especiais aplicáveis. Não usar endereço/nacionalidade do cliente.
- **P107**: Local do imóvel e relação do serviço,incluindo preparação/coordenação de trabalhos imobiliários,peritos/agentes. Independente da sede do prestador.
- **P108**: Execução total ou essencial dos trabalhos/peritagens em bens móveis corpóreos. Independente da sede do prestador.
- **P109**: Local material de actividades artísticas,científicas,desportivas,recreativas,ensino/similares,organizadores e serviços acessórios;6(5)c rectificado2017.
- **P110**: Distância nacional6(5)d rectificada2017;partida/chegada nacionais incluem percurso fora do país6(6);ida/volta são dois trajectos. Identificar distância total/nacional na mesma unidade,sem apuramento monetário.
CIVA6(3),6(4)/(5)a–d,6(6),Lei13/2016 PDF7–8/p1426(265–266);Aviso BR89-I,de08/06/2017,PDF1,rectifica expressamente6(5)c/d:actividades nacionais e transporte pela distância nacional;Lei10/2025 PDF12mantém6(3–6),altera7–9digitais. Recorte2026,classificação territorial de serviços por factos próprios;sem base,taxa,IVA,isenção,dedução/campo11 ou totaisModeloA. Digital/outros6(7)/(8)exigem percursos próprios,não classificados automaticamente. P002transversal não encerrado. Factos/referências/datas/âmbito,entradas imutáveis/histórico/relatório preservados. Desconhecido não é zero;fora do território não é isenção/IVAzero;sem certificados/aprovadores novos.
Compatibilidade com main e destino conferida,sem avanço concorrente encontrado;fast-forward normal,sem sobrescrever alterações. SessãoSSH existente autenticada reutilizada,sem guardar credenciais. Backup novo e restauro real isolado sem rede:174tabelas/369ficheiros/configuração. Conferido apenas delta instalado:revisão servida,manifesto/hash,18marcadores compilados,quatro hashes funcionais e simuladorHTTP200. PostgreSQL pela mesma identidade antes/depois:174tabelas/369ficheiros e29fichas publicadas/28relações/408geometrias preservados;diferenças apenascache/sessões. Zero migrações/importações/alterações de permissões ou ensaios sintéticos no activo. Contenção de novas classificações conferida,não aplicada;leitores/histórico/outrosramos preservados. Release/backup anteriores conservados.
[Manifesto/recibo](../simulations/l1-g8-services-delivery-20261024.json),registo`iva_l1_g8_services_P106_P110_homologation_20261024`. **93entregues +39funcionaispendentes +P001=133**,sem candidatasQApor disponibilizar. Os88fechos anteriores preservados. P084/P085 continuam incluídos nos39,apenas preparação/simulação condicionada;P002transversal eL1abertos;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. ManterQAporramo eentregasconjuntas compatíveis.
## 24/10/2026 — G8B–G8F/P106–P110 concluídos emQA,conjunto compatível
Implementação`ec33fb5b`. Cinco ramos com rastreabilidade/testes próprios,uma candidata conjunta,não cinco entregas. CIVA6(3),6(4)/(5)a–d,6(6),Lei13/2016 PDF7–8/p1426(265–266);Aviso BR89-I,de08/06/2017,PDF1,rectifica expressamente6(5)c/d:actividades nacionais e transporte pela distância nacional;Lei10/2025 PDF12mantém6(3–6),altera7–9digitais.
- **P106**: Sede/EP/domicílio do prestador a partir do qual o serviço é prestado,sem regras especiais aplicáveis. Não usar endereço/nacionalidade do cliente.
- **P107**: Local do imóvel e relação do serviço,incluindo preparação/coordenação de trabalhos imobiliários,peritos/agentes. Independente da sede do prestador.
- **P108**: Execução total ou essencial dos trabalhos/peritagens em bens móveis corpóreos. Independente da sede do prestador.
- **P109**: Local material de actividades artísticas,científicas,desportivas,recreativas,ensino/similares,organizadores e serviços acessórios;6(5)c rectificado2017.
- **P110**: Distância nacional6(5)d rectificada2017;partida/chegada nacionais incluem percurso fora do país6(6);ida/volta são dois trajectos. Identificar distância total/nacional na mesma unidade,sem apuramento monetário.
A divergência de transporte do exemplar2016 foi resolvida pelo Aviso2017já existente no acervo,consultado visualmentePDF1;não permanece impedimento documentalP110. A preparação anterior deP106–109não incluíaP110;este foi inventariado antes dos seus testes e juntou-se após o cotejo. Recorte2026,classificação territorial de serviços por factos próprios;sem base,taxa,IVA,isenção,dedução/campo11 ou totaisModeloA. Digital/outros6(7)/(8)exigem percursos próprios,não classificados automaticamente. P002transversal não encerrado. Fora do território não é isenção/IVAzero;desconhecido não é zero. Pressupostos expressos/referências reutilizáveis,sem certificados/aprovadores novos. Troca conserva referências/locais/trajectos ocultos e limpa condições próprias;escolha técnica de integridade,não nova regra organizacional. serviceLocations por oportunidade no snapshot/API/dossier existentes,sem schema/permissões.
Sete testes funcionais:um por ramo+preservação/persistência/histórico+casos específicos de transporte.APIprivada1teste/48asserções com rollback emQAisolada55441;tipos/build aprovados;Edge/CUA10operações,campo do prestador desconhecido,transporte misto80.25/100.50,gravação/recuperação/relatório e3versões anteriores. Comparação de todos os livros anteriores com congelamento,incluindoP105/P084/P085parciais,88fechos preservados;provas aceites reutilizadas. Relatório`docs\investmoz\simulations\iva-l1-g8-services-qa-20261024.json`,evidência`C:\laragon\www\portal-investidor\outputs\iva-l1-g8-services-20261024/verification.json`. Sem escrita no activo.
**88entregues +5QA +39funcionaispendentes +P001=133**. Homologação`8f14f5dd`;entrega conjunta pendente. P002transversal/P084/P085 eL1abertos;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas. Uma integração/backup/restauro/conferência para este conjunto,reutilizando as provas por ramo.
## 24/10/2026 — preparação conjunta G8B–G8E/P106–P109
Inventariados88fechos antes de testes,sem perdas confirmadas;provas8f14f5dd/aac3f463 reutilizadas. Congelados livros/resultados/históricos incluindoP105 eP084/P085parciais. QAporramo,entrega conjunta futura;sem alterações no activo. CIVA6(3),6(4)/(5)a–c,2016PDF7–8/p1426(265–266);2025PDF12mantém3–6. P110 separado para cotejo textual específico6(5)d/6(6),sem bloquear estes quatro ramos.
## 24/10/2026 — decisão da Tempo: entregas por grupos relacionados
Implementar e testar cada ramo em QA com rastreabilidade própria; agrupar ramos relacionados numa entrega, incluindo os próximos percursos compatíveis de G8. Fazer uma integração, backup/restauro e conferência do conjunto, reutilizando as provas individuais. Entregar isoladamente apenas por correcção urgente, risco especial ou dependência identificada. Estar concluído em QA não obriga à instalação imediata. Esta orientação chegou quando G8A já estava enviado para main e o instalador em execução; a operação iniciada foi acompanhada até à conferência do resultado. Os próximos ramos compatíveis aguardam entrega conjunta. Preservar fechos, alterações concorrentes e limites de âmbito; não criar nova matriz/backlog.
## 24/10/2026 — G8A/P105 entregue:localização territorial dos bens
Homologação **`8f14f5dd`**,pelo processoGit existente,sobre`6f1cf7b7`;candidata`fb724866` expressamente aceite pela Tempo. **P105:um ramo,três tratamentos**:`goods_with_transport`,`goods_without_transport`,`goods_before_import`. CIVA6(1)/(2),Lei13/2016PDF7/p1426(265),mantidosLei10/2025PDF12;recorte2026/bens corpóreos. Localização no início transporte/expedição para adquirente ou,sem transporte,ao pôr à disposição. Regra própria das transmissões pelo importador/subsequentes antes da importação nacional de bens vindos do estrangeiro,com referências de transporte/importação/cadeia e âmbito. Endereço/nacionalidade do cliente não substituem esses factos. Fora do território não equivale a isenção/IVAzero. Classificação não calcula base/taxa/IVA/dedução/campo11/direitos/totaisModeloA,nem aplica esta regra física a digitais/serviços. Desconhecido permanece indeterminado. Troca conserva dados ocultos e limpa condições próprias;referências/datas/âmbito/entradas imutáveis/histórico/relatório preservados;sem certificados/aprovadores novos.
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,três percursos/localização/regra6(2)/referências/â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çãoP105 conferida,não aplicada,leitores/históricos e restantes ramos preservados.
[Manifesto/recibo](../simulations/l1-g8a-delivery-20261024.json),registo`iva_l1_g8a_P105_homologation_20261024`. **88entregues +44funcionaispendentes +P001 =133;sem candidatasQA por disponibilizar.** Os87fechos anteriores permanecem encerrados. P084/P085 continuam nos44,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 — G8A/P105 concluído em QA:localização de bens
Implementação `0682ef74`. Um ramo,três tratamentos: `goods_with_transport`, `goods_without_transport`, `goods_before_import`. CIVA6(1)/(2),Lei13/2016 PDF7/p1426(265);Lei10/2025 PDF12 mantém1/2 e altera7–9 digitais. 2026,bens corpóreos;classificação territorial apenas,sem base,taxa,IVA,isenção,dedução/campo11,direitos ou totaisModeloA. Não abrange digitais/serviços por esta regra.
Identificar local físico e momento relevante;endereço/nacionalidade do cliente não os substituem. Conferir a regra6(2)antes de aplicar6(1):importador e transmissões subsequentes antes da importação nacional,com transporte/cadeia/importação e âmbito identificados. Fora do território não equivale a isenção/IVA zero;desconhecido permanece indeterminado. Reutilizar documentos/dados ou pressupostos expressos. Troca de percurso conserva campos ocultos e exige rever condições próprias,escolha técnica de integridade. Livro incremental goodsLocations,snapshot/API/dossier existentes,sem schema/permissões novos.
Verificação:4testes frontend;API privada1teste/30asserções com rollback emQAisolada55441;tipos/build aprovados;Edge/CUA local desconhecido,gravação/recuperação/relatório de3linhas e4versões anteriores. Livros/resultados/históricos anteriores comparados com congelamento,87fechos preservados;provas anteriores reutilizadas. Relatório `docs\investmoz\simulations\iva-l1-g8a-qa-20261024.json`;evidência `C:\laragon\www\portal-investidor\outputs\iva-l1-g8a-goods-location-20261024/verification.json` e imagem `qa-recovered-report.png`. Sem escrita no activo.
**87entregues +1QA(P105) +44funcionaispendentes +P001=133**. Homologação permanece `6f1cf7b7`;falta integração/disponibilização. P084/P085 parciais e pendentes;L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.
## 24/10/2026 — preparação G8A/P105,inventário antes de testes
G7I/P089 aceite6f1cf7b7/21ce03f6;**87entregues+45funcionaispendentes+P001=133**. Inventariados87fechos,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,incluindoP089/P103/P102/P101/P100/P095/P094/P091/P060/P050/P084/P085parciais. Sem repetir aceitação anterior ou ensaiar no activo.
G8A/P105 executaCIVA6(1)/(2),2016PDF7/p1426(265),mantidos naLei10/2025PDF12,que altera6(7–9)digitais. Três tratamentos no mesmo ramo,recorte2026/bens corpóreos:não usar regra física genérica para bens digitais/serviços. Localização dos bens ao iniciar transporte/expedição para adquirente;sem transporte,ao pôr à disposição;apesar de6(1),transmissões pelo importador e subsequentes de bens transportados/expedidos do estrangeiro antes de importação nacional são abrangidas6(2). Confirmar não aplicação6(2)antes de usar6(1);desconhecido não é fora do território. Endereço/nacionalidade do cliente não determina local dos bens. Referências/local/data/cadeia/âmbito reutilizáveis ou pressupostos expressos,sem certificado/aprovador novo. Classificação territorial,não isenção/taxa/IVA/base/dedução/campo11/direitos/totaisModeloA. Novo livro incremental,snapshot/API/relatório existentes,sem schema/permissões. L1aberto;P00105/06;bebidasL2/L3;P084/P085parciais;Estatísticas/IAadiadas.
## 24/10/2026 — G7I/P089 entregue:valor normal de serviços gratuitos/utilização de bens
Homologação **`6f1cf7b7`**,pelo processoGit existente,sobre`cd530b24`;candidata`a4329bb4` expressamente aceite pela Tempo. **P089:um ramo,três tratamentos**:`free_company_service`,`private_company_asset_use`,`exempt_sector_asset_use`. Base=valor normal do serviço15(2)c/15(4),fundamento/âmbito e composição15(5)/(6),sem próprioIVA. Serviço gratuito pela própria empresa para necessidades particulares do titular/pessoal ou fins alheios4(2)a não exige dedução anterior. Utilização de bens para uso próprio/particular/alheio ou em sector isento4(2)b exige dedução anterior total/parcial nos bens/elementos,com referência;essa referência não calcula nem concede dedução/campo11. Uso não é transmissão permanenteP088;nenhum custo/preço de aquisição dos bens substitui automaticamente valor normal do serviço. Mudança de tratamento conserva montantes/documentos/bens/dedução oculta e limpa condições próprias,mantém comuns. Referências/finalidade/fundamento/âmbito conservados nas entradas imutáveis,versões/histórico/relatório. Desconhecido não é zero;sem avaliadores/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,17marcadores compilados do livro/componente/relatório,três percursos/condições próprias/dedução anterior limitada/fundamento/â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çãoP089 conferida,não aplicada,leitores/históricos e restantes ramos preservados.
[Manifesto/recibo](../simulations/l1-g7i-delivery-20261024.json),registo`iva_l1_g7i_P089_homologation_20261024`. **87entregues +45funcionaispendentes +P001 =133;sem candidatasQA por disponibilizar.** Os86fechos anteriores permanecem encerrados. P084/P085 continuam nos45,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 — 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.
Desconhecido não é zero/correcção presumida. Decimal exacto até6casas,sem arredondamento fiscal presumido. Mudança de contexto/percurso/origem conserva montantes/documentos e limpa confirmações afectadas;projectado→efectivo não reutiliza confirmação do pressuposto. Escolha técnica de integridade,não novo aprovador/certificado/regra organizacional. LivrovalueReviews por oportunidade,snapshot/API/dossier existentes,sem schema/permissões novos. Sem avaliação automática,IVA/incidência/taxa/dedução/campo11/regularizações/totaisModeloA ou execução de acto AT.
Provas do delta:**4testes frontend**,**APIprivada1teste/33asserções**,guarda`simulator_fiscal_delta_20261021_test:55441` e rollback;tipos/build passaram. Interface real Edge/CUA:referência de preço/montante corrigido desconhecidos→indeterminado;comparação inferior1000.25vs1500.50 mantém1000.25;origem efectivo limpa confirmação;correcção fora âmbito não aplicada;regresso à projecção confirma cenário condicionado1400.75,sem substituir por1500.50. Gravação recuperada/relatório:2linhas/5versões anteriores,IVAindeterminado. Dados sintéticos,não aceitação manual atribuída à Tempo.85fechos/livros/resultados/históricos intactos,incluindoP102/P101/P100/P095/P094/P091/P060/P050 eP084/P085parciais;provas anteriores reutilizadas. [RegistoQA](../simulations/iva-l1-g7h-qa-20261024.json).
**85entregues +1emQA(P103) +46funcionaispendentes +P001 =133**. Homologação permanece`5d5f3b41`;falta integração/entrega pelo processoGit,manifesto/backup/restauro e delta instalado. P084/P085 continuam nos46,apenas preparação/simulação condicionada,sem benefícios confirmados. L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.
## 24/10/2026 — preparação G7H/P103,inventário antes de testes
G7G/P102 aceite5d5f3b41/adb849d4;**85entregues+47funcionaispendentes+P001=133**. Inventariados85fechos,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,incluindoP102/P101/P100/P095/P094/P091/P060/P050/P084/P085parciais. Sem repetir aceitação anterior ou ensaiar no activo.
G7H/P103 executaCIVA15(7),2016PDF14/p1426(272):para efeitos15(1),contraprestação inferior à resultante de preços correntes/normais de venda à porta fábrica,por grosso ou retalho,ou do serviço,tendo em conta a natureza das transmissões,AT pode proceder à correcção.2022PDF3mantém7;2025não altera15;2017não rectifica15(7). Fontes/exemplares/inventário aceites,cotejo visual com skillPDF. Dois tratamentos num ramo:comparar sem correcção automática;registar correcção AT referenciada nos dados efectivos ou cenário condicionado expressamente assumido na projecção. Referência/âmbito/contexto do preço e composição equivalente identificados;valor inferior não autoriza o portal a corrigir automaticamente,nem usar máximo/referência como substituto de montante de correcção. Conservar documentos/valores ao mudar percurso/contexto,limpando confirmações afectadas por integridade. Sem novos certificados/aprovadores,IVA/dedução/campo11/regularizações/totaisModeloA. L1aberto;P00105/06;bebidasL2/L3;P084/P085parciais;Estatísticas/IAadiadas.
## 24/10/2026 — G7G/P102 entregue:quatro exclusões da contraprestação
Homologação **`5d5f3b41`**,pelo processoGit existente,sobre`7e5710eb`;candidata`9c2b2c65` expressamente aceite pela Tempo. **P102:um ramo,quatro tratamentos**:`judicial_indemnity`,`granted_discount`,`third_party_payment`,`returnable_packaging`,na mesma base por operação. Indemnização recebida declarada judicialmente por incumprimento total/parcial de contrato;descontos/abatimentos/bónus concedidos;quantias pagas em nome e por conta do adquirente/destinatário,registadas em adequadas contas de terceiros;embalagens não efectivamente transaccionadas com indicação separada e menção expressa da devolução acordada27(5)(b). Não exigir devolução já realizada. Montante inicial sem próprioIVA e com inclusões15(5)consideradas−exclusões ainda incluídas;parcelas já excluídas conservadas sem segunda subtracção. Condições,referências e âmbitos próprios conservados nas entradas imutáveis,versões/histórico/relatório. Desconhecido não é zero/exclusã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,quatro exclusões/condições próprias/âmbito/referências,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çãoP102 conferida,não aplicada,leitores/históricos e restantes ramos preservados.
[Manifesto/recibo](../simulations/l1-g7g-delivery-20261024.json),registo`iva_l1_g7g_P102_homologation_20261024`. **85entregues +47funcionaispendentes +P001 =133;sem candidatasQA por disponibilizar.** Os84fechos anteriores permanecem encerrados. P084/P085 continuam nos47,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 — G7G/P102 concluído emQA:quatro exclusões da contraprestação
Implementação`acc633bf`. **Um ramo,quatro tratamentos**:`judicial_indemnity`,`granted_discount`,`third_party_payment`,`returnable_packaging`,na mesma base por operação. FonteCIVA15(6)(a–d),Lei13/2016PDF14/p1426(272);27(5)(b),PDF17/p1426(275);2022PDF3mantém15(6);2025PDF14mantém27(5)(b),altera27(10),não15. Indemnização recebida declarada judicialmente por incumprimento total/parcial de contrato;descontos/abatimentos/bónus concedidos;quantias pagas em nome e por conta do adquirente/destinatário,registadas em adequadas contas de terceiros;embalagens não efectivamente transaccionadas com indicação separada e menção expressa da devolução acordada na factura/documento equivalente. Não exigir devolução já realizada.
Montante inicial sem próprioIVA e com inclusões15(5)consideradas−exclusões ainda incluídas. Já excluídas conservadas sem segunda subtracção;desconhecido não é zero/exclusão presumida;exclusões superiores ao inicial não criam base negativa/pisozero. Referências e âmbitos por tratamento identificam declaração judicial/contrato,concessão do desconto,contas de terceiros/adquirente e menção documental da embalagem;reutilizar documentos ou pressupostos expressos de projecção,sem certificados/aprovadores novos. Decimal exacto até6casas,sem arredondamento fiscal presumido. LivroconsiderationExclusions por oportunidade/operação/parcelas no snapshot/API/dossier existentes,sem schema/permissões novos. Mudança de tipo conserva valores/referências/âmbito/contas/menção oculta,limpa condições próprias;escolha técnica de integridade. SemIVA/incidência/taxa/dedução/campo11/regularizações/totaisModeloA ou postagem em períodos anteriores. P101 e livros anteriores permanecem intactos.
Provas do delta:**4testes frontend**,**APIprivada1teste/34asserções**,guarda`simulator_fiscal_delta_20261021_test:55441` e rollback;tipos/build passaram. Interface real Edge/CUA:declaração judicial desconhecida,desconto não concedido,condição de contas de terceiros desconhecida e menção de devolução acordada desconhecida impedem exclusão automática. Indemnização100.10já excluída→1000.25−100.45=899.80,sem segunda subtracção. Gravação recuperada/relatório final:1000.25−(100.10+50.25+30.15+20.05)=799.70,IVAindeterminado,1operação/4parcelas/8versões anteriores. Dados sintéticos,não aceitação manual atribuída à Tempo.84fechos/livros/resultados/históricos intactos,incluindoP101/P100/P095/P094/P091/P090,P060/P056/P050 eP084/P085parciais;provas anteriores reutilizadas. [RegistoQA](../simulations/iva-l1-g7g-qa-20261024.json).
**84entregues +1emQA(P102) +47funcionaispendentes +P001 =133**. Homologação permanece`7e5710eb`;falta integração/entrega pelo processoGit,manifesto/backup/restauro e delta instalado. P084/P085 continuam nos47,apenas preparação/simulação condicionada,sem benefícios confirmados. L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.
## 24/10/2026 — preparação G7G/P102,inventário antes de testes
G7F/P101 aceite7e5710eb/a89f9eca;**84entregues+48funcionaispendentes+P001=133**. Inventariados84fechos,sem perdas confirmadas;provas instaladas código/schema/dados/configuração/permissões174tabelas/369ficheiros/29fichas/28relações/408geometrias reutilizadas. Congelados livros/resultados/históricos,incluindoP101(base única),P100(valor normal),P095(TCuma vez),P094(âmbito),P091/P090,P060/P056,P050,P084/P085parciais. Sem repetir aceitação anterior ou ensaiar no activo.
G7G/P102 executaCIVA15(6)(a–d),2016PDF14/p1426(272):indemnização recebida declarada judicialmente por incumprimento total/parcial de contrato;descontos/abatimentos/bónus concedidos;quantias pagas em nome e por conta do adquirente/destinatário,registadas em adequadas contas de terceiros;embalagens não efectivamente transaccionadas com elementos27(5)(b).27(5)(b),PDF17/p1426(275):indicação separada e menção expressa de devolução acordada,não devolução já realizada.2022PDF3mantém15(6);2025PDF14mantém27(5)(b),altera27(10),não15;rectificação2017não altera estes requisitos. Fontes/exemplares/inventário aceites,cotejo visual com skillPDF. Um ramo,quatro tratamentos com condições e referências próprias;desconhecido não é zero/não aplicável. Montante inicial sem próprioIVA e com15(5)considerado;subtrair apenas exclusões ainda incluídas,sem segunda exclusão. Não determinarIVA/dedução/campo11/regularizações/totaisModeloA ou criar certificados/aprovadores. Novo livro incremental,snapshot/API/relatório existentes,sem schema/permissões. L1aberto;P00105/06;bebidasL2/L3;P084/P085parciais;Estatísticas/IAadiadas.
## 24/10/2026 — G7F/P101 entregue:composição da contraprestação sem dupla contagem
Homologação **`7e5710eb`**,pelo processoGit existente,sobre`70b4a640`;candidata`6f90fcb9` expressamente aceite pela Tempo. **P101:um ramo,dois tratamentos de parcela**,`tax_component` e`accessory_component`,na mesma base por operação. Montante inicial sem próprioIVA e com exclusões aplicáveis consideradas+parcelas ainda não incluídas;parcelas já incluídas conservadas sem segunda soma. Natureza,imposições excepto próprioIVA e despesas acessórias relativas a comissões/embalagem/transporte/seguros debitadas por conta do cliente,montantes,inclusão e referências conservados nas entradas imutáveis,versões/histórico/relatório. Sem zero/soma presumidos;respeitar bases especiais15(2)incluindoTCemP095/exclusões15(6). P102detalhado não é fechado por esta entrega. Base separada de incidência/taxa/IVA(IVA/taxa permanecemnull),dedução/campo11/totaisModeloA. Livros anteriores não alterados nem base somada como imposto.
Destino e main conferidos novamente;sem avanço concorrente encontrado. Nova sessãoSSH autenticada para esta entrega,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,15marcadores compilados do livro/componente/relatório,base única/parcelas/natureza/montante/inclusão/referências,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çãoP101 conferida,não aplicada,leitores/históricos e restantes ramos preservados.
[Manifesto/recibo](../simulations/l1-g7f-delivery-20261024.json),registo`iva_l1_g7f_P101_homologation_20261024`. **84entregues +48funcionaispendentes +P001 =133;sem candidatasQA por disponibilizar.** Os83fechos anteriores permanecem encerrados. P084/P085 continuam nos48,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 — G7F/P101 concluído emQA:composição da contraprestação sem dupla contagem
Implementação`e3caf553`. **Um ramo,dois tratamentos de parcela**:`tax_component` e`accessory_component`,na mesma composição por operação. FonteCIVA15(5)(a)/(b),Lei13/2016PDF14/p1426(272),15(1)/(2)/(6);Lei22/2022PDF3mantém5 por remissão;Lei10/2025não altera15. Impostos/direitos/taxas/outras imposições excepto próprioIVA;despesas acessórias debitadas relativas a comissões,embalagem,transporte e seguros por conta do cliente. Uma base por operação,não bases concorrentes por parcela.
Fórmula:montante inicial sem próprioIVA e com exclusões aplicáveis consideradas+parcelas aplicáveis ainda não incluídas. Parcelas já incluídas conservadas sem segunda soma;desconhecido não é zero nem soma/ausência presumida. Montante inicial/parcelas/composição referenciados,com documentos reutilizados ou pressupostos expressos. Respeitar regras especiais15(2),incluindo exclusãoTC deP095;P102(exclusões detalhadas)não é fechado nesta entrega. Sem taxas,IVA,dedução/campo11/totaisModeloA. Decimal exacto até6casas,sem arredondamento fiscal presumido. LivroconsiderationCompositions por oportunidade com operações/parcelas aninhadas,snapshot/API/dossier existentes,sem schema/permissões novos. Mudar natureza da parcela preserva montante/referência/inclusão e limpa confirmação de natureza;escolha técnica de integridade,não regra organizacional. Sem certificados/aprovadores/revalidação genérica de fontes oficiais.
Provas do delta:**4testes frontend**,**APIprivada1teste/31asserções**,guarda`simulator_fiscal_delta_20261021_test:55441` e rollback;tipos/build passaram. Interface real Edge/CUA:inclusão desconhecida→indeterminado;imposição100.10já incluída e transporte50.25não incluído dão1000.25+50.25=1050.50;parcela com próprioIVA→não aplicação desta composição,não isenção/IVAzero. Gravação recuperada/relatório:1000.25+100.10+50.25=1150.60,IVAindeterminado,1operação/2parcelas/6versões anteriores. Dados sintéticos,não aceitação manual atribuída à Tempo.83fechos/livros/resultados/históricos intactos,incluindoP100/P095/P094/P091/P090,P060/P056/P050 eP084/P085parciais;provas anteriores reutilizadas. [RegistoQA](../simulations/iva-l1-g7f-qa-20261024.json).
**83entregues +1emQA(P101) +48funcionaispendentes +P001 =133**. Homologação permanece`70b4a640`;falta integração/entrega pelo processoGit,manifesto/backup/restauro e delta instalado. P084/P085 continuam nos48,apenas preparação/simulação condicionada,sem benefícios confirmados. L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.
## 24/10/2026 — preparação G7F/P101,inventário antes de testes
G7E/P100 aceite70b4a640/0bef805e;**83entregues+49funcionaispendentes+P001=133**. Inventariados83fechos,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,incluindoP100(valor normal),P095(TCuma vez),P094(âmbito),P091/P090(baseIVA),P060/P056,P050(IVAserviço),P084/P085parciais. Sem repetir aceitação anterior ou ensaiar no activo.
G7F/P101 executa CIVA15(5)(a)/(b),2016PDF14/p1426(272):impostos/direitos/taxas/outras imposições excepto próprioIVA;despesas acessórias debitadas relativas a comissões,embalagem,transporte e seguros por conta do cliente.2022PDF3mantém5 por remissão;2025não altera15,2017não rectifica15(5). Fontes/exemplares/inventário aceites,cotejo visual com skillPDF. Um ramo,dois tratamentos de parcela na composição da mesma operação:não criar bases concorrentes por parcela. Montante inicial explicitamente líquido de próprioIVA e exclusões aplicáveis15(6);parcelas já incluídas mantidas sem segunda soma,parcelas não incluídas somadas uma vez. Desconhecido não é zero;respeitar regras especiais15(2),incluindoTC emP095,sem as substituir por inclusão genérica. Regra detalhada das exclusõesP102 não é fechada nesta entrega. Novo livro incremental no snapshot/API/relatório existentes,sem schema/permissões ou cálculoIVA/campo11/totaisModeloA. L1aberto;P00105/06;bebidasL2/L3;P084/P085parciais;Estatísticas/IAadiadas.
## 24/10/2026 — G7E/P100 entregue:contraprestação não monetária total ou parcial
Homologação **`70b4a640`**,pelo processoGit existente,sobre`92a7418c`;candidata`0460c853` expressamente aceite pela Tempo. **P100:um ramo,dois tratamentos**,`noncash_only` e`cash_and_noncash`. Base=valor normal dos bens/serviços dados em troca como contraprestação+montante monetário recebido/a receber quando exista. Ausência de dinheiro expressamente confirmada,não inferida de campo vazio;montante oculto preservado mas não somado quando inteiramente não monetária. Operação,contraprestação,acordo,fundamento/âmbito do valor normal15(4),composição15(5)/(6)sem próprioIVA e documentos/pressupostos conservados nas entradas imutáveis,versões/histórico/relatório. Sem avaliação automática,certificado/avaliador/aprovador novo,conversão cambial ou zero presumido. Base separada de incidência/taxa/IVA(IVA/taxa permanecemnull),dedução/campo11/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,dinheiro/valor normal econtraprestação/fundamento/â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çãoP100 conferida,não aplicada,leitores/históricos e restantes ramos preservados.
[Manifesto/recibo](../simulations/l1-g7e-delivery-20261024.json),registo`iva_l1_g7e_P100_homologation_20261024`. **83entregues +49funcionaispendentes +P001 =133;sem candidatasQA por disponibilizar.** Os82fechos anteriores permanecem encerrados. P084/P085 continuam nos49,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 — G7E/P100 concluído emQA:contraprestação não monetária total ou parcial
Implementação`9f053ac9`. **Um ramo,dois tratamentos**:`noncash_only`(valor normal,sem parte monetária expressamente confirmada) e`cash_and_noncash`(montante monetário recebido/a receber+valor normal dos bens/serviços dados em troca como contraprestação). FonteCIVA15(3)/(4),Lei13/2016PDF14/p1426(272),composição15(5)/(6);Lei22/2022PDF3mantém3–6 por remissão;Lei10/2025não altera15. Referenciar operação,contraprestação em bens/serviços,acordo,fundamento e âmbito do valor normal15(4):concorrência normal,fornecedor independente,mesmo estádio de comercialização,tempo/lugar da operação ou mais próximos e elementos15(5)na medida não incluídos. Documentos existentes/pressupostos expressos,sem avaliação automática,certificado,avaliador ou aprovador novo.
Montantes sem próprioIVA,sem duplicar elementos da composição. Dinheiro desconhecido não confirma ausência ou zero;zero só expresso. Decimal exacto até6casas,sem arredondamento fiscal presumido. Sem conversão cambial,incidência/taxa/IVA,dedução/campo11/totaisModeloA. Livro noncashBases por oportunidade no snapshot/API/dossier existentes,sem schema/permissões novos. Mudar composição conserva montantes/documentos,oculta dinheiro sem o apagar e limpa confirmação correspondente;quando inteiramente não monetária,o dinheiro oculto não é somado. Escolha técnica de integridade,não regra organizacional. Fontes oficiais aceites sem revalidação genérica.
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/dinheiro desconhecidos→indeterminado;troca parcial→total oculta500.25/limpa confirmação,confirmada calcula2200.50;regresso recupera500.25;gravação recuperada/relatório:total2200.50,parcial500.25+2200.50=2700.75,IVAindeterminado,2linhas/5versões anteriores. Dados sintéticos,não aceitação manual atribuída à Tempo.82fechos/livros/resultados/históricos intactos,incluindoP095(TCuma vez),P094(âmbito),P091/P090,P060/P056/P050 eP084/P085parciais;provas anteriores reutilizadas. [RegistoQA](../simulations/iva-l1-g7e-qa-20261024.json).
**82entregues +1emQA(P100) +49funcionaispendentes +P001 =133**. Homologação permanece`92a7418c`;falta integração/entrega pelo processoGit,manifesto/backup/restauro e delta instalado. P084/P085 continuam nos49,apenas preparação/simulação condicionada,sem benefícios confirmados. L1aberto;P00105/06;bebidasL2/L3;Estatísticas/IAadiadas.
## 24/10/2026 — preparação G7E/P100,inventário antes de testes
G7D/P095 aceite92a7418c/6234d343;**82entregues+50funcionaispendentes+P001=133**. Inventariados82fechos,sem perdas confirmadas;provas instaladas código/schema/dados/configuração/permissões174tabelas/369ficheiros/29fichas/28relações/408geometrias reutilizadas. Congelados livros/resultados/históricos,incluindoP095(TCuma vez),P094(âmbito do valor),P091/P090(baseIVA),P060/P056(âmbito),P050(IVAserviço),P084/P085parciais. Sem repetir aceitação anterior ou ensaiar no activo.
G7E/P100 executa regra independente documentada:CIVA15(3)/(4),2016PDF14/p1426(272):contraprestação não definida no todo/em parte em dinheiro,montante recebido/a receber acrescido do valor normal dos bens/serviços dados em troca. Valor normal15(4):preço em concorrência normal,fornecedor independente,mesmo estádio de comercialização,tempo/lugar da operação ou mais próximos,elementos15(5)na medida não incluídos;composição/exclusões15(5)/(6),sem próprioIVA.2022PDF3mantém3–6 por remissão;2025não altera15,2017não rectifica15(3)/(4). Fontes oficiais/exemplares/inventário aceites,cotejo visual com skillPDF. Dois tratamentos no mesmo ramo:inteiramente não monetária ouparte monetária+não monetária;ausência de parte monetária deve ser expressamente confirmada,não inferida de campo vazio. Preservar montante monetário oculto após mudança,sem o somar quando não aplicável. Valor normal exige fundamento/âmbito/elementos identificados ou pressupostos expressos,não avaliação automática/certificado/aprovador. MZN sem conversão cambial;moeda divergente indeterminada. Base separada deIVA/campo11/totaisModeloA. L1aberto;P00105/06;bebidasL2/L3;P084/P085parciais;Estatísticas/IAadiadas.
## 24/10/2026 — G7D/P095 entregue:combustíveis com preço fixado,TC excluída uma vez
Homologação **`92a7418c`**,pelo processoGit existente,sobre`df7cb7fa`;candidata`76be72c3` expressamente aceite pela Tempo. **P095:um ramo,dois tratamentos de composição**,`fuel_tax_included` e`fuel_tax_excluded`. Contraprestação sem próprioIVA ainda incluiTC→subtrairTCexacta identificada;montante já semTC→conservar,sem segunda subtracção. Preço fixado/referência/âmbito/intervalo aplicável à data da transmissão,composição e documentos/pressupostos conservados nas entradas imutáveis,versões/histórico/relatório. Não presume preço actual para outro período,taxa/valorTC ou prazo de expiração inexistente;fim do intervalo pode ficar vazio sem termo fixado,com correspondência temporal confirmada. Desconhecido não é zero. Base separada de incidência/taxa/IVA(IVA/taxa permanecemnull),dedução/campo11/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,15marcadores compilados do livro/componente/relatório,TCincluída/excluída epreço/referência/âmbito/período,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çãoP095 conferida,não aplicada,leitores/históricos e restantes ramos preservados.
[Manifesto/recibo](../simulations/l1-g7d-delivery-20261024.json),registo`iva_l1_g7d_P095_homologation_20261024`. **82entregues +50funcionaispendentes +P001 =133;sem candidatasQA por disponibilizar.** Os81fechos anteriores permanecem encerrados. P084/P085 continuam nos50,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 — 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
File diff suppressed because one or more lines are too long
@@ -0,0 +1,34 @@
import {useState} from 'react';
import {newCompositionBase,newCompositionPart,switchCompositionPart,compositionBook,compositionConditions,compositionCurrent,compositionReportRows,compositionBaseSource,compositionTreatments,recordCompositions,saveCompositionBook,type CompositionBook,type CompositionRow,type CompositionPart} from '@/lib/iva-composition-base';
export function SimulationCompositionBase({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:CompositionBook;
try{book=compositionBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:CompositionBook)=>{try{onChange('modelo_a_snapshot',saveCompositionBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<CompositionRow>)=>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 — impostos e despesas acessórias da contraprestação</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Prepare uma composição por operação. Parta do montante sem próprio IVA e com as exclusões aplicáveis já consideradas. Identifique as parcelas e se já estão incluídas;acrescente apenas as que ainda não constam do montante inicial.</p>
<p>Impostos,direitos,taxas e outras imposições excluem o próprio IVA. Nas despesas acessórias,confirme que são debitadas por conta do cliente e relativas a comissões,embalagem,transporte ou seguros. Respeite as regras especiais da operação,incluindo a exclusão da TC nos combustíveis. Base e IVA são resultados distintos.</p>
<p>{compositionBaseSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newCompositionBase(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar composição de operação</button>
{book.rows.map(row=>{const partChange=(id:string,patch:Partial<CompositionPart>)=>change(row.id,{parts:row.parts.map(p=>p.id===id?{...p,...patch}:p)});return<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>Natureza dos dados<select className="block rounded border p-2" value={row.origin} onChange={e=>change(row.id,{origin:e.target.value as CompositionRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Operação identificada'],['operationRef','Referência da operação / pressuposto'],['initialAmount','Montante inicial sem próprio IVA (moeda indicada)'],['initialRef','Referência do montante inicial e da sua composição'],['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'],['compositionRef','Referência da composição 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={field==='documentDate'?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
</div>
<fieldset><legend>Condições da composição</legend>{compositionConditions.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>
<button type="button" className="underline" onClick={()=>change(row.id,{parts:[...row.parts,newCompositionPart(crypto.randomUUID())]})}>Acrescentar parcela desta operação</button>
{row.parts.map(part=><fieldset key={part.id} className="rounded border p-3"><legend>{part.description||'Parcela por identificar'}</legend>
<label>Natureza da parcela<select className="block rounded border p-2" value={part.treatment} onChange={e=>partChange(part.id,switchCompositionPart(part,e.target.value))}><option value="">Por indicar</option>{compositionTreatments.map(t=><option key={t.id} value={t.id}>{t.label}</option>)}</select></label>
{([['description','Descrição da parcela'],['amount','Montante da parcela sem próprio IVA (moeda indicada)'],['reference','Referência da parcela / pressuposto']] as const).map(([field,label])=><label className="block" key={field}>{label}<input className="block rounded border p-2" value={part[field]} onChange={e=>partChange(part.id,{[field]:e.target.value})}/></label>)}
<label>Esta parcela já está incluída no montante inicial?<select className="block rounded border p-2" value={part.included} onChange={e=>partChange(part.id,{included:e.target.value as CompositionPart['included']})}><option value="">Por indicar</option><option value="yes">Sim — conservar sem somar novamente</option><option value="no">Não — acrescentar uma vez</option></select></label>
{part.treatment&&<label>{part.treatment==='tax_component'?'É imposto,direito,taxa ou outra imposição que integra esta contraprestação nos termos15(5)(a)?':'É despesa acessória debitada por conta do cliente,relativa a comissões,embalagem,transporte ou seguros nos termos15(5)(b)?'}<select className="block rounded border p-2" value={part.natureConfirmed} onChange={e=>partChange(part.id,{natureConfirmed:e.target.value as CompositionPart['natureConfirmed']})}><option value="">Por indicar</option><option value="yes">Sim</option><option value="no">Não</option></select></label>}
<label>A parcela exclui o próprio IVA?<select className="block rounded border p-2" value={part.ownVatExcluded} onChange={e=>partChange(part.id,{ownVatExcluded:e.target.value as CompositionPart['ownVatExcluded']})}><option value="">Por indicar</option><option value="yes">Sim</option><option value="no">Não</option></select></label>
<p>Mudar a natureza conserva os montantes e referências,mas exige rever a correspondência da parcela. Cada parcela será considerada uma única vez nesta operação.</p>
</fieldset>)}
</details>;})}
{!!book.rows.length&&<button type="button" className="rounded bg-emerald-800 p-2 text-white" onClick={()=>{try{save(recordCompositions(draft,book));}catch(cause){setError(String(cause));}}}>Compor bases e guardar versão</button>}
{book.result&&<><p role="status">{compositionCurrent(draft,book)?'Composições correspondentes às entradas guardadas.':'Entradas alteradas;composições 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>{compositionReportRows(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>;
}
@@ -0,0 +1,36 @@
import {useState} from 'react';
import {newExclusionBase,newExclusionPart,switchExclusionPart,exclusionBook,exclusionConditions,exclusionCurrent,exclusionReportRows,exclusionBaseSource,exclusionTreatments,partConditions,recordExclusions,saveExclusionBook,type ExclusionBook,type ExclusionRow,type ExclusionPart} from '@/lib/iva-exclusion-base';
export function SimulationExclusionBase({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:ExclusionBook;
try{book=exclusionBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:ExclusionBook)=>{try{onChange('modelo_a_snapshot',saveExclusionBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<ExclusionRow>)=>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 — exclusões da contraprestação</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Prepare uma composição por operação,partindo do montante sem próprio IVA e com as inclusões aplicáveis já consideradas. Identifique as parcelas e se ainda estão incluídas;subtraia apenas essas parcelas,sem segunda exclusão.</p>
<p>Cada tratamento tem condições próprias. Indemnização judicial não é qualquer compensação;desconto deve estar concedido;pagamento por conta alheia exige nome/conta do adquirente e adequadas contas de terceiros. Nas embalagens,não se exige devolução já realizada:confira a não transmissão,a indicação separada e a menção de devolução acordada. Reutilize documentos ou declare pressupostos de projecção. Base não é IVA nem regularização.</p>
<p>{exclusionBaseSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newExclusionBase(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar exclusões de operação</button>
{book.rows.map(row=>{const partChange=(id:string,patch:Partial<ExclusionPart>)=>change(row.id,{parts:row.parts.map(p=>p.id===id?{...p,...patch}:p)});return<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>Natureza dos dados<select className="block rounded border p-2" value={row.origin} onChange={e=>change(row.id,{origin:e.target.value as ExclusionRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Operação identificada'],['operationRef','Referência da operação / pressuposto'],['initialAmount','Montante inicial sem próprio IVA (moeda indicada)'],['initialRef','Referência do montante inicial e da sua composição'],['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'],['exclusionRef','Referência da composição 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={field==='documentDate'?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
</div>
<fieldset><legend>Condições das exclusões</legend>{exclusionConditions.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>
<button type="button" className="underline" onClick={()=>change(row.id,{parts:[...row.parts,newExclusionPart(crypto.randomUUID())]})}>Acrescentar parcela desta operação</button>
{row.parts.map(part=><fieldset key={part.id} className="rounded border p-3"><legend>{part.description||'Parcela por identificar'}</legend>
<label>Natureza da parcela<select className="block rounded border p-2" value={part.treatment} onChange={e=>partChange(part.id,switchExclusionPart(part,e.target.value))}><option value="">Por indicar</option>{exclusionTreatments.map(t=><option key={t.id} value={t.id}>{t.label}</option>)}</select></label>
{([['description','Descrição da parcela'],['amount','Montante da parcela sem próprio IVA (moeda indicada)'],['reference','Referência da parcela / pressuposto']] as const).map(([field,label])=><label className="block" key={field}>{label}<input className="block rounded border p-2" value={part[field]} onChange={e=>partChange(part.id,{[field]:e.target.value})}/></label>)}
<label>Esta parcela ainda está incluída no montante inicial?<select className="block rounded border p-2" value={part.included} onChange={e=>partChange(part.id,{included:e.target.value as ExclusionPart['included']})}><option value="">Por indicar</option><option value="yes">Sim — excluir uma vez</option><option value="no">Não — já excluída,conservar sem nova subtracção</option></select></label>
<label>Âmbito da exclusão: operação, montantes e condições<input className="block rounded border p-2" value={part.scope} onChange={e=>partChange(part.id,{scope:e.target.value})}/></label>
{part.treatment==='third_party_payment'&&<><label>Referência das adequadas contas de terceiros<input className="block rounded border p-2" value={part.accountRef} onChange={e=>partChange(part.id,{accountRef:e.target.value})}/></label><label>Adquirente/destinatário em nome e por conta de quem se pagou<input className="block rounded border p-2" value={part.beneficiaryRef} onChange={e=>partChange(part.id,{beneficiaryRef:e.target.value})}/></label></>}
{part.treatment==='returnable_packaging'&&<label>Indicação separada e menção de devolução acordada na factura/documento<input className="block rounded border p-2" value={part.documentExcerpt} onChange={e=>partChange(part.id,{documentExcerpt:e.target.value})}/></label>}
{partConditions(part.treatment).map(([key,label])=><label className="block" key={key}>{label}<select className="block rounded border p-2" value={part.conditions[key]??''} onChange={e=>partChange(part.id,{conditions:{...part.conditions,[key]:e.target.value as ExclusionPart['included']}})}><option value="">Por indicar</option><option value="yes">Sim</option><option value="no">Não</option></select></label>)}
<p>Mudar a natureza conserva os montantes e referências,mas exige rever a correspondência da parcela. Cada parcela será excluída uma única vez nesta operação. Os campos sem aplicação ficam ocultos e conservados.</p>
</fieldset>)}
</details>;})}
{!!book.rows.length&&<button type="button" className="rounded bg-emerald-800 p-2 text-white" onClick={()=>{try{save(recordExclusions(draft,book));}catch(cause){setError(String(cause));}}}>Aplicar exclusões à base e guardar versão</button>}
{book.result&&<><p role="status">{exclusionCurrent(draft,book)?'Exclusões correspondentes às entradas guardadas.':'Entradas alteradas;exclusões 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>{exclusionReportRows(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>;
}
@@ -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>;
}
@@ -0,0 +1,35 @@
import {useState} from 'react';
import {newGoodsAllocation,switchAllocationTreatment,switchAllocationValuation,goodsAllocationBook,goodsAllocationConditions,allocationSpecificConditions,goodsAllocationCurrent,goodsAllocationReportRows,goodsAllocationSource,goodsAllocationTreatments,recordGoodsAllocations,saveGoodsAllocationBook,type GoodsAllocationBook,type GoodsAllocationRow} from '@/lib/iva-goods-allocation';
export function SimulationGoodsAllocation({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:GoodsAllocationBook;
try{book=goodsAllocationBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:GoodsAllocationBook)=>{try{onChange('modelo_a_snapshot',saveGoodsAllocationBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<GoodsAllocationRow>)=>save({...book,rows:book.rows.map(row=>row.id===id?{...row,...patch}:row)});
return<details className="space-y-3 rounded border p-3">
<summary>Afectação de bens — classificação ebase de aquisição/custo</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. P124identifica a transmissão assimilada;P088determina a base. Uma operação conserva a sua identidade nos dois requisitos,não se soma duas vezes. Uso temporário de bens como serviçoP089segue o seu percurso.</p>
<p>A dedução anterior total/parcial é um facto histórico dos bens ou elementos;não é calculada nem concedida aqui. A base usa preço de aquisição reportado ao momento da operação ou,na sua falta demonstrada,preço de custo.Não substituir um preço desconhecido por zero ou por custo automaticamente.</p>
<p>{goodsAllocationSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newGoodsAllocation(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar afectação ou transmissão gratuita</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>Percurso de afectação dos bens<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchAllocationTreatment(row,e.target.value))}><option value="">Por indicar</option>{goodsAllocationTreatments.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 GoodsAllocationRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Operação identificada'],['operationRef','Referência da operação / pressuposto'],['currency','Moeda da base'],['operationDate','Data da operação / prevista'],['period','Mês da operação'],['documentRef','Documento / referência da previsão'],['documentDate','Data do documento / prevista'],['goodsRef','Bens/elementos e identificação do conjunto afectado'],['deductionRef','Referência da dedução anterior total ou parcial'],['destinationRef','Destino,finalidade ou sector eâmbito'],['evidence','Fundamento factual / pressupostos']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={['operationDate','documentDate'].includes(field)?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{['permanent_private_goods','free_goods_transfer'].includes(row.treatment)&&<label>Factos/referência sobre excepção de amostras/ofertas de pequeno valor<input className="block rounded border p-2" value={row.exceptionRef} onChange={e=>change(row.id,{exceptionRef:e.target.value})}/></label>}
{row.treatment==='fixed_asset_20a'&&<label>Enquadramento dos bens20(1)a eafectação ao activo imobilizado<input className="block rounded border p-2" value={row.asset20aRef} onChange={e=>change(row.id,{asset20aRef:e.target.value})}/></label>}
<label>Modo de determinação da base15(2)b<select className="block rounded border p-2" value={row.valuationMode} onChange={e=>change(row.id,switchAllocationValuation(row,e.target.value))}><option value="">Por esclarecer</option><option value="acquisition">Preço de aquisição reportado ao momento da operação</option><option value="cost">Preço de custo,na falta demonstrada de preço de aquisição</option></select></label>
{row.valuationMode==='acquisition'&&<><label>Preço de aquisição para o conjunto identificado,sem próprioIVA<input className="block rounded border p-2" value={row.acquisitionPrice} onChange={e=>change(row.id,{acquisitionPrice:e.target.value})}/></label><label>Referência do preço de aquisição reportado ao momento<input className="block rounded border p-2" value={row.acquisitionRef} onChange={e=>change(row.id,{acquisitionRef:e.target.value})}/></label></>}
{row.valuationMode==='cost'&&<><label>Preço de custo para o conjunto identificado,sem próprioIVA<input className="block rounded border p-2" value={row.currentCost} onChange={e=>change(row.id,{currentCost:e.target.value})}/></label><label>Referência do custo reportado ao momento<input className="block rounded border p-2" value={row.costRef} onChange={e=>change(row.id,{costRef:e.target.value})}/></label><label>Falta de preço de aquisição demonstrada para esta operação<select className="block rounded border p-2" value={row.conditions.acquisitionUnavailable??''} onChange={e=>change(row.id,{conditions:{...row.conditions,acquisitionUnavailable:e.target.value as ''|'yes'|'no'}})}><option value="">Por esclarecer</option><option value="yes">Sim</option><option value="no">Não</option></select></label></>}
<label>Momento a que o preço de aquisição/custo é reportado<input type="date" className="block rounded border p-2" value={row.valuationDate} onChange={e=>change(row.id,{valuationDate:e.target.value})}/></label>
<label>Âmbito ecomposição da base,bens/elementos abrangidos<input className="block rounded border p-2" value={row.valuationScope} onChange={e=>change(row.id,{valuationScope:e.target.value})}/></label>
<label>Base reportada ao momento desta operação,sem próprioIVA ecom âmbito correspondente<select className="block rounded border p-2" value={row.conditions.valuationConfirmed??''} onChange={e=>change(row.id,{conditions:{...row.conditions,valuationConfirmed:e.target.value as ''|'yes'|'no'}})}><option value="">Por esclarecer</option><option value="yes">Sim</option><option value="no">Não</option></select></label>
</div>
<p>Mudar percurso/modo conserva referências e valores ocultos,mas exige rever confirmações próprias. Não se presume limiar de oferta,custo histórico actualizado ou nova dedução.</p>
<fieldset><legend>Factos próprios da operação</legend>{[...goodsAllocationConditions,...allocationSpecificConditions(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(recordGoodsAllocations(draft,book));}catch(cause){setError(String(cause));}}}>Classificar afectações,determinar base eguardar versão</button>}
{book.result&&<><p role="status">{goodsAllocationCurrent(draft,book)?'Classificações/bases correspondentes às entradas guardadas.':'Entradas alteradas;resultados históricos conservados. Reveja e determine novamente.'} {book.history?.length??0} versões anteriores. Dedução histórica não é nova dedução/campo11;sem IVA ou regularização calculados.</p><dl>{goodsAllocationReportRows(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>;
}
@@ -0,0 +1,34 @@
import {useState} from 'react';
import {newGoodsLocation,switchGoodsTreatment,goodsLocationBook,goodsLocationConditions,ownGoodsConditions,goodsLocationCurrent,goodsLocationReportRows,goodsLocationSource,goodsLocationTreatments,recordGoodsLocations,saveGoodsLocationBook,type GoodsLocationBook,type GoodsLocationRow} from '@/lib/iva-goods-location';
export function SimulationGoodsLocation({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:GoodsLocationBook;
try{book=goodsLocationBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:GoodsLocationBook)=>{try{onChange('modelo_a_snapshot',saveGoodsLocationBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<GoodsLocationRow>)=>save({...book,rows:book.rows.map(row=>row.id===id?{...row,...patch}:row)});
return<details className="space-y-3 rounded border p-3">
<summary>Localização — transmissões de bens e antes da importação</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Identifique os bens e os factos da transmissão. Com transporte,indique onde se encontram ao iniciá-lo;sem transporte,onde são postos à disposição. O endereço ou nacionalidade do cliente não substituem estes factos.</p>
<p>Na transmissão pelo importador ou subsequente antes da importação nacional de bens vindos do estrangeiro,confira a regra própria6(2). A localização física anterior no estrangeiro não a afasta por si. Fora do âmbito territorial não equivale a isenção ou IVA zero;esta classificação não calcula imposto.</p>
<p>{goodsLocationSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newGoodsLocation(crypto.randomUUID())]})}>Acrescentar localização de transmissã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>Percurso de localização dos bens<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchGoodsTreatment(row,e.target.value))}><option value="">Por indicar</option>{goodsLocationTreatments.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 GoodsLocationRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Bens e transmissão identificados'],['operationRef','Referência da operação / pressuposto'],['operationDate','Data da transmissão / prevista'],['period','Mês da transmissão'],['documentRef','Documento da operação / referência da previsão'],['documentDate','Data do documento / prevista'],['scope','Âmbito: bens, operação, período e condições'],['evidence','Fundamento factual / pressupostos']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={['operationDate','documentDate'].includes(field)?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{row.treatment&&row.treatment!=='goods_before_import'&&<>
<label>{row.treatment==='goods_with_transport'?'Local dos bens no início do transporte/expedição':'Local dos bens quando postos à disposição sem transporte'}<input className="block rounded border p-2" value={row.goodsPlace} onChange={e=>change(row.id,{goodsPlace:e.target.value})}/></label>
<label>Situação desse local face ao território nacional<select className="block rounded border p-2" value={row.placeCountry} onChange={e=>change(row.id,{placeCountry:e.target.value})}><option value="">Por indicar</option><option value="MZ">Em Moçambique</option><option value="foreign">Fora de Moçambique</option></select></label>
<label>Referência da localização dos bens / pressuposto<input className="block rounded border p-2" value={row.placeRef} onChange={e=>change(row.id,{placeRef:e.target.value})}/></label>
</>}
{['goods_with_transport','goods_before_import'].includes(row.treatment)&&<label>Referência do transporte/expedição / pressuposto<input className="block rounded border p-2" value={row.transportRef} onChange={e=>change(row.id,{transportRef:e.target.value})}/></label>}
{row.treatment==='goods_before_import'&&<><label>Referência da importação nacional / pressuposto<input className="block rounded border p-2" value={row.importRef} onChange={e=>change(row.id,{importRef:e.target.value})}/></label><label>Importador/cadeia e posição desta transmissão<input className="block rounded border p-2" value={row.chainRef} onChange={e=>change(row.id,{chainRef:e.target.value})}/></label></>}
</div>
<p>Mudar percurso conserva os locais e referências,mas exige rever os factos próprios. Campos sem aplicação ficam ocultos e conservados.</p>
<fieldset><legend>Factos próprios deste percurso</legend>{[...goodsLocationConditions,...ownGoodsConditions(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(recordGoodsLocations(draft,book));}catch(cause){setError(String(cause));}}}>Classificar localização e guardar versão</button>}
{book.result&&<><p role="status">{goodsLocationCurrent(draft,book)?'Localizações correspondentes às entradas guardadas.':'Entradas alteradas;localizações históricas conservadas. Reveja e classifique novamente.'} {book.history?.length??0} versões anteriores. Classificação não determina isenção,IVA ou campo11.</p><dl>{goodsLocationReportRows(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>;
}
@@ -0,0 +1,41 @@
import {useState} from 'react';
import {newListedService,switchListedTreatment,listedServiceBook,listedServiceConditions,ownListedConditions,listedServiceCurrent,listedServiceReportRows,listedServiceSource,listedServiceTreatments,recordListedServices,saveListedServiceBook,type ListedServiceBook,type ListedServiceRow} from '@/lib/iva-listed-services';
export function SimulationListedServices({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:ListedServiceBook;
try{book=listedServiceBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:ListedServiceBook)=>{try{onChange('modelo_a_snapshot',saveListedServiceBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<ListedServiceRow>)=>save({...book,rows:book.rows.map(row=>row.id===id?{...row,...patch}:row)});
return<details className="space-y-3 rounded border p-3">
<summary>Serviços enumerados — localização e responsável pelas obrigações</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Identifique a natureza do serviço,o estabelecimento a partir do qual o prestador o fornece e o estabelecimento estável ou domicílio do adquirente. Nacionalidade não substitui estes factos.</p>
<p>Adquirente no estrangeiro:conferir6(8). Prestador estrangeiro e adquirente nacional:6(7)inclui sujeitos passivos2(1)a/b que realizem exclusivamente operações isentas sem direito à dedução. Não exigir direito à dedução como condição de localização. Digital,imóveis e outras regras próprias têm os seus percursos.</p>
<p>A classificação não concede isenção nem calcula IVA. A identificação do responsável explica a regra aplicável;não apresenta declaração nem inicia pagamento.</p>
<p>{listedServiceSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newListedService(crypto.randomUUID())]})}>Acrescentar serviço enumerado</button>
{book.rows.map(row=><details key={row.id} className="rounded border p-3"><summary>{row.description||'Serviço por identificar'} — {row.period||'mês por indicar'}</summary>
<div className="grid gap-3 md:grid-cols-2">
<label>Tratamento do serviço<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchListedTreatment(row,e.target.value))}><option value="">Por indicar</option>{listedServiceTreatments.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 ListedServiceRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Serviço identificado'],['operationRef','Referência da operação / pressuposto'],['operationDate','Data do serviço / prevista'],['period','Mês do serviço'],['documentRef','Documento da operação / referência da previsão'],['documentDate','Data do documento / prevista'],['subjectRef','Objecto:direito,campanha,serviço,pessoal,bens ou contrato'],['useRef','Destinatário e utilização / pressuposto'],['scope','Âmbito:serviço,operação,período e condições'],['evidence','Fundamento factual / pressupostos'],['providerPlace','Sede,EP ou domicílio a partir do qual o prestador fornece'],['providerRef','Referência do estabelecimento prestador'],['buyerPlace','Estabelecimento estável ou domicílio do adquirente'],['buyerRef','Referência do estabelecimento ou domicílio adquirente']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={['operationDate','documentDate'].includes(field)?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{([['providerCountry','País do estabelecimento prestador'],['buyerCountry','País do estabelecimento ou domicílio adquirente']] as const).map(([field,label])=><label key={field}>{label}<select className="block rounded border p-2" value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}><option value="">Por indicar</option><option value="MZ">Moçambique</option><option value="foreign">Estrangeiro</option></select></label>)}
{row.providerCountry==='foreign'&&row.buyerCountry==='MZ'&&<>
<label>Qualidade do adquirente2(1)<select className="block rounded border p-2" value={row.recipientType} onChange={e=>change(row.id,{recipientType:e.target.value})}><option value="">Por esclarecer</option><option value="a">Alínea a — actividade independente habitual,incluindo operações isentas sem dedução</option><option value="b">Alínea b — operação independente nos pressupostos legais</option><option value="other">Não corresponde às alíneas a/b</option></select></label>
<label>Referência da qualidade fiscal do adquirente<input className="block rounded border p-2" value={row.recipientRef} onChange={e=>change(row.id,{recipientRef:e.target.value})}/></label>
</>}
{row.providerCountry==='MZ'&&row.buyerCountry==='MZ'&&<>
<label>Prestador sujeito passivo no regime geral<select className="block rounded border p-2" value={row.providerTaxable} onChange={e=>change(row.id,{providerTaxable:e.target.value})}><option value="">Por esclarecer</option><option value="yes">Sim</option><option value="no">Não</option></select></label>
<label>Referência da qualidade fiscal do prestador<input className="block rounded border p-2" value={row.providerTaxRef} onChange={e=>change(row.id,{providerTaxRef:e.target.value})}/></label>
</>}
{['intermediation_service','abstention_service'].includes(row.treatment)&&<>
<label>Alínea6(7)do serviço,direito ou actividade subjacente<select className="block rounded border p-2" value={row.targetClause} onChange={e=>change(row.id,{targetClause:e.target.value})}><option value="">Por indicar</option>{listedServiceTreatments.filter(t=>t.id!==row.treatment).map(t=><option key={t.id} value={t.clause}>{t.clause} — {t.label}</option>)}</select></label>
<label>Referência do subjacente e relação da intermediação/obrigação<input className="block rounded border p-2" value={row.targetRef} onChange={e=>change(row.id,{targetRef:e.target.value})}/></label>
</>}
</div>
<p>Mudar tratamento conserva dados e referências ocultos,mas exige rever os factos próprios. Campos sem aplicação ficam ocultos e conservados.</p>
<fieldset><legend>Factos próprios deste tratamento</legend>{[...listedServiceConditions,...ownListedConditions(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(recordListedServices(draft,book));}catch(cause){setError(String(cause));}}}>Classificar serviços e guardar versão</button>}
{book.result&&<><p role="status">{listedServiceCurrent(draft,book)?'Resultados correspondentes às entradas guardadas.':'Entradas alteradas;resultados históricos conservados. Reveja e classifique novamente.'} {book.history?.length??0} versões anteriores. Localização e responsável não determinam isenção,IVA ou dedução/campo11.</p><dl>{listedServiceReportRows(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,19 @@ 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 { 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 { SimulationGoodsLocation } from './simulation-goods-location';
import { SimulationServiceLocation } from './simulation-service-location';
import { SimulationListedServices } from './simulation-listed-services';
import { SimulationReducedBases } from './simulation-reduced-bases';
import { SimulationOwnName } from './simulation-own-name';
import { SimulationGoodsAllocation } from './simulation-goods-allocation';
import { SimulationSecondhand } from './simulation-secondhand';
import { SimulationOfferPreparations } from './simulation-offer-preparations';
import { SimulationOperations } from './simulation-operations';
@@ -96,6 +109,19 @@ 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} />
<SimulationNoncashBase draft={draft} onChange={onChange} />
<SimulationCompositionBase draft={draft} onChange={onChange} />
<SimulationExclusionBase draft={draft} onChange={onChange} />
<SimulationValueReview draft={draft} onChange={onChange} />
<SimulationServiceNormal draft={draft} onChange={onChange} />
<SimulationGoodsLocation draft={draft} onChange={onChange} />
<SimulationServiceLocation draft={draft} onChange={onChange} />
<SimulationListedServices draft={draft} onChange={onChange} />
<SimulationReducedBases draft={draft} onChange={onChange} />
<SimulationOwnName draft={draft} onChange={onChange} />
<SimulationGoodsAllocation draft={draft} onChange={onChange} />
<SimulationSecondhand draft={draft} onChange={onChange} />
<SimulationOfferPreparations draft={draft} onChange={onChange} />
<SimulationModeloA draft={draft} />
</section>;
@@ -0,0 +1,29 @@
import {useState} from 'react';
import {newNoncashBase,switchNoncashComposition,noncashBaseBook,noncashBaseConditions,noncashBaseCurrent,noncashBaseReportRows,noncashBaseSource,noncashBaseTreatments,recordNoncashBases,saveNoncashBaseBook,type NoncashBaseBook,type NoncashBaseRow} from '@/lib/iva-noncash-base';
export function SimulationNoncashBase({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:NoncashBaseBook;
try{book=noncashBaseBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:NoncashBaseBook)=>{try{onChange('modelo_a_snapshot',saveNoncashBaseBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<NoncashBaseRow>)=>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 — contraprestação não monetária total ou parcial</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Identifique a operação e os bens ou serviços dados em troca como contraprestação. Se houver parte em dinheiro,some o montante recebido ou a receber ao valor normal desses bens ou serviços;se não houver,confirme expressamente a ausência dessa parte.</p>
<p>O valor normal deve ter fundamento e âmbito correspondentes ao artigo15(4),incluindo concorrência normal,fornecedor independente,estádio de comercialização e tempo/lugar da operação ou mais próximos. Reutilize referências existentes ou indique pressupostos de projecção. O portal não avalia automaticamente bens ou serviços. Indique montantes sem o próprio IVA e sem duplicar elementos da composição. Base e IVA são resultados distintos.</p>
<p>{noncashBaseSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newNoncashBase(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar contraprestação não monetária</button>
{book.rows.map(row=>{const rule=noncashBaseTreatments.find(item=>item.id===row.treatment);return<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>Composição da contraprestação<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchNoncashComposition(row,e.target.value))}><option value="">Por indicar</option>{noncashBaseTreatments.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 NoncashBaseRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Operação identificada'],['exchangeDescription','Bens ou serviços dados em troca como contraprestação'],['agreementRef','Acordo / referência da previsão'],['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'],['valuationRef','Fundamento do valor normal / pressuposto'],['valuationScope','Âmbito do valor normal: bens/serviços, estádio, tempo, lugar e condições'],['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={field==='documentDate'?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{rule&&<label>Valor normal dos bens ou serviços dados em troca,sem IVA (moeda indicada)<input className="block rounded border p-2" value={row.normalValue} onChange={e=>change(row.id,{normalValue:e.target.value})}/></label>}
{row.treatment==='cash_and_noncash'&&<><label>Montante monetário recebido ou a receber,sem IVA (moeda indicada)<input className="block rounded border p-2" value={row.cashAmount} onChange={e=>change(row.id,{cashAmount:e.target.value})}/></label><label>Referência da parte monetária / pressuposto<input className="block rounded border p-2" value={row.cashRef} onChange={e=>change(row.id,{cashRef:e.target.value})}/></label></>}
</div>
<p>Mudar a composição conserva valores e documentos,mas exige rever a presença ou ausência da parte monetária. Os valores ocultos e as versões anteriores mantêm-se;um campo vazio não confirma ausência de dinheiro.</p>
{rule?<fieldset><legend>Condições próprias desta operação</legend>{noncashBaseConditions.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(recordNoncashBases(draft,book));}catch(cause){setError(String(cause));}}}>Determinar bases de contraprestação e guardar versão</button>}
{book.result&&<><p role="status">{noncashBaseCurrent(draft,book)?'Bases de contraprestação correspondentes às entradas guardadas.':'Entradas alteradas;bases de contraprestação 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>{noncashBaseReportRows(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>;
}
@@ -0,0 +1,28 @@
import {useState} from 'react';
import {newOwnName,switchOwnNameTreatment,ownNameBook,ownNameConditions,ownNameSpecificConditions,ownNameCurrent,ownNameReportRows,ownNameSource,ownNameTreatments,recordOwnNames,saveOwnNameBook,type OwnNameBook,type OwnNameRow} from '@/lib/iva-own-name';
export function SimulationOwnName({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:OwnNameBook;
try{book=ownNameBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:OwnNameBook)=>{try{onChange('modelo_a_snapshot',saveOwnNameBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<OwnNameRow>)=>save({...book,rows:book.rows.map(row=>row.id===id?{...row,...patch}:row)});
return<details className="space-y-3 rounded border p-3">
<summary>Comissão e mandato — circuitos emnome próprio</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Venda/prestação:mandante ou comitente → agente → terceiro. Aquisição:terceiro → agente → mandante ou comitente. Nos serviços,o mandatário emnome próprio é adquirente eprestador sucessivamente;nos bens,os papéis dependem da comissão de compra ou venda.</p>
<p>Conserve as contraprestações originais das duas relações separadas. Este percurso não as soma,não calcula imposto nem dedução e não cria uma comissão autónoma. A base de comissões de bensP091já entregue mantém o seu cálculo e histórico próprios.</p>
<p>{ownNameSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newOwnName(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar circuito emnome próprio</button>
{book.rows.map(row=><details key={row.id} className="rounded border p-3"><summary>{row.description||'Circuito por identificar'} — {row.period||'mês por indicar'}</summary>
<div className="grid gap-3 md:grid-cols-2">
<label>Natureza e sentido do circuito<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchOwnNameTreatment(row,e.target.value))}><option value="">Por indicar</option>{ownNameTreatments.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 OwnNameRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Circuito identificado'],['operationRef','Referência da operação / pressuposto'],['operationDate','Data da operação / prevista'],['period','Mês da operação'],['documentRef','Documento / referência da previsão'],['documentDate','Data do documento / prevista'],['principalRef','Mandante ou comitente e referência'],['agentRef','Comissário ou mandatário e referência'],['thirdPartyRef','Terceiro e referência'],['contractRef','Contrato de comissão ou mandato'],['subjectRef','Bens ou serviço e âmbito do objecto'],['currency','Moeda original das contraprestações'],['firstAmount','Contraprestação original da relação1'],['firstLegRef','Referência da relação1'],['secondAmount','Contraprestação original da relação2'],['secondLegRef','Referência da relação2'],['scope','Âmbito:partes,objecto,operação eperíodo'],['evidence','Fundamento factual / pressupostos']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={['operationDate','documentDate'].includes(field)?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{ownNameTreatments.find(t=>t.id===row.treatment)?.kind==='goods'&&<label>Referência de baseP091já existente,se aplicável<input className="block rounded border p-2" value={row.existingBaseRef} onChange={e=>change(row.id,{existingBaseRef:e.target.value})}/></label>}
</div>
<p>As relações seguem a ordem indicada no sentido escolhido;contraprestação desconhecida não é zero. A referênciaP091é reutilizável e não constitui nova exigência para identificar o circuito. Mudar sentido/natureza conserva partes,contrato,valores e referências,mas exige rever os factos próprios.</p>
<fieldset><legend>Factos próprios do circuito</legend>{[...ownNameConditions,...ownNameSpecificConditions(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(recordOwnNames(draft,book));}catch(cause){setError(String(cause));}}}>Identificar circuitos e guardar versão</button>}
{book.result&&<><p role="status">{ownNameCurrent(draft,book)?'Circuitos correspondentes às entradas guardadas.':'Entradas alteradas;circuitos históricos conservados. Reveja e identifique novamente.'} {book.history?.length??0} versões anteriores. Duas relações separadas,sem soma de bases,IVA ou dedução/campo11.</p><dl>{ownNameReportRows(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>;
}
@@ -0,0 +1,35 @@
import {useState} from 'react';
import {newReducedBase,switchReducedTreatment,reducedBaseBook,reducedBaseConditions,ownReducedConditions,reducedBaseCurrent,reducedBaseReportRows,reducedBaseSource,reducedBaseTreatments,publicWorkCategories,recordReducedBases,saveReducedBaseBook,type ReducedBaseBook,type ReducedBaseRow} from '@/lib/iva-reduced-bases';
export function SimulationReducedBases({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:ReducedBaseBook;
try{book=reducedBaseBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:ReducedBaseBook)=>{try{onChange('modelo_a_snapshot',saveReducedBaseBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<ReducedBaseRow>)=>save({...book,rows:book.rows.map(row=>row.id===id?{...row,...patch}:row)});
return<details className="space-y-3 rounded border p-3">
<summary>Bases reduzidas — energia,taxas aeronáuticas,obras públicas eágua</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Indique a contraprestação total antes da redução,sem o próprioIVA ecom a composição conferida. Se o montante já está reduzido,reutilize o valor original antes de calcular;se só existe total comIVA,esclareça a composição antes de usar este campo.</p>
<p>Energia62%,taxas aeronáuticas85%,obras públicas40%(redução60%)eágua75%. Percentagem da base não é taxaIVA. A dedução relativa a estas operações fica sujeita à mesma proporção18(6),mas este percurso não calcula nem concede dedução ou preenche campo11.</p>
<p>{reducedBaseSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newReducedBase(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar base reduzida</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 da base reduzida<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchReducedTreatment(row,e.target.value))}><option value="">Por indicar</option>{reducedBaseTreatments.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 ReducedBaseRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Operação identificada'],['currency','Moeda do montante'],['operationDate','Data da operação / prevista'],['period','Mês da operação'],['documentRef','Documento / referência da previsão'],['documentDate','Data do documento / prevista'],['priceScope','Âmbito:objecto,operação,local eperíodo'],['consideration','Contraprestação total antes da redução,sem próprioIVA'],['compositionRef','Referência da composição15(1)/(5)/(6)'],['evidence','Fundamento factual / pressupostos']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={['operationDate','documentDate'].includes(field)?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{row.treatment==='public_works'?<>
<label>Projecto ou contrato de obra pública<input className="block rounded border p-2" value={row.projectRef} onChange={e=>change(row.id,{projectRef:e.target.value})}/></label>
<label>Categoria da obra<select className="block rounded border p-2" value={row.workCategory} onChange={e=>change(row.id,{workCategory:e.target.value})}><option value="">Por indicar</option>{publicWorkCategories.map(c=><option key={c.id} value={c.id}>{c.label}</option>)}</select></label>
</>:row.treatment&&<>
<label>Referência do preço fixado ou taxa aeronáutica<input className="block rounded border p-2" value={row.priceRef} onChange={e=>change(row.id,{priceRef:e.target.value})}/></label>
<label>Preço/taxa aplicável desde<input type="date" className="block rounded border p-2" value={row.priceFrom} onChange={e=>change(row.id,{priceFrom:e.target.value})}/></label>
<label>Preço/taxa aplicável até,se houver termo<input type="date" className="block rounded border p-2" value={row.priceTo} onChange={e=>change(row.id,{priceTo:e.target.value})}/></label>
</>}
</div>
<p>Mudar tratamento conserva dados e referências ocultos,mas exige rever os factos próprios. Não se exige referência de preço fixado para obras públicas;estas dependem do projecto/categoria/âmbito aplicáveis.</p>
<fieldset><legend>Condições deste tratamento</legend>{[...reducedBaseConditions,...ownReducedConditions(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(recordReducedBases(draft,book));}catch(cause){setError(String(cause));}}}>Calcular bases reduzidas e guardar versão</button>}
{book.result&&<><p role="status">{reducedBaseCurrent(draft,book)?'Bases correspondentes às entradas guardadas.':'Entradas alteradas;bases históricas conservadas. Reveja e calcule novamente.'} {book.history?.length??0} versões anteriores. Base eproporção18(6)não são imposto ou dedução concedida.</p><dl>{reducedBaseReportRows(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>;
}
@@ -0,0 +1,35 @@
import {useState} from 'react';
import {newSecondhand,switchSecondhandTreatment,switchSecondhandCategory,secondhandBook,secondhandConditions,secondhandCategoryConditions,secondhandCurrent,secondhandReportRows,secondhandSource,secondhandTreatments,secondhandCategories,recordSecondhands,saveSecondhandBook,type SecondhandBook,type SecondhandRow} from '@/lib/iva-secondhand';
export function SimulationSecondhand({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:SecondhandBook;
try{book=secondhandBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:SecondhandBook)=>{try{onChange('modelo_a_snapshot',saveSecondhandBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<SecondhandRow>)=>save({...book,rows:book.rows.map(row=>row.id===id?{...row,...patch}:row)});
return<details className="space-y-3 rounded border p-3">
<summary>Bens emsegunda mão — revenda pela margem eleilão</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Uma linha porbem.P125identifica categoria/estatuto;P092ouP093determina a base aplicável.Sem compensação de perdas entrebens,nova dedução ou IVAcalculado.</p>
<p>Revendedor:contraprestação total comIVA−preço compra,parcela positiva÷1.16 ebase arredondada à unidade48(6)b.16%é parâmetro do divisor,não IVAcalculado neste percurso.Leilão:facturado−líquidocomitente−IVApróprio identificado;líquido=adjudicação−comissão.Não substituir IVA desconhecido porzero.</p>
<p>{secondhandSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newSecondhand(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar bem individual</button>
{book.rows.map(row=><details key={row.id} className="rounded border p-3"><summary>{row.description||'Bem por identificar'} — {row.period||'mês por indicar'}</summary>
<div className="grid gap-3 md:grid-cols-2">
<label>Percurso da margem<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchSecondhandTreatment(row,e.target.value))}><option value="">Por indicar</option>{secondhandTreatments.map(t=><option key={t.id} value={t.id}>{t.label}</option>)}</select></label>
<label>Categoria do bem<select className="block rounded border p-2" value={row.category} onChange={e=>change(row.id,switchSecondhandCategory(row,e.target.value))}><option value="">Por indicar</option>{secondhandCategories.map(c=><option key={c.id} value={c.id}>{c.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 SecondhandRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Bem/operação identificados'],['operationRef','Referência da operação'],['operationDate','Data da operação / prevista'],['period','Mês da operação'],['currency','Moeda dos montantes'],['documentRef','Documento / referência da previsão'],['documentDate','Data do documento / prevista'],['goodsRef','Identidade do bem individual'],['operatorRef','Operador e estatuto revendedor/organizador'],['categoryRef','Características e referência da classificação'],['sourceRef','Fornecedor/comitente,origem e referência'],['scope','Âmbito:bem,partes,operação eperíodo'],['evidence','Fundamento factual / pressupostos']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={['operationDate','documentDate'].includes(field)?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
<label>Qualidade do fornecedor/comitente<select className="block rounded border p-2" value={row.sourceType} onChange={e=>change(row.id,{sourceType:e.target.value})}><option value="">Por esclarecer</option><option value="private">Particular</option><option value="margin_reseller">Revendedor sujeito à margem</option><option value="exempt_9_12_e">Transmissão no âmbito9(12)e</option><option value="legacy_35_42">Referência histórica a35/42 — conferir situação2026</option><option value="other">Outro enquadramento por esclarecer</option></select></label>
{([['domesticPurchase','Aquisição dos bens no território nacional'],['domesticTaxable','Transmissão interna tributável,não exportação isenta13']] as const).map(([field,label])=><label key={field}>{label}<select className="block rounded border p-2" value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}><option value="">Por esclarecer</option><option value="yes">Sim</option><option value="no">Não</option></select></label>)}
{row.category==='art'&&<><label>Tipo de objecto de arte<select className="block rounded border p-2" value={row.artSubtype} onChange={e=>change(row.id,{artSubtype:e.target.value})}><option value="">Por indicar</option><option value="original">Quadro,pintura ou desenho original</option><option value="print">Gravura,estampa ou litografia</option><option value="sculpture">Escultura ou estatuária</option><option value="ceramic">Cerâmica</option></select></label>{row.artSubtype==='print'&&<label>Tiragem total<input className="block rounded border p-2" value={row.editionCount} onChange={e=>change(row.id,{editionCount:e.target.value})}/></label>}{row.artSubtype==='ceramic'&&<label>Cerâmica única,executada eassinada pelo artista<select className="block rounded border p-2" value={row.ceramicUniqueSigned} onChange={e=>change(row.id,{ceramicUniqueSigned:e.target.value})}><option value="">Por esclarecer</option><option value="yes">Sim</option><option value="no">Não</option></select></label>}</>}
{row.category==='collection'&&<><label>Tipo de colecção<select className="block rounded border p-2" value={row.collectionSubtype} onChange={e=>change(row.id,{collectionSubtype:e.target.value})}><option value="">Por indicar</option><option value="postal">Postal/filatélica</option><option value="scientific">Colecções/espécimes científicos3(6)c</option><option value="historical">Interesse histórico,arqueológico,paleontológico,etnográfico ou numismático</option></select></label>{row.collectionSubtype==='postal'&&<label>Fora decirculação esem destino aser posto emcirculação<select className="block rounded border p-2" value={row.postalNotCirculating} onChange={e=>change(row.id,{postalNotCirculating:e.target.value})}><option value="">Por esclarecer</option><option value="yes">Sim</option><option value="no">Não</option></select></label>}</>}
{row.category==='antique'&&<label>Idade emanos<input className="block rounded border p-2" value={row.ageYears} onChange={e=>change(row.id,{ageYears:e.target.value})}/></label>}
{row.treatment==='reseller_margin'&&<><label>Opção do revendedor<select className="block rounded border p-2" value={row.regimeChoice} onChange={e=>change(row.id,{regimeChoice:e.target.value})}><option value="">Por esclarecer</option><option value="margin">Regime da margem</option><option value="general">Regime geral — outra fórmula</option></select></label>{([['grossSale','Contraprestação total devida pelocliente,comIVA incluído'],['purchasePrice','Preço compra do mesmo bem'],['purchaseRef','Justificação/referência do preço compra']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}</>}
{row.treatment==='auction_margin'&&([['grossInvoice','Montante facturado ao comprador49(4)'],['hammerPrice','Preço de adjudicação'],['principalCommission','Comissão obtida/aobter do comitente'],['auctionRef','Contrato de comissão de venda emnome próprio eleilão'],['principalRef','Comitente e referência do líquido'],['ownVat','IVApróprio relativo àtransmissão,identificado'],['ownVatRef','Referência/composição do IVApróprio identificado']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
</div>
<p>Os montantes ocultos de outro percurso são conservados esó entram na fórmula escolhida.Situação antiga35/42não activa margem automaticamente em2026;sem novo certificado/aprovador.</p>
<fieldset><legend>Condições da classificação eregime</legend>{[...secondhandConditions,...secondhandCategoryConditions(row.category),['regimeConfirmed','Condições47/48(1)ou49(1),papéis/contrato equadro temporal conferidos'],['compositionConfirmed','Composição monetária corresponde ao percurso:revenda comIVA no total,ou leilão comfacturado,líquidocomitente eIVApróprio separados,sem dupla subtracção']] .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(recordSecondhands(draft,book));}catch(cause){setError(String(cause));}}}>Classificar bens,calcular bases eguardar versão</button>}
{book.result&&<><p role="status">{secondhandCurrent(draft,book)?'Classificações/bases correspondentes às entradas guardadas.':'Entradas alteradas;resultados históricos conservados.'} {book.history?.length??0} versões anteriores.Sem compensar margens entrebens,calcular IVA ou dedução/campo11.</p><dl>{secondhandReportRows(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>;
}
@@ -0,0 +1,42 @@
import {useState} from 'react';
import {newServiceLocation,switchServiceTreatment,serviceLocationBook,serviceLocationConditions,ownServiceConditions,serviceLocationCurrent,serviceLocationReportRows,serviceLocationSource,serviceLocationTreatments,recordServiceLocations,saveServiceLocationBook,type ServiceLocationBook,type ServiceLocationRow} from '@/lib/iva-service-location';
export function SimulationServiceLocation({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:ServiceLocationBook;
try{book=serviceLocationBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:ServiceLocationBook)=>{try{onChange('modelo_a_snapshot',saveServiceLocationBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<ServiceLocationRow>)=>save({...book,rows:book.rows.map(row=>row.id===id?{...row,...patch}:row)});
return<details className="space-y-3 rounded border p-3">
<summary>Localização — serviços, imóveis, trabalhos, actividades e transporte</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Regra geral:ponto de estabelecimento do prestador a partir do qual o serviço é prestado. Imóveis,execução total/essencial em bens móveis e actividades materiais têm percursos próprios,independentemente da sede do prestador.</p>
<p>Conferir primeiro a natureza e as regras especiais. Endereço/nacionalidade do cliente não substituem os factos relevantes. Digital e outros6(7)/(8)seguem os seus percursos. Classificação territorial não concede isenção nem calcula IVA.</p>
<p>{serviceLocationSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newServiceLocation(crypto.randomUUID())]})}>Acrescentar localização de serviç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>Percurso de localização do serviç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>{serviceLocationTreatments.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 ServiceLocationRow['origin']})}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Serviço identificado'],['operationRef','Referência da operação / pressuposto'],['operationDate','Data do serviço / prevista'],['period','Mês do serviço'],['documentRef','Documento da operação / referência da previsão'],['documentDate','Data do documento / prevista'],['scope','Âmbito: serviço, operação, período e condições'],['evidence','Fundamento factual / pressupostos']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={['operationDate','documentDate'].includes(field)?'date':field==='period'?'month':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{row.treatment==='transport_service'?<>
<p>Uma linha por trajecto;ida e volta separadas. Use a mesma unidade nas duas distâncias. Partida e chegada nacionais incluem percurso fora do país6(6).</p>
{([['routeRef','Trajecto e referência / pressuposto'],['totalDistance','Distância total'],['nationalDistance','Distância fisicamente nacional']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
{([['departure','País do ponto de partida'],['arrival','País do ponto de chegada']] as const).map(([field,label])=><label key={field}>{label}<select className="block rounded border p-2" value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}><option value="">Por indicar</option><option value="MZ">Moçambique</option><option value="foreign">Estrangeiro</option></select></label>)}
</>:row.treatment==='general_service'?<>
<label>Estabelecimento do prestador a partir do qual o serviço é prestado<input className="block rounded border p-2" value={row.providerPlace} onChange={e=>change(row.id,{providerPlace:e.target.value})}/></label>
<label>País desse estabelecimento<select className="block rounded border p-2" value={row.providerCountry} onChange={e=>change(row.id,{providerCountry:e.target.value})}><option value="">Por indicar</option><option value="MZ">Moçambique</option><option value="foreign">Estrangeiro</option></select></label>
<label>Referência do estabelecimento prestador / pressuposto<input className="block rounded border p-2" value={row.providerRef} onChange={e=>change(row.id,{providerRef:e.target.value})}/></label>
</>:row.treatment&&<>
<label>{row.treatment==='immovable_service'?'Local do imóvel':row.treatment==='movable_work'?'Local de execução total ou essencial':'Local material da actividade ou serviço acessório'}<input className="block rounded border p-2" value={row.servicePlace} onChange={e=>change(row.id,{servicePlace:e.target.value})}/></label>
<label>Situação do local relevante<select className="block rounded border p-2" value={row.placeCountry} onChange={e=>change(row.id,{placeCountry:e.target.value})}><option value="">Por indicar</option><option value="MZ">Moçambique</option><option value="foreign">Estrangeiro</option></select></label>
<label>Referência da localização / pressuposto<input className="block rounded border p-2" value={row.placeRef} onChange={e=>change(row.id,{placeRef:e.target.value})}/></label>
<label>Imóvel, bens ou actividade e relação do serviço<input className="block rounded border p-2" value={row.subjectRef} onChange={e=>change(row.id,{subjectRef:e.target.value})}/></label>
</>}
</div>
<p>Mudar percurso conserva os locais e referências,mas exige rever os factos próprios. Campos sem aplicação ficam ocultos e conservados.</p>
<fieldset><legend>Factos próprios deste percurso</legend>{[...serviceLocationConditions,...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(recordServiceLocations(draft,book));}catch(cause){setError(String(cause));}}}>Classificar localização e guardar versão</button>}
{book.result&&<><p role="status">{serviceLocationCurrent(draft,book)?'Localizações correspondentes às entradas guardadas.':'Entradas alteradas;localizações históricas conservadas. Reveja e classifique novamente.'} {book.history?.length??0} versões anteriores. Classificação não determina isenção,IVA ou campo11.</p><dl>{serviceLocationReportRows(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>;
}
@@ -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>;
}
@@ -0,0 +1,32 @@
import {useState} from 'react';
import {newValueReview,switchValueReview,switchPriceContext,switchValueOrigin,valueReviewBook,valueReviewConditions,valueReviewCurrent,valueReviewReportRows,valueReviewSource,valueReviewTreatments,priceContexts,recordValueReviews,saveValueReviewBook,type ValueReviewBook,type ValueReviewRow} from '@/lib/iva-value-review';
export function SimulationValueReview({draft,onChange}:{draft:Record<string,unknown>;onChange:(field:string,value:string)=>void}){
const[error,setError]=useState('');let book:ValueReviewBook;
try{book=valueReviewBook(draft);}catch(cause){return<p role="alert">{String(cause)}</p>;}
const save=(next:ValueReviewBook)=>{try{onChange('modelo_a_snapshot',saveValueReviewBook(draft,next));setError('');}catch(cause){setError(String(cause));}};
const change=(id:string,patch:Partial<ValueReviewRow>)=>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 — comparação de preços e correcção referenciada</summary>
<p>Oportunidade: {String(draft.context_opportunity||'entrada geral')}. Compare a contraprestação com o preço corrente ou normal correspondente à natureza da operação. Um preço inferior permite à AT proceder à correcção;esta comparação não exerce esse poder nem substitui automaticamente a contraprestação.</p>
<p>Para registar uma correcção,identifique o montante,referência,data e âmbito aplicáveis à operação e período. Na projecção,um cenário condicionado permanece identificado como pressuposto,não decisão AT concedida. Base e IVA são resultados distintos.</p>
<p>{valueReviewSource}</p>{error&&<p role="alert">{error}</p>}
<button type="button" className="underline" onClick={()=>save({...book,rows:[...book.rows,newValueReview(crypto.randomUUID(),String(draft.currency??''))]})}>Acrescentar comparação de contraprestaçã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>Percurso da comparação<select className="block rounded border p-2" value={row.treatment} onChange={e=>change(row.id,switchValueReview(row,e.target.value))}><option value="">Por indicar</option>{valueReviewTreatments.map(t=><option key={t.id} value={t.id}>{t.label}</option>)}</select></label>
<label>Contexto do preço de referência<select className="block rounded border p-2" value={row.priceContext} onChange={e=>change(row.id,switchPriceContext(row,e.target.value))}><option value="">Por indicar</option>{priceContexts.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,switchValueOrigin(row,e.target.value as ValueReviewRow['origin']))}><option value="projected">Projectados / pressupostos</option><option value="effective">Efectivos declarados</option></select></label>
{([['description','Operação identificada'],['operationRef','Referência da operação / pressuposto'],['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'],['declaredAmount','Contraprestação declarada sem IVA (moeda indicada)'],['referenceAmount','Preço corrente ou normal comparável sem IVA (moeda indicada)'],['referenceRef','Referência do preço corrente ou normal / pressuposto'],['referenceScope','Âmbito do preço: bens/serviços, estádio, período, local e condições'],['compositionRef','Referência da composição equivalente 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==='referenced_correction'&&<>
{([['correctedAmount','Montante da base corrigida / pressuposto condicionado'],['correctionRef','Referência da correcção AT / pressuposto condicionado'],['correctionScope','Âmbito da correcção: bens/serviços, operação, período e condições'],['correctionDate','Data da correcção / prevista']] as const).map(([field,label])=><label key={field}>{label}<input className="block rounded border p-2" type={field==='correctionDate'?'date':'text'} value={row[field]} onChange={e=>change(row.id,{[field]:e.target.value})}/></label>)}
<label>{row.origin==='projected'?'O cenário condicionado assume expressamente esta correcção e âmbito,sem afirmar decisão AT concedida?':'A correcção AT referenciada aplica-se a estes bens/serviços,operação,período e condições?'}<select className="block rounded border p-2" value={row.correctionApplies} onChange={e=>change(row.id,{correctionApplies:e.target.value as ValueReviewRow['correctionApplies']})}><option value="">Por indicar</option><option value="yes">Sim</option><option value="no">Não</option></select></label>
</>}
</div>
<p>Mudar percurso/contexto conserva montantes e documentos,mas exige rever as correspondências afectadas. Campos sem aplicação ficam ocultos e conservados;uma comparação não concede nem determina uma correcção.</p>
<fieldset><legend>Condições próprias da comparação</legend>{valueReviewConditions.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>
</details>)}
{!!book.rows.length&&<button type="button" className="rounded bg-emerald-800 p-2 text-white" onClick={()=>{try{save(recordValueReviews(draft,book));}catch(cause){setError(String(cause));}}}>Comparar e guardar versão</button>}
{book.result&&<><p role="status">{valueReviewCurrent(draft,book)?'Comparações correspondentes às entradas guardadas.':'Entradas alteradas;comparações 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>{valueReviewReportRows(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>;
}
+65
View File
@@ -0,0 +1,65 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const compositionBaseVersion='consideration-composition-base/1';
export const compositionBaseSource='CIVA republicado Lei13/2016,15(5)(a)/(b),PDF14/p1426(272):o valor tributável inclui impostos,direitos,taxas e outras imposições,excepto o próprioIVA;e despesas acessórias debitadas relativas a comissões,embalagem,transporte e seguros por conta do cliente. Respeitar regras especiais15(2) e exclusões15(6);não substitui a exclusãoTC emP095. Lei22/2022PDF3mantém15(5)por remissão;Lei10/2025não altera15. Recorte2026/MZN,composição da base apenas,sem incidência,taxas,IVA,dedução/campo11 ou totaisModeloA.';
export const compositionTreatments=[{id:'tax_component',label:'Impostos,direitos,taxas ou outras imposições,excepto próprio IVA'},{id:'accessory_component',label:'Despesas acessórias debitadas por conta do cliente'}] as const;
export const compositionConditions=[
['taxableOperation','A operação sujeita a IVA e a contraprestação correspondente estão identificadas'],
['initialNet','O montante inicial está identificado,sem próprio IVA e com as exclusões aplicáveis15(6)já consideradas; a referência explica a composição'],
['completeComposition','As parcelas aplicáveis15(5)estão reconciliadas com o montante inicial,sem omissões ou dupla contagem'],
['specialRules','Esta composição respeita a regra aplicável da operação,sem substituir bases especiais15(2),exclusões15(6)ou a exclusão da TC de combustíveis'],
] as const;
type Choice=''|'yes'|'no';type Condition=typeof compositionConditions[number][0];
export type CompositionPart={id:string;treatment:string;description:string;amount:string;included:Choice;reference:string;natureConfirmed:Choice;ownVatExcluded:Choice};
export type CompositionRow={id:string;description:string;period:string;origin:'projected'|'effective';currency:string;initialAmount:string;initialRef:string;operationRef:string;documentRef:string;documentDate:string;compositionRef:string;evidence:string;conditions:Partial<Record<Condition,Choice>>;parts:CompositionPart[]};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';baseAmount:string|null;vat:null;rate:null;reason:string};
export type CompositionCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:CompositionRow[];rows:LineResult[]};
export type CompositionBook={rows:CompositionRow[];result?:CompositionCalculation;history?:CompositionCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{considerationCompositions?:Record<string,CompositionBook>};
export function newCompositionPart(id:string):CompositionPart{return{id,treatment:'',description:'',amount:'',included:'',reference:'',natureConfirmed:'',ownVatExcluded:''};}
export function newCompositionBase(id:string,currency:string):CompositionRow{return{id,description:'',period:'',origin:'projected',currency,initialAmount:'',initialRef:'',operationRef:'',documentRef:'',documentDate:'',compositionRef:'',evidence:'',conditions:{},parts:[]};}
export function switchCompositionPart(part:CompositionPart,treatment:string):CompositionPart{return{...part,treatment,natureConfirmed:''};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.considerationCompositions!==undefined&&(!store.considerationCompositions||typeof store.considerationCompositions!=='object'||Array.isArray(store.considerationCompositions)))throw new Error('Composições não recuperáveis;originais preservados.');
const fields=Object.keys(newCompositionBase('','')).filter(key=>!['conditions','parts'].includes(key));const partFields=Object.keys(newCompositionPart(''));
for(const book of Object.values(store.considerationCompositions??{}))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 CompositionRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)||!Array.isArray(row.parts)||row.parts.some(part=>!part||partFields.some(key=>typeof part[key as keyof CompositionPart]!=='string'))))throw new Error('Linhas de composição não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function compositionBook(draft:Record<string,unknown>):CompositionBook{return readStore(draft).considerationCompositions?.[acquisitionScope(draft)]??{rows:[]};}
export function saveCompositionBook(draft:Record<string,unknown>,book:CompositionBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,considerationCompositions:{...current.considerationCompositions,[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 evaluateComposition(row:CompositionRow,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(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.');
const failed=compositionConditions.filter(([key])=>row.conditions[key]==='no');if(failed.length)return stop('Não se aplica esta composição: '+failed.map(([,label])=>label).join('; ')+'. Não é isenção nem IVA zero.','not_applicable');
const missing=compositionConditions.filter(([key])=>row.conditions[key]!=='yes');if(missing.length)return stop('Condições por indicar: '+missing.map(([,label])=>label).join('; ')+'. Desconhecido não é zero.');
if(!row.description.trim()||!row.initialRef.trim()||!row.operationRef.trim()||!row.documentRef.trim()||!row.compositionRef.trim()||!row.evidence.trim()||!validDate(row.documentDate))return stop('Identifique operação,montante inicial,documento/data,composição e fundamento ou pressupostos expressos;reutilize referências existentes,sem certificado/aprovador novo.');
const initial=decimal(row.initialAmount);if(initial===null)return stop('Indique o montante inicial sem próprio IVA e com exclusões aplicáveis consideradas;desconhecido não é zero.');
if(!row.parts.length||new Set(row.parts.map(p=>p.id)).size!==row.parts.length||row.parts.some(p=>!p.id.trim()))return stop('Identifique as parcelas desta operação com identificadores distintos;sem soma de linhas vazias ou duplicadas.');
let additions=0n;const formulas:string[]=[];
for(const part of row.parts){
const rule=compositionTreatments.find(t=>t.id===part.treatment);if(!rule)return stop('Identifique a natureza de cada parcela:imposição excepto próprioIVA ou despesa acessória debitada por conta do cliente.');
if(part.natureConfirmed==='no'||part.ownVatExcluded==='no')return stop('A parcela '+part.id+' não corresponde ao tratamento ou inclui próprioIVA;reveja a composição,não se transforma em exclusão/isenção automática.','not_applicable');
if(part.natureConfirmed!=='yes'||part.ownVatExcluded!=='yes'||!['yes','no'].includes(part.included))return stop('Confirme a natureza,exclusão do próprioIVA e se a parcela '+part.id+' já está no montante inicial;desconhecido não permite presumir soma ou ausência.');
if(!part.description.trim()||!part.reference.trim())return stop('Identifique descrição e referência da parcela '+part.id+',ou pressuposto expresso;sem novo documento obrigatório.');
const amount=decimal(part.amount);if(amount===null)return stop('Indique o montante exacto da parcela '+part.id+';desconhecido não é zero.');
if(part.included==='no')additions+=amount;
formulas.push(`${part.id}:${rule.label},${money(amount)}MZN,${part.included==='yes'?'já incluída,sem segunda soma':'acrescida uma vez'}`);
}
const base=initial+additions;return{...result,status:'determined',baseAmount:money(base),reason:`Base15(5):montante inicial ${money(initial)} + parcelas ainda não incluídas ${money(additions)} = ${money(base)}MZN;${formulas.join('; ')},${row.origin==='projected'?'nas condições expressamente assumidas na projecção':'nos dados efectivos declarados'}. Base única por operação,não uma base por parcela. Base não é imposto;IVA/taxa,dedução/campo11 e totaisModeloA não são determinados por esta composição.`};
}
function key(draft:Record<string,unknown>,book:CompositionBook):string{return JSON.stringify({version:compositionBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function compositionCurrent(draft:Record<string,unknown>,book:CompositionBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordCompositions(draft:Record<string,unknown>,book:CompositionBook):CompositionBook{
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:CompositionCalculation={version:compositionBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:compositionBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateComposition(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveCompositionBook(draft,next);return next;
}
export function compositionReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=compositionBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Base P101 — ${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};${compositionCurrent(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'};operação ${row.operationRef};montante inicial ${row.initialAmount} ${row.currency},referência ${row.initialRef};parcelas ${row.parts.map(p=>`${p.id}/${p.treatment},${p.description},${p.amount} ${row.currency},já incluída:${p.included==='yes'?'Sim':p.included==='no'?'Não':'Por indicar'},natureza:${p.natureConfirmed},sem próprioIVA:${p.ownVatExcluded},referência ${p.reference}`).join('; ')};composição ${row.compositionRef};documento ${row.documentRef},${row.documentDate};condições ${compositionConditions.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','Composição da contraprestação','Dados não recuperáveis','Originais preservados;sem substituir por zero.']];}
}
+77
View File
@@ -0,0 +1,77 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const exclusionBaseVersion='consideration-exclusions-base/1';
export const exclusionBaseSource='CIVA republicado Lei13/2016,15(6)(a–d),PDF14/p1426(272):exclui indemnizações declaradas judicialmente por incumprimento total/parcial de contratos;descontos,abatimentos ou bónus concedidos;quantias pagas em nome e por conta do adquirente/destinatário registadas em adequadas contas de terceiros;embalagens não efectivamente transaccionadas com elementos27(5)(b)na factura/documento equivalente.27(5)(b),PDF17/p1426(275):indicação separada e menção expressa da devolução acordada. Lei22/2022PDF3mantém15(6);Lei10/2025PDF14mantém27(5)(b),altera27(10),não15. Recorte2026/MZN,base apenas,sem IVA/dedução/campo11/regularizações ou totaisModeloA.';
export const exclusionTreatments=[{id:'judicial_indemnity',label:'Indemnização declarada judicialmente por incumprimento contratual'},{id:'granted_discount',label:'Desconto,abatimento ou bónus concedido'},{id:'third_party_payment',label:'Quantia paga em nome e por conta do adquirente/destinatário'},{id:'returnable_packaging',label:'Embalagem não efectivamente transaccionada,com devolução acordada'}] as const;
export const exclusionConditions=[
['operationIdentified','A operação e os montantes relacionados estão identificados'],
['initialNet','O montante inicial exclui o próprio IVA e tem a composição aplicável15(5)identificada,antes das exclusões ainda não consideradas'],
['completeComposition','As exclusões aplicáveis estão reconciliadas com o montante inicial,sem omissões ou dupla subtracção'],
['specialRules','Esta composição respeita a regra aplicável da operação,sem substituir bases especiais ou regularizações de outros períodos'],
] as const;
export const exclusionPartConditions={
judicial_indemnity:[['judicialDeclaration','A indemnização recebida foi declarada judicialmente'],['contractBreach','Corresponde ao incumprimento total ou parcial de contrato']],
granted_discount:[['granted','O desconto,abatimento ou bónus está concedido e corresponde a esta operação']],
third_party_payment:[['paidInName','A quantia foi paga em nome do adquirente/destinatário identificado'],['paidForAccount','A quantia foi paga por conta desse adquirente/destinatário'],['thirdPartyAccounts','Está registada pelo contribuinte em adequadas contas de terceiros']],
returnable_packaging:[['notTransacted','As embalagens não foram efectivamente transaccionadas'],['separateIndication','Constam separadamente na factura ou documento equivalente'],['returnMention','Consta menção expressa de que foi acordada a devolução das embalagens']],
} as const;
export function partConditions(treatment:string):ReadonlyArray<readonly[string,string]>{return exclusionPartConditions[treatment as keyof typeof exclusionPartConditions]??[];}
type Choice=''|'yes'|'no';type Condition=typeof exclusionConditions[number][0];
export type ExclusionPart={id:string;treatment:string;description:string;amount:string;included:Choice;reference:string;scope:string;accountRef:string;beneficiaryRef:string;documentExcerpt:string;conditions:Partial<Record<string,Choice>>};
export type ExclusionRow={id:string;description:string;period:string;origin:'projected'|'effective';currency:string;initialAmount:string;initialRef:string;operationRef:string;documentRef:string;documentDate:string;exclusionRef:string;evidence:string;conditions:Partial<Record<Condition,Choice>>;parts:ExclusionPart[]};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';baseAmount:string|null;vat:null;rate:null;reason:string};
export type ExclusionCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:ExclusionRow[];rows:LineResult[]};
export type ExclusionBook={rows:ExclusionRow[];result?:ExclusionCalculation;history?:ExclusionCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{considerationExclusions?:Record<string,ExclusionBook>};
export function newExclusionPart(id:string):ExclusionPart{return{id,treatment:'',description:'',amount:'',included:'',reference:'',scope:'',accountRef:'',beneficiaryRef:'',documentExcerpt:'',conditions:{}};}
export function newExclusionBase(id:string,currency:string):ExclusionRow{return{id,description:'',period:'',origin:'projected',currency,initialAmount:'',initialRef:'',operationRef:'',documentRef:'',documentDate:'',exclusionRef:'',evidence:'',conditions:{},parts:[]};}
export function switchExclusionPart(part:ExclusionPart,treatment:string):ExclusionPart{return{...part,treatment,conditions:{}};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.considerationExclusions!==undefined&&(!store.considerationExclusions||typeof store.considerationExclusions!=='object'||Array.isArray(store.considerationExclusions)))throw new Error('Exclusões não recuperáveis;originais preservados.');
const fields=Object.keys(newExclusionBase('','')).filter(key=>!['conditions','parts'].includes(key));const partFields=Object.keys(newExclusionPart('')).filter(key=>key!=='conditions');
for(const book of Object.values(store.considerationExclusions??{}))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 ExclusionRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)||!Array.isArray(row.parts)||row.parts.some(part=>!part||partFields.some(key=>typeof part[key as keyof ExclusionPart]!=='string')||!part.conditions||typeof part.conditions!=='object'||Array.isArray(part.conditions))))throw new Error('Linhas de exclusão não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function exclusionBook(draft:Record<string,unknown>):ExclusionBook{return readStore(draft).considerationExclusions?.[acquisitionScope(draft)]??{rows:[]};}
export function saveExclusionBook(draft:Record<string,unknown>,book:ExclusionBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,considerationExclusions:{...current.considerationExclusions,[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 evaluateExclusion(row:ExclusionRow,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(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.');
const failed=exclusionConditions.filter(([key])=>row.conditions[key]==='no');if(failed.length)return stop('Não se aplica esta composição: '+failed.map(([,label])=>label).join('; ')+'. Não é isenção nem IVA zero.','not_applicable');
const missing=exclusionConditions.filter(([key])=>row.conditions[key]!=='yes');if(missing.length)return stop('Condições por indicar: '+missing.map(([,label])=>label).join('; ')+'. Desconhecido não é zero.');
if(!row.description.trim()||!row.initialRef.trim()||!row.operationRef.trim()||!row.documentRef.trim()||!row.exclusionRef.trim()||!row.evidence.trim()||!validDate(row.documentDate))return stop('Identifique operação,montante inicial,documento/data,composição e fundamento ou pressupostos expressos;reutilize referências existentes,sem certificado/aprovador novo.');
const initial=decimal(row.initialAmount);if(initial===null)return stop('Indique o montante inicial sem próprio IVA,com as inclusões aplicáveis consideradas e antes das exclusões ainda não realizadas;desconhecido não é zero.');
if(!row.parts.length||new Set(row.parts.map(p=>p.id)).size!==row.parts.length||row.parts.some(p=>!p.id.trim()))return stop('Identifique as parcelas desta operação com identificadores distintos;sem subtracção de linhas vazias ou duplicadas.');
let exclusions=0n;const formulas:string[]=[];
for(const part of row.parts){
const rule=exclusionTreatments.find(t=>t.id===part.treatment);if(!rule)return stop('Identifique o tratamento de cada parcela;uma descrição genérica não demonstra exclusão.');
const own=partConditions(part.treatment),failed=own.filter(([key])=>part.conditions[key]==='no');
if(failed.length)return stop('Não se aplica a exclusão da parcela '+part.id+': '+failed.map(([,label])=>label).join('; ')+'. Sem subtracção automática ou IVA zero.','not_applicable');
if(own.some(([key])=>part.conditions[key]!=='yes')||!['yes','no'].includes(part.included))return stop('Confirme as condições próprias da parcela '+part.id+' e se ainda está incluída no montante inicial;desconhecido não permite presumir exclusão ou zero.');
if(!part.description.trim()||!part.reference.trim()||!part.scope.trim())return stop('Identifique descrição,referência e âmbito da parcela '+part.id+',ou pressuposto expresso. Na indemnização,a referência identifica a declaração judicial e o contrato;no desconto,a concessão.');
if(part.treatment==='third_party_payment'&&(!part.accountRef.trim()||!part.beneficiaryRef.trim()))return stop('Identifique as adequadas contas de terceiros e o adquirente/destinatário em nome e por conta de quem se pagou,ou pressupostos expressos;despesa própria não equivale a pagamento por conta alheia.');
if(part.treatment==='returnable_packaging'&&!part.documentExcerpt.trim())return stop('Identifique na referência da factura/documento a indicação separada e a menção expressa da devolução acordada,ou pressuposto expresso;sem exigir devolução já realizada.');
const amount=decimal(part.amount);if(amount===null)return stop('Indique o montante exacto da parcela '+part.id+';desconhecido não é zero.');
if(part.included==='yes')exclusions+=amount;
formulas.push(`${part.id}:${rule.label},${money(amount)}MZN,${part.included==='yes'?'excluída uma vez':'já excluída,sem segunda subtracção'}`);
}
if(exclusions>initial)return stop('As exclusões ainda incluídas excedem o montante inicial;reveja a composição,sem base negativa ou piso zero presumido.');
const base=initial-exclusions;return{...result,status:'determined',baseAmount:money(base),reason:`Base15(6):montante inicial ${money(initial)} − exclusões ainda incluídas ${money(exclusions)} = ${money(base)}MZN;${formulas.join('; ')},${row.origin==='projected'?'nas condições expressamente assumidas na projecção':'nos dados efectivos declarados'}. Base única por operação. Base não é imposto;IVA/taxa,dedução/campo11,regularizações e totaisModeloA não são determinados por esta composição.`};
}
function key(draft:Record<string,unknown>,book:ExclusionBook):string{return JSON.stringify({version:exclusionBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function exclusionCurrent(draft:Record<string,unknown>,book:ExclusionBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordExclusions(draft:Record<string,unknown>,book:ExclusionBook):ExclusionBook{
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:ExclusionCalculation={version:exclusionBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:exclusionBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateExclusion(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveExclusionBook(draft,next);return next;
}
export function exclusionReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=exclusionBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Base P102 — ${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};${exclusionCurrent(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'};operação ${row.operationRef};montante inicial ${row.initialAmount} ${row.currency},referência ${row.initialRef};parcelas ${row.parts.map(p=>`${p.id}/${p.treatment},${p.description},${p.amount} ${row.currency},já incluída:${p.included==='yes'?'Sim':p.included==='no'?'Não':'Por indicar'},referência ${p.reference},âmbito ${p.scope}${p.treatment==='third_party_payment'?`,contas ${p.accountRef},adquirente/destinatário ${p.beneficiaryRef}`:''}${p.treatment==='returnable_packaging'?`,menção documental ${p.documentExcerpt}`:''},condições ${partConditions(p.treatment).map(([key,label])=>label+': '+(p.conditions[key]==='yes'?'Sim':p.conditions[key]==='no'?'Não':'Por indicar')).join('; ')}`).join('; ')};composição ${row.exclusionRef};documento ${row.documentRef},${row.documentDate};condições ${exclusionConditions.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','Composição da contraprestação','Dados não recuperáveis','Originais preservados;sem substituir por zero.']];}
}
+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.']];}
}
+65
View File
@@ -0,0 +1,65 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const goodsAllocationVersion='goods-allocation-base/1';
export const goodsAllocationSource='CIVA3(3)e/f,Lei13/2016PDF6–7/p1426(264–265):afectação permanente de bens a uso próprio/particular/alheio,transmissão gratuita,afectação a sector isento ou ao activo imobilizado de bens20(1)a,com dedução total/parcial anterior nos bens/elementos;excepção de amostras/ofertas de pequeno valor na alíneae. Art15(2)b,PDF13/p1426(271):preço de aquisição ou,na sua falta,preço de custo,reportados ao momento da operação. Art20(1)a,PDF15/p1426(273). Lei22/2022PDF3mantém15(2)b e20(1)a;Lei10/2025mantém3(3)e/f e não altera15/20. Recorte2026/MZN,sem nova dedução/campo11,regularização,taxa,IVA ou totaisModeloA. Uso temporário de bens como serviçoP089 é distinto.';
export const goodsAllocationTreatments=[{id:'permanent_private_goods',label:'Afectação permanente a uso próprio,particular ou fins alheios',clause:'e'},{id:'free_goods_transfer',label:'Transmissão gratuita de bens',clause:'e'},{id:'exempt_sector_goods',label:'Afectação de bens a sector de actividade isento',clause:'f'},{id:'fixed_asset_20a',label:'Afectação ao activo imobilizado de bens20(1)a',clause:'f'}] as const;
export const goodsAllocationConditions=[['businessGoods','São bens da empresa identificados,não uma prestação de serviços ou venda onerosa normal'],['priorDeduction','Houve dedução total ou parcial anterior nos bens ou elementos que os constituem,com referência histórica'],['factsCorrespond','Objecto,destino,operação,data eâmbito correspondem ao percurso identificado']] as const;
export const allocationOwnConditions={
permanent_private_goods:[['permanentAllocation','A afectação dos bens é permanente,não mero uso temporário'],['privatePurpose','Uso próprio do titular,pessoal ou fins alheios à empresa identificado'],['notSmallGift','Não se trata de amostra ou oferta de pequeno valor abrangida pela excepção3(3)e']],
free_goods_transfer:[['gratuitousTransfer','Está identificada uma transmissão gratuita dos bens'],['notSmallGift','Não se trata de amostra ou oferta de pequeno valor abrangida pela excepção3(3)e']],
exempt_sector_goods:[['exemptSector','Os bens são afectados ao sector de actividade isento identificado']],
fixed_asset_20a:[['fixedAsset','Está identificada a afectação ao activo imobilizado'],['goods20a','Os bens correspondem aos referidos em20(1)a,com âmbito e referência identificados']],
} as const;
export function allocationSpecificConditions(treatment:string):ReadonlyArray<readonly[string,string]>{return allocationOwnConditions[treatment as keyof typeof allocationOwnConditions]??[];}
type Choice=''|'yes'|'no';type Condition=typeof goodsAllocationConditions[number][0];
export type GoodsAllocationRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';currency:string;operationDate:string;operationRef:string;documentRef:string;documentDate:string;goodsRef:string;deductionRef:string;destinationRef:string;exceptionRef:string;asset20aRef:string;valuationMode:string;acquisitionPrice:string;acquisitionRef:string;currentCost:string;costRef:string;valuationDate:string;valuationScope:string;evidence:string;conditions:Partial<Record<string,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';classification:'assimilated_goods'|'not_applicable'|'indeterminate';baseAmount:string|null;vat:null;rate:null;reason:string};
export type GoodsAllocationCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:GoodsAllocationRow[];rows:LineResult[]};
export type GoodsAllocationBook={rows:GoodsAllocationRow[];result?:GoodsAllocationCalculation;history?:GoodsAllocationCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{regulatedGoodsAllocations?:Record<string,GoodsAllocationBook>};
export function newGoodsAllocation(id:string,currency:string):GoodsAllocationRow{return{id,treatment:'',description:'',period:'',origin:'projected',currency,operationDate:'',operationRef:'',documentRef:'',documentDate:'',goodsRef:'',deductionRef:'',destinationRef:'',exceptionRef:'',asset20aRef:'',valuationMode:'',acquisitionPrice:'',acquisitionRef:'',currentCost:'',costRef:'',valuationDate:'',valuationScope:'',evidence:'',conditions:{}};}
export function switchAllocationTreatment(row:GoodsAllocationRow,treatment:string):GoodsAllocationRow{return{...row,treatment,conditions:Object.fromEntries(goodsAllocationConditions.map(([key])=>[key,row.conditions[key]??'']))};}
export function switchAllocationValuation(row:GoodsAllocationRow,valuationMode:string):GoodsAllocationRow{return{...row,valuationMode,conditions:{...row.conditions,valuationConfirmed:'',acquisitionUnavailable:''}};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.regulatedGoodsAllocations!==undefined&&(!store.regulatedGoodsAllocations||typeof store.regulatedGoodsAllocations!=='object'||Array.isArray(store.regulatedGoodsAllocations)))throw new Error('Afectações de bens não recuperáveis;originais preservados.');
const fields=Object.keys(newGoodsAllocation('','')).filter(key=>key!=='conditions');
for(const book of Object.values(store.regulatedGoodsAllocations??{}))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 GoodsAllocationRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)))throw new Error('Linhas de afectações de bens não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function goodsAllocationBook(draft:Record<string,unknown>):GoodsAllocationBook{return readStore(draft).regulatedGoodsAllocations?.[acquisitionScope(draft)]??{rows:[]};}
export function saveGoodsAllocationBook(draft:Record<string,unknown>,book:GoodsAllocationBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,regulatedGoodsAllocations:{...current.regulatedGoodsAllocations,[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 evaluateGoodsAllocation(row:GoodsAllocationRow,currency:unknown):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',classification:'indeterminate',baseAmount:null,vat:null,rate:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,classification:status==='not_applicable'?'not_applicable' as const:result.classification,reason});
const rule=goodsAllocationTreatments.find(t=>t.id===row.treatment);if(!rule)return stop('Identifique afectação permanente,transmissão gratuita,sector isento ou activo imobilizado20(1)a.');
if(!/^2026-(0[1-9]|1[0-2])$/.test(row.period)||!['projected','effective'].includes(row.origin)||!validDate(row.operationDate)||row.operationDate.slice(0,7)!==row.period)return stop('Identifique mês2026,data correspondente e dados efectivos ou pressupostos expressos.');
const conditions=[...goodsAllocationConditions,...allocationSpecificConditions(row.treatment)];if(conditions.some(([key])=>row.conditions[key]==='no'))return stop('Este percurso de transmissão assimilada não se aplica aos factos declarados;conferir natureza,dedução histórica ou excepção,não presumir isenção/IVAzero.','not_applicable');
if(conditions.some(([key])=>row.conditions[key]!=='yes'))return stop('Factos próprios ou dedução anterior por esclarecer;desconhecido não é não aplicável ou zero. Dedução histórica não é nova dedução concedida.');
if(!row.description.trim()||!row.operationRef.trim()||!row.documentRef.trim()||!validDate(row.documentDate)||!row.goodsRef.trim()||!row.deductionRef.trim()||!row.destinationRef.trim()||!row.evidence.trim())return stop('Identifique bens,operação,documento/data,dedução histórica,destino eâmbito factual ou pressupostos expressos;reutilize referências,sem certificado/aprovador novo.');
if(rule.clause==='e'&&!row.exceptionRef.trim())return stop('Identifique os factos/referência que distinguem a operação da excepção de amostras/ofertas de pequeno valor,ou pressuposto expresso;sem limiar inventado.');
if(row.treatment==='fixed_asset_20a'&&!row.asset20aRef.trim())return stop('Identifique enquadramento dos bens20(1)a eafectação ao activo imobilizado,com referência/âmbito.');
result.classification='assimilated_goods';
if(currency!=='MZN'||row.currency!==currency)return stop('Operação3(3)'+rule.clause+' identificada;moeda fora do recorteMZN ou divergente,base indeterminada,sem conversão silenciosa.');
if(!['acquisition','cost'].includes(row.valuationMode))return stop('Operação3(3)'+rule.clause+' identificada;base15(2)b por esclarecer:preço aquisição ou,na sua falta demonstrada,preço custo,reportados ao momento da operação.');
if(row.conditions.valuationConfirmed!=='yes'||!validDate(row.valuationDate)||row.valuationDate!==row.operationDate||!row.valuationScope.trim())return stop('Operação assimilada identificada;base por esclarecer. Confirme preço de aquisição/custo reportado ao momento desta operação,data/âmbito ecomposição sem próprioIVA;não usar custo histórico automaticamente.');
if(row.valuationMode==='cost'&&row.conditions.acquisitionUnavailable!=='yes')return stop('Operação assimilada identificada;não substituir aquisição desconhecida por custo. O custo15(2)b só é usado na falta demonstrada de preço aquisição;conferir esse facto.');
const raw=row.valuationMode==='acquisition'?row.acquisitionPrice:row.currentCost,ref=row.valuationMode==='acquisition'?row.acquisitionRef:row.costRef;const amount=decimal(raw);
if(amount===null||!ref.trim())return stop('Operação assimilada identificada;indique o preço e referência correspondentes ao modo escolhido,reportados ao momento da operação;desconhecido não é zero.');
return{...result,status:'determined',baseAmount:money(amount),reason:`P124:transmissão assimilada3(3)${rule.clause};P088:base15(2)b=${money(amount)}MZN,${row.valuationMode==='acquisition'?'preço aquisição':'preço custo,na falta demonstrada de preço aquisição'},reportado a${row.operationDate},${row.origin==='projected'?'sob pressupostos expressos':'segundo dados efectivos declarados'}. Dedução anterior total/parcial é facto histórico dos bens/elementos,não nova dedução/campo11. Não confundir afectação/transmissão de bens comserviço por uso temporárioP089. Sem calcular IVA,taxa,regularização ou totaisModeloA.`};
}
function key(draft:Record<string,unknown>,book:GoodsAllocationBook):string{return JSON.stringify({version:goodsAllocationVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function goodsAllocationCurrent(draft:Record<string,unknown>,book:GoodsAllocationBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordGoodsAllocations(draft:Record<string,unknown>,book:GoodsAllocationBook):GoodsAllocationBook{
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:GoodsAllocationCalculation={version:goodsAllocationVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:goodsAllocationSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateGoodsAllocation(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveGoodsAllocationBook(draft,next);return next;
}
export function goodsAllocationReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=goodsAllocationBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>{const line=result.rows[index],rule=goodsAllocationTreatments.find(t=>t.id===row.treatment);return['IVA mensal',`Afectação P124/baseP088 — ${row.period} — ${row.id}`,`${row.description};classificação:${line.classification==='assimilated_goods'?'Transmissão assimilada de bens':line.classification==='not_applicable'?'Percurso não aplicável':'Indeterminada'};base:${line.baseAmount??'Indeterminada'} ${row.currency};IVA: Indeterminado;${line.reason}`,`${result.opportunity};${result.location};${goodsAllocationCurrent(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'};${rule?.label??'Percurso por indicar'};operação ${row.operationRef},${row.operationDate};bens ${row.goodsRef};dedução histórica ${row.deductionRef};destino ${row.destinationRef};${rule?.clause==='e'?`excepção amostras/ofertas ${row.exceptionRef};`:''}${row.treatment==='fixed_asset_20a'?`enquadramento20(1)a ${row.asset20aRef};`:''}base ${row.valuationMode};${row.valuationMode==='cost'?`custo ${row.currentCost},${row.costRef};falta aquisição ${row.conditions.acquisitionUnavailable??'por indicar'}`:`aquisição ${row.acquisitionPrice},${row.acquisitionRef}`};data/âmbito base ${row.valuationDate},${row.valuationScope};documento ${row.documentRef},${row.documentDate};condições ${[...goodsAllocationConditions,...allocationSpecificConditions(row.treatment)].map(([key,label])=>label+': '+(row.conditions[key]==='yes'?'Sim':row.conditions[key]==='no'?'Não':'Por indicar')).join('; ')};fundamento ${row.evidence};sem nova dedução/campo11/IVA/regularização/totaisModeloA.`];});}
catch{return[['IVA mensal','Afectação de bens','Dados não recuperáveis','Originais preservados;sem base ou classificação por defeito.']];}
}
+61
View File
@@ -0,0 +1,61 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const goodsLocationVersion='goods-territoriality/1';
export const goodsLocationSource='CIVA republicado Lei13/2016,6(1)/(2),PDF7/p1426(265):localização dos bens no território nacional ao iniciar transporte/expedição para o adquirente ou,sem transporte/expedição,ao pôr à sua disposição. Não obstante6(1),são também tributáveis transmissões pelo importador e subsequentes de bens transportados/expedidos do estrangeiro,antes da importação. Lei10/2025PDF12mantém6(1)/(2),altera6(7–9)quanto a digitais;recorte2026,bens corpóreos,não digitais. Endereço/nacionalidade do cliente não substituem localização dos bens. Classificação territorial apenas,não isenção/taxa/IVA/dedução/campo11/direitos aduaneiros ou totaisModeloA.';
export const goodsLocationTreatments=[{id:'goods_with_transport',label:'Bens com transporte ou expedição para o adquirente'},{id:'goods_without_transport',label:'Bens sem transporte ou expedição'},{id:'goods_before_import',label:'Transmissão pelo importador ou subsequente,antes da importação'}] as const;
export const goodsLocationConditions=[
['goodsSupply','Está identificada uma transmissão de bens corpóreos,não uma prestação de serviços ou bens digitais abrangidos por regras próprias'],
['factsCorrespond','Os factos,referências e âmbito correspondem a esta operação e período,não apenas ao endereço ou nacionalidade do adquirente'],
] as const;
export const goodsOwnConditions={
goods_with_transport:[['transportToBuyer','Os bens são transportados ou expedidos para o adquirente'],['notBeforeImport','Não corresponde à transmissão pré-importação abrangida pelo artigo6(2)']],
goods_without_transport:[['noTransport','Não há expedição ou transporte dos bens para esta transmissão'],['notBeforeImport','Não corresponde à transmissão pré-importação abrangida pelo artigo6(2)']],
goods_before_import:[['fromAbroad','Os bens são transportados ou expedidos do estrangeiro'],['nationalImport','Está identificada a importação desses bens para o território nacional'],['importerChain','A transmissão é feita pelo importador ou é subsequente na cadeia desses bens'],['beforeImport','Esta transmissão ocorre antes da importação identificada']],
} as const;
export function ownGoodsConditions(treatment:string):ReadonlyArray<readonly[string,string]>{return goodsOwnConditions[treatment as keyof typeof goodsOwnConditions]??[];}
type Choice=''|'yes'|'no';type Condition=typeof goodsLocationConditions[number][0];
export type GoodsLocationRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';operationDate:string;operationRef:string;documentRef:string;documentDate:string;goodsPlace:string;placeCountry:string;placeRef:string;transportRef:string;importRef:string;chainRef:string;scope:string;evidence:string;conditions:Partial<Record<string,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';territory:'national'|'outside'|null;baseAmount:null;vat:null;rate:null;reason:string};
export type GoodsLocationCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:GoodsLocationRow[];rows:LineResult[]};
export type GoodsLocationBook={rows:GoodsLocationRow[];result?:GoodsLocationCalculation;history?:GoodsLocationCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{goodsLocations?:Record<string,GoodsLocationBook>};
export function newGoodsLocation(id:string):GoodsLocationRow{return{id,treatment:'',description:'',period:'',origin:'projected',operationDate:'',operationRef:'',documentRef:'',documentDate:'',goodsPlace:'',placeCountry:'',placeRef:'',transportRef:'',importRef:'',chainRef:'',scope:'',evidence:'',conditions:{}};}
export function switchGoodsTreatment(row:GoodsLocationRow,treatment:string):GoodsLocationRow{return{...row,treatment,conditions:Object.fromEntries(goodsLocationConditions.map(([key])=>[key,row.conditions[key]??'']))};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.goodsLocations!==undefined&&(!store.goodsLocations||typeof store.goodsLocations!=='object'||Array.isArray(store.goodsLocations)))throw new Error('Bases de contraprestação não recuperáveis;originais preservados.');
const fields=Object.keys(newGoodsLocation('')).filter(key=>key!=='conditions');
for(const book of Object.values(store.goodsLocations??{}))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 GoodsLocationRow]!=='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 goodsLocationBook(draft:Record<string,unknown>):GoodsLocationBook{return readStore(draft).goodsLocations?.[acquisitionScope(draft)]??{rows:[]};}
export function saveGoodsLocationBook(draft:Record<string,unknown>,book:GoodsLocationBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,goodsLocations:{...current.goodsLocations,[acquisitionScope(draft)]:book}});readStore({...draft,modelo_a_snapshot:encoded});return encoded;}
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 evaluateGoodsLocation(row:GoodsLocationRow):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',territory:null,baseAmount:null,vat:null,rate:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,reason});
const rule=goodsLocationTreatments.find(t=>t.id===row.treatment);if(!rule)return stop('Identifique transporte,ausência de transporte ou transmissão antes da importação;desconhecido não determina território.');
if(!/^2026-(0[1-9]|1[0-2])$/.test(row.period)||!['projected','effective'].includes(row.origin)||!validDate(row.operationDate)||row.operationDate.slice(0,7)!==row.period)return stop('Identifique mês em2026 e data da operação correspondentes,com dados efectivos declarados ou pressupostos expressos de projecção.');
const required=[...goodsLocationConditions,...ownGoodsConditions(row.treatment)];const failed=required.filter(([key])=>row.conditions[key]==='no');if(failed.length)return stop('Este percurso não se aplica: '+failed.map(([,label])=>label).join('; ')+'. Rever o percurso,não classificar automaticamente como fora do território ou isento.','not_applicable');
if(required.some(([key])=>row.conditions[key]!=='yes'))return stop('Confirme os factos próprios deste percurso;desconhecido não é fora do território,isenção ou IVA zero.');
if(!row.description.trim()||!row.operationRef.trim()||!row.documentRef.trim()||!validDate(row.documentDate)||!row.scope.trim()||!row.evidence.trim())return stop('Identifique bens/operação,documento/data,âmbito e factos ou pressupostos expressos;reutilize referências existentes,sem certificado/aprovador novo.');
if(row.treatment==='goods_before_import'){
if(!row.transportRef.trim()||!row.importRef.trim()||!row.chainRef.trim())return stop('Identifique transporte/expedição do estrangeiro,importação nacional e posição da transmissão na cadeia,ou pressupostos expressos;não inferir a condição pelo endereço do adquirente.');
return{...result,status:'determined',territory:'national',reason:`Art6(2):transmissão pelo importador ou subsequente de bens transportados/expedidos do estrangeiro,antes da importação nacional identificada;abrangida territorialmente emMoçambique,${row.origin==='projected'?'nas condições expressamente assumidas na projecção':'nos dados efectivos declarados'}. A localização física anterior no estrangeiro não afasta por si esta regra. Classificação não determina isenção,base,taxa,IVA,dedução/campo11,direitos ou totaisModeloA.`};
}
if(!row.goodsPlace.trim()||!row.placeRef.trim()||!['MZ','foreign'].includes(row.placeCountry))return stop('Identifique onde os bens se encontram no momento relevante e respectiva referência:início do transporte/expedição ou colocação à disposição sem transporte;endereço do cliente não substitui esse facto.');
if(row.treatment==='goods_with_transport'&&!row.transportRef.trim())return stop('Identifique o transporte/expedição correspondente ao início referido,ou pressuposto expresso.');
const territory=row.placeCountry==='MZ'?'national':'outside';return{...result,status:'determined',territory,reason:`Art6(1):bens ${territory==='national'?'situados emMoçambique':'situados fora deMoçambique'} ${row.treatment==='goods_with_transport'?'ao iniciar o transporte/expedição para o adquirente':'ao serem postos à disposição do adquirente,sem transporte/expedição'},${row.origin==='projected'?'nas condições expressamente assumidas na projecção':'nos dados efectivos declarados'}. Factos de6(2)conferidos como não aplicáveis a este percurso. ${territory==='outside'?'Fora deste âmbito territorial não equivale a isenção ou taxa/IVA zero.':'Abrangência territorial não confirma isenção,taxa ou IVA.'} Classificação não determina base,dedução/campo11,direitos ou totaisModeloA.`};
}
function key(draft:Record<string,unknown>,book:GoodsLocationBook):string{return JSON.stringify({version:goodsLocationVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},rows:book.rows});}
export function goodsLocationCurrent(draft:Record<string,unknown>,book:GoodsLocationBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordGoodsLocations(draft:Record<string,unknown>,book:GoodsLocationBook):GoodsLocationBook{
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:GoodsLocationCalculation={version:goodsLocationVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:goodsLocationSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateGoodsLocation(row))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveGoodsLocationBook(draft,next);return next;
}
export function goodsLocationReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=goodsLocationBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Localização P105 — ${row.period} — ${row.id}`,`${row.description};classificação territorial: ${result.rows[index].territory==='national'?'Moçambique':result.rows[index].territory==='outside'?'Fora do território nacional':'Indeterminada'};IVA: Indeterminado;${result.rows[index].reason}`,`${result.opportunity};${result.location};${goodsLocationCurrent(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'};${goodsLocationTreatments.find(t=>t.id===row.treatment)?.label??'Percurso por indicar'};operação ${row.operationRef},${row.operationDate};${row.treatment==='goods_before_import'?`transporte ${row.transportRef};importação ${row.importRef};cadeia ${row.chainRef}`:`local dos bens ${row.goodsPlace},${row.placeCountry};referência ${row.placeRef}${row.treatment==='goods_with_transport'?`;transporte ${row.transportRef}`:''}`};âmbito ${row.scope};documento ${row.documentRef},${row.documentDate};condições ${[...goodsLocationConditions,...ownGoodsConditions(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 determina isenção/IVA/campo11/totaisModeloA.`]);}
catch{return[['IVA mensal','Localização de bens','Dados não recuperáveis','Originais preservados;sem classificar por defeito.']];}
}
+81
View File
@@ -0,0 +1,81 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const listedServiceVersion='listed-nondigital-services/1';
export const listedServiceSource='CIVA2(1)a/b,2(2),6(3),6(7)a–j e6(8),Lei13/2016PDF6–8/p1426(264–266);obrigações23(1)/(2),25(4),26(1–3),2016PDF16–17;Lei10/2025PDF12mantém alíneasa–j ealtera6(7)/(8)/(9),PDF13art23(2)excluik,PDF14mantém26(1–3),adita26(4)digital ealtera33(2). Recorte2026,não digital. Regime digital/P121 eoutros6(4)/(5)seguem percurso próprio. Localização/obrigações não confirmam isenção,taxa,IVA,dedução/campo11 ou montante a pagar.';
export const listedServiceTreatments=[
{id:'rights_service',branch:'P111',clause:'a',label:'P111 — Direitos de autor,patentes,licenças e marcas'},
{id:'advertising_service',branch:'P112',clause:'b',label:'P112 — Publicidade'},
{id:'telecom_service',branch:'P113',clause:'c',label:'P113 — Telecomunicações'},
{id:'consulting_service',branch:'P114',clause:'d',label:'P114 — Consultoria,engenharia,advocacia,economia e contabilidade'},
{id:'data_service',branch:'P115',clause:'e',label:'P115 — Tratamento de dados e informações'},
{id:'finance_service',branch:'P116',clause:'f',label:'P116 — Banca,finanças,seguro e resseguro'},
{id:'staff_service',branch:'P117',clause:'g',label:'P117 — Colocação de pessoal'},
{id:'intermediation_service',branch:'P118',clause:'h',label:'P118 — Intermediação em nome e por conta de outrem'},
{id:'abstention_service',branch:'P119',clause:'i',label:'P119 — Obrigação de não exercer actividade ou direito'},
{id:'movable_lease_service',branch:'P120',clause:'j',label:'P120 — Locação de bens móveis corpóreos e financeira'},
] as const;
export const listedServiceConditions=[['serviceSupply','Está identificada uma prestação de serviços desta operação e período'],['nonDigital','A natureza foi conferida:este caso não é bem/serviço digital abrangido por6(7)k/6(9)/26(4)'],['placeRulesExcluded','Foram conferidas as regras de imóveis,trabalhos em móveis,actividades e transporte6(4)/(5):não exigem outro percurso neste caso']] as const;
export const listedOwnConditions={
rights_service:[['rightsNature','Cessão ou autorização para utilizar direitos de autor,licenças,marcas de fábrica/comércio ou outros direitos análogos identificados']],
advertising_service:[['advertisingNature','Serviço de publicidade identificado']],
telecom_service:[['telecomNature','Serviço de telecomunicações identificado']],
consulting_service:[['consultingNature','Consultores,engenheiros,advogados,economistas,contabilistas ou gabinetes de estudo,organização,investigação e desenvolvimento ou domínio similar identificado']],
data_service:[['dataNature','Tratamento de dados ou fornecimento de informações identificado']],
finance_service:[['financeNature','Operação bancária,financeira,de seguro ou resseguro identificada;localização não determina a eventual isenção']],
staff_service:[['staffNature','Colocação de pessoal identificada']],
intermediation_service:[['intermediaryNature','Intermediário intervém em nome e por conta de outrem no fornecimento de serviço enumerado neste número']],
abstention_service:[['abstentionNature','Obrigação de não exercer,mesmo parcialmente,actividade profissional ou direito mencionado nas alíneas deste número']],
movable_lease_service:[['leaseNature','Locação de bens móveis corpóreos,incluindo locação financeira,com bens e contrato identificados']],
} as const;
export function ownListedConditions(treatment:string):ReadonlyArray<readonly[string,string]>{return listedOwnConditions[treatment as keyof typeof listedOwnConditions]??[];}
type Choice=''|'yes'|'no';type Condition=typeof listedServiceConditions[number][0];
export type ListedServiceRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';operationDate:string;operationRef:string;documentRef:string;documentDate:string;providerPlace:string;providerCountry:string;providerRef:string;buyerPlace:string;buyerCountry:string;buyerRef:string;recipientType:string;recipientRef:string;providerTaxable:string;providerTaxRef:string;useRef:string;subjectRef:string;targetClause:string;targetRef:string;scope:string;evidence:string;conditions:Partial<Record<string,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';territory:'national'|'outside'|null;responsible:'acquirer'|'provider'|'outside'|'indeterminate';obligationReason:string;baseAmount:null;vat:null;rate:null;reason:string};
export type ListedServiceCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:ListedServiceRow[];rows:LineResult[]};
export type ListedServiceBook={rows:ListedServiceRow[];result?:ListedServiceCalculation;history?:ListedServiceCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{listedServices?:Record<string,ListedServiceBook>};
export function newListedService(id:string):ListedServiceRow{return{id,treatment:'',description:'',period:'',origin:'projected',operationDate:'',operationRef:'',documentRef:'',documentDate:'',providerPlace:'',providerCountry:'',providerRef:'',buyerPlace:'',buyerCountry:'',buyerRef:'',recipientType:'',recipientRef:'',providerTaxable:'',providerTaxRef:'',useRef:'',subjectRef:'',targetClause:'',targetRef:'',scope:'',evidence:'',conditions:{}};}
export function switchListedTreatment(row:ListedServiceRow,treatment:string):ListedServiceRow{return{...row,treatment,conditions:Object.fromEntries(listedServiceConditions.map(([key])=>[key,row.conditions[key]??'']))};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.listedServices!==undefined&&(!store.listedServices||typeof store.listedServices!=='object'||Array.isArray(store.listedServices)))throw new Error('Serviços enumerados não recuperáveis;originais preservados.');
const fields=Object.keys(newListedService('')).filter(key=>key!=='conditions');
for(const book of Object.values(store.listedServices??{}))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 ListedServiceRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)))throw new Error('Linhas de serviços enumerados não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function listedServiceBook(draft:Record<string,unknown>):ListedServiceBook{return readStore(draft).listedServices?.[acquisitionScope(draft)]??{rows:[]};}
export function saveListedServiceBook(draft:Record<string,unknown>,book:ListedServiceBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,listedServices:{...current.listedServices,[acquisitionScope(draft)]:book}});readStore({...draft,modelo_a_snapshot:encoded});return encoded;}
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 evaluateListedService(row:ListedServiceRow):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',territory:null,responsible:'indeterminate',obligationReason:'Responsável indeterminado;sem obrigação ou montante presumido.',baseAmount:null,vat:null,rate:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,reason});
const rule=listedServiceTreatments.find(t=>t.id===row.treatment);if(!rule)return stop('Identifique o serviço enumerado,não digital,e a natureza efectiva da operação.');
if(!/^2026-(0[1-9]|1[0-2])$/.test(row.period)||!['projected','effective'].includes(row.origin)||!validDate(row.operationDate)||row.operationDate.slice(0,7)!==row.period)return stop('Identifique mês2026,data correspondente e dados efectivos ou pressupostos expressos.');
const required=[...listedServiceConditions,...ownListedConditions(row.treatment)];
if(required.some(([key])=>row.conditions[key]==='no'))return stop('Este percurso não se aplica:conferir natureza digital,regra territorial própria ou tratamento indicado;nenhum IVAzero/isenção presumido.','not_applicable');
if(required.some(([key])=>row.conditions[key]!=='yes'))return stop('Natureza ou regra própria por esclarecer;desconhecido não é fora do território,isenção ou IVAzero.');
if(!row.description.trim()||!row.operationRef.trim()||!row.documentRef.trim()||!validDate(row.documentDate)||!row.scope.trim()||!row.evidence.trim()||!row.useRef.trim()||!row.subjectRef.trim())return stop('Identifique serviço,objecto,destinatário/utilização,operação,documento/data,âmbito e factos ou pressupostos expressos;reutilize referências,sem certificado/aprovador novo.');
if(['intermediation_service','abstention_service'].includes(row.treatment)&&(!'abcdefghij'.includes(row.targetClause)||row.targetClause.length!==1||row.targetClause===rule.clause||!row.targetRef.trim()))return stop('Identifique o serviço/direito/actividade subjacente e a sua alínea de6(7),com referência;digitalk exige percurso próprio,não presumir pelo título.');
if(!['MZ','foreign'].includes(row.buyerCountry)||!row.buyerPlace.trim()||!row.buyerRef.trim())return stop('Identifique o estabelecimento estável ou domicílio do adquirente,país e referência correspondentes,não apenas nacionalidade.');
if(row.buyerCountry==='foreign')return{...result,status:'determined',territory:'outside',responsible:'outside',obligationReason:'Artigo6(8):fora do âmbito territorial de Moçambique;sem obrigação nacional calculada por este percurso ou imposto estrangeiro presumido.',reason:`${rule.branch}:6(8),Lei10/2025PDF12,adquirente estabelecido ou domiciliado no estrangeiro;serviço6(7)${rule.clause} não tributável neste âmbito,ainda que prestador tenha sede/EP/domicílio nacional. Não é concessão de isenção nem IVAzero;sem dedução/campo11 ou imposto estrangeiro presumido.`};
if(!['MZ','foreign'].includes(row.providerCountry)||!row.providerPlace.trim()||!row.providerRef.trim())return stop('Identifique sede/EP/domicílio do prestador a partir do qual o serviço é prestado,país e referência.');
if(row.providerCountry==='foreign'){
if(row.recipientType==='other')return stop('Adquirente não corresponde a2(1)a/b:6(7)não demonstrado por este percurso;conferir outra regra aplicável,sem classificar automaticamente fora do território.','not_applicable');
if(!['a','b'].includes(row.recipientType)||!row.recipientRef.trim())return stop('Identifique qualidade do adquirente2(1)a/b e referência;inclui quem pratica exclusivamente operações isentas sem direito à dedução,não exigir direito à dedução.');
return{...result,status:'determined',territory:'national',responsible:'acquirer',obligationReason:'Adquirente sujeito passivo2(2)/6(7)/23(2),redacção2025:entrega declaração33(2)eimposto exigível,nos termos a regulamentar. Não se aplica26(4)digital,nem prazo32(1)c digital a este caso. Eventual isenção/taxa/montante eprocedimento de pagamento não são apurados aqui.',reason:`${rule.branch}:6(7)${rule.clause},prestador estrangeiro sem sede/EP/domicílio nacional a partir do qual presta;adquirente2(1)${row.recipientType} comEP/domicílio nacional,mesmo que pratique exclusivamente operações isentas sem dedução. Localização nacional não confirma isenção,IVA ou dedução/campo11.`};
}
const liable=row.providerTaxable==='yes'&&!!row.providerTaxRef.trim();
return{...result,status:'determined',territory:'national',responsible:liable?'provider':'indeterminate',obligationReason:liable?'Prestador sujeito passivo no regime geral:23(1),sem activação automática de cobrança;eventual isenção,taxa,IVA eapuramento independentes.':'Localização6(3)determinada;qualidade fiscal do prestador ou referência por esclarecer,sem atribuir obrigação automaticamente.',reason:`${rule.branch}:6(3),prestador comsede/EP/domicílio nacional a partir do qual presta eadquirente nacional,sem regras6(4)/(5)ou digitais aplicáveis. Qualidade do adquirente2(1)a/b não é pré-condição deste percurso doméstico. Localização não concede isenção nem calculaIVA/dedução.`};
}
function key(draft:Record<string,unknown>,book:ListedServiceBook):string{return JSON.stringify({version:listedServiceVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},rows:book.rows});}
export function listedServiceCurrent(draft:Record<string,unknown>,book:ListedServiceBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordListedServices(draft:Record<string,unknown>,book:ListedServiceBook):ListedServiceBook{
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:ListedServiceCalculation={version:listedServiceVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:listedServiceSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateListedService(row))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveListedServiceBook(draft,next);return next;
}
export function listedServiceReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=listedServiceBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>{const line=result.rows[index];return['IVA mensal',`Serviço ${listedServiceTreatments.find(t=>t.id===row.treatment)?.branch??'enumerado'} — ${row.period} — ${row.id}`,`${row.description};classificação territorial: ${line.territory==='national'?'Moçambique':line.territory==='outside'?'Fora do território nacional':'Indeterminada'};IVA: Indeterminado;${line.reason};responsável: ${line.responsible==='acquirer'?'Adquirente':line.responsible==='provider'?'Prestador':line.responsible==='outside'?'Fora deste âmbito':'Indeterminado'};${line.obligationReason}`,`${result.opportunity};${result.location};${listedServiceCurrent(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'};${listedServiceTreatments.find(t=>t.id===row.treatment)?.label??'Percurso por indicar'};operação ${row.operationRef},${row.operationDate};prestador ${row.providerPlace},${row.providerCountry},${row.providerRef};adquirente ${row.buyerPlace},${row.buyerCountry},${row.buyerRef};${row.buyerCountry==='MZ'&&row.providerCountry==='foreign'?`qualidade adquirente2(1)${row.recipientType},${row.recipientRef};`:''}${row.buyerCountry==='MZ'&&row.providerCountry==='MZ'?`qualidade prestador ${row.providerTaxable},${row.providerTaxRef};`:''}objecto ${row.subjectRef};destinatário/utilização ${row.useRef};${['intermediation_service','abstention_service'].includes(row.treatment)?`subjacente6(7)${row.targetClause},${row.targetRef};`:''}âmbito ${row.scope};documento ${row.documentRef},${row.documentDate};condições ${[...listedServiceConditions,...ownListedConditions(row.treatment)].map(([key,label])=>label+': '+(row.conditions[key]==='yes'?'Sim':row.conditions[key]==='no'?'Não':'Por indicar')).join('; ')};fundamento ${row.evidence};sem isenção/IVA/campo11/totaisModeloA.`];});}
catch{return[['IVA mensal','Serviços enumerados','Dados não recuperáveis','Originais preservados;sem classificação por defeito.']];}
}
+59
View File
@@ -0,0 +1,59 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const noncashBaseVersion='noncash-consideration-base/1';
export const noncashBaseSource='CIVA republicado Lei13/2016,15(3)/(4),PDF14/p1426(272): contraprestação não definida,no todo ou em parte,em dinheiro;valor tributável=montante recebido ou a receber acrescido do valor normal dos bens ou serviços dados em troca. Valor normal:preço em concorrência normal,a fornecedor independente,no mesmo estádio de comercialização,tempo e lugar da operação ou mais próximos,aumentado dos elementos15(5)na medida não incluídos. Composição/exclusões15(5)/(6),sem próprioIVA. Lei22/2022PDF3mantém15(3–6)por remissão;Lei10/2025não altera15. Recorte2026/MZN,sem conversão cambial;base apenas,sem avaliação automática,incidência,taxaIVA,IVA,dedução/campo11 ou totaisModeloA.';
export const noncashBaseTreatments=[{id:'noncash_only',label:'Contraprestação inteiramente não monetária'},{id:'cash_and_noncash',label:'Contraprestação em parte monetária e em parte não monetária'}] as const;
export const noncashBaseConditions=[
['taxableOperation','Está identificada a operação sujeita a IVA cuja contraprestação não é definida no todo ou em parte em dinheiro'],
['exchangeIdentified','Estão identificados os bens ou serviços dados em troca como contraprestação desta operação; não se somam o valor da própria operação e a respectiva contraprestação'],
['cashComposition','A composição escolhida corresponde à operação:inteiramente não monetária,sem parte em dinheiro,ou com montante monetário recebido/a receber identificado'],
['normalValueBasis','O valor normal corresponde ao artigo15(4):concorrência normal,fornecedor independente,mesmo estádio de comercialização,tempo/lugar da operação ou mais próximos,com fundamento identificado'],
['netComposition','Os montantes excluem o próprio IVA e incluem a composição aplicável15(5)/(6),sem omissões ou dupla contagem dos mesmos elementos'],
] as const;
type Choice=''|'yes'|'no';type Condition=typeof noncashBaseConditions[number][0];
export type NoncashBaseRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';currency:string;exchangeDescription:string;agreementRef:string;documentRef:string;documentDate:string;cashAmount:string;cashRef:string;normalValue:string;valuationRef:string;valuationScope: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 NoncashBaseCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:NoncashBaseRow[];rows:LineResult[]};
export type NoncashBaseBook={rows:NoncashBaseRow[];result?:NoncashBaseCalculation;history?:NoncashBaseCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{noncashBases?:Record<string,NoncashBaseBook>};
export function newNoncashBase(id:string,currency:string):NoncashBaseRow{return{id,treatment:'',description:'',period:'',origin:'projected',currency,exchangeDescription:'',agreementRef:'',documentRef:'',documentDate:'',cashAmount:'',cashRef:'',normalValue:'',valuationRef:'',valuationScope:'',compositionRef:'',evidence:'',conditions:{}};}
export function switchNoncashComposition(row:NoncashBaseRow,treatment:string):NoncashBaseRow{return{...row,treatment,conditions:{...row.conditions,cashComposition:''}};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.noncashBases!==undefined&&(!store.noncashBases||typeof store.noncashBases!=='object'||Array.isArray(store.noncashBases)))throw new Error('Bases de contraprestação não recuperáveis;originais preservados.');
const fields=Object.keys(newNoncashBase('','')).filter(key=>key!=='conditions');
for(const book of Object.values(store.noncashBases??{}))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 NoncashBaseRow]!=='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 noncashBaseBook(draft:Record<string,unknown>):NoncashBaseBook{return readStore(draft).noncashBases?.[acquisitionScope(draft)]??{rows:[]};}
export function saveNoncashBaseBook(draft:Record<string,unknown>,book:NoncashBaseBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,noncashBases:{...current.noncashBases,[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 evaluateNoncashBase(row:NoncashBaseRow,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(!noncashBaseTreatments.some(item=>item.id===row.treatment))return stop('Identifique a composição não monetária total ou parcial;parte monetária desconhecida não equivale a ausência de dinheiro.');
if(currency!=='MZN'||row.currency!==currency)return stop('Moeda fora do âmbito MZN ou divergente do projecto;sem conversão silenciosa ou taxa de câmbio presumida.');
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=noncashBaseConditions.filter(([key])=>row.conditions[key]==='no');if(failed.length)return stop('Não se aplica esta determinação da base: '+failed.map(([,label])=>label).join('; ')+'. Não é isenção nem IVA zero.','not_applicable');
const missing=noncashBaseConditions.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.exchangeDescription.trim()||!row.agreementRef.trim()||!row.documentRef.trim()||!row.valuationRef.trim()||!row.valuationScope.trim()||!row.compositionRef.trim()||!row.evidence.trim()||!validDate(row.documentDate))return stop('Identifique operação,contraprestação em bens/serviços,acordo,documento/data,fundamento e âmbito do valor normal e composição,ou pressupostos expressos;reutilize referências existentes,sem novo certificado/avaliador/aprovador.');
const normal=decimal(row.normalValue);if(normal===null)return stop('Indique o valor normal dos bens/serviços dados em troca;desconhecido não é zero nem valor avaliado automaticamente pelo portal.');
let base=normal,formula=`valor normal ${money(normal)},sem parte monetária expressamente confirmada`;
if(row.treatment==='cash_and_noncash'){
const cash=decimal(row.cashAmount);if(cash===null||!row.cashRef.trim())return stop('Identifique montante monetário recebido/a receber e referência ou pressuposto expresso;um montante desconhecido não é zero.');
base=cash+normal;formula=`montante monetário ${money(cash)} + valor normal ${money(normal)}`;
}
return{...result,status:'determined',baseAmount:money(base),reason:`Base15(3)/(4): ${formula} = ${money(base)}MZN,${row.origin==='projected'?'nas condições expressamente assumidas na projecção':'nos dados efectivos declarados'}. Valor normal/fundamento/âmbito e composição identificados,sem avaliação automática. 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:NoncashBaseBook):string{return JSON.stringify({version:noncashBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function noncashBaseCurrent(draft:Record<string,unknown>,book:NoncashBaseBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordNoncashBases(draft:Record<string,unknown>,book:NoncashBaseBook):NoncashBaseBook{
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:NoncashBaseCalculation={version:noncashBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:noncashBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateNoncashBase(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveNoncashBaseBook(draft,next);return next;
}
export function noncashBaseReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=noncashBaseBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Base P100 — ${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};${noncashBaseCurrent(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'};${noncashBaseTreatments.find(item=>item.id===row.treatment)?.label??'Composição por indicar'};bens/serviços dados em troca ${row.exchangeDescription};acordo ${row.agreementRef};${row.treatment==='cash_and_noncash'?`montante monetário ${row.cashAmount} ${row.currency},referência ${row.cashRef}`:'Sem parte monetária,expressamente confirmado'};valor normal ${row.normalValue} ${row.currency};fundamento ${row.valuationRef};âmbito ${row.valuationScope};composição ${row.compositionRef};documento ${row.documentRef},${row.documentDate};condições ${noncashBaseConditions.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','Base de contraprestação não monetária','Dados não recuperáveis','Originais preservados;sem substituir por zero.']];}
}
+55
View File
@@ -0,0 +1,55 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const ownNameVersion='own-name-chains/1';
export const ownNameSource='CIVA3(3)c,Lei13/2016PDF6/p1426(264):transferências em execução de contrato de comissão,incluindo consignação;comissário considerado comprador na comissão de venda,comitente na de compra. Art4(3),PDF7/p1426(265):mandatário emnome próprio é adquirente eprestador do serviço sucessivamente. Lei10/2025PDF12mantém3(3)c e não altera4. Base de bens15(2)e/P091já entregue,não recalculada ou somada neste percurso. Recorte2026:circuito/contraprestações originais separados,sem localização,isenção,taxa,IVA,dedução/campo11 ou totaisModeloA presumidos.';
export const ownNameTreatments=[{id:'goods_sale_commission',branch:'P122',label:'P122 — Comissão de venda de bens',kind:'goods',direction:'sale'},{id:'goods_purchase_commission',branch:'P122',label:'P122 — Comissão de compra de bens',kind:'goods',direction:'purchase'},{id:'service_sale_mandate',branch:'P128',label:'P128 — Mandato de venda/prestação de serviços',kind:'services',direction:'sale'},{id:'service_purchase_mandate',branch:'P128',label:'P128 — Mandato de aquisição de serviços',kind:'services',direction:'purchase'}] as const;
export const ownNameConditions=[['ownName','O comissário/mandatário actua emnome próprio,não apenas emnome do mandante'],['forAnother','Actua por conta de outrem identificado ecom relação documentada ou pressuposto expresso'],['factsCorrespond','Objecto,partes,referências eperíodo correspondem à operação identificada']] as const;
const goodsConditions=[['goodsNature','São transferências de bens,não serviço autónomo de intermediação'],['commissionContract','As transferências executam contrato de comissão identificado,conforme3(3)c,incluindo consignação quando aplicável'],['directionConfirmed','Papéis e duas relações correspondem ao sentido de venda ou compra escolhido']] as const;
const serviceConditions=[['serviceNature','Está identificada uma prestação de serviços,não transferência de bens'],['mandateContract','A prestação é efectuada por intervenção de mandatário emnome próprio,com mandato identificado4(3)'],['successiveService','Mandatário é adquirente eprestador do serviço sucessivamente;referências distinguem as duas prestações'],['directionConfirmed','Papéis e duas relações correspondem ao sentido de venda/prestação ou aquisição escolhido']] as const;
export function ownNameSpecificConditions(treatment:string):ReadonlyArray<readonly[string,string]>{const rule=ownNameTreatments.find(t=>t.id===treatment);return rule?.kind==='goods'?goodsConditions:rule?.kind==='services'?serviceConditions:[];}
type Choice=''|'yes'|'no';type Condition=typeof ownNameConditions[number][0];
export type OwnNameRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';operationDate:string;operationRef:string;documentRef:string;documentDate:string;principalRef:string;agentRef:string;thirdPartyRef:string;contractRef:string;subjectRef:string;currency:string;firstAmount:string;secondAmount:string;firstLegRef:string;secondLegRef:string;existingBaseRef:string;scope:string;evidence:string;conditions:Partial<Record<string,Choice>>};
type Leg={supplier:string;acquirer:string;consideration:string;currency:string;reference:string};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';legs:Leg[];baseAmount:null;vat:null;rate:null;reason:string};
export type OwnNameCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:OwnNameRow[];rows:LineResult[]};
export type OwnNameBook={rows:OwnNameRow[];result?:OwnNameCalculation;history?:OwnNameCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{ownNames?:Record<string,OwnNameBook>};
export function newOwnName(id:string,currency=''):OwnNameRow{return{id,treatment:'',description:'',period:'',origin:'projected',operationDate:'',operationRef:'',documentRef:'',documentDate:'',principalRef:'',agentRef:'',thirdPartyRef:'',contractRef:'',subjectRef:'',currency,firstAmount:'',secondAmount:'',firstLegRef:'',secondLegRef:'',existingBaseRef:'',scope:'',evidence:'',conditions:{}};}
export function switchOwnNameTreatment(row:OwnNameRow,treatment:string):OwnNameRow{return{...row,treatment,conditions:Object.fromEntries(ownNameConditions.map(([key])=>[key,row.conditions[key]??'']))};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.ownNames!==undefined&&(!store.ownNames||typeof store.ownNames!=='object'||Array.isArray(store.ownNames)))throw new Error('Circuitos emnome próprio não recuperáveis;originais preservados.');
const fields=Object.keys(newOwnName('')).filter(key=>key!=='conditions');
for(const book of Object.values(store.ownNames??{}))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 OwnNameRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)))throw new Error('Linhas de circuitos emnome próprio não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function ownNameBook(draft:Record<string,unknown>):OwnNameBook{return readStore(draft).ownNames?.[acquisitionScope(draft)]??{rows:[]};}
export function saveOwnNameBook(draft:Record<string,unknown>,book:OwnNameBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,ownNames:{...current.ownNames,[acquisitionScope(draft)]:book}});readStore({...draft,modelo_a_snapshot:encoded});return encoded;}
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 evaluateOwnName(row:OwnNameRow,currency:unknown):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',legs:[],baseAmount:null,vat:null,rate:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,reason});
const rule=ownNameTreatments.find(t=>t.id===row.treatment);if(!rule)return stop('Identifique bens/serviços e o sentido da comissão/mandato;sem inferir pelo pagamento de uma comissão.');
if(!/^2026-(0[1-9]|1[0-2])$/.test(row.period)||!['projected','effective'].includes(row.origin)||!validDate(row.operationDate)||row.operationDate.slice(0,7)!==row.period)return stop('Identifique mês2026,data correspondente e dados efectivos ou pressupostos expressos.');
const required=[...ownNameConditions,...ownNameSpecificConditions(row.treatment)];if(required.some(([key])=>row.conditions[key]==='no'))return stop('Este circuito emnome próprio não se aplica aos factos declarados;rever mandato/comissão/natureza/papéis,sem classificar mera intermediação como duas operações ou presumir isenção/IVAzero.','not_applicable');
if(required.some(([key])=>row.conditions[key]!=='yes'))return stop('Natureza,actuação emnome próprio ou papéis por esclarecer;desconhecido não é não aplicável ou zero.');
if(!row.description.trim()||!row.operationRef.trim()||!row.documentRef.trim()||!validDate(row.documentDate)||!row.scope.trim()||!row.evidence.trim()||!row.subjectRef.trim()||!row.contractRef.trim()||![row.principalRef,row.agentRef,row.thirdPartyRef,row.firstLegRef,row.secondLegRef].every(v=>!!v.trim()))return stop('Identifique objecto,mandante/comitente,comissário/mandatário,terceiro,contrato,duas relações,operação/documento/data eâmbito;reutilize referências ou pressupostos expressos,sem certificado/aprovador novo.');
if(typeof currency!=='string'||!/^[A-Z]{3}$/.test(currency)||row.currency!==currency)return stop('Identifique moeda original coerente com o contexto;sem converter ou reinterpretarUSDcomoMZN.');
const amount=(v:string):string|null=>/^\d{1,15}(\.\d{1,6})?$/.test(v.trim())?v.trim():null;const first=amount(row.firstAmount),second=amount(row.secondAmount);
if(first===null||second===null)return stop('Identifique separadamente as contraprestações originais das duas relações;desconhecido não é zero. Não inferir uma delas da comissão ou somá-las como uma única base.');
const before=rule.direction==='sale'?row.principalRef:row.thirdPartyRef,after=rule.direction==='sale'?row.thirdPartyRef:row.principalRef;
const legs=[{supplier:before,acquirer:row.agentRef,consideration:first,currency:row.currency,reference:row.firstLegRef},{supplier:row.agentRef,acquirer:after,consideration:second,currency:row.currency,reference:row.secondLegRef}];
return{...result,status:'determined',legs,reason:`${rule.branch}:${rule.kind==='goods'?`art3(3)c,comissão de${rule.direction==='sale'?'venda:comissário considerado comprador':'compra:comitente considerado comprador'}`:'art4(3),mandatário emnome próprio considerado adquirente eprestador do serviço sucessivamente'}. ${row.origin==='projected'?'Circuito sob pressupostos expressos.':'Circuito segundo dados efectivos declarados.'} Duas relações com objecto/partes/contraprestações originais separadas,sem soma ou compensação automática. ${rule.kind==='goods'?'BaseP091/15(2)e já entregue permanece separada e não é recalculada.':'Não transformar este circuito emcomissão autónoma ou aplicar15(2)e de bens aos serviços.'} Sem determinar localização,isenção,base,taxa,IVA,dedução/campo11 ou totaisModeloA.`};
}
function key(draft:Record<string,unknown>,book:OwnNameBook):string{return JSON.stringify({version:ownNameVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function ownNameCurrent(draft:Record<string,unknown>,book:OwnNameBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordOwnNames(draft:Record<string,unknown>,book:OwnNameBook):OwnNameBook{
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:OwnNameCalculation={version:ownNameVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:ownNameSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateOwnName(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveOwnNameBook(draft,next);return next;
}
export function ownNameReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=ownNameBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>{const line=result.rows[index],rule=ownNameTreatments.find(t=>t.id===row.treatment);return['IVA mensal',`Circuito ${rule?.branch??'emnome próprio'} — ${row.period} — ${row.id}`,`${row.description};${line.status==='determined'?'Circuito identificado':line.status==='not_applicable'?'Circuito não aplicável':'Circuito indeterminado'};IVA: Indeterminado;${line.reason};${line.legs.map((leg,i)=>`Relação${i+1}:${leg.supplier} → ${leg.acquirer},contraprestação original ${leg.consideration} ${leg.currency},referência ${leg.reference}`).join('; ')};sem soma das duas relações`,`${result.opportunity};${result.location};${ownNameCurrent(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'};${rule?.label??'Percurso por indicar'};operação ${row.operationRef},${row.operationDate};objecto ${row.subjectRef};contrato ${row.contractRef};mandante/comitente ${row.principalRef};agente ${row.agentRef};terceiro ${row.thirdPartyRef};relações ${row.firstLegRef}/${row.secondLegRef};${rule?.kind==='goods'?`referênciaP091existente ${row.existingBaseRef||'não indicada;sem nova base calculada'};`:''}âmbito ${row.scope};documento ${row.documentRef},${row.documentDate};condições ${[...ownNameConditions,...ownNameSpecificConditions(row.treatment)].map(([key,label])=>label+': '+(row.conditions[key]==='yes'?'Sim':row.conditions[key]==='no'?'Não':'Por indicar')).join('; ')};fundamento ${row.evidence};sem IVA/dedução/campo11/totaisModeloA.`];});}
catch{return[['IVA mensal','Circuito emnome próprio','Dados não recuperáveis','Originais preservados;sem circuito ou valor por defeito.']];}
}
+63
View File
@@ -0,0 +1,63 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const reducedBaseVersion='proportional-bases/1';
export const reducedBaseSource='CIVA15(2)j/k/l/m,15(1)/(5)/(6)/(9),Lei13/2016PDF13–14/p1426(271–272);Lei22/2022PDF3mantém15(2)j–m;Lei10/2025não altera15 eadita18(6),PDF13:dedução do imposto suportado relativo a estas operações na mesma proporção da base reduzida. Recorte2026/MZN;base apenas,sem taxaIVA/IVA/dedução/campo11 ou totaisModeloA. Energia62%,taxas aeronáuticas85%,obras redução60%(base40%),água75%. Percentagem de base não é taxaIVA.';
export const reducedBaseTreatments=[{id:'regulated_energy',branch:'P096',clause:'j',label:'P096 — Energia com preço fixado por Autoridade Pública',percent:62},{id:'aeronautical_fees',branch:'P097',clause:'k',label:'P097 — Serviços com preço fixado por taxas aeronáuticas',percent:85},{id:'public_works',branch:'P098',clause:'l',label:'P098 — Obras públicas abrangidas',percent:40},{id:'public_water',branch:'P099',clause:'m',label:'P099 — Água potável por rede pública e preço fixado',percent:75}] as const;
export const reducedBaseConditions=[['taxableOperation','Está identificada a operação sujeita a IVA e a correspondência com este tratamento'],['fullNetInvoice','O montante é a contraprestação total da operação/factura antes desta redução,sem o próprioIVA ecom composição15(1)/(5)/(6)conferida'],['scopeMatches','Documentos/referências ou pressupostos expressos correspondem ao objecto,local,operação eperíodo']] as const;
export const reducedOwnConditions={
regulated_energy:[['energySupply','Transmissão de energia identificada'],['publicFixedPrice','Preço fixado pela Autoridade Pública identificada na referência aplicável']],
aeronautical_fees:[['aeronauticalPrice','Preço do serviço fixado através de taxas aeronáuticas;uma descrição de comunicações,saneamento ou telecomunicações não basta']],
public_works:[['publicWorks','Construção ou reabilitação de obras públicas abrangidas15(2)l/15(9)'],['workCategoryMatches','A categoria eâmbito da obra correspondem ao projecto público identificado']],
public_water:[['potableWater','Fornecimento de água potável'],['publicNetwork','Fornecimento através de rede pública'],['publicFixedPrice','Preço fixado pela Autoridade Pública identificada na referência aplicável']],
} as const;
export const publicWorkCategories=[{id:'roads',label:'Estradas'},{id:'bridges',label:'Pontes'},{id:'water_infrastructure',label:'Infra-estruturas de abastecimento de água/saneamento15(9)a'},{id:'rural_electricity',label:'Electrificação rural em projectos públicos15(9)b'},{id:'agricultural_hydraulics',label:'Hidráulica agrícola no âmbito definido15(9)c'}] as const;
export function ownReducedConditions(treatment:string):ReadonlyArray<readonly[string,string]>{return reducedOwnConditions[treatment as keyof typeof reducedOwnConditions]??[];}
type Choice=''|'yes'|'no';type Condition=typeof reducedBaseConditions[number][0];
export type ReducedBaseRow={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;projectRef:string;workCategory:string;compositionRef:string;evidence:string;conditions:Partial<Record<string,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';baseAmount:string|null;deductionProportion:string|null;vat:null;rate:null;reason:string};
export type ReducedBaseCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:ReducedBaseRow[];rows:LineResult[]};
export type ReducedBaseBook={rows:ReducedBaseRow[];result?:ReducedBaseCalculation;history?:ReducedBaseCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{regulatedReducedBases?:Record<string,ReducedBaseBook>};
export function newReducedBase(id:string,currency:string):ReducedBaseRow{return{id,treatment:'',description:'',period:'',origin:'projected',currency,operationDate:'',priceRef:'',priceScope:'',priceFrom:'',priceTo:'',documentRef:'',documentDate:'',consideration:'',projectRef:'',workCategory:'',compositionRef:'',evidence:'',conditions:{}};}
export function switchReducedTreatment(row:ReducedBaseRow,treatment:string):ReducedBaseRow{return{...row,treatment,conditions:Object.fromEntries(reducedBaseConditions.map(([key])=>[key,row.conditions[key]??'']))};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.regulatedReducedBases!==undefined&&(!store.regulatedReducedBases||typeof store.regulatedReducedBases!=='object'||Array.isArray(store.regulatedReducedBases)))throw new Error('Bases reduzidas não recuperáveis;originais preservados.');
const fields=Object.keys(newReducedBase('','')).filter(key=>key!=='conditions');
for(const book of Object.values(store.regulatedReducedBases??{}))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 ReducedBaseRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)))throw new Error('Linhas de bases reduzidas não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function reducedBaseBook(draft:Record<string,unknown>):ReducedBaseBook{return readStore(draft).regulatedReducedBases?.[acquisitionScope(draft)]??{rows:[]};}
export function saveReducedBaseBook(draft:Record<string,unknown>,book:ReducedBaseBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,regulatedReducedBases:{...current.regulatedReducedBases,[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/100000000n}.${(n%100000000n).toString().padStart(8,'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 evaluateReducedBase(row:ReducedBaseRow,currency:unknown):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',baseAmount:null,deductionProportion:null,vat:null,rate:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,reason});
const rule=reducedBaseTreatments.find(t=>t.id===row.treatment);if(!rule)return stop('Identifique energia,taxas aeronáuticas,obras públicas ou água;sem percentagem por defeito.');
if(currency!=='MZN'||row.currency!==currency)return stop('Moeda fora do âmbitoMZN 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ês2026 e dados efectivos ou pressupostos expressos de projecção.');
const conditions=[...reducedBaseConditions,...ownReducedConditions(row.treatment)];if(conditions.some(([key])=>row.conditions[key]==='no'))return stop('Este tratamento de base reduzida não se aplica aos factos declarados;rever natureza/composição/âmbito,sem isenção ou IVAzero presumido.','not_applicable');
if(conditions.some(([key])=>row.conditions[key]!=='yes'))return stop('Condições por esclarecer;desconhecido não é não aplicável ou zero. Confirme o montante total antes da redução,sem próprioIVA.');
if(!row.description.trim()||!row.documentRef.trim()||!row.compositionRef.trim()||!row.evidence.trim()||!row.priceScope.trim()||!validDate(row.documentDate)||!validDate(row.operationDate)||row.operationDate.slice(0,7)!==row.period)return stop('Identifique operação,data/mês,documento/data,âmbito e composição ou pressupostos expressos;reutilize referências sem certificado/aprovador novo.');
if(row.treatment==='public_works'){
if(!row.projectRef.trim()||!publicWorkCategories.some(c=>c.id===row.workCategory))return stop('Identifique projecto/contrato público,categoria eâmbito da obra15(2)l/15(9);não aplicar a qualquer obra privada.');
}else if(!row.priceRef.trim()||!validDate(row.priceFrom)||row.operationDate<row.priceFrom||(row.priceTo!==''&&(!validDate(row.priceTo)||row.priceFrom>row.priceTo||row.operationDate>row.priceTo)))return stop('Identifique referência aplicável do preço/taxa e intervalo que abrange a operação;fim pode ficar vazio sem termo fixado,com correspondência temporal confirmada. Sem preço actual presumido para outro período.');
const amount=decimal(row.consideration);if(amount===null)return stop('Indique contraprestação total antes da redução,sem próprioIVA;desconhecido/inválido não é zero. Se só existe total comIVA,separe a composição no percurso aplicável antes de usar este campo.');
const base=money(amount*BigInt(rule.percent));
return{...result,status:'determined',baseAmount:base,deductionProportion:String(rule.percent)+'%',reason:`${rule.branch}:15(2)${rule.clause},base=${row.consideration}×${rule.percent}%=${base}MZN,${row.origin==='projected'?'sob pressupostos expressos':'nos dados efectivos declarados'}. ${row.treatment==='public_works'?'Redução de60% significa base40%,não base60%.':'Percentagem aplicada uma única vez ao montante total antes da redução,sem próprioIVA.'} Art18(6),Lei10/2025:dedução relativa a estas operações na mesma proporção(${rule.percent}%),sujeita às condições próprias;isto não calcula nem concede dedução/campo11. Base não é imposto;sem taxaIVA,IVA ou totaisModeloA. Decimal exacto,sem arredondamento fiscal presumido.`};
}
function key(draft:Record<string,unknown>,book:ReducedBaseBook):string{return JSON.stringify({version:reducedBaseVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function reducedBaseCurrent(draft:Record<string,unknown>,book:ReducedBaseBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordReducedBases(draft:Record<string,unknown>,book:ReducedBaseBook):ReducedBaseBook{
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:ReducedBaseCalculation={version:reducedBaseVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:reducedBaseSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateReducedBase(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveReducedBaseBook(draft,next);return next;
}
export function reducedBaseReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=reducedBaseBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Base ${reducedBaseTreatments.find(t=>t.id===row.treatment)?.branch??'reduzida'} — ${row.period} — ${row.id}`,`${row.description};base tributável: ${result.rows[index].baseAmount??'Indeterminada'} ${row.currency};IVA: Indeterminado;proporção18(6):${result.rows[index].deductionProportion??'Indeterminada'}(sem dedução calculada);${result.rows[index].reason}`,`${result.opportunity};${result.location};${reducedBaseCurrent(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'};operação ${row.operationDate};âmbito ${row.priceScope};${row.treatment==='public_works'?`projecto/contrato ${row.projectRef};categoria ${row.workCategory}`:`preço/taxa ${row.priceRef};intervalo ${row.priceFrom} a ${row.priceTo||'sem termo fixado,correspondência confirmada'}`};contraprestação total antes redução ${row.consideration} ${row.currency};composição ${row.compositionRef};documento ${row.documentRef},${row.documentDate};condições ${[...reducedBaseConditions,...ownReducedConditions(row.treatment)].map(([key,label])=>label+': '+(row.conditions[key]==='yes'?'Sim':row.conditions[key]==='no'?'Não':'Por indicar')).join('; ')};fundamento ${row.evidence};sem dedução/campo11/totaisModeloA.`]);}
catch{return[['IVA mensal','Bases reduzidas','Dados não recuperáveis','Originais preservados;sem substituir por zero.']];}
}
+84
View File
@@ -0,0 +1,84 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const secondhandVersion='secondhand-individual-margin/1';
export const secondhandSource='CIVA3(3)g/3(6),15(2)f/g,Lei13/2016PDF7/13;Lei22/2022PDF3mantém15f/g efixa17(1)16%;Lei10/2025não altera15/17,revoga regimes35/42. RIVADecreto7/2008arts47–49,BR16-I16/04/2008PDF8–9/p106–107:revenda porbem,margem positiva dividida por1.16 ebase arredondada à unidade;sem compensar perdas entrebens. Leilão:facturado−líquidocomitente−IVApróprio identificado,líquido=adjudicação−comissão. ClassificaçãoP125 separada da baseP092/P093. Sem nova dedução/campo11,isenção automática,IVA calculado ou totaisModeloA.';
export const secondhandTreatments=[{id:'reseller_margin',branch:'P092',label:'Revendedor — margem individual'},{id:'auction_margin',branch:'P093',label:'Organizador emnome próprio — venda em leilão'}] as const;
export const secondhandCategories=[{id:'used_goods',label:'Bem móvel usado3(6)a'},{id:'art',label:'Objecto de arte3(6)b'},{id:'collection',label:'Objecto de colecção3(6)c'},{id:'antique',label:'Antiguidade3(6)d'}] as const;
export const secondhandConditions=[['goodsIdentity','Bem individual identificado,com aquisição,transmissão e referências correspondentes'],['operatorRole','Sujeito passivo revendedor ou organizador de leilão identificado,no exercício da actividade epercurso escolhido']] as const;
export const categoryConditions={
used_goods:[['reusableUsed','Bem móvel usado susceptível de reutilização no estado ou após reparação'],['notRenewedTransformed','Não é renovado nem transformado:renovado se materiais de reparação excedem aquisição+mão-de-obra;transformado se reparação modifica características essenciais'],['notPreciousExcluded','Não são pedras/metais preciosos excluídos3(6)a;moedas/artefactos desses materiais não são excluídos só por esse motivo']],
art:[['artistOriginal','Obra da autoria do artista,no âmbito3(6)b;sem desenho industrial,ourivesaria ou joalharia']],
collection:[['collectionNature','Objecto de colecção no âmbito3(6)c,com natureza e características identificadas']],
antique:[['notArtCollection','Não é objecto de arte ou de colecção já classificado nessas categorias']],
} as const;
export function secondhandCategoryConditions(category:string):ReadonlyArray<readonly[string,string]>{return categoryConditions[category as keyof typeof categoryConditions]??[];}
type Choice=''|'yes'|'no';type Condition=typeof secondhandConditions[number][0];
export type SecondhandRow={id:string;treatment:string;category:string;description:string;period:string;origin:'projected'|'effective';currency:string;operationDate:string;operationRef:string;documentRef:string;documentDate:string;goodsRef:string;operatorRef:string;categoryRef:string;artSubtype:string;editionCount:string;ceramicUniqueSigned:string;collectionSubtype:string;postalNotCirculating:string;ageYears:string;sourceType:string;sourceRef:string;domesticPurchase:string;regimeChoice:string;domesticTaxable:string;grossSale:string;purchasePrice:string;purchaseRef:string;grossInvoice:string;hammerPrice:string;principalCommission:string;auctionRef:string;principalRef:string;ownVat:string;ownVatRef:string;scope:string;evidence:string;conditions:Partial<Record<string,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';classification:'qualified_goods'|'not_applicable'|'indeterminate';baseAmount:string|null;grossMargin:string|null;principalNet:string|null;baseDivisorRate:string|null;vat:null;rate:null;reason:string};
export type SecondhandCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:SecondhandRow[];rows:LineResult[]};
export type SecondhandBook={rows:SecondhandRow[];result?:SecondhandCalculation;history?:SecondhandCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{regulatedSecondhands?:Record<string,SecondhandBook>};
export function newSecondhand(id:string,currency:string):SecondhandRow{return{id,treatment:'',category:'',description:'',period:'',origin:'projected',currency,operationDate:'',operationRef:'',documentRef:'',documentDate:'',goodsRef:'',operatorRef:'',categoryRef:'',artSubtype:'',editionCount:'',ceramicUniqueSigned:'',collectionSubtype:'',postalNotCirculating:'',ageYears:'',sourceType:'',sourceRef:'',domesticPurchase:'',regimeChoice:'',domesticTaxable:'',grossSale:'',purchasePrice:'',purchaseRef:'',grossInvoice:'',hammerPrice:'',principalCommission:'',auctionRef:'',principalRef:'',ownVat:'',ownVatRef:'',scope:'',evidence:'',conditions:{}};}
export function switchSecondhandTreatment(row:SecondhandRow,treatment:string):SecondhandRow{return{...row,treatment,conditions:{...row.conditions,regimeConfirmed:'',compositionConfirmed:''}};}
export function switchSecondhandCategory(row:SecondhandRow,category:string):SecondhandRow{return{...row,category,conditions:Object.fromEntries(secondhandConditions.map(([key])=>[key,row.conditions[key]??'']))};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.regulatedSecondhands!==undefined&&(!store.regulatedSecondhands||typeof store.regulatedSecondhands!=='object'||Array.isArray(store.regulatedSecondhands)))throw new Error('Afectações de bens não recuperáveis;originais preservados.');
const fields=Object.keys(newSecondhand('','')).filter(key=>key!=='conditions');
for(const book of Object.values(store.regulatedSecondhands??{}))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 SecondhandRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)))throw new Error('Linhas de afectações de bens não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function secondhandBook(draft:Record<string,unknown>):SecondhandBook{return readStore(draft).regulatedSecondhands?.[acquisitionScope(draft)]??{rows:[]};}
export function saveSecondhandBook(draft:Record<string,unknown>,book:SecondhandBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,regulatedSecondhands:{...current.regulatedSecondhands,[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 evaluateSecondhand(row:SecondhandRow,currency:unknown):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',classification:'indeterminate',baseAmount:null,grossMargin:null,principalNet:null,baseDivisorRate:null,vat:null,rate:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,reason});
if(!secondhandTreatments.some(t=>t.id===row.treatment)||!secondhandCategories.some(c=>c.id===row.category))return stop('Identifique revendedor/leilão e categoria do bem;sem regime ou base por defeito.');
if(!/^2026-(0[1-9]|1[0-2])$/.test(row.period)||!['projected','effective'].includes(row.origin)||!validDate(row.operationDate)||row.operationDate.slice(0,7)!==row.period)return stop('Identifique mês2026,data correspondente e natureza efectiva/projectada dos dados.');
const required=[...secondhandConditions,...secondhandCategoryConditions(row.category)];if(required.some(([k])=>row.conditions[k]==='no'))return{...stop('Definição/estatuto deste percurso não correspondem aos factos;rever classificação3(6),sem basezero ou isenção presumida.','not_applicable'),classification:'not_applicable'};
if(required.some(([k])=>row.conditions[k]!=='yes'))return stop('Natureza do bem ou estatuto do operador por esclarecer;desconhecido não é zero.');
if(![row.description,row.operationRef,row.documentRef,row.goodsRef,row.operatorRef,row.categoryRef,row.scope,row.evidence].every(v=>!!v.trim())||!validDate(row.documentDate))return stop('Identifique bem individual,operador,categoria,operação,documento/data,âmbito e factos ou pressupostos expressos;sem certificado/aprovador novo.');
if(row.category==='art'){
if(!['original','print','sculpture','ceramic'].includes(row.artSubtype))return stop('Identifique pintura/desenho original,gravura/estampa/litografia,escultura/estatuária ou cerâmica.');
if(row.artSubtype==='print'&&(!/^\d+$/.test(row.editionCount)||BigInt(row.editionCount)<1n))return stop('Identifique tiragem da gravura/estampa/litografia.');
if(row.artSubtype==='print'&&BigInt(row.editionCount)>200n)return{...stop('Tiragem superior a200 não corresponde a esta definição de arte3(6)b.','not_applicable'),classification:'not_applicable'};
if(row.artSubtype==='ceramic'&&row.ceramicUniqueSigned!=='yes')return stop('Esclareça se a cerâmica é exemplar único executado eassinado pelo artista3(6)b.');
}
if(row.category==='collection'&&(!['postal','scientific','historical'].includes(row.collectionSubtype)||(row.collectionSubtype==='postal'&&row.postalNotCirculating!=='yes')))return stop('Identifique colecção postal não emcirculação/nem destinada acircular,colecções/espécimes científicos ou interesse histórico/arqueológico/paleontológico/etnográfico/numismático3(6)c.');
if(row.category==='antique'){
const age=decimal(row.ageYears);if(age===null)return stop('Identifique idade emanos do bem.');if(age<=100000000n)return{...stop('A definição de antiguidade3(6)d exige mais de100anos.','not_applicable'),classification:'not_applicable'};
}
result.classification='qualified_goods';
if(row.domesticPurchase!=='yes'||!row.sourceRef.trim())return stop('P125identificado;P092/P093 por esclarecer:origem nacional equalidade do fornecedor/comitente comreferência48(1)/49(1).');
if(row.sourceType==='legacy_35_42')return stop('P125identificado;referência histórica aos regimes35/42 não activa margem em2026:Lei10/2025revogou essas subsecções. Conferir situação aplicável sem reactivar regime revogado.');
if(!['private','margin_reseller','exempt_9_12_e'].includes(row.sourceType))return stop('P125identificado;origem elegível particular,revendedor na margem ou transmissão9(12)e não demonstrada. Outro regime permanece por esclarecer.');
if(row.treatment==='reseller_margin'&&row.regimeChoice==='general')return stop('P125identificado;opção pelo regime geral47(1)não aplica esta fórmula de margem.','not_applicable');
if(row.treatment==='reseller_margin'&&row.regimeChoice!=='margin')return stop('P125identificado;esclareça opção margem/regime geral do revendedor47(1).');
if(row.domesticTaxable!=='yes'||row.conditions.regimeConfirmed!=='yes'||row.conditions.compositionConfirmed!=='yes')return stop('P125identificado;base por esclarecer:transmissão interna tributável,natureza/regime elegível ecomposição confirmados;exportação13/48(7)tem percurso próprio.');
if(currency!=='MZN'||row.currency!==currency)return stop('P125identificado;base fora do recorteMZN ou moeda divergente,sem conversão silenciosa.');
if(row.treatment==='reseller_margin'){
const sale=decimal(row.grossSale),purchase=decimal(row.purchasePrice);if(sale===null||purchase===null||!row.purchaseRef.trim())return stop('Identifique contraprestação total devida pelocliente comIVA incluído epreço compra justificado do mesmo bem;desconhecido não é zero.');
const diff=sale-purchase,positive=diff>0n?diff:0n,denominator=116000000n;const whole=(positive*100n+denominator/2n)/denominator;
return{...result,status:'determined',baseAmount:money(whole*1000000n),grossMargin:diff<0n?'-'+money(-diff):money(diff),baseDivisorRate:'16%',reason:`P092:48(2)/(3)/(6),margem individual=${money(sale)}−${money(purchase)}=${diff<0n?'-'+money(-diff):money(diff)}MZN;parcela positiva÷1.16,base arredondada à unidade=${money(whole*1000000n)}MZN. ${diff<0n?'Excesso do preço compra registado neste bem,sem compensar outras transmissões;sem margem positiva tributável.':''} Taxa16% utilizada só no divisor da base17(1)/48(6)b;não há IVA ou dedução calculados. Factura com menção IVA-Bens emSegundaMão,sem discriminarIVA48(8)/(9);registos separados48(10)/(11).`};
}
const invoice=decimal(row.grossInvoice),hammer=decimal(row.hammerPrice),commission=decimal(row.principalCommission),tax=decimal(row.ownVat);
if(invoice===null||hammer===null||commission===null||tax===null||![row.auctionRef,row.principalRef,row.ownVatRef].every(v=>!!v.trim()))return stop('Identifique montante facturado,adjudicação,comissão do comitente eIVApróprio relativo à transmissão,comreferências;IVA desconhecido não é zero.');
if(commission>hammer)return stop('Comissão excede adjudicação;conferir componentes antes de determinar líquido comitente49(3).');
const net=hammer-commission;if(invoice<net+tax)return stop('Facturado inferior ao líquido comitente+IVAindicado;conferir composição,sem base negativa ou zero substituto.');
return{...result,status:'determined',baseAmount:money(invoice-net-tax),principalNet:money(net),reason:`P093:15(2)g/49(2)/(3),líquido comitente=${money(hammer)}−${money(commission)}=${money(net)}MZN;base=${money(invoice)}facturado−${money(net)}líquido−${money(tax)}IVApróprio identificado=${money(invoice-net-tax)}MZN. IVAindicado é componente referenciada,não calculada aqui. Factura IVA-Regime específico devendas emleilão,sem discriminarIVA49(5);relatório ao comitente em5dias úteis49(6)/(7),sem calendário de feriados presumido;contas deterceiros49(8). Sem nova dedução/campo11 ou totaisModeloA.`};
}
function key(draft:Record<string,unknown>,book:SecondhandBook):string{return JSON.stringify({version:secondhandVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function secondhandCurrent(draft:Record<string,unknown>,book:SecondhandBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordSecondhands(draft:Record<string,unknown>,book:SecondhandBook):SecondhandBook{
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:SecondhandCalculation={version:secondhandVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:secondhandSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateSecondhand(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveSecondhandBook(draft,next);return next;
}
export function secondhandReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=secondhandBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,i)=>{const line=result.rows[i],rule=secondhandTreatments.find(t=>t.id===row.treatment);return['IVA mensal',`Bem P125/base${rule?.branch??'margem'} — ${row.period} — ${row.id}`,`${row.description};P125:${line.classification==='qualified_goods'?'Categoria/estatuto identificados':line.classification==='not_applicable'?'Percurso não aplicável':'Indeterminado'};base:${line.baseAmount??'Indeterminada'} ${row.currency};IVA: Indeterminado;${line.reason}`,`${result.opportunity};${result.location};${secondhandCurrent(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'};${rule?.label};categoria ${row.category},${row.categoryRef};critérios ${row.category==='art'?`${row.artSubtype},tiragem ${row.editionCount},cerâmica única/assinada ${row.ceramicUniqueSigned}`:row.category==='collection'?`${row.collectionSubtype},postal fora de circulação ${row.postalNotCirculating}`:row.category==='antique'?`idade ${row.ageYears} anos`:JSON.stringify(row.conditions)};bem ${row.goodsRef};operador ${row.operatorRef};origem ${row.sourceType},${row.sourceRef};operação ${row.operationRef},${row.operationDate};documento ${row.documentRef},${row.documentDate};${row.treatment==='reseller_margin'?`venda comIVA ${row.grossSale};compra ${row.purchasePrice},${row.purchaseRef};margem ${line.grossMargin??'indeterminada'};divisor ${line.baseDivisorRate??'indeterminado'}`:`facturado ${row.grossInvoice};adjudicação ${row.hammerPrice};comissão comitente ${row.principalCommission};líquido ${line.principalNet??'indeterminado'},${row.principalRef};IVAcomponente ${row.ownVat},${row.ownVatRef};leilão ${row.auctionRef}`};âmbito ${row.scope};fundamento ${row.evidence};sem nova dedução/campo11/totaisModeloA.`];});}
catch{return[['IVA mensal','Bens usados/margem','Dados não recuperáveis','Originais preservados;sem base por defeito.']];}
}
+66
View File
@@ -0,0 +1,66 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const serviceLocationVersion='service-territoriality/1';
export const serviceLocationSource='CIVA6(3),6(4)/(5)(a–d),6(6),Lei13/2016PDF7–8/p1426(265–266);AvisoBR89-I,08/06/2017,PDF1 rectifica6(5)c/d:actividades materialmente nacionais e transporte pela distância nacional;Lei10/2025PDF12mantém6(3–6),altera7–9digitais. Recorte2026:regra geral sem regras especiais aplicáveis;imóveis,trabalhos/peritagens em móveis e actividades presenciais pelos factos próprios. Sem taxa/IVA/isenção/dedução/campo11/totaisModeloA;digital e outros6(7)/(8)não classificados por estes percursos.';
export const serviceLocationTreatments=[{id:'general_service',label:'P106 — Regra geral dos serviços',branch:'P106'},{id:'immovable_service',label:'P107 — Serviços relacionados com imóveis',branch:'P107'},{id:'movable_work',label:'P108 — Trabalhos/peritagens em bens móveis',branch:'P108'},{id:'activity_service',label:'P109 — Actividades presenciais e serviços acessórios',branch:'P109'},{id:'transport_service',label:'P110 — Transporte por distância e percurso',branch:'P110'}] as const;
export const serviceLocationConditions=[['serviceSupply','Está identificada uma prestação de serviços e a operação/período correspondentes'],['otherSpecialRulesExcluded','Foi conferida a natureza da operação: não está abrangida neste caso por regime digital ou regras6(7)/(8)que exijam outro percurso']] as const;
export const serviceOwnConditions={
general_service:[['noPlaceException','Não se aplica nenhuma excepção de localização6(4)/(5):imóveis,trabalhos/peritagens em móveis,actividades materiais ou transporte'],['providerEstablishment','Identificada a sede,estabelecimento estável ou domicílio do prestador a partir do qual este serviço é prestado']],
immovable_service:[['propertyRelation','O serviço relaciona-se com o imóvel identificado,incluindo preparação/coordenação de trabalhos imobiliários,peritos ou agentes imobiliários']],
movable_work:[['corporealMovable','São trabalhos em bens móveis corpóreos ou peritagens a eles referentes'],['totalEssential','O local indicado corresponde à execução total ou essencial dos trabalhos/peritagens']],
activity_service:[['activityNature','Serviço artístico,científico,desportivo,recreativo,de ensino ou similar,incluindo organizadores e serviços acessórios dessa actividade'],['materialActivity','A actividade ou serviço acessório tem materialmente lugar no local indicado']],
transport_service:[['transportNature','Prestação de transporte com percurso e distâncias identificados'],['routeCorresponds','Distâncias e pontos de partida/chegada correspondem a este trajecto;ida e volta são trajectos distintos6(6)']],
} 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 serviceLocationConditions[number][0];
export type ServiceLocationRow={id:string;treatment:string;description:string;period:string;origin:'projected'|'effective';operationDate:string;operationRef:string;documentRef:string;documentDate:string;servicePlace:string;placeCountry:string;placeRef:string;totalDistance:string;nationalDistance:string;departure:string;arrival:string;routeRef:string;providerRef:string;providerPlace:string;providerCountry:string;subjectRef:string;scope:string;evidence:string;conditions:Partial<Record<string,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';territory:'national'|'outside'|'partial'|null;baseAmount:null;vat:null;rate:null;reason:string};
export type ServiceLocationCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:ServiceLocationRow[];rows:LineResult[]};
export type ServiceLocationBook={rows:ServiceLocationRow[];result?:ServiceLocationCalculation;history?:ServiceLocationCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{serviceLocations?:Record<string,ServiceLocationBook>};
export function newServiceLocation(id:string):ServiceLocationRow{return{id,treatment:'',description:'',period:'',origin:'projected',operationDate:'',operationRef:'',documentRef:'',documentDate:'',servicePlace:'',placeCountry:'',placeRef:'',totalDistance:'',nationalDistance:'',departure:'',arrival:'',routeRef:'',providerRef:'',providerPlace:'',providerCountry:'',subjectRef:'',scope:'',evidence:'',conditions:{}};}
export function switchServiceTreatment(row:ServiceLocationRow,treatment:string):ServiceLocationRow{return{...row,treatment,conditions:Object.fromEntries(serviceLocationConditions.map(([key])=>[key,row.conditions[key]??'']))};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.serviceLocations!==undefined&&(!store.serviceLocations||typeof store.serviceLocations!=='object'||Array.isArray(store.serviceLocations)))throw new Error('Localizações de serviços não recuperáveis;originais preservados.');
const fields=Object.keys(newServiceLocation('')).filter(key=>key!=='conditions');
for(const book of Object.values(store.serviceLocations??{}))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 ServiceLocationRow]!=='string')||!row.conditions||typeof row.conditions!=='object'||Array.isArray(row.conditions)))throw new Error('Linhas de localização de serviços não recuperáveis;originais preservados,sem substituição por lista vazia.');
return store;
}
export function serviceLocationBook(draft:Record<string,unknown>):ServiceLocationBook{return readStore(draft).serviceLocations?.[acquisitionScope(draft)]??{rows:[]};}
export function saveServiceLocationBook(draft:Record<string,unknown>,book:ServiceLocationBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,serviceLocations:{...current.serviceLocations,[acquisitionScope(draft)]:book}});readStore({...draft,modelo_a_snapshot:encoded});return encoded;}
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 evaluateServiceLocation(row:ServiceLocationRow):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',territory:null,baseAmount:null,vat:null,rate:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,reason});
const rule=serviceLocationTreatments.find(t=>t.id===row.treatment);if(!rule)return stop('Identifique o percurso do serviço;desconhecido não determina território.');
if(!/^2026-(0[1-9]|1[0-2])$/.test(row.period)||!['projected','effective'].includes(row.origin)||!validDate(row.operationDate)||row.operationDate.slice(0,7)!==row.period)return stop('Identifique mês2026,data correspondente e natureza efectiva/projectada dos dados.');
const conditions=[...serviceLocationConditions,...ownServiceConditions(row.treatment)];
if(conditions.some(([key])=>row.conditions[key]==='no'))return stop('Este percurso não se aplica aos factos declarados;rever a regra própria,sem presumir fora do território,isenção ou IVAzero.','not_applicable');
if(conditions.some(([key])=>row.conditions[key]!=='yes'))return stop('Factos ou regra própria por esclarecer;localização indeterminada,não isenção ou IVAzero.');
if(!row.description.trim()||!row.operationRef.trim()||!row.documentRef.trim()||!validDate(row.documentDate)||!row.scope.trim()||!row.evidence.trim())return stop('Identifique serviço/operação,documento/data,âmbito e fundamento factual ou pressupostos expressos;reutilize dados sem certificado/aprovador novo.');
if(row.treatment==='transport_service'){
const parse=(v:string):bigint|null=>/^\d{1,18}(\.\d{1,6})?$/.test(v)?BigInt(v.split('.')[0])*1000000n+BigInt((v.split('.')[1]??'').padEnd(6,'0')):null;
const total=parse(row.totalDistance),national=parse(row.nationalDistance);
if(total===null||total===0n||national===null||national>total||!['MZ','foreign'].includes(row.departure)||!['MZ','foreign'].includes(row.arrival)||!row.routeRef.trim())return stop('Identifique percurso,pontos de partida/chegada e distâncias na mesma unidade,total positiva e nacional entre zero e total;desconhecido não é zero.');
const deemed=row.departure==='MZ'&&row.arrival==='MZ';const covered=deemed?total:national;const territory=covered===0n?'outside':covered===total?'national':'partial';
return{...result,status:'determined',territory,reason:`P110:artigo6(4)d/6(5)d rectificado pelo AvisoBR89-I,08/06/2017,PDF1,e6(6). ${deemed?'Partida e chegada no território nacional:inclui o percurso efectuado fora dos mesmos.':`Parcela nacional:distância ${row.nationalDistance} de ${row.totalDistance},na mesma unidade,sem arredondamento ou apuramento monetário.`} Ida e volta são trajectos distintos:recolher uma linha por trajecto. ${row.origin==='projected'?'Pressupostos expressos.':'Dados efectivos declarados.'} Fora do território não equivale a isenção/IVAzero;sem base,taxa,IVA,dedução/campo11 ou totaisModeloA.`};
}
const general=row.treatment==='general_service';const country=general?row.providerCountry:row.placeCountry;
if(!['MZ','foreign'].includes(country)||!(general?row.providerPlace:row.servicePlace).trim()||!(general?row.providerRef:row.placeRef).trim()||(!general&&!row.subjectRef.trim()))return stop(general?'Identifique sede/EP/domicílio do prestador a partir do qual o serviço é prestado,país e referência;endereço do cliente não substitui esse estabelecimento.':'Identifique local,país,referência e imóvel/bens/actividade a que respeita;endereço do cliente ou sede do prestador não substituem esses factos.');
const territory=country==='MZ'?'national':'outside';const clause=general?'6(3)':`6(${territory==='national'?'5':'4'})(${row.treatment==='immovable_service'?'a':row.treatment==='movable_work'?'b':'c'})`;
const fact=general?'estabelecimento do prestador a partir do qual o serviço é prestado':row.treatment==='immovable_service'?'local do imóvel':row.treatment==='movable_work'?'local de execução total ou essencial dos trabalhos/peritagens':'local material da actividade ou serviço acessório';
return{...result,status:'determined',territory,reason:`${rule.branch}:artigo${clause},${fact} ${territory==='national'?'emMoçambique':'fora deMoçambique'},${row.origin==='projected'?'sob pressupostos expressos':'segundo dados efectivos declarados'}. ${general?'Regras especiais conferidas como não aplicáveis.':'Regra territorial própria,independente da sede nacional ou estrangeira do prestador.'} Fora deste âmbito não equivale a isenção/IVAzero;não calcula base,taxa,IVA,dedução/campo11 ou totaisModeloA.`};
}
function key(draft:Record<string,unknown>,book:ServiceLocationBook):string{return JSON.stringify({version:serviceLocationVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},rows:book.rows});}
export function serviceLocationCurrent(draft:Record<string,unknown>,book:ServiceLocationBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordServiceLocations(draft:Record<string,unknown>,book:ServiceLocationBook):ServiceLocationBook{
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:ServiceLocationCalculation={version:serviceLocationVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:serviceLocationSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateServiceLocation(row))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveServiceLocationBook(draft,next);return next;
}
export function serviceLocationReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=serviceLocationBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Localização ${serviceLocationTreatments.find(t=>t.id===row.treatment)?.branch??'serviço'} — ${row.period} — ${row.id}`,`${row.description};classificação territorial: ${result.rows[index].territory==='national'?'Moçambique':result.rows[index].territory==='outside'?'Fora do território nacional':result.rows[index].territory==='partial'?'Parcela nacional do transporte':'Indeterminada'};IVA: Indeterminado;${result.rows[index].reason}`,`${result.opportunity};${result.location};${serviceLocationCurrent(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'};${serviceLocationTreatments.find(t=>t.id===row.treatment)?.label??'Percurso por indicar'};operação ${row.operationRef},${row.operationDate};${row.treatment==='transport_service'?`trajecto ${row.routeRef};partida ${row.departure};chegada ${row.arrival};distâncias nacional/total ${row.nationalDistance}/${row.totalDistance}`:row.treatment==='general_service'?`estabelecimento prestador ${row.providerPlace},${row.providerCountry};referência ${row.providerRef}`:`local ${row.servicePlace},${row.placeCountry};referência ${row.placeRef};imóvel/bens/actividade ${row.subjectRef}`};âmbito ${row.scope};documento ${row.documentRef},${row.documentDate};condições ${[...serviceLocationConditions,...ownServiceConditions(row.treatment)].map(([key,label])=>label+': '+(row.conditions[key]==='yes'?'Sim':row.conditions[key]==='no'?'Não':'Por indicar')).join('; ')};fundamento ${row.evidence};não determina isenção/IVA/campo11/totaisModeloA.`]);}
catch{return[['IVA mensal','Localização de serviços','Dados não recuperáveis','Originais preservados;sem classificar por defeito.']];}
}
+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.']];}
}
+64
View File
@@ -0,0 +1,64 @@
import {acquisitionScope,readAcquisitionStore} from './iva-acquisitions.ts';
export const valueReviewVersion='value-review-base/1';
export const valueReviewSource='CIVA republicado Lei13/2016,15(7),PDF14/p1426(272):para efeitos15(1),quando a contraprestação é inferior à resultante dos preços correntes ou normais de venda à porta da fábrica,por grosso ou a retalho,ou aos preços correntes/normais do serviço,tendo em conta a natureza das transmissões,a Administração Tributária pode proceder à correcção. Lei22/2022PDF3mantém15(7);Lei10/2025não altera15. Recorte2026/MZN;comparação não exerce o poder da AT,nem substitui automaticamente a contraprestação pelo valor de referência. Sem incidência,taxa,IVA,dedução/campo11,regularizações ou totaisModeloA.';
export const valueReviewTreatments=[{id:'price_comparison',label:'Comparar sem correcção automática'},{id:'referenced_correction',label:'Registar correcção referenciada / cenário condicionado'}] as const;
export const priceContexts=[{id:'factory',label:'Venda à porta da fábrica'},{id:'wholesale',label:'Venda por grosso'},{id:'retail',label:'Venda a retalho'},{id:'service',label:'Preço corrente ou normal do serviço'}] as const;
export const valueReviewConditions=[
['taxableOperation','A operação e a contraprestação para efeitos15(1)estão identificadas'],
['referenceCorresponds','O preço corrente ou normal e o contexto escolhido correspondem à natureza desta transmissão ou serviço,no período e âmbito identificados'],
['netComposition','Os montantes comparados têm composição equivalente,sem próprioIVA,com inclusões/exclusões aplicáveis15(5)/(6)consideradas'],
] as const;
type Choice=''|'yes'|'no';type Condition=typeof valueReviewConditions[number][0];
export type ValueReviewRow={id:string;treatment:string;priceContext:string;description:string;period:string;origin:'projected'|'effective';currency:string;operationRef:string;documentRef:string;documentDate:string;declaredAmount:string;referenceAmount:string;referenceRef:string;referenceScope:string;compositionRef:string;evidence:string;correctedAmount:string;correctionRef:string;correctionScope:string;correctionDate:string;correctionApplies:Choice;conditions:Partial<Record<Condition,Choice>>};
type LineResult={id:string;status:'determined'|'not_applicable'|'indeterminate';baseAmount:string|null;vat:null;rate:null;comparison:'below'|'not_below'|null;reason:string};
export type ValueReviewCalculation={version:string;revision:number;calculatedAt:string;opportunity:string;location:string;sourceKey:string;source:string;inputs:ValueReviewRow[];rows:LineResult[]};
export type ValueReviewBook={rows:ValueReviewRow[];result?:ValueReviewCalculation;history?:ValueReviewCalculation[]};
type Store=ReturnType<typeof readAcquisitionStore>&{valueReviews?:Record<string,ValueReviewBook>};
export function newValueReview(id:string,currency:string):ValueReviewRow{return{id,treatment:'',priceContext:'',description:'',period:'',origin:'projected',currency,operationRef:'',documentRef:'',documentDate:'',declaredAmount:'',referenceAmount:'',referenceRef:'',referenceScope:'',compositionRef:'',evidence:'',correctedAmount:'',correctionRef:'',correctionScope:'',correctionDate:'',correctionApplies:'',conditions:{}};}
export function switchValueReview(row:ValueReviewRow,treatment:string):ValueReviewRow{return{...row,treatment,correctionApplies:''};}
export function switchPriceContext(row:ValueReviewRow,priceContext:string):ValueReviewRow{return{...row,priceContext,conditions:{...row.conditions,referenceCorresponds:''},correctionApplies:''};}
export function switchValueOrigin(row:ValueReviewRow,origin:ValueReviewRow['origin']):ValueReviewRow{return{...row,origin,correctionApplies:''};}
function readStore(draft:Record<string,unknown>):Store{
const store=readAcquisitionStore(draft.modelo_a_snapshot) as Store;
if(store.valueReviews!==undefined&&(!store.valueReviews||typeof store.valueReviews!=='object'||Array.isArray(store.valueReviews)))throw new Error('Bases de contraprestação não recuperáveis;originais preservados.');
const fields=Object.keys(newValueReview('','')).filter(key=>key!=='conditions');
for(const book of Object.values(store.valueReviews??{}))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 ValueReviewRow]!=='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 valueReviewBook(draft:Record<string,unknown>):ValueReviewBook{return readStore(draft).valueReviews?.[acquisitionScope(draft)]??{rows:[]};}
export function saveValueReviewBook(draft:Record<string,unknown>,book:ValueReviewBook):string{const current=readStore(draft),encoded=JSON.stringify({...current,valueReviews:{...current.valueReviews,[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 evaluateValueReview(row:ValueReviewRow,currency:unknown):LineResult{
const result:LineResult={id:row.id,status:'indeterminate',baseAmount:null,vat:null,rate:null,comparison:null,reason:''};const stop=(reason:string,status:LineResult['status']='indeterminate')=>({...result,status,reason});
if(!valueReviewTreatments.some(item=>item.id===row.treatment)||!priceContexts.some(item=>item.id===row.priceContext))return stop('Identifique o percurso e o contexto do preço de referência;desconhecido não permite presumir correcçã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 failed=valueReviewConditions.filter(([key])=>row.conditions[key]==='no');if(failed.length)return stop('Não se aplica esta comparação: '+failed.map(([,label])=>label).join('; ')+'. Não é isenção nem IVA zero.','not_applicable');
if(valueReviewConditions.some(([key])=>row.conditions[key]!=='yes'))return stop('Confirme as condições próprias da comparação;desconhecido não é zero,não aplicável ou correcção.');
if(!row.description.trim()||!row.operationRef.trim()||!row.documentRef.trim()||!validDate(row.documentDate)||!row.referenceRef.trim()||!row.referenceScope.trim()||!row.compositionRef.trim()||!row.evidence.trim())return stop('Identifique operação,documento/data,preço corrente/normal,referência/âmbito e composição,ou pressupostos expressos;sem avaliação automática/certificado/aprovador novo.');
const declared=decimal(row.declaredAmount),reference=decimal(row.referenceAmount);if(declared===null||reference===null)return stop('Indique contraprestação e preço de referência comparáveis;valor desconhecido ou inválido não é zero.');
result.comparison=declared<reference?'below':'not_below';
const comparison=declared<reference?`Contraprestação ${money(declared)} inferior à referência ${money(reference)} por ${money(reference-declared)}MZN;AT pode proceder à correcção,sem automatismo.`:`Contraprestação ${money(declared)} não inferior à referência ${money(reference)}MZN;não se demonstra este pressuposto15(7).`;
if(row.treatment==='price_comparison')return{...result,status:'determined',baseAmount:money(declared),reason:comparison+' Contraprestação declarada conservada como base neste recorte,sem correcção pelo portal;IVA/taxa,dedução/campo11,regularizações e totaisModeloA não determinados.'};
if(declared>=reference)return stop(comparison+' A correcção deste percurso15(7)não é aplicada. Registo e referências conservados.','not_applicable');
if(row.correctionApplies==='no')return stop(comparison+' A correcção referenciada não abrange esta operação/período/condições;sem aplicação automática.','not_applicable');
if(row.correctionApplies!=='yes'||!row.correctionRef.trim()||!row.correctionScope.trim()||!validDate(row.correctionDate))return stop(comparison+' Identifique referência,data e âmbito da correcção AT aplicável ou pressuposto expresso do cenário condicionado;comparar não substitui uma correcção.');
const corrected=decimal(row.correctedAmount);if(corrected===null)return stop(comparison+' Indique o montante da correcção referenciada ou pressuposto condicionado;sem usar automaticamente o maior valor ou a referência.');
return{...result,status:'determined',baseAmount:money(corrected),reason:comparison+` ${row.origin==='projected'?'Cenário condicionado à correcção expressamente assumida,não decisão AT concedida':'Correcção AT nos dados efectivos declarados,com referência/data/âmbito identificados'}:base ${money(corrected)}MZN. Montante da referência não substituído automaticamente. Sem IVA/taxa,dedução/campo11,regularizações ou totaisModeloA.`};
}
function key(draft:Record<string,unknown>,book:ValueReviewBook):string{return JSON.stringify({version:valueReviewVersion,scope:acquisitionScope(draft),location:draft.selection_labels??{},currency:draft.currency,rows:book.rows});}
export function valueReviewCurrent(draft:Record<string,unknown>,book:ValueReviewBook):boolean{return!!book.result&&book.result.sourceKey===key(draft,book);}
export function recordValueReviews(draft:Record<string,unknown>,book:ValueReviewBook):ValueReviewBook{
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:ValueReviewCalculation={version:valueReviewVersion,revision:(book.result?.revision??0)+1,calculatedAt:new Date().toISOString(),opportunity:acquisitionScope(draft),location:JSON.stringify(draft.selection_labels??{}),sourceKey:key(draft,book),source:valueReviewSource,inputs:structuredClone(book.rows),rows:book.rows.map(row=>evaluateValueReview(row,draft.currency))};
const next={...book,result,history:[...(book.history??[]),...(book.result?[book.result]:[])]};saveValueReviewBook(draft,next);return next;
}
export function valueReviewReportRows(draft:Record<string,unknown>):Array<[string,string,string,string]>{
try{const book=valueReviewBook(draft),result=book.result;if(!result)return[];return result.inputs.map((row,index)=>['IVA mensal',`Base P103 — ${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};${valueReviewCurrent(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'};${valueReviewTreatments.find(t=>t.id===row.treatment)?.label??'Percurso por indicar'};contexto ${priceContexts.find(t=>t.id===row.priceContext)?.label??'Por indicar'};operação ${row.operationRef};contraprestação ${row.declaredAmount};preço referência ${row.referenceAmount},${row.referenceRef};âmbito ${row.referenceScope};${row.treatment==='referenced_correction'?`correcção ${row.correctedAmount},referência ${row.correctionRef},data ${row.correctionDate},âmbito ${row.correctionScope},aplica:${row.correctionApplies==='yes'?'Sim':row.correctionApplies==='no'?'Não':'Por indicar'}`:'Sem correcção automática'};composição ${row.compositionRef};documento ${row.documentRef},${row.documentDate};condições ${valueReviewConditions.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','Comparação/correcção da contraprestação','Dados não recuperáveis','Originais preservados;sem substituir por zero.']];}
}
+26
View File
@@ -8,6 +8,19 @@ 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 { 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 { goodsLocationReportRows } from './iva-goods-location.ts';
import { serviceLocationReportRows } from './iva-service-location.ts';
import { listedServiceReportRows } from './iva-listed-services.ts';
import { reducedBaseReportRows } from './iva-reduced-bases.ts';
import { ownNameReportRows } from './iva-own-name.ts';
import { goodsAllocationReportRows } from './iva-goods-allocation.ts';
import { secondhandReportRows } from './iva-secondhand.ts';
import { offerPreparationReportRows } from './iva-offer-preparations.ts';
import { salesReportRows } from './iva-operations.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
@@ -626,6 +639,19 @@ export function buildProjectDossierRows(
rows.push(...publicBaseReportRows(draft));
rows.push(...commissionBaseReportRows(draft));
rows.push(...actSaleReportRows(draft));
rows.push(...fuelBaseReportRows(draft));
rows.push(...noncashBaseReportRows(draft));
rows.push(...compositionReportRows(draft));
rows.push(...exclusionReportRows(draft));
rows.push(...valueReviewReportRows(draft));
rows.push(...serviceNormalReportRows(draft));
rows.push(...goodsLocationReportRows(draft));
rows.push(...serviceLocationReportRows(draft));
rows.push(...listedServiceReportRows(draft));
rows.push(...reducedBaseReportRows(draft));
rows.push(...ownNameReportRows(draft));
rows.push(...goodsAllocationReportRows(draft));
rows.push(...secondhandReportRows(draft));
rows.push(...offerPreparationReportRows(draft));
const operationRows = salesReportRows(draft);
rows.push(...operationRows);
@@ -0,0 +1,58 @@
<?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 IvaCompositionBaseDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_composition_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-g7f-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:344', $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['considerationCompositions']['opportunity:344'];
$this->assertCount(1, $book['rows']);
$this->assertCount(2, $book['rows'][0]['parts']);
$this->assertSame(['tax_component','accessory_component'], array_column($book['rows'][0]['parts'], 'treatment'));
$this->assertSame(['1150.60'], array_column($book['result']['rows'], 'baseAmount'));
$this->assertSame(['determined'], array_column($book['result']['rows'], 'status'));
$this->assertSame([null], array_column($book['result']['rows'], 'vat'));
$this->assertSame([null], array_column($book['result']['rows'], 'rate'));
$this->assertSame('1000.25', $book['rows'][0]['initialAmount']);
$this->assertSame(['100.10','50.25'], array_column($book['rows'][0]['parts'], 'amount'));
$this->assertSame(['no','no'], array_column($book['rows'][0]['parts'], 'included'));
$this->assertSame(['yes','yes'], array_column($book['rows'][0]['parts'], 'ownVatExcluded'));
$this->assertStringContainsString('operação A', $book['rows'][0]['operationRef']);
$this->assertStringContainsString('próprioIVA', $book['rows'][0]['initialRef']);
$this->assertStringContainsString('referência tax_component', $book['rows'][0]['parts'][0]['reference']);
$this->assertStringContainsString('cliente', $book['rows'][0]['parts'][1]['description']);
$this->assertStringContainsString('15(5)', $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-g7f-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, ['considerationCompositions' => 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-g7f-composition-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
@@ -0,0 +1,61 @@
<?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 IvaExclusionBaseDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_exclusion_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-g7g-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:345', $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['considerationExclusions']['opportunity:345'];
$this->assertCount(1, $book['rows']);
$this->assertCount(4, $book['rows'][0]['parts']);
$this->assertSame(['judicial_indemnity','granted_discount','third_party_payment','returnable_packaging'], array_column($book['rows'][0]['parts'], 'treatment'));
$this->assertSame(['799.70'], array_column($book['result']['rows'], 'baseAmount'));
$this->assertSame(['determined'], array_column($book['result']['rows'], 'status'));
$this->assertSame([null], array_column($book['result']['rows'], 'vat'));
$this->assertSame([null], array_column($book['result']['rows'], 'rate'));
$this->assertSame('1000.25', $book['rows'][0]['initialAmount']);
$this->assertSame(['100.10','50.25','30.15','20.05'], array_column($book['rows'][0]['parts'], 'amount'));
$this->assertSame(['yes','yes','yes','yes'], array_column($book['rows'][0]['parts'], 'included'));
$this->assertSame('yes', $book['rows'][0]['parts'][0]['conditions']['judicialDeclaration']);
$this->assertSame('yes', $book['rows'][0]['parts'][1]['conditions']['granted']);
$this->assertSame('yes', $book['rows'][0]['parts'][2]['conditions']['thirdPartyAccounts']);
$this->assertSame('yes', $book['rows'][0]['parts'][3]['conditions']['returnMention']);
$this->assertStringContainsString('contas de terceiros A', $book['rows'][0]['parts'][2]['accountRef']);
$this->assertStringContainsString('adquirente B', $book['rows'][0]['parts'][2]['beneficiaryRef']);
$this->assertStringContainsString('devolução acordada', $book['rows'][0]['parts'][3]['documentExcerpt']);
$this->assertStringContainsString('declaração judicial', $book['rows'][0]['parts'][0]['reference']);
$this->assertStringContainsString('15(6)', $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-g7g-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, ['considerationExclusions' => 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-g7g-exclusions-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
+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));
}
}
@@ -0,0 +1,49 @@
<?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 IvaGoodsAllocationDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_goods_allocation_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-goods-allocation.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:353', $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['regulatedGoodsAllocations']['opportunity:353'];
$this->assertCount(4, $book['rows']);
$this->assertSame(['permanent_private_goods','free_goods_transfer','exempt_sector_goods','fixed_asset_20a'],array_column($book['rows'],'treatment'));
$this->assertSame(['1000.25','800.15','1000.25','800.15'],array_column($book['result']['rows'],'baseAmount'));
$this->assertSame(array_fill(0,4,'assimilated_goods'),array_column($book['result']['rows'],'classification'));
foreach ($book['result']['rows'] as $row) {
$this->assertNull($row['vat']);$this->assertNull($row['rate']);
}
$this->assertSame($book['rows'], $book['result']['inputs']);
$this->assertCount(1, $book['history']);
$this->assertSame('1000.25',$book['history'][0]['rows'][0]['baseAmount']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-goods-allocation-preserved.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, ['regulatedGoodsAllocations' => 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-goods-allocation-20261025/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
@@ -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 IvaGoodsLocationDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_goods_locations_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-g8a-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:348', $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['goodsLocations']['opportunity:348'];
$this->assertCount(3, $book['rows']);
$this->assertSame(['goods_with_transport','goods_without_transport','goods_before_import'], array_column($book['rows'], 'treatment'));
$this->assertSame(['national','outside','national'], array_column($book['result']['rows'], 'territory'));
$this->assertSame(['determined','determined','determined'], array_column($book['result']['rows'], 'status'));
$this->assertSame([null,null,null], array_column($book['result']['rows'], 'baseAmount'));
$this->assertSame([null,null,null], array_column($book['result']['rows'], 'vat'));
$this->assertSame([null,null,null], array_column($book['result']['rows'], 'rate'));
$this->assertSame(['MZ','foreign','foreign'], array_column($book['rows'], 'placeCountry'));
$this->assertSame('2026-12-12', $book['rows'][0]['operationDate']);
$this->assertSame('yes', $book['rows'][2]['conditions']['beforeImport']);
$this->assertStringContainsString('importação nacional A', $book['rows'][2]['importRef']);
$this->assertStringContainsString('importador A', $book['rows'][2]['chainRef']);
$this->assertStringContainsString('local físico', $book['rows'][0]['goodsPlace']);
$this->assertStringContainsString('não equivale a isenção', $book['result']['rows'][1]['reason']);
$this->assertStringContainsString('6(1)/(2)', $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-g8a-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, ['goodsLocations' => 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-g8a-goods-location-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
@@ -0,0 +1,49 @@
<?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 IvaListedServicesDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_listed_services_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-g9-nondigital.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:350', $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['listedServices']['opportunity:350'];
$this->assertCount(30, $book['rows']);
$this->assertCount(10,array_unique(array_column($book['rows'],'treatment')));
$this->assertSame(array_merge(...array_fill(0,10,['national','outside','national'])),array_column($book['result']['rows'],'territory'));
$this->assertSame(array_merge(...array_fill(0,10,['acquirer','outside','provider'])),array_column($book['result']['rows'],'responsible'));
foreach ($book['result']['rows'] as $row) {
$this->assertNull($row['baseAmount']);$this->assertNull($row['vat']);$this->assertNull($row['rate']);
}
$this->assertSame($book['rows'], $book['result']['inputs']);
$this->assertCount(1, $book['history']);
$this->assertNull($book['history'][0]['rows'][0]['baseAmount']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-g9-nondigital-preserved.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, ['listedServices' => 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-g9-nondigital-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
+56
View File
@@ -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 IvaNoncashBaseDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_noncash_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-g7e-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:343', $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['noncashBases']['opportunity:343'];
$this->assertCount(2, $book['rows']);
$this->assertSame(['noncash_only','cash_and_noncash'], array_column($book['rows'], 'treatment'));
$this->assertSame(['2200.50','2700.75'], 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('500.25', $book['rows'][0]['cashAmount']);
$this->assertSame('2200.50', $book['rows'][0]['normalValue']);
$this->assertStringContainsString('parte monetária', $book['rows'][0]['cashRef']);
$this->assertStringContainsString('bens/serviços B', $book['rows'][0]['exchangeDescription']);
$this->assertStringContainsString('acordo A', $book['rows'][0]['agreementRef']);
$this->assertStringContainsString('fundamento A', $book['rows'][0]['valuationRef']);
$this->assertStringContainsString('retalho', $book['rows'][0]['valuationScope']);
$this->assertStringContainsString('15(3)/(4)', $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-g7e-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, ['noncashBases' => 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-g7e-noncash-base-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
+49
View File
@@ -0,0 +1,49 @@
<?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 IvaOwnNameDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_own_name_circuits_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-g10-own-name.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:352', $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['ownNames']['opportunity:352'];
$this->assertCount(4, $book['rows']);
$this->assertSame(['goods_sale_commission','goods_purchase_commission','service_sale_mandate','service_purchase_mandate'],array_column($book['rows'],'treatment'));
foreach ($book['result']['rows'] as $row) {
$this->assertCount(2,$row['legs']);
$this->assertSame(['1000.25','1100.75'],array_column($row['legs'],'consideration'));
$this->assertNull($row['baseAmount']);$this->assertNull($row['vat']);$this->assertNull($row['rate']);
}
$this->assertSame($book['rows'], $book['result']['inputs']);
$this->assertCount(1, $book['history']);
$this->assertSame('1000.25',$book['history'][0]['rows'][0]['legs'][0]['consideration']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-g10-own-name-preserved.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, ['ownNames' => 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-g10-own-name-20261025/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
@@ -0,0 +1,49 @@
<?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 IvaReducedBasesDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_reduced_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-g7-reduced.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:351', $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['regulatedReducedBases']['opportunity:351'];
$this->assertCount(4, $book['rows']);
$this->assertSame(['regulated_energy','aeronautical_fees','public_works','public_water'],array_column($book['rows'],'treatment'));
$this->assertSame(['620.155','850.2125','400.10','750.1875'],array_column($book['result']['rows'],'baseAmount'));
$this->assertSame(['62%','85%','40%','75%'],array_column($book['result']['rows'],'deductionProportion'));
foreach ($book['result']['rows'] as $row) {
$this->assertNull($row['vat']);$this->assertNull($row['rate']);
}
$this->assertSame($book['rows'], $book['result']['inputs']);
$this->assertCount(1, $book['history']);
$this->assertSame('620.155',$book['history'][0]['rows'][0]['baseAmount']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-g7-reduced-preserved.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, ['regulatedReducedBases' => 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-g7-reduced-bases-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
+49
View File
@@ -0,0 +1,49 @@
<?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 IvaSecondhandDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_secondhand_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-secondhand.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:354', $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['regulatedSecondhands']['opportunity:354'];
$this->assertCount(8, $book['rows']);
$this->assertSame(array_merge(array_fill(0,4,'reseller_margin'),array_fill(0,4,'auction_margin')),array_column($book['rows'],'treatment'));
$this->assertSame(array_merge(array_fill(0,4,'138.00'),array_fill(0,4,'344.83')),array_column($book['result']['rows'],'baseAmount'));
$this->assertSame(array_fill(0,8,'qualified_goods'),array_column($book['result']['rows'],'classification'));
foreach ($book['result']['rows'] as $row) {
$this->assertNull($row['vat']);$this->assertNull($row['rate']);
}
$this->assertSame($book['rows'], $book['result']['inputs']);
$this->assertCount(1, $book['history']);
$this->assertSame('138.00',$book['history'][0]['rows'][0]['baseAmount']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-secondhand-preserved.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, ['regulatedSecondhands' => 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-secondhand-20261025/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
@@ -0,0 +1,48 @@
<?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 IvaServiceLocationDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_service_locations_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-g8-services.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:349', $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['serviceLocations']['opportunity:349'];
$this->assertCount(10, $book['rows']);
$this->assertSame(['general_service','general_service','immovable_service','immovable_service','movable_work','movable_work','activity_service','activity_service','transport_service','transport_service'],array_column($book['rows'],'treatment'));
$this->assertSame(['national','outside','national','outside','national','outside','national','outside','national','outside'],array_column($book['result']['rows'],'territory'));
foreach ($book['result']['rows'] as $row) {
$this->assertNull($row['baseAmount']);$this->assertNull($row['vat']);$this->assertNull($row['rate']);
}
$this->assertSame($book['rows'], $book['result']['inputs']);
$this->assertCount(1, $book['history']);
$this->assertNull($book['history'][0]['rows'][0]['baseAmount']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-g8-services-preserved.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, ['serviceLocations' => 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-g8-services-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
@@ -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));
}
}
+60
View File
@@ -0,0 +1,60 @@
<?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 IvaValueReviewDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_value_reviews_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-g7h-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:346', $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['valueReviews']['opportunity:346'];
$this->assertCount(2, $book['rows']);
$this->assertSame(['price_comparison','referenced_correction'], array_column($book['rows'], 'treatment'));
$this->assertSame(['1000.25','1400.75'], 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(['below','below'], array_column($book['result']['rows'], 'comparison'));
$this->assertSame('1000.25', $book['rows'][0]['declaredAmount']);
$this->assertSame('1500.50', $book['rows'][0]['referenceAmount']);
$this->assertSame('1400.75', $book['rows'][1]['correctedAmount']);
$this->assertSame('projected', $book['rows'][1]['origin']);
$this->assertSame('yes', $book['rows'][1]['correctionApplies']);
$this->assertSame('retail', $book['rows'][1]['priceContext']);
$this->assertSame('2026-12-20', $book['rows'][1]['correctionDate']);
$this->assertStringContainsString('condicionado correcção A', $book['rows'][1]['correctionRef']);
$this->assertStringContainsString('dezembro2026', $book['rows'][1]['correctionScope']);
$this->assertStringContainsString('Cenário condicionado', $book['result']['rows'][1]['reason']);
$this->assertStringContainsString('15(7)', $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-g7h-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, ['valueReviews' => 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-g7h-value-review-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
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More