Preserve dossier context and expose contextual applicability in QA
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentZones;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentContextContinuityTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$db = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
$this->assertSame('simulator_fiscal_delta_20261021_test', $db->name);
|
||||
$this->assertSame(55441, (int) $db->port);
|
||||
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
}
|
||||
|
||||
private function dossier(User $user, string $title): string
|
||||
{
|
||||
return $this->actingAs($user)->postJson('/investimentos', ['title' => $title, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
public function test_same_dossier_context_reuses_linked_draft_and_preserves_account_and_project_boundaries(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$a = $this->dossier($owner, 'A');
|
||||
$b = $this->dossier($owner, 'B');
|
||||
foreach ([[$a, 'MZN', 'national'], [$b, 'USD', 'foreign']] as [$id,$currency,$origin]) {
|
||||
$this->actingAs($owner)->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => ['investor_origin' => $origin, 'tax_residency_country' => 'ZA', 'person_type' => 'collective'], 'economic_snapshot' => ['purpose' => 'simulate_only', 'project_title' => $id, 'currency' => $currency, 'expected_start_date' => '2026-01-01']], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated();
|
||||
$v = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk();
|
||||
$v->assertJsonPath('prefill.simulator.currency', $currency)->assertJsonPath('prefill.simulator.investor_origin', $origin)->assertJsonPath('prefill.simulator.tax_residency_country', 'ZA');
|
||||
$this->assertSame('linked_simulation', $v->json('context.provenance.currency.kind'));
|
||||
}
|
||||
$this->actingAs(User::factory()->create())->getJson('/investimentos/'.$a.'/contexto')->assertForbidden();
|
||||
$this->actingAs($owner)->getJson('/investimentos/'.$a.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.currency', 'MZN');
|
||||
}
|
||||
|
||||
public function test_context_change_is_previewed_versioned_and_idempotent_without_changing_the_source_draft(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$id = $this->dossier($owner, 'Impacto');
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
|
||||
$body = ['version' => $view['case']['version'], 'selection' => [], 'declarations' => ['currency' => 'USD', 'investor_origin' => 'foreign', 'tax_residency_country' => 'MZ'], 'replace_fields' => []];
|
||||
$plan = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
|
||||
$this->assertNotEmpty($plan['updated']);
|
||||
$this->assertTrue($plan['dependency_changed']);
|
||||
$control = [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true];
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', $control)->assertOk();
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', $control)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.currency', 'USD')->assertJsonPath('prefill.simulator.tax_residency_country', 'MZ');
|
||||
}
|
||||
|
||||
public function test_zone_selection_reuses_existing_reference_and_impact_workflow_without_granting_a_benefit(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$id = $this->dossier($owner, 'Zonas QA');
|
||||
$template = app(InvestmentZones::class)->visible()->where('category', 'industrial_park')->firstOrFail();
|
||||
foreach (['zee', 'zfi', 'industrial_park'] as $category) {
|
||||
// Synthetic catalogue metadata, rolled back. Never a legal source or published rule in homologation.
|
||||
$zone = $template->replicate();
|
||||
$zone->id = (string) Str::uuid();
|
||||
$zone->code = 'SINT-CONTEXT-'.Str::random(12);
|
||||
$zone->name = 'SINTÉTICO QA '.$category;
|
||||
$zone->category = $category;
|
||||
$zone->legal_regime = $category === 'industrial_park' ? 'pending' : $category;
|
||||
$zone->source_evidence = [['source_type' => 'government', 'url' => 'https://example.test/synthetic-zone', 'supports' => 'Synthetic test only; no legal or eligibility conclusion']];
|
||||
$zone->save();
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
|
||||
$body = ['version' => $view['case']['version'], 'selection' => ['park' => 'park:'.$zone->id]];
|
||||
$plan = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
|
||||
$this->assertSame($category, $plan['fields']['investment_regime']);
|
||||
$this->assertContains('S17', $plan['review_steps']);
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
|
||||
$after = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk();
|
||||
$after->assertJsonPath('prefill.simulator.investment_regime', $category);
|
||||
$snapshot = json_decode($after->json('prefill.simulator.context_applicability_snapshot'), true);
|
||||
$this->assertSame($zone->id, $snapshot['zone']['id']);
|
||||
$this->assertArrayNotHasKey('benefit_rate', $snapshot);
|
||||
}
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->json();
|
||||
$body = ['version' => $view['case']['version'], 'selection' => ['park' => null]];
|
||||
$plan = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
|
||||
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.investment_regime', 'general')->assertJsonPath('prefill.simulator.special_zone_id', '');
|
||||
}
|
||||
|
||||
public function test_a_title_edit_does_not_invalidate_applicability_or_ask_for_irrelevant_reviews(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$id = $this->dossier($owner, 'Título original');
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/previa', ['version' => $view['case']['version'], 'selection' => [], 'declarations' => ['project_title' => 'Título revisto']])
|
||||
->assertOk()->assertJsonPath('dependency_changed', false)->assertJsonPath('review_steps', []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { inheritCompatibleFields, inheritSimulatorFields } from '../../resources/js/lib/context-inheritance.ts';
|
||||
import { serializeBusinessPlanSnapshot } from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { monthlySalesFromDraft } from '../../resources/js/lib/monthly-iva.ts';
|
||||
import { restoreSimulationDraft, partitionSimulationDraft } from '../../resources/js/lib/simulation-form.ts';
|
||||
|
||||
test('inherited source updates follow through recovery while local edits and deliberate clears survive',()=>{
|
||||
const first=inheritCompatibleFields('dossier:A:simulator',{}, {currency:'MZN',project_title:'A'}, null);
|
||||
const saved={...first.patch,context_reuse:first.metadata};
|
||||
const changed=inheritCompatibleFields('dossier:A:simulator',saved,{currency:'USD',project_title:'A2'},saved.context_reuse);
|
||||
assert.deepEqual(changed.patch,{currency:'USD',project_title:'A2'});
|
||||
const edited=inheritCompatibleFields('dossier:A:simulator',{...saved,currency:'EUR',project_title:''},{currency:'USD',project_title:'A2'},saved.context_reuse);
|
||||
assert.deepEqual(edited.patch,{});assert.deepEqual(edited.conflicts,['currency','project_title']);
|
||||
const recovered=JSON.parse(JSON.stringify({...saved,currency:'EUR',project_title:''}));
|
||||
assert.deepEqual(inheritCompatibleFields('dossier:A:simulator',recovered,{currency:'USD',project_title:'A2'},recovered.context_reuse).patch,{});
|
||||
assert.ok(!first.metadata.includes('MZN'));assert.ok(!first.metadata.includes('project_title":"A'));
|
||||
});
|
||||
test('a different dossier cannot take ownership of existing values using another dossier metadata',()=>{
|
||||
const first=inheritCompatibleFields('dossier:A:simulator',{}, {currency:'MZN'}, null);
|
||||
const second=inheritCompatibleFields('dossier:B:simulator',first.patch,{currency:'USD'},first.metadata);
|
||||
assert.deepEqual(second.patch,{});assert.deepEqual(second.conflicts,['currency']);
|
||||
});
|
||||
test('a local geographic override protects the entire hierarchy',()=>{
|
||||
const first=inheritCompatibleFields('A',{}, {province_id:'p1',district_id:'d1'},null);
|
||||
const update=inheritCompatibleFields('A',{...first.patch,province_id:'p-local'},{province_id:'p2',district_id:'d2'},first.metadata);
|
||||
assert.deepEqual(update.patch,{});
|
||||
});
|
||||
test('compatible currency and date reuse survives backend partition and new session recovery without invented tax scope',()=>{
|
||||
const initial=inheritSimulatorFields({currency:'USD',expected_start_date:'2026-03-01',purpose:'simulate_only'});
|
||||
assert.equal(initial.fiscal_currency,'USD');assert.equal(initial.published_iva_currency,'USD');assert.equal(initial.opportunity_currency,'USD');
|
||||
assert.equal(JSON.parse(initial.monthly_iva_settings).start,'2026-03');assert.equal(JSON.parse(initial.monthly_iva_settings).declared,false);
|
||||
assert.equal(initial.published_iva_date,undefined);
|
||||
assert.equal(inheritSimulatorFields({expected_start_date:'2026-01-01',monthly_iva_settings:'[invalid stored input'}).monthly_iva_settings,'[invalid stored input');
|
||||
const saved=partitionSimulationDraft(initial,true);const recovered=restoreSimulationDraft(saved.economic_snapshot,saved.personal_snapshot);
|
||||
assert.equal(recovered.published_iva_currency,'USD');assert.strictEqual(inheritSimulatorFields(recovered),recovered);
|
||||
const changed=inheritSimulatorFields({...recovered,currency:'EUR'});assert.equal(changed.fiscal_currency,'EUR');
|
||||
const override=inheritSimulatorFields({...changed,fiscal_currency:'MZN',published_iva_currency:''});assert.equal(override.fiscal_currency,'MZN');assert.equal(override.published_iva_currency,'');
|
||||
});
|
||||
test('land consumer reuses geography inside an empty parcel and preserves all other parcel data',()=>{
|
||||
const first=inheritCompatibleFields('land', {parcels:[{area:'12',province_id:''},{area:'20',province_id:'other'}]}, {parcels:[{province_id:'P',district_id:'D'}]},null);
|
||||
assert.equal(first.patch.parcels[0].area,'12');assert.equal(first.patch.parcels[0].district_id,'D');assert.equal(first.patch.parcels[1].province_id,'other');
|
||||
const changed=inheritCompatibleFields('land',{parcels:[{...first.patch.parcels[0],area:'13'},first.patch.parcels[1]]},{parcels:[{province_id:'P2'}]},first.metadata);
|
||||
assert.equal(changed.patch.parcels[0].area,'13');assert.equal(changed.patch.parcels[0].district_id,'');
|
||||
});
|
||||
test('clearing an inherited zone reference clears only the inherited value, preserving a deliberate override',()=>{
|
||||
const first=inheritCompatibleFields('A',{}, {special_zone_id:'zone'},null);
|
||||
assert.equal(inheritCompatibleFields('A',first.patch,{special_zone_id:''},first.metadata).patch.special_zone_id,'');
|
||||
assert.deepEqual(inheritCompatibleFields('A',{special_zone_id:'local'},{special_zone_id:''},first.metadata).patch,{});
|
||||
});
|
||||
test('conflicting saved sales currency is explained instead of relabelled or converted',()=>{
|
||||
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(key=>[key,'0'])),currency:'MZN',periods:4,depreciationLifeMonths:60,products:[{label:'QA',monthlyUnits:'1',unitPrice:'100',unitVariableCost:'0'}]};
|
||||
assert.throws(()=>monthlySalesFromDraft({currency:'USD',business_plan_snapshot:serializeBusinessPlanSnapshot(plan)}),/projecção de vendas está em MZN.*projecto está em USD/);
|
||||
});
|
||||
|
||||
test('report preserves consulted zone version and makes unsupported benefit explicit without inventing a fiscal result',()=>{
|
||||
const context={version:1,context_revision:3,zone:{title:'Referência QA',version:7,href:'/zonas/qa'},fields:{currency:'USD'}};
|
||||
const draft={project_title:'QA',currency:'USD',context_applicability_snapshot:JSON.stringify(context)};
|
||||
const saved=JSON.stringify(draft);const report=createProjectDossierReport(draft,{selectedSections:new Set(['sources'])});
|
||||
assert.match(JSON.stringify(report),/Referência QA, versão 7/);assert.match(JSON.stringify(report),/Benefício fiscal da zona indeterminado/);assert.equal(JSON.stringify(draft),saved);
|
||||
});
|
||||
Reference in New Issue
Block a user