fix: preserve cashflow currency and recover admitted monthly IVA executions in QA
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\RunSimulation;
|
||||
use App\Models\Simulation;
|
||||
use App\Models\SimulationTaxRuleVersion;
|
||||
use App\Models\User;
|
||||
use App\Services\SimulationExecution;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class SimulatorClosureRecoveryTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
public function test_existing_monthly_admission_can_be_read_and_finished_when_new_admissions_are_off(): 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);
|
||||
Queue::fake();
|
||||
// Reuse the existing isolated synthetic rule. No create/publish/suspend of any rule.
|
||||
$rule = SimulationTaxRuleVersion::findOrFail('01a15e50-7972-72e0-8991-82ca28df9b49');
|
||||
$before = $this->ruleFingerprint();
|
||||
config(['simulation-fiscal-consumer.enabled' => true, 'simulation-fiscal-consumer.rule_id' => $rule->id, 'simulation-fiscal-consumer.rule_version' => $rule->rule_version]);
|
||||
$actor = User::factory()->create(['email_verified_at' => now()]);
|
||||
$input = ['scenario_kind' => 'fiscal_rule_published', 'currency' => 'MZN', 'scope_declared' => true, 'sales_vat_basis' => 'net', 'monthly_sales' => [['date' => '2026-01-01', 'amount' => '1000.03']]];
|
||||
$id = $this->actingAs($actor)->postJson('/api/v1/simulations', $input, ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted()->json('data.id');
|
||||
$count = Simulation::count();
|
||||
config(['simulation-fiscal-consumer.enabled' => false]);
|
||||
$this->getJson('/api/v1/fiscal-consumer')->assertOk()->assertJsonPath('data.enabled', false);
|
||||
$this->getJson('/api/v1/simulations/'.$id)->assertOk()->assertJsonPath('data.id', $id)->assertJsonPath('data.status', 'queued');
|
||||
$this->postJson('/api/v1/simulations', $input, ['Idempotency-Key' => (string) Str::uuid()])->assertStatus(503);
|
||||
(new RunSimulation($id, $actor->id, null))->handle(app(SimulationExecution::class));
|
||||
$this->getJson('/api/v1/simulations/'.$id)->assertOk()->assertJsonPath('data.id', $id)->assertJsonPath('data.status', 'completed');
|
||||
$this->assertSame($count, Simulation::count());
|
||||
$this->actingAs(User::factory()->create(['email_verified_at' => now()]))->getJson('/api/v1/simulations/'.$id)->assertNotFound();
|
||||
$this->assertSame($before, $this->ruleFingerprint());
|
||||
}
|
||||
|
||||
private function ruleFingerprint(): string
|
||||
{
|
||||
return 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;
|
||||
}
|
||||
|
||||
public function test_cashflow_original_currency_and_amounts_round_trip_in_the_existing_private_draft(): 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]);
|
||||
$actor = User::factory()->create(['email_verified_at' => now()]);
|
||||
$this->actingAs($actor);
|
||||
$id = $this->postJson('/investimentos', ['title' => 'SYNTHETIC QA — moeda de tesouraria', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$snapshot = json_encode(['version' => 2, 'currency' => 'USD', 'taxMode' => 'fixed', 'inputs' => ['monthlyRevenue' => '123', 'monthlyTaxSchedule' => ['0', '', '0']]], JSON_THROW_ON_ERROR);
|
||||
$this->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => [], 'economic_snapshot' => ['purpose' => 'simulate_only', 'project_title' => 'SYNTHETIC QA — moeda', 'currency' => 'MZN', 'cashflow_snapshot' => $snapshot]], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated();
|
||||
$this->actingAs($actor->fresh());
|
||||
$saved = $this->getJson('/api/v1/simulation-drafts/current?context='.$id)->assertOk()->json('data.economic_snapshot');
|
||||
$this->assertSame('MZN', $saved['currency']);
|
||||
$this->assertSame($snapshot, $saved['cashflow_snapshot']);
|
||||
$this->assertSame('USD', json_decode($saved['cashflow_snapshot'], true)['currency']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import {serializeBusinessPlanSnapshot} from '../../../resources/js/lib/business-financial-plan.ts';
|
||||
|
||||
export function closureFixture(status='completed') {
|
||||
const fields=['openingCash','monthlyCollections','monthlyVariableCostPayments','monthlyInventoryPurchases','monthlyOperatingExpenses','monthlyOperatingPayments','monthlyPayrollExpense','monthlyPayrollPayments','assetInvestment','inventory','receivables','payables','equity','shareholderLoans','bankLoanProceeds','grants','assetDepreciation','monthlyInterestExpense','monthlyInterestPayment','monthlyPrincipalRepayment'];
|
||||
const plan={...Object.fromEntries(fields.map(k=>[k,'0'])),currency:'MZN',periods:4,depreciationLifeMonths:60,products:[{label:'SYNTHETIC QA',monthlyUnits:'1',unitPrice:'1000.03',unitVariableCost:'0',monthlyUnitsByPeriod:['1','2','0','']}]};
|
||||
const 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};
|
||||
// Frozen numbers already accepted in the monthly QA receipt; no tax calculation here.
|
||||
const 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'}];
|
||||
const 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,rows,cash_treatment:'IVA separado da tesouraria; não é imposto final a pagar.'}};
|
||||
const execution={id:'06566910-9672-4176-804d-aad8350417cb',status,version_no:2,result_snapshot:status==='completed'?snapshot:null};
|
||||
const context={version:1,context_revision:13,consumer_opportunity:'opportunity:309',opportunity_choices:[{opportunity:{key:'opportunity:309',title:'SYNTHETIC QA — segunda oportunidade Manica'}}],path:{steps:[]}};
|
||||
return {input,snapshot,execution,draft:{project_title:'SYNTHETIC QA — fecho do simulador S1 S2 S3',currency:'MZN',context_opportunity:'opportunity:309',context_applicability_snapshot:JSON.stringify(context),business_plan_snapshot:serializeBusinessPlanSnapshot(plan),monthly_iva_settings:JSON.stringify({start:'2026-01',basis:'net',declared:true,auto:false}),monthly_iva_snapshot:JSON.stringify({input,execution})}};
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdir,writeFile} from 'node:fs/promises';
|
||||
import JSZip from 'jszip';
|
||||
import {defaultCashflowDraftInputs,serializeCashflowDraftSnapshot,restoreCashflowDraftSnapshot,cashflowCurrency} from '../../resources/js/lib/monthly-cashflow.ts';
|
||||
import {monthlyIvaInput,recoverMonthlyIvaRecord} from '../../resources/js/lib/monthly-iva.ts';
|
||||
import {exportProjectDossierCsv,buildProjectDossierRows} from '../../resources/js/lib/project-dossier.ts';
|
||||
import {createProjectDossierReport,generateProjectDossierDocx,createProjectDossierPrintHtml} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
import {closureFixture} from './fixtures/simulator-closure-fixture.mjs';
|
||||
|
||||
test('S1 saved USD stays USD in report and cannot be reused as MZN for IVA',()=>{
|
||||
const inputs={...defaultCashflowDraftInputs(),monthlyRevenue:'123',monthlyTaxAssessed:'0'};
|
||||
const snapshot=serializeCashflowDraftSnapshot('fixed',inputs,'USD');
|
||||
const draft={currency:'MZN',cashflow_snapshot:snapshot};
|
||||
const saved=restoreCashflowDraftSnapshot(snapshot);
|
||||
assert.equal(saved.currency,'USD');assert.deepEqual(saved.inputs,inputs);
|
||||
assert.equal(cashflowCurrency(saved,'MZN').matchesProject,false);
|
||||
assert.throws(()=>monthlyIvaInput(draft,{start:'2026-01',basis:'net',declared:true,auto:false}),/continuam em USD/);
|
||||
const rows=buildProjectDossierRows(draft).filter(r=>r[0]==='Tesouraria');
|
||||
assert.match(rows.find(r=>r[1]==='Pressupostos e período')[2],/moeda USD/);
|
||||
assert.match(rows.find(r=>r[1]==='Divergência de moeda')[2],/não foram convertidos/);
|
||||
const restoredProject={...draft,currency:'USD'};
|
||||
assert.equal(cashflowCurrency(restoreCashflowDraftSnapshot(restoredProject.cashflow_snapshot),restoredProject.currency).matchesProject,true);
|
||||
assert.equal(restoredProject.cashflow_snapshot,snapshot);
|
||||
});
|
||||
test('S1 legacy amounts remain readable but require explicit origin currency before reuse',()=>{
|
||||
const inputs={...defaultCashflowDraftInputs(),monthlyRevenue:'123'};
|
||||
const legacy=serializeCashflowDraftSnapshot('fixed',inputs);const saved=restoreCashflowDraftSnapshot(legacy);
|
||||
assert.equal(saved.version,1);assert.throws(()=>cashflowCurrency(saved,'MZN'),/por confirmar/);
|
||||
const confirmed=restoreCashflowDraftSnapshot(serializeCashflowDraftSnapshot(saved.taxMode,saved.inputs,'USD'));
|
||||
assert.deepEqual(confirmed.inputs,saved.inputs);assert.equal(confirmed.currency,'USD');
|
||||
assert.equal(restoreCashflowDraftSnapshot(legacy).version,1);
|
||||
});
|
||||
test('S2 recovery is a same-ID authenticated GET without new admission and preserves denied records',async()=>{
|
||||
const pending=closureFixture('queued');const completed=closureFixture();const calls=[];
|
||||
const record={input:pending.input,execution:pending.execution};const before=JSON.stringify(record);
|
||||
const request=async(url,options)=>{calls.push({url,options});return new Response(JSON.stringify({data:completed.execution}),{status:200});};
|
||||
const recovered=await recoverMonthlyIvaRecord(record,request);
|
||||
assert.equal(recovered.execution.id,pending.execution.id);assert.equal(recovered.execution.status,'completed');assert.deepEqual(recovered.input,pending.input);
|
||||
assert.equal(calls.length,1);assert.equal(calls[0].options.credentials,'same-origin');assert.equal(calls[0].options.method,undefined);assert.match(calls[0].url,/simulations\/06566910/);
|
||||
await assert.rejects(()=>recoverMonthlyIvaRecord(record,async()=>new Response('{}',{status:403})),/preservados/);
|
||||
await assert.rejects(()=>recoverMonthlyIvaRecord(record,async()=>new Response(JSON.stringify({data:{...completed.execution,id:'00000000-0000-4000-8000-000000000000'}}),{status:200})),/preservados/);
|
||||
assert.equal(JSON.stringify(record),before);
|
||||
});
|
||||
test('S3 final CSV Word and print source retain frozen monthly values context source and version',async()=>{
|
||||
const {draft}=closureFixture();
|
||||
const report=createProjectDossierReport(draft,{selectedSections:new Set(['sources','finance']),version:'SYNTHETIC QA S3'});
|
||||
const csv=exportProjectDossierCsv(draft);const html=await createProjectDossierPrintHtml(report,[],false);
|
||||
const docx=await generateProjectDossierDocx(report,[],true);const bytes=new Uint8Array(await docx.arrayBuffer());const word=await JSZip.loadAsync(bytes);const xml=await word.file('word/document.xml').async('string');
|
||||
for(const text of [csv,html,xml]) for(const expected of ['160.0048','320.0096','1160.0348','MZN','2026-01','2026-04','Fonte sintética QA','IVA-GERAL-BASE-LIQUIDA','segunda oportunidade Manica','opportunity:309']) assert.ok(text.includes(expected),expected);
|
||||
for(const text of [csv,html,xml]) assert.match(text,/IVA-GERAL-BASE-LIQUIDA[^\n<]{0,30}4/);
|
||||
assert.match(html,/segunda oportunidade Manica/);assert.match(xml,/segunda oportunidade Manica/);
|
||||
const out='outputs/simulator-closure-qa-20261024';await mkdir(out,{recursive:true});
|
||||
await Promise.all([writeFile(`${out}/monthly-final.csv`,csv),writeFile(`${out}/monthly-final.docx`,bytes),writeFile(`${out}/monthly-final.html`,html),writeFile(`${out}/frozen-fixture.json`,JSON.stringify(draft,null,2))]);
|
||||
});
|
||||
@@ -17,7 +17,7 @@ test('cashflow draft recovery preserves unanswered months and invalid editable v
|
||||
openingCash: '77.01',
|
||||
monthlyTaxSchedule: ['10', '', '20', ...Array(9).fill('0')],
|
||||
};
|
||||
const stored = serializeCashflowDraftSnapshot('schedule', inputs);
|
||||
const stored = serializeCashflowDraftSnapshot('schedule', inputs, 'MZN');
|
||||
const restored = restoreCashflowDraftSnapshot(stored);
|
||||
assert.equal(restored.taxMode, 'schedule');
|
||||
assert.deepEqual(restored.inputs, inputs);
|
||||
@@ -65,7 +65,7 @@ test('cashflow draft recovery preserves unanswered months and invalid editable v
|
||||
assert.equal(restoreCashflowDraftSnapshot('{"version":2}'), null);
|
||||
assert.equal(
|
||||
restoreCashflowDraftSnapshot(
|
||||
stored.replace('"version":1', '"version":2'),
|
||||
stored.replace('"version":2', '"version":3'),
|
||||
),
|
||||
null,
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user