feat: implement opportunity-scoped Modelo A acquisitions in QA

This commit is contained in:
2026-10-24 12:13:57 +02:00
parent 355656b5c8
commit d18ff0f049
14 changed files with 731 additions and 4 deletions
@@ -0,0 +1,69 @@
<?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 ModeloAAcquisitionsDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_ui_calculated_payload_is_saved_recovered_and_used_as_the_report_source(): void
{
$identity = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('simulator_fiscal_delta_20261021_test', $identity->name);
$this->assertSame(55441, (int) $identity->port);
$this->actingAs(User::factory()->create(['email_verified_at' => now()]));
$path = getenv('IVA_ACQUISITION_UI_INPUT') ?: base_path('tests/frontend/fixtures/modelo-a-acquisitions.json');
$draft = json_decode(file_get_contents($path), true, flags: JSON_THROW_ON_ERROR);
$draft['purpose'] = 'simulate_only';
$created = $this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => [], 'economic_snapshot' => $draft], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated();
$recovered = $this->getJson('/api/v1/simulation-drafts/'.$created->json('data.id'))->assertOk()->json('data.economic_snapshot');
$this->assertSame($draft['modelo_a_snapshot'], $recovered['modelo_a_snapshot']);
$this->assertSame($draft['context_opportunity'], $recovered['context_opportunity']);
if (getenv('IVA_ACQUISITION_UI_RECOVERED_OUT')) file_put_contents(getenv('IVA_ACQUISITION_UI_RECOVERED_OUT'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
public function test_calculated_acquisitions_round_trip_in_private_draft_and_other_owner_cannot_read(): void
{
$identity = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('simulator_fiscal_delta_20261021_test', $identity->name);
$this->assertSame(55441, (int) $identity->port);
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$fingerprint = DB::selectOne("select md5(string_agg(row_to_json(r)::text,E'\\n' order by id)) as hash from simulation_tax_rule_versions r")->hash;
$actor = User::factory()->create(['email_verified_at' => now()]);
$this->actingAs($actor);
$draft = json_decode(file_get_contents(base_path('tests/frontend/fixtures/modelo-a-acquisitions.json')), true, flags: JSON_THROW_ON_ERROR);
$draft['purpose'] = 'simulate_only';
$created = $this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => [], 'economic_snapshot' => $draft], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated();
$id = $created->json('data.id');
$this->assertNotEmpty($id);
$saved = $this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk();
$economic = $saved->json('data.economic_snapshot');
$this->assertSame($draft['modelo_a_snapshot'], $economic['modelo_a_snapshot']);
$store = json_decode($economic['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$first = $store['books']['opportunity:309'];
$this->assertSame('144.0048', $first['result']['periods'][0]['fields'][17]);
$store['books']['opportunity:310'] = $first;
$store['books']['opportunity:310']['rows'][0]['net'] = '200';
$store['books']['opportunity:310']['rows'][0]['vat'] = '32';
$economic['context_opportunity'] = 'opportunity:310';
$economic['modelo_a_snapshot'] = json_encode($store, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
$this->putJson('/api/v1/simulation-drafts/'.$id, ['personal_snapshot' => [], 'economic_snapshot' => $economic], ['If-Match' => $saved->headers->get('ETag')])->assertOk();
$recovered = $this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk()->json('data.economic_snapshot');
$this->assertSame($economic['modelo_a_snapshot'], $recovered['modelo_a_snapshot']);
$this->assertSame($first, json_decode($recovered['modelo_a_snapshot'], true)['books']['opportunity:309']);
if (getenv('IVA_ACQUISITION_RECOVERED_OUT')) {
// The original calculated opportunity, recovered through the real private API, is the report source.
$economic['context_opportunity'] = 'opportunity:309';
file_put_contents(getenv('IVA_ACQUISITION_RECOVERED_OUT'), json_encode($economic, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
$this->actingAs(User::factory()->create(['email_verified_at' => now()]));
$this->getJson('/api/v1/simulation-drafts/'.$id)->assertNotFound();
$this->assertSame($fingerprint, DB::selectOne("select md5(string_agg(row_to_json(r)::text,E'\\n' order by id)) as hash from simulation_tax_rule_versions r")->hash);
}
}
@@ -0,0 +1,15 @@
{
"project_title": "SYNTHETIC QA — aquisições e apuramento parcial Modelo A",
"currency": "MZN",
"context_opportunity": "opportunity:309",
"context_applicability_snapshot": "{\"version\":1,\"context_revision\":13,\"consumer_opportunity\":\"opportunity:309\",\"opportunity_choices\":[{\"opportunity\":{\"key\":\"opportunity:309\",\"title\":\"SYNTHETIC QA — segunda oportunidade Manica\"}}],\"path\":{\"steps\":[]}}",
"business_plan_snapshot": "{\"version\":17,\"plan\":{\"openingCash\":\"0\",\"monthlyCollections\":\"0\",\"monthlyVariableCostPayments\":\"0\",\"monthlyInventoryPurchases\":\"0\",\"monthlyOperatingExpenses\":\"0\",\"monthlyOperatingPayments\":\"0\",\"monthlyPayrollExpense\":\"0\",\"monthlyPayrollPayments\":\"0\",\"assetInvestment\":\"0\",\"inventory\":\"0\",\"receivables\":\"0\",\"payables\":\"0\",\"equity\":\"0\",\"shareholderLoans\":\"0\",\"bankLoanProceeds\":\"0\",\"grants\":\"0\",\"assetDepreciation\":\"0\",\"monthlyInterestExpense\":\"0\",\"monthlyInterestPayment\":\"0\",\"monthlyPrincipalRepayment\":\"0\",\"currency\":\"MZN\",\"periods\":4,\"depreciationLifeMonths\":60,\"products\":[{\"label\":\"SYNTHETIC QA\",\"monthlyUnits\":\"1\",\"unitPrice\":\"1000.03\",\"unitVariableCost\":\"0\",\"monthlyUnitsByPeriod\":[\"1\",\"2\",\"0\",\"\"]}],\"inventoryPurchaseLeadMonths\":0,\"inventoryPurchaseSchedule\":null,\"useInventoryPurchaseSchedule\":false,\"useProductInventorySchedule\":false,\"useSupplierPaymentTerms\":false,\"monthlyVariableCostPaymentsByPeriod\":null,\"salesCollectionLagMonths\":null,\"salesCollectionPercent\":\"100\",\"openingReceivablesCollectionMonth\":null,\"openingReceivablesCollectionPercent\":\"100\",\"openingReceivablesInstallments\":[],\"openingPayablesInstallments\":[],\"salesRecoverySchedule\":[]}}",
"monthly_iva_settings": "{\"start\":\"2026-01\",\"basis\":\"net\",\"declared\":true,\"auto\":false}",
"monthly_iva_snapshot": "{\"input\":{\"scenario_kind\":\"fiscal_rule_published\",\"monthly_sales\":[{\"date\":\"2026-01-01\",\"amount\":\"1000.03\"},{\"date\":\"2026-02-01\",\"amount\":\"2000.06\"},{\"date\":\"2026-03-01\",\"amount\":\"0.00\"},{\"date\":\"2026-04-01\",\"amount\":null}],\"sales_vat_basis\":\"net\",\"currency\":\"MZN\",\"scope_declared\":true},\"execution\":{\"id\":\"06566910-9672-4176-804d-aad8350417cb\",\"status\":\"completed\",\"version_no\":2,\"result_snapshot\":{\"contract_version\":1,\"scenario_kind\":\"fiscal_rule_published\",\"base\":null,\"currency\":\"MZN\",\"indicative_total\":null,\"legal_interpretation\":false,\"formula_version\":\"investmoz.tax.v1\",\"context\":{\"reference_date\":\"2026-01-01\",\"currency\":\"MZN\",\"currency_fraction_digits\":2,\"scenario_id\":\"61000100-0000-4000-8000-000000000099\",\"scenario_version\":1,\"engine_version\":\"fiscal-published-v1\",\"ruleset_version\":\"IVA-GERAL-BASE-LIQUIDA:4\"},\"result\":{\"status\":\"indeterminate\",\"value\":null,\"unit\":\"MZN\",\"explanation\":\"IVA das vendas projectadas; sem apuramento final.\",\"missing_inputs\":[\"monthly_sales\"],\"source_ids\":[\"synthetic-qa-source\"]},\"presentation\":{\"value\":null,\"rounding_applied\":false},\"fiscal_provenance\":{\"rule\":{\"rule_code\":\"IVA-GERAL-BASE-LIQUIDA\",\"rule_version\":4,\"valid_from\":\"2023-01-01\",\"valid_until\":null,\"source_sha256\":\"synthetic-qa-source-hash\",\"source\":{\"diploma\":\"Fonte sintética QA — regra já ensaiada\",\"article\":\"Cópia do snapshot aceite\"}},\"scope_status\":\"user_declared\"},\"monthly_projection\":{\"input\":{\"scenario_kind\":\"fiscal_rule_published\",\"monthly_sales\":[{\"date\":\"2026-01-01\",\"amount\":\"1000.03\"},{\"date\":\"2026-02-01\",\"amount\":\"2000.06\"},{\"date\":\"2026-03-01\",\"amount\":\"0.00\"},{\"date\":\"2026-04-01\",\"amount\":null}],\"sales_vat_basis\":\"net\",\"currency\":\"MZN\",\"scope_declared\":true},\"rows\":[{\"date\":\"2026-01-01\",\"sales_declared\":\"1000.03\",\"net_sales\":\"1000.03\",\"rate\":\"16\",\"vat\":\"160.0048\",\"gross_sales\":\"1160.0348\",\"status\":\"calculated\"},{\"date\":\"2026-02-01\",\"sales_declared\":\"2000.06\",\"net_sales\":\"2000.06\",\"rate\":\"16\",\"vat\":\"320.0096\",\"gross_sales\":\"2320.0696\",\"status\":\"calculated\"},{\"date\":\"2026-03-01\",\"sales_declared\":\"0.00\",\"net_sales\":\"0.00\",\"rate\":\"16\",\"vat\":\"0\",\"gross_sales\":\"0\",\"status\":\"calculated\"},{\"date\":\"2026-04-01\",\"sales_declared\":null,\"net_sales\":null,\"rate\":null,\"vat\":null,\"gross_sales\":null,\"status\":\"missing_sales\"}],\"cash_treatment\":\"IVA separado da tesouraria; não é imposto final a pagar.\"}}}}",
"province_id": "cf5e81f1-ffbc-535d-b1b6-b44b445c4421",
"district_id": "",
"selection_labels": {
"province_id": "Manica"
},
"modelo_a_snapshot": "{\"version\":1,\"books\":{\"opportunity:309\":{\"currency\":\"MZN\",\"taxpayerRegistered\":\"yes\",\"rows\":[{\"id\":\"qa-inventory\",\"field\":\"09\",\"period\":\"2026-01\",\"origin\":\"projected\",\"sourceMonth\":null,\"sourceAmount\":null,\"sourceCurrency\":\"MZN\",\"sourceBasis\":\"\",\"net\":\"100\",\"vat\":\"16\",\"gross\":\"116\",\"documentType\":\"invoice\",\"documentRef\":\"SYNTHETIC QA 001\",\"documentDate\":\"2026-01-10\",\"documentLine\":\"\",\"supplier\":\"SYNTHETIC QA supplier\",\"supplierRegistered\":\"yes\",\"legalDocument\":\"yes\",\"held\":\"yes\",\"domestic\":\"yes\",\"allocation\":\"taxable_only\",\"exclusion\":\"none\",\"integrity\":\"yes\",\"description\":\"SYNTHETIC QA existências\"}],\"periods\":[{\"period\":\"2026-01\",\"complete\":true,\"absent\":[\"03\",\"04\",\"05\",\"06\",\"07\",\"11\",\"12\",\"13\"]},{\"period\":\"2026-02\",\"complete\":true,\"absent\":[\"03\",\"04\",\"05\",\"06\",\"07\",\"11\",\"12\",\"13\"]},{\"period\":\"2026-03\",\"complete\":true,\"absent\":[\"03\",\"04\",\"05\",\"06\",\"07\",\"11\",\"12\",\"13\"]},{\"period\":\"2026-04\",\"complete\":true,\"absent\":[\"03\",\"04\",\"05\",\"06\",\"07\",\"11\",\"12\",\"13\"]}],\"result\":{\"version\":\"modelo-a-internal-acquisitions/1\",\"revision\":1,\"calculatedAt\":\"2026-10-24T12:00:00.000Z\",\"opportunity\":\"opportunity:309\",\"location\":\"Manica\",\"currency\":\"MZN\",\"sourceKey\":\"5009:840f2acff1252a8e\",\"basis\":\"CIVA arts.18(1)(a),18(2) (Lei10/2025),18(3–5),19(1)(a),19(2),20 (Lei22/2022),21(1–3); âmbito interno, afectação exclusiva, mesmo período, sem exclusões ou dedução parcial.\",\"sources\":\"Modelo A DOCX 62c198e9 / v1 63d45fa8; VAT Return.pdf SHA256 9c0b99a810c7db53eb75d63c22ee22fb86a50ba57bd5509041ed80ee10f75741, p.1; CIVA republicado Lei13/2016, PDF14–16; Lei22/2022, art.20; Lei10/2025, arts.18/19, PDF13.\",\"declarations\":{\"taxpayerRegistered\":\"yes\",\"periods\":[{\"period\":\"2026-01\",\"complete\":true,\"absent\":[\"03\",\"04\",\"05\",\"06\",\"07\",\"11\",\"12\",\"13\"]},{\"period\":\"2026-02\",\"complete\":true,\"absent\":[\"03\",\"04\",\"05\",\"06\",\"07\",\"11\",\"12\",\"13\"]},{\"period\":\"2026-03\",\"complete\":true,\"absent\":[\"03\",\"04\",\"05\",\"06\",\"07\",\"11\",\"12\",\"13\"]},{\"period\":\"2026-04\",\"complete\":true,\"absent\":[\"03\",\"04\",\"05\",\"06\",\"07\",\"11\",\"12\",\"13\"]}]},\"rows\":[{\"id\":\"qa-inventory\",\"net\":\"100.00\",\"vat\":\"16.00\",\"gross\":\"116.00\",\"deductible\":\"16.00\",\"reason\":\"Dedução projectada sob pressupostos explícitos; não certifica factura ou declaração.\"}],\"inputs\":[{\"id\":\"qa-inventory\",\"field\":\"09\",\"period\":\"2026-01\",\"origin\":\"projected\",\"sourceMonth\":null,\"sourceAmount\":null,\"sourceCurrency\":\"MZN\",\"sourceBasis\":\"\",\"net\":\"100\",\"vat\":\"16\",\"gross\":\"116\",\"documentType\":\"invoice\",\"documentRef\":\"SYNTHETIC QA 001\",\"documentDate\":\"2026-01-10\",\"documentLine\":\"\",\"supplier\":\"SYNTHETIC QA supplier\",\"supplierRegistered\":\"yes\",\"legalDocument\":\"yes\",\"held\":\"yes\",\"domestic\":\"yes\",\"allocation\":\"taxable_only\",\"exclusion\":\"none\",\"integrity\":\"yes\",\"description\":\"SYNTHETIC QA existências\"}],\"periods\":[{\"period\":\"2026-01\",\"fields\":{\"10\":\"0.00\",\"11\":\"0.00\",\"12\":\"0.00\",\"13\":\"0.00\",\"14\":\"1000.03\",\"15\":\"16.00\",\"16\":\"160.0048\",\"17\":\"144.0048\",\"18\":\"0.00\",\"01\":\"1000.03\",\"02\":\"160.0048\",\"03\":\"0.00\",\"04\":\"0.00\",\"05\":\"0.00\",\"06\":\"0.00\",\"07\":\"0.00\",\"08\":\"0.00\",\"09\":\"16.00\"},\"reasons\":[]},{\"period\":\"2026-02\",\"fields\":{\"10\":\"0.00\",\"11\":\"0.00\",\"12\":\"0.00\",\"13\":\"0.00\",\"14\":\"2000.06\",\"15\":\"0.00\",\"16\":\"320.0096\",\"17\":\"320.0096\",\"18\":\"0.00\",\"01\":\"2000.06\",\"02\":\"320.0096\",\"03\":\"0.00\",\"04\":\"0.00\",\"05\":\"0.00\",\"06\":\"0.00\",\"07\":\"0.00\",\"08\":\"0.00\",\"09\":\"0.00\"},\"reasons\":[]},{\"period\":\"2026-03\",\"fields\":{\"10\":\"0.00\",\"11\":\"0.00\",\"12\":\"0.00\",\"13\":\"0.00\",\"14\":\"0.00\",\"15\":\"0.00\",\"16\":\"0.00\",\"17\":\"0.00\",\"18\":\"0.00\",\"01\":\"0.00\",\"02\":\"0\",\"03\":\"0.00\",\"04\":\"0.00\",\"05\":\"0.00\",\"06\":\"0.00\",\"07\":\"0.00\",\"08\":\"0.00\",\"09\":\"0.00\"},\"reasons\":[]},{\"period\":\"2026-04\",\"fields\":{\"10\":\"0.00\",\"11\":\"0.00\",\"12\":\"0.00\",\"13\":\"0.00\",\"14\":null,\"15\":\"0.00\",\"16\":null,\"17\":null,\"18\":null,\"01\":null,\"02\":null,\"03\":\"0.00\",\"04\":\"0.00\",\"05\":\"0.00\",\"06\":\"0.00\",\"07\":\"0.00\",\"08\":\"0.00\",\"09\":\"0.00\"},\"reasons\":[\"01/02: vendas ou IVA mensal em falta, execução incompleta ou desactualizada.\"]}]}}}}"
}
+78
View File
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import fs from 'node:fs';
import {closureFixture} from './fixtures/simulator-closure-fixture.mjs';
import {acquisitionBook,acquisitionCurrent,acquisitionExcludedFields,acquisitionPlanReferences,acquisitionReportRows,calculateAcquisitions,evaluateAcquisition,newAcquisition,reuseAcquisitions,saveAcquisitionBook} from '../../resources/js/lib/iva-acquisitions.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
import {serializeBusinessPlanSnapshot,restoreBusinessPlanSnapshot} from '../../resources/js/lib/business-financial-plan.ts';
export function acquisitionsFixture(){
const draft=closureFixture().draft;
draft.project_title='SYNTHETIC QA — aquisições e apuramento parcial Modelo A';
draft.province_id='cf5e81f1-ffbc-535d-b1b6-b44b445c4421';draft.district_id='';draft.selection_labels={province_id:'Manica'};
const book={currency:'MZN',taxpayerRegistered:'yes',rows:[{...newAcquisition('qa-inventory','2026-01','MZN'),net:'100',vat:'16',gross:'116',documentType:'invoice',documentRef:'SYNTHETIC QA 001',documentDate:'2026-01-10',supplier:'SYNTHETIC QA supplier',supplierRegistered:'yes',legalDocument:'yes',held:'yes',domestic:'yes',allocation:'taxable_only',exclusion:'none',integrity:'yes',description:'SYNTHETIC QA existências'}],periods:['2026-01','2026-02','2026-03','2026-04'].map(period=>({period,complete:true,absent:[...acquisitionExcludedFields]}))};
return {draft,book};
}
test('a recorded purchase does not establish VAT, legal document or deduction',()=>{
const row=newAcquisition('a','2026-01','MZN');row.net='100';
assert.equal(evaluateAcquisition(row,'MZN','yes').deductible,null);
row.vat='16';let r=evaluateAcquisition(row,'MZN','yes');assert.equal(r.gross,'116.00');assert.equal(r.deductible,null);
row.gross='117';assert.match(evaluateAcquisition(row,'MZN','yes').reason,/corresponder/);
});
test('eligibility handles exclusions, mixed use, document, supplier, date and currency without inventing rules',()=>{
const row=acquisitionsFixture().book.rows[0];
assert.equal(evaluateAcquisition(row,'MZN').deductible,null);
assert.equal(evaluateAcquisition(row,'MZN','yes').deductible,'16.00');
for(const patch of [{documentRef:''},{supplierRegistered:''},{held:''},{allocation:'mixed'},{exclusion:'special'},{documentDate:'2026-02-10'},{documentDate:'2026-99-10'},{domestic:'no'},{sourceCurrency:'USD'}]) assert.equal(evaluateAcquisition({...row,...patch},'MZN','yes').deductible,null,JSON.stringify(patch));
for(const patch of [{supplierRegistered:'no'},{allocation:'no_right'},{exclusion:'excluded'},{integrity:'no'}]) assert.equal(evaluateAcquisition({...row,...patch},'MZN','yes').deductible,'0.00');
assert.equal(evaluateAcquisition({...row,origin:'effective'},'MZN','yes').deductible,'16.00');
assert.equal(evaluateAcquisition({...row,net:'100',vat:'0',gross:'100',documentRef:''},'MZN','yes').deductible,'0.00');
});
test('duplicates, ambiguous opportunity and absent declarations are not silently accepted',()=>{
const {draft,book}=acquisitionsFixture();
book.rows.push({...book.rows[0],id:'duplicate'});assert.throws(()=>calculateAcquisitions(draft,book),/repetido/);
assert.throws(()=>acquisitionBook({...draft,context_opportunity:'',context_applicability_snapshot:JSON.stringify({opportunity_choices:[{},{}]})}),/Escolha a oportunidade/);
const missing=acquisitionsFixture();missing.book.periods[0].absent=[];missing.book.result=calculateAcquisitions(missing.draft,missing.book);missing.draft.modelo_a_snapshot=saveAcquisitionBook(missing.draft,missing.book);
assert.match(JSON.stringify(acquisitionReportRows(missing.draft)),/nenhum/);
assert.equal(missing.book.result.periods[0].fields['17'],null);
});
test('08–10, formulas14–18, decimal precision, missing parcels and explicit absence',()=>{
const {draft,book}=acquisitionsFixture();
book.rows.push({...book.rows[0],id:'asset',field:'08',documentLine:'2',net:'200',vat:'32',gross:'232'},{...book.rows[0],id:'service',field:'10',documentLine:'3',net:'50',vat:'8',gross:'58'});
const result=calculateAcquisitions(draft,book);const f=result.periods[0].fields;
assert.equal(f['08'],'32.00');assert.equal(f['09'],'16.00');assert.equal(f['10'],'8.00');assert.equal(f['14'],'1000.03');assert.equal(f['15'],'56.00');assert.equal(f['16'],'160.0048');assert.equal(f['17'],'104.0048');assert.equal(f['18'],'0.00');
assert.equal(result.periods[2].fields['17'],'0.00');assert.equal(result.periods[3].fields['17'],null);
book.periods[0].absent=[];const incomplete=calculateAcquisitions(draft,book).periods[0];for(const field of ['14','15','16','17','18'])assert.equal(incomplete.fields[field],null);
book.periods[0].absent=[...acquisitionExcludedFields];book.periods[0].complete=false;assert.equal(calculateAcquisitions(draft,book).periods[0].fields['15'],null);
const credit=acquisitionsFixture();credit.book.rows[0]={...credit.book.rows[0],net:'2000',vat:'320',gross:'2320'};assert.equal(calculateAcquisitions(credit.draft,credit.book).periods[0].fields['18'],'159.9952');
assert.throws(()=>calculateAcquisitions({...draft,imports:'5'},book),/importa/);
});
test('reuse keeps source values unclassified, preserves deliberate changes and detects source drift',()=>{
const {draft}=acquisitionsFixture();let book=reuseAcquisitions(draft,acquisitionBook(draft));assert.equal(book.rows[0].sourceAmount,'0.00');assert.equal(book.rows[0].net,'');assert.equal(book.rows[0].sourceBasis,'');
book.rows[0].net='123';book=reuseAcquisitions(draft,book);assert.equal(book.rows[0].net,'123');assert.equal(book.rows.length,4);
const plan=restoreBusinessPlanSnapshot(draft.business_plan_snapshot);plan.monthlyInventoryPurchases='1';const changed={...draft,business_plan_snapshot:serializeBusinessPlanSnapshot(plan)};assert.throws(()=>calculateAcquisitions(changed,book),/plano mudaram/);
});
test('asset and operating budgets can be reused explicitly without becoming VAT or deductions',()=>{
const {draft,book}=acquisitionsFixture();const plan=restoreBusinessPlanSnapshot(draft.business_plan_snapshot);plan.assetInvestment='200';plan.monthlyOperatingExpenses='50';draft.business_plan_snapshot=serializeBusinessPlanSnapshot(plan);
const refs=acquisitionPlanReferences(draft);assert.equal(refs.find(r=>r.kind==='asset').amount,'200');assert.equal(refs.find(r=>r.key==='operating:1').amount,'50');
const row={...newAcquisition('asset-reference','2026-01','MZN'),field:'08',sourceField:'asset',sourceMonth:1,sourceAmount:'200',sourceBasis:'net',net:'200'};book.rows=[row];assert.equal(calculateAcquisitions(draft,book).rows[0].deductible,null);
row.vat='32';assert.equal(calculateAcquisitions(draft,book).rows[0].deductible,null);
assert.equal(calculateAcquisitions(draft,book).rows[0].gross,'232.00');
});
test('order month is retained as origin and never forces invoice or deduction month',()=>{
const {draft}=acquisitionsFixture();const plan=restoreBusinessPlanSnapshot(draft.business_plan_snapshot);plan.useInventoryPurchaseSchedule=true;plan.inventoryPurchaseSchedule=[{amount:'100',leadMonths:0},{amount:'0',leadMonths:0},{amount:'0',leadMonths:0},{amount:'0',leadMonths:0}];draft.business_plan_snapshot=serializeBusinessPlanSnapshot(plan);
let book=reuseAcquisitions(draft,acquisitionBook(draft));book.taxpayerRegistered='yes';book.periods=book.periods.map(p=>({...p,complete:true,absent:[...acquisitionExcludedFields]}));
book.rows=book.rows.map(row=>({...row,net:row.sourceAmount,vat:'0',sourceBasis:'net'}));
book.rows[0]={...book.rows[0],...acquisitionsFixture().book.rows[0],id:'plan-1',sourceMonth:1,sourcePeriod:'2026-01',sourceAmount:'100.00',sourceBasis:'net',period:'2026-02',documentDate:'2026-02-10'};
const result=calculateAcquisitions(draft,book);assert.equal(result.rows[0].deductible,'16.00');assert.equal(result.periods[0].fields['09'],'0.00');assert.equal(result.periods[1].fields['09'],'16.00');assert.equal(result.inputs[0].sourcePeriod,'2026-01');
});
test('second opportunity changes preserve first book, frozen results and report context after recovery',()=>{
const {draft,book}=acquisitionsFixture();draft.context_opportunity='opportunity:1';book.result=calculateAcquisitions(draft,book);draft.modelo_a_snapshot=saveAcquisitionBook(draft,book);const first=JSON.stringify(acquisitionBook(draft));
draft.context_opportunity='opportunity:309';assert.equal(acquisitionBook(draft).rows.length,0);const second=acquisitionsFixture().book;second.rows[0].vat='32';second.rows[0].net='200';second.rows[0].gross='232';second.result=calculateAcquisitions(draft,second);draft.modelo_a_snapshot=saveAcquisitionBook(draft,second);
const recovered=JSON.parse(JSON.stringify(draft));assert.equal(acquisitionCurrent(recovered,acquisitionBook(recovered)),true);assert.equal(acquisitionBook(recovered).result.periods[0].fields['17'],'128.0048');
assert.equal(JSON.stringify(acquisitionBook({...draft,context_opportunity:'opportunity:1'})),first);
const report=JSON.stringify(createProjectDossierReport(recovered,{selectedSections:new Set(['finance'])}));assert.match(report,/128\.0048/);assert.match(report,/opportunity:309/);assert.doesNotMatch(report,/opportunity:1;/);
const old=JSON.stringify(second.result);second.rows[0].vat='33';draft.modelo_a_snapshot=saveAcquisitionBook(draft,second);assert.equal(acquisitionCurrent(draft,second),false);assert.equal(JSON.stringify(second.result),old);assert.match(JSON.stringify(acquisitionReportRows(draft)),/Histórico desactualizado/);
assert.throws(()=>acquisitionBook({modelo_a_snapshot:'broken'}));
});
if(process.env.IVA_ACQUISITION_FIXTURE_OUT){const {draft,book}=acquisitionsFixture();book.result=calculateAcquisitions(draft,book,'2026-10-24T12:00:00.000Z');draft.modelo_a_snapshot=saveAcquisitionBook(draft,book);fs.writeFileSync(process.env.IVA_ACQUISITION_FIXTURE_OUT,JSON.stringify(draft,null,2));}