Preserve selected portfolio context through investment preparation

This commit is contained in:
2026-10-23 14:35:50 +02:00
parent 6948ed62fc
commit 3d877ec745
16 changed files with 271 additions and 28 deletions
@@ -130,8 +130,13 @@ final class InvestmentOpportunityChoicesTest extends TestCase
$snapshot = $view['prefill']['simulator']['context_applicability_snapshot'];
$this->assertCount(34, json_decode($snapshot, true)['opportunity_choices']);
$this->assertLessThan(1000000, strlen($snapshot));
// Mirror the existing browser partition: labels are persisted under selection_labels.
$economic = [...$view['prefill']['simulator'], 'purpose' => 'simulate_only', 'currency' => 'MZN'];
foreach (array_keys($economic) as $field) if (str_ends_with($field, '_label')) {
$economic['selection_labels'][substr($field, 0, -6)] = $economic[$field]; unset($economic[$field]);
}
$draft = $this->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => [],
'economic_snapshot' => [...$view['prefill']['simulator'], 'purpose' => 'simulate_only', 'currency' => 'MZN']], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json();
'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json();
$this->assertNotEmpty($draft);
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('context.opportunity_choices.33.opportunity.key', 'opportunity:'.$records[33]->id);
}
@@ -0,0 +1,95 @@
<?php
namespace Tests\Feature;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\CorridorAgribusinessOpportunities;
use App\Services\InvestmentCorridorContext;
use App\Services\InvestmentOpportunityChoices;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
final class InvestmentPortfolioContinuityTest extends TestCase
{
use DatabaseTransactions;
private User $actor;
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]);
$this->actor=User::factory()->create(); $this->actingAs($this->actor);
}
private function records(): array
{
$entries=collect(app(CorridorAgribusinessOpportunities::class)->entries())->where('corridor',config('investment_corridors.beira.name'))->take(2);
$opportunities=Opportunity::whereIn('management_creation_key',$entries->pluck('key'))->orderBy('id')->get();
$project=InvestmentPortfolioController::visible()->whereNotNull('project_id')->firstOrFail();
$cluster=InvestmentPortfolioController::visible()->whereNotNull('cluster_id')->firstOrFail();
foreach($opportunities as $opportunity) {
// Synthetic links exist only inside this rolled-back QA transaction.
DB::table('opportunity_projects')->insertOrIgnore(['opportunity_id'=>$opportunity->id,'project_id'=>$project->project_id]);
DB::table('opportunity_clusters')->insertOrIgnore(['opportunity_id'=>$opportunity->id,'cluster_id'=>$cluster->cluster_id]);
}
return [$opportunities,$project,$cluster];
}
public function test_origin_and_location_survive_entry_draft_confirmation_and_simulator_without_resetting_deliberate_values(): void
{
[$records,$origin,$cluster]=$this->records(); $opportunity=$records[0];
$province=collect(app(InvestmentCorridorContext::class)->provinces('beira'))->firstWhere('source_code','07')->id;
$query='?source=opportunity:'.$opportunity->id.'&from_dossier='.$origin->id.'&province_id='.$province;
auth()->logout();
$this->get('/investimentos/iniciar'.$query)->assertRedirect(route('login'));
parse_str(parse_url(session('url.intended'),PHP_URL_QUERY),$intended);
$this->assertSame($origin->id,$intended['from_dossier']);$this->assertSame($province,$intended['province_id']);
$this->actingAs($this->actor);
$this->get('/investimentos/iniciar'.$query)->assertOk()->assertInertia(fn(Assert $p)=>$p->where('opportunityChoices.0.portfolio_origins.0.id',$origin->id)->where('opportunityChoices.0.territory.id',$province)->where('entryQuery.from_dossier',$origin->id));
$id=$this->postJson('/investimentos',['title'=>'QA título deliberado','client_key'=>(string)Str::uuid(),'reuse_consent'=>true])->assertCreated()->json('id');
$body=['version'=>$this->getJson('/investimentos/'.$id.'/contexto')->json('case.version'),'selection'=>[],'opportunity_choices'=>[
['source'=>'opportunity:'.$opportunity->id,'territory'=>'territory:'.$province,'portfolio_origins'=>[$origin->id],'activities'=>['trade']],
['source'=>'opportunity:'.$records[1]->id,'territory'=>'territory:'.$province,'portfolio_origins'=>[$origin->id,$cluster->id]],
]];
$this->postJson('/investimentos/'.$id.'/contexto/rascunho',[...$body,'draft_sequence'=>1])->assertOk();
$this->flushSession();$this->actingAs($this->actor);
$this->get('/investimentos/'.$id.'/contexto/editar')->assertOk()->assertInertia(fn(Assert $p)=>$p->where('requestedChoices.0.portfolio_origins.0.id',$origin->id)->where('requestedChoices.0.territory.id',$province));
$preview=$this->postJson('/investimentos/'.$id.'/contexto/previa',$body)->assertOk()->json();
$this->assertGreaterThan(0,$preview['opportunity_choices'][0]['portfolio_origins'][0]['version']);
$this->assertSame('QA título deliberado',$preview['fields']['project_title']);
$this->postJson('/investimentos/'.$id.'/contexto/confirmar',[...$body,'preview_hash'=>$preview['preview_hash'],'operation_key'=>(string)Str::uuid(),'confirm'=>true])->assertOk();
$view=$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
$this->assertSame($view['context']['opportunity_choices'],json_decode($view['prefill']['simulator']['context_applicability_snapshot'],true)['opportunity_choices']);
$this->assertSame($province,$view['prefill']['simulator']['province_id']);
$this->assertSame('QA título deliberado',$view['prefill']['simulator']['project_title']);
$created=$this->postJson('/api/v1/simulation-drafts',['context'=>$id,'personal_snapshot'=>[],'economic_snapshot'=>['purpose'=>'simulate_only','project_title'=>'QA edição deliberada no simulador','context_applicability_snapshot'=>$view['prefill']['simulator']['context_applicability_snapshot']]],['Idempotency-Key'=>(string)Str::uuid()])->assertCreated();
$this->flushSession();$this->actingAs($this->actor);
$simulation=$this->getJson('/api/v1/simulation-drafts/'.$created->json('data.id').'?context='.$id)->assertOk()->assertJsonPath('data.economic_snapshot.project_title','QA edição deliberada no simulador')->json('data.economic_snapshot');
$this->assertSame($view['context']['opportunity_choices'],json_decode($simulation['context_applicability_snapshot'],true)['opportunity_choices']);
$manica=collect(app(InvestmentCorridorContext::class)->provinces('beira'))->firstWhere('source_code','06')->id;
$this->get('/investimentos/'.$id.'/contexto/editar?source=opportunity:'.$opportunity->id.'&from_dossier='.$cluster->id.'&province_id='.$manica)
->assertOk()->assertInertia(fn(Assert $p)=>$p->where('requestedChoices.0.territory.id',$province)->where('requestedChoices.0.activities.0','trade')->has('requestedChoices',2)->has('requestedChoices.0.portfolio_origins',2)->has('entryLocationDifferences',1));
$body['version']=$this->getJson('/investimentos/'.$id.'/contexto')->json('case.version');
$body['opportunity_choices'][0]['portfolio_origins'][]=$cluster->id;
$associations=$this->postJson('/investimentos/'.$id.'/contexto/previa',$body)->assertOk()->json();
$this->assertFalse($associations['calculation_inputs_changed']);$this->assertSame([],$associations['review_steps']);
$this->postJson('/investimentos/'.$id.'/contexto/confirmar',[...$body,'preview_hash'=>$associations['preview_hash'],'operation_key'=>(string)Str::uuid(),'confirm'=>true])->assertOk();
$this->getJson('/investimentos/'.$id.'/contexto')->assertJsonPath('context.dependency_hash',$view['context']['dependency_hash'])->assertJsonCount(2,'context.opportunity_choices.0.portfolio_origins');
}
public function test_unrelated_or_private_origins_are_rejected_in_entry_draft_and_preview(): void
{
[$records,$origin]=$this->records();
DB::table('opportunity_projects')->where('opportunity_id',$records[0]->id)->where('project_id',$origin->project_id)->delete();
$this->get('/investimentos/iniciar?source=opportunity:'.$records[0]->id.'&from_dossier='.$origin->id)->assertUnprocessable();
$id=$this->postJson('/investimentos',['title'=>'QA origem inválida','client_key'=>(string)Str::uuid(),'reuse_consent'=>true])->json('id');
$body=['version'=>$this->getJson('/investimentos/'.$id.'/contexto')->json('case.version'),'selection'=>[],'opportunity_choices'=>[['source'=>'opportunity:'.$records[0]->id,'portfolio_origins'=>[$origin->id]]]];
$this->postJson('/investimentos/'.$id.'/contexto/rascunho',[...$body,'draft_sequence'=>1])->assertUnprocessable();
$this->postJson('/investimentos/'.$id.'/contexto/previa',$body)->assertUnprocessable();
$origin->publication_status='draft';$origin->save();
$this->get('/investimentos/iniciar?source=opportunity:'.$records[1]->id.'&from_dossier='.$origin->id)->assertNotFound();
}
}
@@ -0,0 +1,25 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { inheritCompatibleFields } from '../../resources/js/lib/context-inheritance.ts';
import { buildProjectDossierRows, exportProjectDossierCsv } from '../../resources/js/lib/project-dossier.ts';
import { createProjectDossierReport, createProjectDossierPrintHtml } from '../../resources/js/lib/project-dossier-report.ts';
test('selected associations stay attached to each opportunity in reports and do not replace deliberate simulator answers', async()=>{
const choices=[
{opportunity:{key:'opportunity:1',title:'Oportunidade QA A'},territory:{title:'Sofala / Dondo'},portfolio_origins:[{title:'Âncora QA',id:'p',sha256:'internal-hash'}]},
{opportunity:{key:'opportunity:2',title:'Oportunidade QA B'},territory:{title:'Manica'},portfolio_origins:[{title:'Cluster QA',id:'c'}]},
];
const snapshot=JSON.stringify({version:1,context_revision:3,opportunity_choices:choices,land_preparation:{need:'unknown'}});
const values={project_title:'Título deliberado',province_id:'local-edit',context_applicability_snapshot:'old'};
const result=inheritCompatibleFields('dossier:A:simulator',values,{project_title:'Origem',province_id:'source',context_applicability_snapshot:snapshot},null);
assert.equal(result.patch.project_title,undefined);assert.equal(result.patch.province_id,undefined);
assert.equal(result.patch.context_applicability_snapshot,snapshot);
const draft={...values,...result.patch};const before=JSON.stringify(draft);
const rows=buildProjectDossierRows(draft);
assert.ok(rows.some(row=>row[1]==='Associação escolhida na carteira'&&row[2]==='Âncora QA'&&row[3].startsWith('Oportunidade QA A;')));
assert.ok(rows.some(row=>row[1]==='Associação escolhida na carteira'&&row[2]==='Cluster QA'&&row[3].startsWith('Oportunidade QA B;')));
assert.match(exportProjectDossierCsv(draft),/Sofala \/ Dondo/);
const html=await createProjectDossierPrintHtml(createProjectDossierReport(draft,{selectedSections:new Set(['location'])}),[],false);
assert.match(html,/Âncora QA/);assert.match(html,/Cluster QA/);assert.match(html,/Manica/);
assert.doesNotMatch(html,/internal-hash/);assert.equal(JSON.stringify(draft),before);
});
+10 -1
View File
@@ -1,6 +1,15 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { searchTerritoryHref } from '../../resources/js/lib/search-territory.ts';
import { searchTerritoryHref, investmentPreparationHref } from '../../resources/js/lib/search-territory.ts';
test('preparation carries only the validated portfolio origin and territorial choices, including nested catalogue return context',()=>{
const href=investmentPreparationHref(53,'/oportunidades/florestas?province_id=p&district_id=d&q=private-note&context=other','origin');
const query=new URL(href,'https://portal.invalid').searchParams;
assert.equal(query.get('source'),'opportunity:53');assert.equal(query.get('from_dossier'),'origin');
assert.equal(query.get('province_id'),'p');assert.equal(query.get('district_id'),'d');
assert.equal(query.has('q'),false);assert.equal(query.has('context'),false);
assert.equal(new URL(investmentPreparationHref(53,'/oportunidades/florestas?catalogue_query='+encodeURIComponent('province_id=p&district_id=d')),'https://portal.invalid').searchParams.get('district_id'),'d');
});
test('portfolio to catalogue to related screen retains only territorial search filters', () => {
const start = '/carteira?province_id=inh&district_id=vil&q=airport&kind=project';