Entrega dashboard e correccoes transversais preservando Ofertas instalado
tests / ci (push) Canceled after 0s
tests / ci (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\FundingProgrammes;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class FundingCriteriaCoherenceTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
private User $editor;
|
||||
private array $geo = [];
|
||||
private int $sector;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp(); $this->withoutVite();
|
||||
$db = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
$this->assertSame('investor_intent_20261115_test', $db->name); $this->assertSame(55441, (int) $db->port);
|
||||
$this->editor = User::factory()->create(); config(['portal.managers' => [$this->editor->email]]);
|
||||
$parent = null;
|
||||
foreach (['country', 'province', 'district'] as $type) {
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$type, 'code' => $id, 'location_type' => $type, 'source_system' => 'cartografia-workbook', 'data_classification' => 'public', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
|
||||
$this->geo[$type] = $id; $parent = $id;
|
||||
}
|
||||
$this->sector = Sector::create(['slug' => 'synthetic-funding-qa', 'name' => 'SYNTHETIC sector', 'is_active' => true, 'published_at' => now()])->id;
|
||||
}
|
||||
|
||||
private function publish(string $code, string $kind = 'institution', array $overrides = []): string
|
||||
{
|
||||
$source = ['source_url' => 'https://example.invalid/synthetic-qa', 'source_reference' => 'SYNTHETIC QA ONLY', 'checked_on' => today()->toDateString()];
|
||||
$draft = ['title' => 'SYNTHETIC '.$code, 'kind' => $kind, 'manager_name' => 'SYNTHETIC manager', 'summary' => 'Synthetic isolated record, not real content.', 'source_url' => $source['source_url'], 'source_reference' => $source['source_reference'], 'source_checked_on' => $source['checked_on'], 'source_status' => 'identified', 'coverage' => 'national', 'sectors_scope' => 'all', 'funding_needs' => ['investment'], 'windows' => []];
|
||||
if ($kind === 'institution') $draft += ['institution_key' => $code, 'institution_nature' => 'bank', 'institution_categories' => ['banking'], 'institution_types' => ['commercial_bank'], 'institution_status' => 'reported',
|
||||
'locations' => [['role' => 'headquarters', 'label' => 'Synthetic headquarters', 'territory_id' => $this->geo['district'], 'evidence_status' => 'reported', ...$source]],
|
||||
'products' => [['code' => 'investment', 'title' => 'Synthetic investment product', 'needs' => ['investment'], 'coverage' => 'national', 'availability' => 'documented', ...$source]]];
|
||||
$service = app(FundingProgrammes::class);
|
||||
$id = $service->save($this->editor, null, ['version' => 0, 'code' => $code, 'reason' => 'Synthetic QA fixture', 'draft' => array_replace($draft, $overrides)]);
|
||||
$plan = $service->preview($this->editor, $id);
|
||||
$service->publish($this->editor, $id, ['version' => $plan['version'], 'hash' => $plan['hash'], 'confirm' => true, 'reason' => 'Synthetic QA only, rolled back']);
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_bank_filters_apply_to_the_shared_query_and_never_return_brokers_or_microinsurers(): void
|
||||
{
|
||||
$bank = $this->publish('qa-bank');
|
||||
$this->publish('qa-broker', overrides: ['institution_categories' => ['intermediation'], 'institution_types' => ['broker']]);
|
||||
$this->publish('qa-microinsurance', overrides: ['institution_categories' => ['insurance'], 'institution_types' => ['microinsurer']]);
|
||||
$fund = $this->publish('qa-fund', 'fund');
|
||||
$service = app(FundingProgrammes::class);
|
||||
$filters = ['category' => 'banking', 'institution_type' => 'commercial_bank', 'kind' => 'institution', 'certainty' => 'documented', 'location_mode' => 'physical', 'territory' => $this->geo['district'], 'sector' => $this->sector, 'need' => 'investment'];
|
||||
$this->assertSame([$bank], $service->catalogueQuery($filters)->pluck('p.id')->all());
|
||||
$this->assertSame([$fund], $service->catalogueQuery(['kind' => 'fund'])->pluck('p.id')->all());
|
||||
$this->assertSame(0, $service->catalogueQuery(['q' => 'no-such-record'])->count());
|
||||
$this->assertSame(0, $service->catalogueQuery(['category' => 'banking', 'institution_type' => 'investment_bank'])->count(), 'A valid combination without records is an empty result, not an invalid combination.');
|
||||
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $bank)->where('territorySelection.0.id', $this->geo['province'])->where('territorySelection.1.id', $this->geo['district']));
|
||||
$returnFilters = [...$filters, 'q' => 'qa', 'state' => 'closed', 'kind' => 'institution', 'include_historical' => '0', 'province_id' => $this->geo['province'], 'district_id' => $this->geo['district'], 'page' => '2'];
|
||||
$this->get('/fundos/'.$bank.'?'.http_build_query($returnFilters))->assertOk()->assertInertia(function ($page) use ($returnFilters) {
|
||||
foreach ($returnFilters as $key => $value) $page->where('selection.'.$key, (string) $value);
|
||||
});
|
||||
$this->getJson('/api/v1/investment/territory-options?type=district')->assertOk()->assertJsonCount(0, 'data');
|
||||
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$this->geo['province'])->assertOk()->assertJsonCount(1, 'data');
|
||||
}
|
||||
|
||||
public function test_contradictory_type_or_record_kind_and_incomplete_hierarchy_are_rejected(): void
|
||||
{
|
||||
foreach ([['category' => 'banking', 'institution_type' => 'broker'], ['category' => 'banking', 'institution_type' => 'commercial_bank', 'kind' => 'fund', 'location_mode' => 'physical'], ['district_id' => $this->geo['district']]] as $filters) {
|
||||
try { app(FundingProgrammes::class)->catalogueQuery($filters)->count(); $this->fail('Contradictory criteria must not silently broaden a query.'); }
|
||||
catch (ValidationException $error) { $this->assertNotEmpty($error->errors()); }
|
||||
$this->getJson('/fundos?'.http_build_query($filters))->assertUnprocessable();
|
||||
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page->has('criteriaErrors')->has('items.data', 0));
|
||||
}
|
||||
}
|
||||
|
||||
public function test_unknown_scope_is_not_a_documented_match_and_physical_presence_does_not_prove_coverage(): void
|
||||
{
|
||||
$this->publish('qa-unknown', overrides: ['sectors_scope' => 'unknown', 'products' => []]);
|
||||
$service = app(FundingProgrammes::class);
|
||||
$this->assertSame(0, $service->catalogueQuery(['need' => 'investment', 'certainty' => 'documented'])->count());
|
||||
$this->assertSame(0, $service->catalogueQuery(['sector' => $this->sector, 'certainty' => 'documented'])->count());
|
||||
$this->assertSame(1, $service->catalogueQuery(['territory' => $this->geo['district'], 'location_mode' => 'physical', 'certainty' => 'documented'])->count());
|
||||
$this->assertSame(0, $service->catalogueQuery(['territory' => $this->geo['district'], 'location_mode' => 'coverage', 'certainty' => 'documented'])->count());
|
||||
$this->assertSame(1, $service->catalogueQuery(['need' => 'investment', 'certainty' => 'include_unknown'])->count());
|
||||
$this->assertSame(0, $service->catalogueQuery(['state' => 'closed'])->count(), 'An institution without a window is not a closed funding window.');
|
||||
}
|
||||
|
||||
public function test_window_state_and_scope_are_matched_on_the_same_window_without_inventing_a_local_window(): void
|
||||
{
|
||||
$source = ['source_url' => 'https://example.invalid/synthetic-qa', 'source_reference' => 'Synthetic window', 'checked_on' => today()->toDateString()];
|
||||
$id = $this->publish('qa-closed-window', overrides: ['windows' => [['code' => 'closed', 'title' => 'Synthetic closed window', 'mode' => 'closed', 'coverage' => 'unknown', ...$source]]]);
|
||||
$service = app(FundingProgrammes::class);
|
||||
$criteria = ['territory' => $this->geo['district'], 'certainty' => 'documented', 'state' => 'closed', 'location_mode' => 'coverage'];
|
||||
$this->assertSame(0, $service->catalogueQuery($criteria)->count());
|
||||
$this->assertSame([$id], $service->catalogueQuery([...$criteria, 'certainty' => 'include_unknown'])->pluck('p.id')->all());
|
||||
$this->assertSame([$id], $service->catalogueQuery([...$criteria, 'location_mode' => 'physical'])->pluck('p.id')->all());
|
||||
$this->assertSame(0, $service->catalogueQuery([...$criteria, 'state' => 'open'])->count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Requests\StoreSimulationFormDraftRequest;
|
||||
use App\Models\InvestmentZone;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestorContext;
|
||||
use App\Services\ProactiveSupply;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class InvestorIntentContinuityTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$db = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
$this->assertSame('investor_intent_20261115_test', $db->name);
|
||||
$this->assertSame(55441, (int) $db->port);
|
||||
$this->withoutVite();
|
||||
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
}
|
||||
|
||||
public function test_internal_business_observations_remain_closed_to_an_ordinary_investor(): void
|
||||
{
|
||||
$this->expectException(HttpException::class);
|
||||
app(ProactiveSupply::class)->authorize(User::factory()->create());
|
||||
}
|
||||
|
||||
public function test_demography_source_recovers_its_hierarchy_without_replacing_a_saved_location(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$parent = null;
|
||||
$ids = [];
|
||||
foreach (['country', 'province', 'district'] as $type) {
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$type, 'code' => $id, 'location_type' => $type,
|
||||
'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
|
||||
$ids[$type] = $id;
|
||||
$parent = $id;
|
||||
}
|
||||
$id = $this->actingAs($owner)->postJson('/investimentos', ['title' => 'SYNTHETIC demography source', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$url = '/investimentos/'.$id.'/contexto/editar?'.http_build_query(['source' => 'territory:'.$ids['district']]);
|
||||
$this->get($url)->assertOk()->assertInertia(fn ($page) => $page->where('entryTerritory.id', $ids['district'])->where('territorySelection.0.id', $ids['province'])->where('territorySelection.1.id', $ids['district']));
|
||||
$version = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json('case.version');
|
||||
$body = ['version' => $version, 'selection' => ['territory' => 'territory:'.$ids['province']], 'opportunity_choices' => [], 'declarations' => []];
|
||||
$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->get($url)->assertOk()->assertInertia(fn ($page) => $page->where('initial.context.selection.territory.id', $ids['province'])->where('territorySelection.0.id', $ids['province'])->has('territorySelection', 1));
|
||||
$this->actingAs(User::factory()->create())->get($url)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_an_own_idea_preserves_sector_locality_and_budget_interval_without_any_advert_or_corridor(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$parent = null;
|
||||
$path = [];
|
||||
foreach (['country' => 'QA Mozambique', 'province' => 'Maputo Provincia', 'district' => 'Boane', 'admin_post' => 'Matola Rio', 'locality' => 'Matola Rio-Sede'] as $type => $name) {
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$name, 'code' => $id, 'location_type' => $type,
|
||||
'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
|
||||
$path[$type.'_id'] = $id;
|
||||
$parent = $id;
|
||||
}
|
||||
$reviewer = User::factory()->create();
|
||||
$zone = InvestmentZone::query()->create(['id' => (string) Str::uuid(), 'code' => 'SINT-QA-'.Str::random(8), 'name' => 'SYNTHETIC documented site',
|
||||
'category' => 'industrial_park', 'physical_category' => 'industrial_park', 'primary_territory_id' => $parent, 'publication_status' => 'published', 'validation_status' => 'validated',
|
||||
'editor_id' => $owner->id, 'reviewer_id' => $reviewer->id, 'published_at' => now(), 'source_evidence' => [['source_type' => 'promoter', 'url' => 'https://example.invalid/synthetic-qa', 'supports' => 'Synthetic QA only, no operational or legal assertion.']]]);
|
||||
$zones = $this->actingAs($owner)->getJson('/investimentos/opcoes-corredor?include_corridors=0&territory='.$parent);
|
||||
$this->assertSame(200, $zones->status(), $zones->getContent());
|
||||
$zones->assertJsonPath('parks.0.id', $zone->id)->assertJsonCount(1, 'parks');
|
||||
$this->getJson('/investimentos/opcoes-corredor?include_corridors=0')->assertOk()->assertJsonPath('parks', []);
|
||||
config(['investor-path.aggregate_supply_qa_enabled' => true]);
|
||||
$source = hash('sha256', 'Synthetic private aggregate source');
|
||||
DB::table('proactive_supply_sources')->insert(['sha256' => $source, 'name' => 'PRIVATE-SOURCE-NOT-FOR-OUTPUT.xlsx', 'period' => '2020', 'limitations' => 'Synthetic only', 'receipt' => '{}', 'imported_at' => now()]);
|
||||
$base = ['source_hash' => $source, 'sheet' => 'PRIVATE-SHEET', 'entity_key' => hash('sha256', 'entity-a'), 'name' => 'PRIVATE-COMPANY-NAME', 'province' => 'Synthetic', 'district' => 'Synthetic', 'cae' => '01110', 'activity' => 'PRIVATE-CONTACT-+258000000000', 'sector' => 'PRIVATE-RAW-SECTOR', 'source_date' => '2020', 'fingerprint' => hash('sha256', 'fingerprint'), 'duplicate_of' => null, 'identity_conflict' => false, 'territory_id' => $path['district_id'], 'territory_resolution' => 'exact_normalized_province_district'];
|
||||
foreach ([1 => [], 2 => ['duplicate_of' => hash('sha256', 'row-1')], 3 => ['identity_conflict' => true, 'entity_key' => hash('sha256', 'uncertain')], 4 => ['entity_key' => hash('sha256', 'unclassified'), 'cae' => 'PRIVATE-UNCLASSIFIED-TEXT']] as $number => $changes) {
|
||||
DB::table('proactive_supply_observations')->insert([...$base, 'id' => hash('sha256', 'row-'.$number), 'row_number' => $number, ...$changes]);
|
||||
}
|
||||
foreach (['Agronegocio' => 'agro-qa', 'Criar Hotel' => 'hotel-qa'] as $title => $slug) {
|
||||
$sector = Sector::create(['name' => 'SYNTHETIC '.$slug, 'slug' => $slug, 'is_active' => true]);
|
||||
$id = $this->actingAs($owner)->postJson('/investimentos', ['title' => $title, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
|
||||
$entry = [...array_diff_key($path, ['country_id' => true]), 'sector_id' => (string) $sector->id, 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000'];
|
||||
$this->get('/investimentos/iniciar?'.http_build_query($entry))->assertOk()->assertInertia(fn ($page) => $page->where('entryQuery.investment_budget_max', '5000000')->where('entryQuery.locality_id', $parent));
|
||||
$this->get('/investimentos/'.$id.'/contexto/editar?'.http_build_query($entry))->assertOk()->assertInertia(fn ($page) => $page->where('entryTerritory.id', $parent)->where('entryIdea.sector_id', (string) $sector->id));
|
||||
$body = ['version' => $view['case']['version'], 'selection' => ['sector' => 'sector:'.$sector->id, 'territory' => 'territory:'.$parent],
|
||||
'opportunity_choices' => [], 'declarations' => ['project_title' => $title, 'products_services' => 'SYNTHETIC explicit activity '.$slug, 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
|
||||
$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();
|
||||
$saved = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.locality_id', $parent)
|
||||
->assertJsonPath('prefill.simulator.investment_budget_min', '1000000')->assertJsonPath('prefill.simulator.investment_budget_max', '5000000')
|
||||
->assertJsonPath('prefill.simulator.project_title', $title)->json();
|
||||
$this->assertSame('SYNTHETIC explicit activity '.$slug, $saved['prefill']['simulator']['products_services']);
|
||||
$this->assertEmpty($saved['context']['opportunity_choices'] ?? []);
|
||||
$this->assertEmpty($saved['context']['selection']['opportunity'] ?? null);
|
||||
$this->assertEmpty($saved['prefill']['simulator']['total_investment'] ?? null);
|
||||
$command = ['version' => $saved['case']['version'], 'operation_key' => (string) Str::uuid()];
|
||||
$url = '/investimentos/'.$id.'/contexto/oferta-agregada';
|
||||
$aggregate = $this->postJson($url, $command)->assertOk()->assertJsonPath('analysis.entities', 2)->assertJsonPath('analysis.repeated', 1)->assertJsonPath('analysis.uncertain', 1)
|
||||
->assertJsonPath('analysis.broader_context', true)->assertJsonPath('analysis.scope.id', $path['district_id']);
|
||||
$this->assertStringNotContainsString('PRIVATE-', $aggregate->getContent());
|
||||
$this->assertStringNotContainsString($source, $aggregate->getContent());
|
||||
$this->postJson($url, $command)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'supply_aggregates')->assertJsonPath('supply_aggregates.0.entities', 2);
|
||||
config(['investor-path.aggregate_supply_qa_enabled' => false]);
|
||||
$this->postJson($url, $command)->assertNotFound();
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('supply_aggregates', [])->assertJsonPath('supply_aggregate_enabled', false);
|
||||
config(['investor-path.aggregate_supply_qa_enabled' => true]);
|
||||
$this->actingAs(User::factory()->create())->postJson($url, $command)->assertForbidden();
|
||||
$this->actingAs($owner);
|
||||
// UI keeps display labels in selection_labels, outside canonical fields.
|
||||
$economic = array_filter($saved['prefill']['simulator'], fn ($key) => ! str_ends_with($key, '_label') && $key !== 'email', ARRAY_FILTER_USE_KEY);
|
||||
$economic['purpose'] = 'own_investment';
|
||||
// Explicit synthetic scenario; the budget interval remains separate.
|
||||
$economic['total_investment'] = '2000000';
|
||||
$economic['secured_amount'] = '1000000';
|
||||
$economic['annual_revenue'] = '300000';
|
||||
$economic['planning_loan'] = 'no';
|
||||
$economic['planning_assumptions_snapshot'] = json_encode(['version' => 1, 'data' => ['model' => 'other', 'capacity' => '100', 'price' => '250', 'occupancy' => '', 'frequency' => '12', 'source' => 'Synthetic explicit assumptions', 'costs' => []]], JSON_THROW_ON_ERROR);
|
||||
$economic['financial_tools_snapshot'] = json_encode(['version' => 1, 'data' => ['budgetPeriod' => 'Mensal',
|
||||
'loan' => ['principal' => '', 'rate' => '', 'months' => '', 'rateType' => 'nominal', 'periodMonths' => '1', 'gracePeriods' => '', 'upfrontFee' => '', 'recurringFee' => ''],
|
||||
'breakEven' => ['fixed' => '100000', 'price' => '5000', 'variable' => '2000'], 'funding' => ['total' => '2000000', 'secured' => '1000000'],
|
||||
'incomes' => [['label' => 'Synthetic declared revenue', 'amount' => '300000']], 'expenses' => [['label' => 'Synthetic declared costs', 'amount' => '200000']]]], JSON_THROW_ON_ERROR);
|
||||
$allowed = explode(',', substr((new StoreSimulationFormDraftRequest)->rules()['economic_snapshot'][1], 6));
|
||||
$this->assertSame([], array_values(array_diff(array_keys($economic), $allowed)));
|
||||
$simulation = $this->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
|
||||
$draft = $this->getJson('/api/v1/simulation-drafts/'.$simulation)->assertOk()->assertJsonPath('data.economic_snapshot.investment_budget_min', '1000000')->assertJsonPath('data.economic_snapshot.investment_budget_max', '5000000')->assertJsonPath('data.economic_snapshot.financial_tools_snapshot', $economic['financial_tools_snapshot'])->json('data');
|
||||
$dossier = $this->getJson('/investimentos/'.$id)->assertOk()->json();
|
||||
$return = ['version' => $dossier['case']['version'], 'draft_id' => $simulation, 'draft_version' => $draft['version_no'], 'context_revision' => $dossier['investment_context']['revision'], 'context_reviewed' => true];
|
||||
$result = $this->postJson('/investimentos/'.$id.'/resultados', $return)->assertOk()->assertJsonPath('result.financial_snapshot', $economic['financial_tools_snapshot'])->assertJsonPath('result.preparation_snapshot.planning_loan', 'no')->assertJsonPath('result.preparation_snapshot.annual_revenue', '300000')->assertJsonPath('result.preparation_snapshot.planning_assumptions_snapshot', $economic['planning_assumptions_snapshot'])->json('result.id');
|
||||
$this->postJson('/investimentos/'.$id.'/resultados', $return)->assertOk()->assertJsonPath('result.id', $result);
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'results')->assertJsonPath('results.0.id', $result)->assertJsonPath('results.0.currency', 'MZN');
|
||||
$this->actingAs(User::factory()->create())->getJson('/api/v1/simulation-drafts/'.$simulation)->assertNotFound();
|
||||
$this->actingAs($owner);
|
||||
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.investment_budget_max', '5000000');
|
||||
$this->actingAs(User::factory()->create())->getJson('/investimentos/'.$id.'/contexto')->assertForbidden();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_an_incomplete_currency_can_be_recovered_privately_but_cannot_be_confirmed(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create());
|
||||
$id = $this->postJson('/investimentos', ['title' => 'Synthetic draft', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
|
||||
$body = ['version' => $view['case']['version'], 'selection' => [], 'declarations' => ['currency' => 'MZ']];
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/rascunho', [...$body, 'draft_sequence' => 1])->assertOk();
|
||||
$this->assertSame('MZ', app(InvestorContext::class)->draft(auth()->user(), $id)['declarations']['currency']);
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertUnprocessable()->assertJsonValidationErrors('declarations.currency');
|
||||
$body['declarations'] = ['currency' => 'MZN', 'investment_budget_min' => '5000000', 'investment_budget_max' => '1000000'];
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertUnprocessable()->assertJsonValidationErrors('declarations.investment_budget_max');
|
||||
}
|
||||
|
||||
public function test_district_demography_is_never_presented_as_locality_population(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$parent = null;
|
||||
$district = null;
|
||||
foreach (['country', 'province', 'district', 'admin_post', 'locality'] as $type) {
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$type, 'code' => $id, 'location_type' => $type, 'data_classification' => 'public',
|
||||
'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
|
||||
if ($type === 'district') {
|
||||
$district = $id;
|
||||
}
|
||||
$parent = $id;
|
||||
}
|
||||
$batch = (string) Str::uuid();
|
||||
DB::table('demographic_imports')->insert(['id' => $batch, 'sha256' => hash('sha256', $batch), 'file_name' => 'SYNTHETIC.xlsx', 'source' => 'Synthetic only', 'publication_version' => 'QA/1', 'status' => 'approved', 'report' => '{}', 'preview_sha256' => str_repeat('0', 64), 'prepared_by' => $owner->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
DB::table('demographic_observations')->insert(['import_id' => $batch, 'geo_location_id' => $district, 'year' => 2026, 'indicator' => 'population', 'sex' => 'all', 'residence' => 'all', 'age_group' => 'all', 'unit' => 'pessoas', 'data_kind' => 'projected', 'original_value' => '12345', 'numeric_value' => '12345', 'sheet' => '2026', 'cell' => 'B4', 'validation_status' => 'valid']);
|
||||
$url = '/api/v1/investment/demography?'.http_build_query(['territories' => [$parent], 'start_year' => 2026, 'investment_context' => 1]);
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('broader_context', true)->assertJsonPath('requested_territory.id', $parent)
|
||||
->assertJsonPath('territories.0.id', $district)->assertJsonPath('territories.0.level', 'district')->assertJsonPath('territories.0.series.0.values.0.original_value', '12345');
|
||||
DB::table('geo_locations')->where('id', $parent)->update(['data_classification' => 'internal']);
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('requested_territory', null)->assertJsonPath('territories', []);
|
||||
}
|
||||
|
||||
public function test_guided_unknown_answers_and_their_labels_save_and_recover_in_the_existing_simulator_contract(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create());
|
||||
$economic = ['purpose' => 'simulate_only', 'journey_type' => 'investor'];
|
||||
$economic['preparation_step'] = 'operating';
|
||||
$economic['fiscal_tools_selection'] = ['tax:sales', 'iva:acquisitions'];
|
||||
$economic['initial_budget_snapshot'] = json_encode(['version' => 1, 'rows' => [['label' => 'Synthetic equipment', 'amount' => '1000000']]], JSON_THROW_ON_ERROR);
|
||||
$economic['planning_assumptions_snapshot'] = json_encode(['version' => 1, 'data' => ['model' => 'hotel', 'capacity' => '10', 'price' => '5000', 'occupancy' => '50', 'frequency' => '300', 'source' => 'Synthetic only', 'costs' => []]], JSON_THROW_ON_ERROR);
|
||||
foreach (['customer_validation_status', 'location_assessment_status', 'cost_estimate_status', 'receivables_timing_status', 'funding_status'] as $field) {
|
||||
$economic[$field] = 'unknown';
|
||||
$economic['selection_labels'][$field] = 'Ainda não sei';
|
||||
}
|
||||
$id = $this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
|
||||
$this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk()->assertJsonPath('data.economic_snapshot.selection_labels.funding_status', 'Ainda não sei')->assertJsonPath('data.economic_snapshot.preparation_step', 'operating')->assertJsonPath('data.economic_snapshot.planning_assumptions_snapshot', $economic['planning_assumptions_snapshot'])->assertJsonPath('data.economic_snapshot.fiscal_tools_selection', $economic['fiscal_tools_selection'])->assertJsonPath('data.economic_snapshot.initial_budget_snapshot', $economic['initial_budget_snapshot']);
|
||||
$economic['selection_labels']['unsupported_field'] = 'Unsupported';
|
||||
$this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertUnprocessable()->assertJsonValidationErrors('economic_snapshot.selection_labels.unsupported_field');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?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 InvestorPromoterContinuityTest 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('investor_intent_20261115_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 $owner, string $title): string
|
||||
{
|
||||
$id = $this->actingAs($owner)->postJson('/investimentos', ['title' => $title, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
|
||||
$body = ['version' => $view['case']['version'], 'selection' => [], 'declarations' => ['products_services' => 'SYNTHETIC activity '.$title, 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
|
||||
$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();
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_existing_company_is_reused_without_changing_ownership_or_repeating_the_comparison(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$this->actingAs($owner);
|
||||
$company = $this->postJson('/api/v1/investment/companies', ['version' => 0, 'operation_key' => (string) Str::uuid(), 'payload' => ['name' => 'SYNTHETIC Hotel Company', 'incorporation_country_code' => 'MZ', 'registration' => 'SYNTHETIC-QA-REG', 'role' => 'SYNTHETIC representative', 'legal_form' => 'quotas']])->assertSuccessful()->json('id');
|
||||
$id = $this->dossier($owner, 'Criar Hotel');
|
||||
$options = $this->getJson('/investimentos/'.$id.'/contexto/entidade')->assertOk()->assertJsonPath('companies.0.id', $company)->json();
|
||||
$memberships = DB::table('memberships')->count();
|
||||
$command = ['version' => $options['version'], 'operation_key' => (string) Str::uuid(), 'kind' => 'company', 'id' => $company, 'source_version' => 1];
|
||||
$url = '/investimentos/'.$id.'/contexto/entidade';
|
||||
$this->postJson($url, $command)->assertOk()->assertJsonPath('continue', '/investimentos/'.$id);
|
||||
$this->postJson($url, $command)->assertOk()->assertJsonPath('replayed', true);
|
||||
$case = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$this->assertSame($owner->id, (int) $case->user_id);
|
||||
$this->assertNull($case->organization_id);
|
||||
$this->assertSame($company, $case->company_id);
|
||||
$this->assertSame($memberships, DB::table('memberships')->count());
|
||||
$this->assertSame(1, DB::table('investment_company_declarations')->where('user_id', $owner->id)->count());
|
||||
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.legal_name', 'SYNTHETIC Hotel Company')->assertJsonPath('prefill.simulator.legal_form', 'quotas')->assertJsonPath('prefill.simulator.entity_stage', 'existing')->assertJsonPath('prefill.simulator.investment_budget_max', '5000000');
|
||||
$preparation = $this->getJson('/investimentos/'.$id.'/preparar-empresa')->assertOk()->assertJsonPath('facts.proposed_name', 'SYNTHETIC Hotel Company')->assertJsonPath('facts.form', 'quotas')->json();
|
||||
$facts = $preparation['facts'];
|
||||
$facts['notes'] = 'SYNTHETIC deliberate note';
|
||||
$this->postJson('/investimentos/'.$id.'/preparar-empresa', ['version' => $preparation['case']['version'], 'operation_key' => (string) Str::uuid(), 'facts' => $facts])->assertOk();
|
||||
$recovered = $this->getJson('/investimentos/'.$id.'/preparar-empresa')->assertOk()->assertJsonPath('facts.notes', 'SYNTHETIC deliberate note')->json();
|
||||
$facts['form'] = 'anonymous';
|
||||
$this->postJson('/investimentos/'.$id.'/preparar-empresa', ['version' => $recovered['case']['version'], 'operation_key' => (string) Str::uuid(), 'facts' => $facts])->assertUnprocessable();
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('tools.simulator', '/simulador-fiscal?context='.$id);
|
||||
$this->actingAs(User::factory()->create())->postJson($url, $command)->assertForbidden();
|
||||
$otherCase = $this->dossier(auth()->user(), 'Another private idea');
|
||||
$v = $this->getJson('/investimentos/'.$otherCase.'/contexto/entidade')->assertOk()->assertJsonCount(0, 'companies')->json('version');
|
||||
$this->postJson('/investimentos/'.$otherCase.'/contexto/entidade', [...$command, 'version' => $v, 'operation_key' => (string) Str::uuid()])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_optional_comparison_can_continue_into_the_same_unconstituted_entity_and_recover_without_creating_a_company(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
foreach (['Criar Hotel', 'Agronegocio QA'] as $title) {
|
||||
$id = $this->dossier($owner, $title);
|
||||
$comparison = $this->getJson('/investimentos/'.$id.'/forma-juridica')->assertOk()->json();
|
||||
$answers = $comparison['answers'];
|
||||
$answers['preferred'] = 'quotas';
|
||||
$body = ['version' => $comparison['case']['version'], 'operation_key' => (string) Str::uuid(), 'answers' => $answers, 'continue_preparation' => true];
|
||||
$this->postJson('/investimentos/'.$id.'/forma-juridica', $body)->assertOk();
|
||||
$this->postJson('/investimentos/'.$id.'/forma-juridica', $body)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.entity_stage', 'being_formed');
|
||||
$preparation = $this->getJson('/investimentos/'.$id.'/preparar-empresa?form=quotas')->assertOk()->assertJsonPath('facts.form', 'quotas')->assertJsonPath('facts.activities', 'SYNTHETIC activity '.$title)->json();
|
||||
$facts = $preparation['facts'];
|
||||
$facts['proposed_name'] = 'SYNTHETIC new company '.$title;
|
||||
$this->postJson('/investimentos/'.$id.'/preparar-empresa', ['version' => $preparation['case']['version'], 'operation_key' => (string) Str::uuid(), 'facts' => $facts])->assertOk();
|
||||
$this->getJson('/investimentos/'.$id.'/preparar-empresa?form=anonymous')->assertOk()->assertJsonPath('facts.form', 'quotas')->assertJsonPath('proposedForm', 'anonymous');
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('investment_context.promoter_entity.kind', 'being_formed');
|
||||
$this->assertSame(0, DB::table('investment_company_declarations')->where('user_id', $owner->id)->count());
|
||||
$this->assertNull(DB::table('desk_cases')->where('id', $id)->value('company_id'));
|
||||
$version = $this->getJson('/investimentos/'.$id.'/contexto/entidade')->json('version');
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/entidade', ['version' => $version, 'operation_key' => (string) Str::uuid(), 'kind' => 'undetermined'])->assertOk();
|
||||
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('investment_context.promoter_entity.kind', 'undetermined')->assertJsonPath('tools.simulator', '/simulador-fiscal?context='.$id);
|
||||
$this->getJson('/investimentos/'.$id.'/preparar-empresa')->assertOk()->assertJsonPath('facts.proposed_name', $facts['proposed_name']);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_an_authorised_organization_snapshot_does_not_transfer_the_case_or_grant_master_write_access(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC represented organization', 'source_system' => 'unit-qa', 'organization_type' => 'private']);
|
||||
DB::table('memberships')->insert(['user_id' => $owner->id, 'organization_id' => $org, 'role' => 'viewer']);
|
||||
$id = $this->dossier($owner, 'Hotel with existing organization');
|
||||
$url = '/investimentos/'.$id.'/contexto/entidade';
|
||||
$options = $this->getJson($url)->assertOk()->assertJsonPath('organizations.0.id', $org)->json();
|
||||
$command = ['kind' => 'organization', 'id' => $org, 'version' => $options['version'], 'operation_key' => (string) Str::uuid(), 'source_version' => 99];
|
||||
$this->postJson($url, $command)->assertConflict();
|
||||
$command['source_version'] = 1;
|
||||
$this->postJson($url, $command)->assertOk();
|
||||
$case = DB::table('desk_cases')->where('id', $id)->first();
|
||||
$this->assertNull($case->organization_id); $this->assertNull($case->company_id); $this->assertSame($owner->id, (int) $case->user_id);
|
||||
$this->assertSame('viewer', DB::table('memberships')->where('user_id', $owner->id)->where('organization_id', $org)->value('role'));
|
||||
config(['portal.organization_country_enabled' => true]);
|
||||
$this->putJson('/api/v1/investment/organizations/'.$org.'/country', ['version' => 1, 'country' => 'MZ', 'source_reference' => 'Synthetic QA'])->assertForbidden();
|
||||
DB::table('memberships')->where('user_id', $owner->id)->where('organization_id', $org)->update(['deleted_at' => now()]);
|
||||
$current = $this->getJson($url)->assertOk()->assertJsonCount(0, 'organizations')->assertJsonPath('selected.snapshot.name', 'SYNTHETIC represented organization')->json();
|
||||
$this->postJson($url, [...$command, 'version' => $current['version'], 'operation_key' => (string) Str::uuid()])->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,707 @@
|
||||
{
|
||||
"provenance": "Texto colado(5).txt fornecido pela Tempo, conferido na página pública em 2026-11-15; Manica.xlsx, folha 2026, B/E/H54 e B/E/H56:72. Valores de apresentação, não reimportação.",
|
||||
"values": [
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "all",
|
||||
"residence": "all",
|
||||
"value": "248518.44160696748",
|
||||
"original_value": "248518.44160696748",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B54",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "all",
|
||||
"residence": "urban",
|
||||
"value": "86749.367563197302",
|
||||
"original_value": "86749.367563197302",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E54",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "all",
|
||||
"residence": "rural",
|
||||
"value": "161769.0740437702",
|
||||
"original_value": "161769.0740437702",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H54",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "0-4",
|
||||
"residence": "all",
|
||||
"value": "44289.138086159306",
|
||||
"original_value": "44289.138086159306",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B56",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "0-4",
|
||||
"residence": "urban",
|
||||
"value": "14514.88099755138",
|
||||
"original_value": "14514.88099755138",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E56",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "0-4",
|
||||
"residence": "rural",
|
||||
"value": "29774.257088607934",
|
||||
"original_value": "29774.257088607934",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H56",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "5-9",
|
||||
"residence": "all",
|
||||
"value": "35827.776591901806",
|
||||
"original_value": "35827.776591901806",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B57",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "5-9",
|
||||
"residence": "urban",
|
||||
"value": "11793.491606737534",
|
||||
"original_value": "11793.491606737534",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E57",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "5-9",
|
||||
"residence": "rural",
|
||||
"value": "24034.284985164271",
|
||||
"original_value": "24034.284985164271",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H57",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "10-14",
|
||||
"residence": "all",
|
||||
"value": "33152.970732328176",
|
||||
"original_value": "33152.970732328176",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B58",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "10-14",
|
||||
"residence": "urban",
|
||||
"value": "10676.607713136782",
|
||||
"original_value": "10676.607713136782",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E58",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "10-14",
|
||||
"residence": "rural",
|
||||
"value": "22476.363019191398",
|
||||
"original_value": "22476.363019191398",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H58",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "15-19",
|
||||
"residence": "all",
|
||||
"value": "29611.438388752566",
|
||||
"original_value": "29611.438388752566",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B59",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "15-19",
|
||||
"residence": "urban",
|
||||
"value": "10262.814463997336",
|
||||
"original_value": "10262.814463997336",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E59",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "15-19",
|
||||
"residence": "rural",
|
||||
"value": "19348.623924755229",
|
||||
"original_value": "19348.623924755229",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H59",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "20-24",
|
||||
"residence": "all",
|
||||
"value": "24355.209722981959",
|
||||
"original_value": "24355.209722981959",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B60",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "20-24",
|
||||
"residence": "urban",
|
||||
"value": "9042.4481146842572",
|
||||
"original_value": "9042.4481146842572",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E60",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "20-24",
|
||||
"residence": "rural",
|
||||
"value": "15312.761608297704",
|
||||
"original_value": "15312.761608297704",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H60",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "25-29",
|
||||
"residence": "all",
|
||||
"value": "19575.376496383324",
|
||||
"original_value": "19575.376496383324",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B61",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "25-29",
|
||||
"residence": "urban",
|
||||
"value": "7599.5545011499053",
|
||||
"original_value": "7599.5545011499053",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E61",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "25-29",
|
||||
"residence": "rural",
|
||||
"value": "11975.82199523342",
|
||||
"original_value": "11975.82199523342",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H61",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "30-34",
|
||||
"residence": "all",
|
||||
"value": "14806.636171744825",
|
||||
"original_value": "14806.636171744825",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B62",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "30-34",
|
||||
"residence": "urban",
|
||||
"value": "6262.1273781029959",
|
||||
"original_value": "6262.1273781029959",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E62",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "30-34",
|
||||
"residence": "rural",
|
||||
"value": "8544.5087936418295",
|
||||
"original_value": "8544.5087936418295",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H62",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "35-39",
|
||||
"residence": "all",
|
||||
"value": "11161.453343365156",
|
||||
"original_value": "11161.453343365156",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B63",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "35-39",
|
||||
"residence": "urban",
|
||||
"value": "4625.8522262806891",
|
||||
"original_value": "4625.8522262806891",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E63",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "35-39",
|
||||
"residence": "rural",
|
||||
"value": "6535.6011170844686",
|
||||
"original_value": "6535.6011170844686",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H63",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "40-44",
|
||||
"residence": "all",
|
||||
"value": "8538.8490092624561",
|
||||
"original_value": "8538.8490092624561",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B64",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "40-44",
|
||||
"residence": "urban",
|
||||
"value": "3443.8323932108847",
|
||||
"original_value": "3443.8323932108847",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E64",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "40-44",
|
||||
"residence": "rural",
|
||||
"value": "5095.0166160515719",
|
||||
"original_value": "5095.0166160515719",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H64",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "45-49",
|
||||
"residence": "all",
|
||||
"value": "7101.0415927196163",
|
||||
"original_value": "7101.0415927196163",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B65",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "45-49",
|
||||
"residence": "urban",
|
||||
"value": "2463.4886973717157",
|
||||
"original_value": "2463.4886973717157",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E65",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "45-49",
|
||||
"residence": "rural",
|
||||
"value": "4637.5528953479006",
|
||||
"original_value": "4637.5528953479006",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H65",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "50-54",
|
||||
"residence": "all",
|
||||
"value": "5226.3070949472531",
|
||||
"original_value": "5226.3070949472531",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B66",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "50-54",
|
||||
"residence": "urban",
|
||||
"value": "1679.6467072735772",
|
||||
"original_value": "1679.6467072735772",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E66",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "50-54",
|
||||
"residence": "rural",
|
||||
"value": "3546.6603876736754",
|
||||
"original_value": "3546.6603876736754",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H66",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "55-59",
|
||||
"residence": "all",
|
||||
"value": "3998.2566339012192",
|
||||
"original_value": "3998.2566339012192",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B67",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "55-59",
|
||||
"residence": "urban",
|
||||
"value": "1240.8880754969321",
|
||||
"original_value": "1240.8880754969321",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E67",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "55-59",
|
||||
"residence": "rural",
|
||||
"value": "2757.3685584042869",
|
||||
"original_value": "2757.3685584042869",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H67",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "60-64",
|
||||
"residence": "all",
|
||||
"value": "3135.4929526634714",
|
||||
"original_value": "3135.4929526634714",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B68",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "60-64",
|
||||
"residence": "urban",
|
||||
"value": "1009.9040617408737",
|
||||
"original_value": "1009.9040617408737",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E68",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "60-64",
|
||||
"residence": "rural",
|
||||
"value": "2125.5888909225978",
|
||||
"original_value": "2125.5888909225978",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H68",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "65-69",
|
||||
"residence": "all",
|
||||
"value": "2537.0624121248256",
|
||||
"original_value": "2537.0624121248256",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B69",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "65-69",
|
||||
"residence": "urban",
|
||||
"value": "753.99704079870799",
|
||||
"original_value": "753.99704079870799",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E69",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "65-69",
|
||||
"residence": "rural",
|
||||
"value": "1783.0653713261181",
|
||||
"original_value": "1783.0653713261181",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H69",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "70-74",
|
||||
"residence": "all",
|
||||
"value": "2016.6006284927157",
|
||||
"original_value": "2016.6006284927157",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B70",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "70-74",
|
||||
"residence": "urban",
|
||||
"value": "576.8557228333616",
|
||||
"original_value": "576.8557228333616",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E70",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "70-74",
|
||||
"residence": "rural",
|
||||
"value": "1439.7449056593541",
|
||||
"original_value": "1439.7449056593541",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H70",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "75-79",
|
||||
"residence": "all",
|
||||
"value": "1320.7863269208433",
|
||||
"original_value": "1320.7863269208433",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B71",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "75-79",
|
||||
"residence": "urban",
|
||||
"value": "331.39109408599069",
|
||||
"original_value": "331.39109408599069",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E71",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "75-79",
|
||||
"residence": "rural",
|
||||
"value": "989.39523283485266",
|
||||
"original_value": "989.39523283485266",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H71",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "80+",
|
||||
"residence": "all",
|
||||
"value": "1864.0454223179609",
|
||||
"original_value": "1864.0454223179609",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "B72",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "80+",
|
||||
"residence": "urban",
|
||||
"value": "471.58676874437788",
|
||||
"original_value": "471.58676874437788",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "E72",
|
||||
"validation_status": "warning"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"indicator": "population",
|
||||
"age_group": "80+",
|
||||
"residence": "rural",
|
||||
"value": "1392.458653573583",
|
||||
"original_value": "1392.458653573583",
|
||||
"unit": "pessoas",
|
||||
"data_kind": "projected",
|
||||
"sheet": "2026",
|
||||
"cell": "H72",
|
||||
"validation_status": "warning"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
catalogueDetailHref,
|
||||
catalogueReturnHref,
|
||||
catalogueQuery,
|
||||
} from '../../resources/js/lib/catalogue-context.ts';
|
||||
|
||||
test('return preserves deliberate destination edits, including cleared ancestors, without stale descendants', () => {
|
||||
const detail = catalogueDetailHref(
|
||||
'/carteira/a',
|
||||
'q=energia&province_id=p&district_id=d&page=4',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueReturnHref('/carteira?q=turismo&province_id=', detail),
|
||||
'/carteira?q=turismo&province_id=&page=4',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueReturnHref('/carteira?province_id=other', detail),
|
||||
'/carteira?province_id=other&q=energia&page=4',
|
||||
);
|
||||
});
|
||||
test('different catalogue families share geography but not text, kind, price, page or private context', () => {
|
||||
const detail =
|
||||
'/carteira/a?catalogue_query=' +
|
||||
encodeURIComponent(
|
||||
'q=airport&kind=project&page=4&province_id=p&context=private&min_amount=200',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueReturnHref('/zonas?category=zee', detail),
|
||||
'/zonas?category=zee&province_id=p',
|
||||
);
|
||||
assert.equal(catalogueReturnHref('/documentos', detail), '/documentos');
|
||||
});
|
||||
test('resource-specific return queries do not inherit from other tabs or mutable storage', () => {
|
||||
const a = catalogueDetailHref(
|
||||
'/oportunidades/a',
|
||||
'q=rice&facets[]=2&facets[]=3¤cy=MZN',
|
||||
);
|
||||
const b = catalogueDetailHref('/oportunidades/b', 'q=gas¤cy=USD');
|
||||
const back = catalogueReturnHref('/oportunidades', a);
|
||||
assert.deepEqual(
|
||||
new URL(back, 'https://portal.invalid').searchParams.getAll('facets[]'),
|
||||
['2', '3'],
|
||||
);
|
||||
assert.match(back, /q=rice/);
|
||||
assert.match(catalogueReturnHref('/oportunidades', b), /q=gas/);
|
||||
assert.equal(
|
||||
catalogueReturnHref('/oportunidades', '/oportunidades/c'),
|
||||
'/oportunidades',
|
||||
);
|
||||
});
|
||||
test('detail URL preserves existing parameters and fragment; unsafe and recursive filters are not carried', () => {
|
||||
const href = catalogueDetailHref(
|
||||
'/oportunidades/a?from_dossier=origin#details',
|
||||
'q=rice&context=other&catalogue_query=recursive&password=secret&kind=cluster',
|
||||
);
|
||||
const url = new URL(href, 'https://portal.invalid');
|
||||
assert.equal(url.searchParams.get('from_dossier'), 'origin');
|
||||
assert.equal(url.hash, '#details');
|
||||
assert.equal(url.searchParams.get('catalogue_query'), 'q=rice');
|
||||
assert.equal(
|
||||
catalogueDetailHref('https://outside.test/a', 'q=rice'),
|
||||
'https://outside.test/a',
|
||||
);
|
||||
});
|
||||
test('only positive finite page numbers survive; repeated scalar criteria have one deliberate value', () => {
|
||||
assert.equal(
|
||||
catalogueQuery(
|
||||
'/carteira',
|
||||
'q=old&q=new&page=-1&per_page=Infinity',
|
||||
).toString(),
|
||||
'q=new',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueReturnHref(
|
||||
'/carteira',
|
||||
'/carteira/a?catalogue_query=' +
|
||||
encodeURIComponent('https://outside.test'),
|
||||
),
|
||||
'/carteira',
|
||||
);
|
||||
});
|
||||
@@ -26,6 +26,23 @@ function load(file, mocks = {}) {
|
||||
return module.exports;
|
||||
}
|
||||
const lib = load('../../resources/js/lib/company-preparation.ts');
|
||||
test('historical delivery wording is presented professionally without changing the stored notice or legal limits', () => {
|
||||
const legal =
|
||||
' Esta ficha prepara dados para revisão; não é uma minuta contratual, assinatura, registo ou licença.';
|
||||
const stored =
|
||||
'Os sete exemplares referidos no complemento ainda não foram fornecidos.' +
|
||||
legal;
|
||||
assert.equal(
|
||||
lib.companyPreparationNotice(stored),
|
||||
'Os modelos contratuais não estão disponíveis nesta preparação.' +
|
||||
legal,
|
||||
);
|
||||
assert.match(stored, /sete exemplares/);
|
||||
assert.equal(
|
||||
lib.companyPreparationNotice('Outro aviso específico.'),
|
||||
'Outro aviso específico.',
|
||||
);
|
||||
});
|
||||
const party = {
|
||||
id: 'SYNTHETIC-party',
|
||||
name: '<SYNTHETIC>',
|
||||
@@ -148,6 +165,7 @@ function harness() {
|
||||
router: { visit: (...args) => visits.push(args) },
|
||||
},
|
||||
'./shared': { Frame: 'main', card: '', input: '', button: '' },
|
||||
'@/components/currency-select': { default: () => null },
|
||||
'@/lib/company-preparation': lib,
|
||||
'@/lib/operation-key': {
|
||||
createOperationKey: () => 'SYNTHETIC-operation',
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
import pathModule from 'node:path';
|
||||
const require = createRequire(import.meta.url);
|
||||
function load(path, overrides = {}) {
|
||||
const source = fs.readFileSync(
|
||||
new URL('../../resources/js/' + path, import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const module = { exports: {} };
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(n) => {
|
||||
if (n in overrides) return overrides[n];
|
||||
const relative = n.startsWith('@/') ? n.slice(2) : n.startsWith('.') ? pathModule.posix.join(pathModule.posix.dirname(path), n) : null;
|
||||
if (relative) {
|
||||
for (const candidate of [relative, relative + '.tsx', relative + '.ts']) {
|
||||
if (fs.existsSync(new URL('../../resources/js/' + candidate, import.meta.url))) return load(candidate, overrides);
|
||||
}
|
||||
}
|
||||
return require(n);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return module.exports;
|
||||
}
|
||||
const helpers = load('lib/demographic-reading.ts');
|
||||
const Summary = load('components/demographic-reading-summary.tsx', {
|
||||
'@/lib/demographic-reading': helpers,
|
||||
}).default;
|
||||
const Details = load('components/evidence-details.tsx').default;
|
||||
const Component = load('components/demographic-evidence.tsx', {
|
||||
'./demographic-reading-summary': { default: Summary },
|
||||
'./evidence-details': { default: Details },
|
||||
}).default;
|
||||
const row = (age, value, residence = 'all', year = 2026, extra = {}) => ({
|
||||
year,
|
||||
indicator: 'population',
|
||||
age_group: age,
|
||||
residence,
|
||||
value,
|
||||
original_value: value,
|
||||
unit: 'pessoas',
|
||||
data_kind: 'projected',
|
||||
sheet: String(year),
|
||||
cell: `${age}-${residence}`,
|
||||
validation_status: 'valid',
|
||||
...extra,
|
||||
});
|
||||
const series = (values) => ({
|
||||
import_id: 'source-one',
|
||||
source: 'INE',
|
||||
version: 'SYNTHETIC test edition',
|
||||
sha256: 'a'.repeat(64),
|
||||
file_name: 'source.xlsx',
|
||||
missing_years: [],
|
||||
issue_counts: {},
|
||||
values,
|
||||
});
|
||||
const ages = [
|
||||
'15-19',
|
||||
'20-24',
|
||||
'25-29',
|
||||
'30-34',
|
||||
'35-39',
|
||||
'40-44',
|
||||
'45-49',
|
||||
'50-54',
|
||||
'55-59',
|
||||
'60-64',
|
||||
];
|
||||
const base = () =>
|
||||
series([
|
||||
row('all', '1000.1234567890123'),
|
||||
row('all', '400', 'urban'),
|
||||
row('all', '600.1234567890123', 'rural'),
|
||||
row('0-4', '100'),
|
||||
row('5-9', '100'),
|
||||
row('10-14', '100'),
|
||||
...ages.map((a) => row(a, '50')),
|
||||
]);
|
||||
const evidence = (s) => ({
|
||||
state: 'available',
|
||||
start_year: 2026,
|
||||
end_year: 2026,
|
||||
sector: 'general',
|
||||
limitations: ['Population is not demand.'],
|
||||
comparisons: [],
|
||||
differences: [],
|
||||
territories: [
|
||||
{
|
||||
id: 'district-one',
|
||||
name: 'Báruè',
|
||||
level: 'district',
|
||||
factors_to_assess: [],
|
||||
series: s,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
test('summarises compatible age/residence groups without changing original decimals', () => {
|
||||
const s = base(),
|
||||
before = JSON.stringify(s),
|
||||
r = helpers.demographicReading(s, 2026, 2026);
|
||||
assert.equal(r.last.under15, 300);
|
||||
assert.equal(r.last.age15to64, 500);
|
||||
assert.ok(Math.abs(r.last.ruralShare - 60.00493766) < 0.00001);
|
||||
assert.equal(JSON.stringify(s), before);
|
||||
assert.equal(r.growth, null);
|
||||
});
|
||||
test('missing age bands remain unknown; zeros are preserved', () => {
|
||||
const s = base();
|
||||
s.values = s.values.filter((r) => r.age_group !== '5-9');
|
||||
assert.equal(helpers.demographicReading(s, 2026, 2026).last.under15, null);
|
||||
const r = helpers.demographicReading(
|
||||
series([
|
||||
row('all', '0'),
|
||||
row('all', '0', 'urban'),
|
||||
row('all', '0', 'rural'),
|
||||
]),
|
||||
2026,
|
||||
2026,
|
||||
);
|
||||
assert.equal(r.last.total, 0);
|
||||
assert.equal(r.last.ruralShare, null);
|
||||
});
|
||||
test('duplicate dimensions and incompatible kinds cannot supply invented shares', () => {
|
||||
const s = base();
|
||||
s.values.push(row('0-4', '200'));
|
||||
s.values.find((r) => r.residence === 'rural').data_kind = 'observed';
|
||||
const r = helpers.demographicReading(s, 2026, 2026).last;
|
||||
assert.equal(r.under15, null);
|
||||
assert.equal(r.rural, null);
|
||||
assert.equal(r.ruralShare, null);
|
||||
});
|
||||
test('inconsistent residence components do not produce percentages', () => {
|
||||
const s = series([
|
||||
row('all', '100'),
|
||||
row('all', '80', 'urban'),
|
||||
row('all', '80', 'rural'),
|
||||
]);
|
||||
const r = helpers.demographicReading(s, 2026, 2026).last;
|
||||
assert.equal(r.urban, 80);
|
||||
assert.equal(r.urbanShare, null);
|
||||
assert.equal(r.ruralShare, null);
|
||||
});
|
||||
test('growth uses explicit comparable endpoints and does not fill missing intermediate years', () => {
|
||||
const s = series([
|
||||
row('all', '100', 'all', 2026),
|
||||
row('all', '120', 'all', 2028),
|
||||
]);
|
||||
const r = helpers.demographicReading(s, 2026, 2028);
|
||||
assert.equal(r.growth, 20);
|
||||
assert.equal(r.years[1].total, null);
|
||||
assert.equal(helpers.demographicReading(s, 2026, 2030).growth, null);
|
||||
s.values[1].data_kind = 'observed';
|
||||
assert.equal(helpers.demographicReading(s, 2026, 2028).growth, null);
|
||||
});
|
||||
test('technical source and full decimals remain available in closed details after a readable summary', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Component, { evidence: evidence([base()]) }),
|
||||
);
|
||||
assert.ok(
|
||||
html.indexOf('Retrato da população') <
|
||||
html.indexOf('Valores originais por ano'),
|
||||
);
|
||||
assert.match(html, /1000.1234567890123/);
|
||||
assert.match(html, /Valores por dimensão, fonte e advertências/);
|
||||
assert.doesNotMatch(html, /<details[^>]*\bopen\b/);
|
||||
assert.match(html, /um único ano/);
|
||||
assert.match(html, /capacidade instalada/);
|
||||
assert.match(html, /qualificações/);
|
||||
});
|
||||
test('multiple editions receive separate summaries rather than a summed population', () => {
|
||||
const a = series([row('all', '100')]),
|
||||
b = { ...series([row('all', '900')]), import_id: 'source-two' };
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Component, { evidence: evidence([a, b]) }),
|
||||
);
|
||||
assert.equal((html.match(/Retrato da população/g) || []).length, 2);
|
||||
assert.match(html, />100<\/dd>/);
|
||||
assert.match(html, />900<\/dd>/);
|
||||
});
|
||||
test('demographic page offers territory-only preparation independent of old commercial filters', () => {
|
||||
const Page = load('pages/investment/demography.tsx', {
|
||||
'@inertiajs/react': { router: {} },
|
||||
'@/components/demographic-evidence': { default: Component },
|
||||
'./shared': {
|
||||
Frame: ({ children }) =>
|
||||
React.createElement('main', null, children),
|
||||
button: '',
|
||||
},
|
||||
}).default;
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Page, {
|
||||
evidence: evidence([base()]),
|
||||
filters: { territories: ['district-one'], sector: 'general' },
|
||||
territories: [],
|
||||
sectors: { general: 'Contexto geral' },
|
||||
}),
|
||||
);
|
||||
assert.match(html, /source=territory%3Adistrict-one/);
|
||||
assert.doesNotMatch(html, /compra de propriedade|sector=turismo|modality=/);
|
||||
assert.match(html, /Não é necessário haver uma oportunidade publicada/);
|
||||
});
|
||||
|
||||
test('Barue 2026 provided evidence produces the readable proportions without changing originals', () => {
|
||||
const fixture = JSON.parse(
|
||||
fs.readFileSync(
|
||||
new URL('../Fixtures/demography/barue-2026.json', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const s = series(fixture.values),
|
||||
before = JSON.stringify(s);
|
||||
const r = helpers.demographicReading(s, 2026, 2026).last;
|
||||
assert.equal(Math.round(r.total), 248518);
|
||||
assert.equal(Number(r.ruralShare.toFixed(1)), 65.1);
|
||||
assert.equal(Number(r.under15Share.toFixed(1)), 45.6);
|
||||
assert.equal(Number(r.age15to64Share.toFixed(1)), 51.3);
|
||||
assert.equal(JSON.stringify(s), before);
|
||||
});
|
||||
@@ -325,7 +325,8 @@ void test('financial tools CSV records reproducible assumptions, periods, formul
|
||||
});
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
assert.match(csv, /financial-tools-v1/);
|
||||
assert.match(csv, /valores iniciais sao exemplos demonstrativos/);
|
||||
assert.match(csv, /Pressupostos editáveis introduzidos ou recuperados pelo utilizador/);
|
||||
assert.doesNotMatch(csv, /valores iniciais sao exemplos demonstrativos/);
|
||||
assert.match(csv, /2026-10-02T10:00:00\.000Z/);
|
||||
assert.match(csv, /Período do orçamento e dos custos fixos,Mensal/);
|
||||
assert.match(csv, /saldo decrescente/i);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
import * as finance from '../../resources/js/lib/financial-calculators.ts';
|
||||
import * as contract from '../../resources/js/lib/simulation-contract.ts';
|
||||
import * as fundingContext from '../../resources/js/lib/planning-finance-context.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const nodes = tree => Array.isArray(tree) ? tree.flatMap(nodes) : tree && typeof tree === 'object' ? [tree, ...nodes(tree.props?.children)] : [];
|
||||
const text = tree => Array.isArray(tree) ? tree.map(text).join('') : tree?.props ? text(tree.props.children) : typeof tree === 'string' ? tree : '';
|
||||
function harness(snapshot = '') {
|
||||
let cursor=0, queue=[], dirty=false, tree;
|
||||
const memory=[], deps=[];
|
||||
const hooks={...React, useState(initial) {const id=cursor++;if(!(id in memory))memory[id]=typeof initial==='function'?initial():initial;return[memory[id],next=>{const value=typeof next==='function'?next(memory[id]):next;if(!Object.is(value,memory[id])){memory[id]=value;dirty=true;}}];},useEffect(effect, next) {const id=cursor++;if(!deps[id]||next.some((value,i)=>!Object.is(value,deps[id][i]))){queue.push(effect);deps[id]=next;}}};
|
||||
const module={exports:{}};
|
||||
compileFunction(ts.transpileModule(fs.readFileSync('resources/js/components/simulation-financial-tools.tsx','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText,['require','module','exports'])(id=>id==='react'?hooks:id==='@/components/currency-select'?{default:()=>null}:id==='@/lib/financial-calculators'?finance:id==='@/lib/simulation-contract'?contract:id==='@/lib/planning-finance-context'?fundingContext:require(id),module,module.exports);
|
||||
const props={currency:'MZN',focus:'funding',loanRelevant:false,snapshot,sourceFunding:{total:'2000000',secured:''},onSnapshotChange(value){props.snapshot=value;dirty=true;},onCurrencyChange(){},onFundingChange(key,value){props.sourceFunding={...props.sourceFunding,[key]:value};dirty=true;}};
|
||||
const render=()=>{for(let i=0;i<12;i++){cursor=0;queue=[];dirty=false;tree=module.exports.SimulationFinancialTools(props);for(const effect of queue)effect();if(!dirty)return;}throw new Error('Render did not settle');};
|
||||
render();
|
||||
return{props,render,text:()=>text(tree),field:label=>nodes(tree).find(node=>node.props?.label===label),button:label=>nodes(tree).find(node=>node.type==='button'&&text(node).startsWith(label))};
|
||||
}
|
||||
|
||||
test('editing canonical mobilised funding updates the attached calculator and snapshot without showing hidden-tool errors',()=>{
|
||||
const h=harness();
|
||||
h.props.sourceFunding={total:'2000000',secured:'1000000'};h.render();
|
||||
assert.equal(h.field('Montante já mobilizado').props.value,'1000000');
|
||||
assert.match(h.text(),/1000000.00/);
|
||||
assert.equal(finance.restoreFinancialToolsSnapshot(h.props.snapshot).funding.secured,'1000000');
|
||||
assert.doesNotMatch(h.text(),/Empréstimo:|Ponto de equilíbrio:|Orçamento:|valores da calculadora diferem/);
|
||||
assert.equal(h.button('Exportar resultados'),undefined);
|
||||
});
|
||||
|
||||
test('a known different recovered calculator value is preserved until the user resolves its source',()=>{
|
||||
const snapshot=finance.serializeFinancialToolsSnapshot({budgetPeriod:'Mensal',loan:{principal:'',rate:'',months:'',rateType:'nominal',periodMonths:'1',gracePeriods:'',upfrontFee:'',recurringFee:''},breakEven:{fixed:'',price:'',variable:''},funding:{total:'2000000',secured:'250000'},incomes:[{label:'Receitas',amount:''}],expenses:[{label:'Custos',amount:''}]});
|
||||
const h=harness(snapshot);h.props.sourceFunding={total:'2000000',secured:'1000000'};h.render();
|
||||
assert.equal(h.field('Montante já mobilizado').props.value,'250000');
|
||||
assert.match(h.text(),/valores da calculadora diferem/);
|
||||
h.button('Usar os valores do investimento').props.onClick();h.render();
|
||||
assert.equal(h.field('Montante já mobilizado').props.value,'1000000');
|
||||
h.props.sourceFunding={total:'2000000',secured:'1500000'};h.render();
|
||||
assert.equal(h.field('Montante já mobilizado').props.value,'1500000');
|
||||
assert.match(h.text(),/500000.00/);
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
import { monthlyIvaInput } from '../../resources/js/lib/monthly-iva.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const module = { exports: {} };
|
||||
const Choice = () => null;
|
||||
compileFunction(
|
||||
ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
'resources/js/components/fiscal-operation-picker.tsx',
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText,
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(id) =>
|
||||
id === '@/components/catalogue-choice-select'
|
||||
? { default: Choice }
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const nodes = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.flatMap(nodes)
|
||||
: tree && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
|
||||
test('additional treatments are not mounted until explicitly selected, and removal preserves their stored data', () => {
|
||||
const mounted = [];
|
||||
const state = {
|
||||
selected: ['irpc:normal'],
|
||||
saved: 'unchanged-private-snapshot',
|
||||
};
|
||||
const props = {
|
||||
family: 'iva',
|
||||
selected: state.selected,
|
||||
operations: ['miners', 'fuel', 'travel'].map((id) => ({
|
||||
id,
|
||||
label: `Operação ${id}`,
|
||||
description: 'Confirmar se aplicável.',
|
||||
render() {
|
||||
mounted.push(id);
|
||||
return React.createElement('div', null, id);
|
||||
},
|
||||
})),
|
||||
onChange(selected) {
|
||||
state.selected = selected;
|
||||
props.selected = selected;
|
||||
},
|
||||
};
|
||||
let tree = module.exports.default(props);
|
||||
assert.deepEqual(
|
||||
mounted,
|
||||
[],
|
||||
'a list of available treatments is not a declaration that they apply',
|
||||
);
|
||||
nodes(tree)
|
||||
.find((node) => node.type === Choice)
|
||||
.props.onChange('fuel');
|
||||
assert.deepEqual(state.selected, ['irpc:normal', 'iva:fuel']);
|
||||
tree = module.exports.default(props);
|
||||
assert.deepEqual(mounted, ['fuel']);
|
||||
nodes(tree)
|
||||
.find((node) => node.type === 'button')
|
||||
.props.onClick();
|
||||
assert.deepEqual(state.selected, ['irpc:normal']);
|
||||
assert.equal(state.saved, 'unchanged-private-snapshot');
|
||||
});
|
||||
|
||||
test('a chosen 2027 period cannot silently use a 2026 monthly IVA projection', () => {
|
||||
const settings = {
|
||||
start: '2026-01',
|
||||
basis: 'net',
|
||||
declared: true,
|
||||
auto: false,
|
||||
};
|
||||
assert.throws(
|
||||
() => monthlyIvaInput({ fiscal_period: '2027' }, settings),
|
||||
/nenhum ano foi alterado/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
monthlyIvaInput(
|
||||
{ fiscal_period: '2027' },
|
||||
{ ...settings, start: '2027-01' },
|
||||
),
|
||||
/cobertura apenas para 2026/,
|
||||
);
|
||||
assert.equal(settings.start, '2026-01');
|
||||
});
|
||||
@@ -0,0 +1,222 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const nodes = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.flatMap(nodes)
|
||||
: tree && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
const text = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.map(text).join('')
|
||||
: tree?.props
|
||||
? text(tree.props.children)
|
||||
: typeof tree === 'string'
|
||||
? tree
|
||||
: '';
|
||||
|
||||
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
|
||||
function harness(filters, errors = {}) {
|
||||
const memory = [];
|
||||
let cursor = 0;
|
||||
const state = (initial) => {
|
||||
const id = cursor++;
|
||||
if (!(id in memory)) memory[id] = initial;
|
||||
return [
|
||||
memory[id],
|
||||
(next) => {
|
||||
memory[id] =
|
||||
typeof next === 'function' ? next(memory[id]) : next;
|
||||
},
|
||||
];
|
||||
};
|
||||
let submitted;
|
||||
let form;
|
||||
const TerritoryFields = () => null;
|
||||
const module = { exports: {} };
|
||||
const source = fs.readFileSync(
|
||||
'resources/js/pages/funding/index.tsx',
|
||||
'utf8',
|
||||
);
|
||||
compileFunction(
|
||||
ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText,
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(id) => {
|
||||
if (id === 'react')
|
||||
return {
|
||||
...React,
|
||||
useState: state,
|
||||
useRef(initial) {
|
||||
const [value] = state({ current: initial });
|
||||
return value;
|
||||
},
|
||||
};
|
||||
if (id === '@inertiajs/react')
|
||||
return {
|
||||
Link: 'a',
|
||||
useForm(initial) {
|
||||
const [data, set] = state(initial);
|
||||
form = {
|
||||
data,
|
||||
errors: {},
|
||||
processing: false,
|
||||
setData(key, value) {
|
||||
set(
|
||||
typeof key === 'string'
|
||||
? { ...data, [key]: value }
|
||||
: key,
|
||||
);
|
||||
},
|
||||
get(url) {
|
||||
submitted = { url, data };
|
||||
},
|
||||
};
|
||||
return form;
|
||||
},
|
||||
};
|
||||
if (id === '@/pages/investment/shared')
|
||||
return { Frame: 'main', card: '', button: '' };
|
||||
if (id === '@/components/funding-classification')
|
||||
return {
|
||||
financialCategories: {
|
||||
banking: 'Banca',
|
||||
insurance_intermediation: 'Mediação de seguros',
|
||||
},
|
||||
financialTypes: {
|
||||
commercial_bank: 'Banco comercial',
|
||||
broker: 'Corretora',
|
||||
other: 'Outro',
|
||||
},
|
||||
};
|
||||
if (id === '@/components/investment-territory')
|
||||
return { TerritoryFields };
|
||||
if (id === '@/components/funding-institution')
|
||||
return { InstitutionView: 'article' };
|
||||
if (id === './shared') return { windowLabels: {} };
|
||||
return require(id);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const props = {
|
||||
filters,
|
||||
criteriaErrors: errors,
|
||||
items: { data: [], links: [] },
|
||||
options: { sectors: [], territories: [] },
|
||||
kinds: { institution: 'Instituição', fund: 'Fundo' },
|
||||
management: false,
|
||||
categoryTypes: {
|
||||
banking: ['commercial_bank'],
|
||||
insurance_intermediation: ['broker'],
|
||||
},
|
||||
};
|
||||
let tree;
|
||||
function render() {
|
||||
cursor = 0;
|
||||
const wrapper = module.exports.default(props);
|
||||
tree = wrapper.type(wrapper.props);
|
||||
return tree;
|
||||
}
|
||||
const select = (label) =>
|
||||
nodes(
|
||||
nodes(tree).find(
|
||||
(n) => n.type === 'label' && text(n).startsWith(label),
|
||||
),
|
||||
).find((n) => n.type === 'select');
|
||||
render();
|
||||
return {
|
||||
render,
|
||||
select,
|
||||
form: () => form,
|
||||
tree: () => tree,
|
||||
submitted: () => submitted,
|
||||
territory: () => nodes(tree).find((n) => n.type === TerritoryFields),
|
||||
};
|
||||
}
|
||||
|
||||
test('institution category restricts types and removes only an incompatible dependent choice', () => {
|
||||
const h = harness({
|
||||
category: 'insurance_intermediation',
|
||||
institution_type: 'broker',
|
||||
sector: '7',
|
||||
need: 'investment',
|
||||
territory: 'district-qa',
|
||||
});
|
||||
h.select('Categoria da instituição').props.onChange({
|
||||
target: { value: 'banking' },
|
||||
});
|
||||
h.render();
|
||||
assert.equal(h.form().data.institution_type, '');
|
||||
for (const [key, value] of Object.entries({
|
||||
sector: '7',
|
||||
need: 'investment',
|
||||
territory: 'district-qa',
|
||||
}))
|
||||
assert.equal(h.form().data[key], value);
|
||||
assert.deepEqual(
|
||||
nodes(h.select('Tipo de instituição'))
|
||||
.filter((n) => n.type === 'option')
|
||||
.map((n) => n.props.value),
|
||||
['', 'commercial_bank', 'other'],
|
||||
);
|
||||
assert.match(text(h.tree()), /tipo anterior não pertence/);
|
||||
const results = nodes(h.tree()).find((n) => n.type === 'details');
|
||||
assert.equal(results.props.open, false);
|
||||
assert.match(text(results), /pesquisa anterior/);
|
||||
});
|
||||
|
||||
test('contradictory record criteria remain explicit until the user chooses a correction', () => {
|
||||
const h = harness(
|
||||
{
|
||||
kind: 'fund',
|
||||
category: 'banking',
|
||||
institution_type: 'commercial_bank',
|
||||
location_mode: 'physical',
|
||||
province_id: 'province-qa',
|
||||
sector: '8',
|
||||
state: 'closed',
|
||||
certainty: 'documented',
|
||||
},
|
||||
{ kind: ['Combinação incompatível.'] },
|
||||
);
|
||||
assert.match(text(h.tree()), /A pesquisa não foi executada/);
|
||||
assert.equal(h.form().data.kind, 'fund');
|
||||
const action = nodes(h.tree()).find(
|
||||
(n) => n.type === 'button' && /Manter o fundo/.test(text(n)),
|
||||
);
|
||||
action.props.onClick();
|
||||
h.render();
|
||||
assert.equal(h.form().data.category, '');
|
||||
assert.equal(h.form().data.institution_type, '');
|
||||
assert.equal(h.form().data.location_mode, 'coverage');
|
||||
for (const [key, value] of Object.entries({
|
||||
kind: 'fund',
|
||||
province_id: 'province-qa',
|
||||
sector: '8',
|
||||
state: 'closed',
|
||||
certainty: 'documented',
|
||||
}))
|
||||
assert.equal(h.form().data[key], value);
|
||||
nodes(h.tree())
|
||||
.find((n) => n.type === 'form')
|
||||
.props.onSubmit({ preventDefault() {} });
|
||||
assert.equal(h.submitted().url, '/fundos');
|
||||
assert.equal(h.submitted().data.province_id, 'province-qa');
|
||||
assert.ok(
|
||||
h.territory(),
|
||||
'the catalogue consumes the common hierarchical location control',
|
||||
);
|
||||
});
|
||||
@@ -212,6 +212,15 @@ export function harness(initial = props()) {
|
||||
mocks['@/lib/investment-profile-editor'] = load(
|
||||
'resources/js/lib/investment-profile-editor.ts',
|
||||
);
|
||||
mocks['@/lib/catalogue-choice'] = load(
|
||||
'resources/js/lib/catalogue-choice.ts',
|
||||
);
|
||||
mocks['./territory-search-select'] = load(
|
||||
'resources/js/components/territory-search-select.tsx',
|
||||
);
|
||||
mocks['./catalogue-choice-select'] = load(
|
||||
'resources/js/components/catalogue-choice-select.tsx',
|
||||
);
|
||||
mocks['./country-select'] = load(
|
||||
'resources/js/components/country-select.tsx',
|
||||
);
|
||||
@@ -324,17 +333,36 @@ export function harness(initial = props()) {
|
||||
return nodes(formLabel ? this.form(formLabel) : tree).find(
|
||||
(n) =>
|
||||
['input', 'textarea', 'select'].includes(n.type) &&
|
||||
n.props['aria-label'] === label,
|
||||
(n.props['aria-label'] === label ||
|
||||
(n.props.role === 'combobox' &&
|
||||
n.props['aria-label'] === 'Pesquisar ' + label)),
|
||||
);
|
||||
},
|
||||
value(label, formLabel) {
|
||||
return this.field(label, formLabel)?.props.value;
|
||||
const field = this.field(label, formLabel);
|
||||
// The public control shows the readable label; domain assertions use its ISO code.
|
||||
return field?.props.role === 'combobox'
|
||||
? (field.props.value.match(/— ([A-Z]{2})$/)?.[1] ??
|
||||
field.props.value)
|
||||
: field?.props.value;
|
||||
},
|
||||
change(label, value, formLabel) {
|
||||
const field = this.field(label, formLabel);
|
||||
if (!field) throw Error('Missing field ' + label);
|
||||
field.props.onChange({ target: { value } });
|
||||
render();
|
||||
if (field.props.role === 'combobox') {
|
||||
const option = nodes(
|
||||
formLabel ? this.form(formLabel) : tree,
|
||||
).find(
|
||||
(node) =>
|
||||
node.props?.role === 'option' &&
|
||||
text(node).endsWith('— ' + value),
|
||||
);
|
||||
if (!option) throw Error('Missing selectable country ' + value);
|
||||
option.props.onClick();
|
||||
render();
|
||||
}
|
||||
},
|
||||
button(label, formLabel) {
|
||||
return nodes(formLabel ? this.form(formLabel) : tree).find(
|
||||
|
||||
@@ -70,3 +70,92 @@ await test('blocked browser storage cannot prevent authentication or clearing a
|
||||
'/participar/entrar?return=%2Foportunidades%2Fteste%3Fsector%3D1',
|
||||
);
|
||||
});
|
||||
|
||||
test('reused interest hook isolates opportunities, retains deliberate edits and restores after reload', () => {
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/hooks/use-interest-draft.ts',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const output = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
},
|
||||
}).outputText;
|
||||
const saved = new Map();
|
||||
let sequence = 0;
|
||||
function mount(storage = saved) {
|
||||
let value, changed, effect;
|
||||
const module = { exports: {} };
|
||||
compileFunction(output, [
|
||||
'require',
|
||||
'module',
|
||||
'exports',
|
||||
'sessionStorage',
|
||||
'window',
|
||||
'location',
|
||||
])(
|
||||
(name) =>
|
||||
name === 'react'
|
||||
? {
|
||||
useState(init) {
|
||||
value ??= init();
|
||||
return [
|
||||
value,
|
||||
(next) => {
|
||||
value =
|
||||
typeof next === 'function'
|
||||
? next(value)
|
||||
: next;
|
||||
changed = true;
|
||||
},
|
||||
];
|
||||
},
|
||||
useEffect(callback) {
|
||||
effect = callback;
|
||||
},
|
||||
}
|
||||
: { newSubmissionKey: () => 'synthetic-' + ++sequence },
|
||||
module,
|
||||
module.exports,
|
||||
{
|
||||
getItem: (key) => storage.get(key) ?? null,
|
||||
setItem: (key, data) => storage.set(key, data),
|
||||
removeItem: (key) => storage.delete(key),
|
||||
},
|
||||
{ location: { assign() {} } },
|
||||
{ pathname: '/negocios/a', search: '?province_id=p' },
|
||||
);
|
||||
return (name, initial = { message: 'initial ' + name }) => {
|
||||
changed = false;
|
||||
let result = module.exports.useInterestDraft(name, initial);
|
||||
// React discards a render-phase reset and renders the new scoped state.
|
||||
if (changed)
|
||||
result = module.exports.useInterestDraft(name, initial);
|
||||
effect();
|
||||
return result;
|
||||
};
|
||||
}
|
||||
const render = mount();
|
||||
const a = render('business:A');
|
||||
a.setForm({ message: 'deliberate A' });
|
||||
render('business:A');
|
||||
const b = render('business:B');
|
||||
assert.equal(b.form.message, 'initial business:B');
|
||||
assert.notEqual(a.key, b.key);
|
||||
b.setForm({ message: 'deliberate B' });
|
||||
render('business:B');
|
||||
assert.equal(render('business:A').form.message, 'deliberate A');
|
||||
assert.equal(mount()('business:B').form.message, 'deliberate B');
|
||||
assert.equal(
|
||||
mount(new Map())('business:A').form.message,
|
||||
'initial business:A',
|
||||
);
|
||||
assert.equal(
|
||||
JSON.parse(saved.get('investemoz-interest:business:A')).form.message,
|
||||
'deliberate A',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
import * as finance from '../../resources/js/lib/financial-calculators.ts';
|
||||
import * as operating from '../../resources/js/lib/investment-operating-assistance.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const nodes = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.flatMap(nodes)
|
||||
: tree && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
const text = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.map(text).join('')
|
||||
: tree?.props
|
||||
? text(tree.props.children)
|
||||
: typeof tree === 'string'
|
||||
? tree
|
||||
: '';
|
||||
function harness(file, snapshot = '') {
|
||||
let cursor = 0,
|
||||
tree;
|
||||
const memory = [],
|
||||
changes = [];
|
||||
const module = { exports: {} };
|
||||
const hooks = {
|
||||
...React,
|
||||
useState(initial) {
|
||||
const id = cursor++;
|
||||
if (!(id in memory))
|
||||
memory[id] =
|
||||
typeof initial === 'function' ? initial() : initial;
|
||||
return [
|
||||
memory[id],
|
||||
(next) => {
|
||||
memory[id] =
|
||||
typeof next === 'function' ? next(memory[id]) : next;
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
compileFunction(
|
||||
ts.transpileModule(
|
||||
fs.readFileSync('resources/js/components/' + file, 'utf8'),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText,
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(id) =>
|
||||
id === 'react'
|
||||
? hooks
|
||||
: id === '@/lib/financial-calculators'
|
||||
? finance
|
||||
: id === '@/lib/investment-operating-assistance'
|
||||
? operating
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const props = {
|
||||
snapshot,
|
||||
currency: 'MZN',
|
||||
onChange(key, value) {
|
||||
changes.push([key, value]);
|
||||
},
|
||||
};
|
||||
const render = () => {
|
||||
cursor = 0;
|
||||
tree = module.exports.default(props);
|
||||
};
|
||||
render();
|
||||
return {
|
||||
render,
|
||||
changes,
|
||||
nodes: () => nodes(tree),
|
||||
text: () => text(tree),
|
||||
button: (label) =>
|
||||
nodes(tree).find(
|
||||
(node) =>
|
||||
node.type === 'button' && text(node).startsWith(label),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
test('initial budget has no sample amounts and adopts a sum only through the explicit action', () => {
|
||||
const h = harness('investment-initial-budget.tsx');
|
||||
const amounts = () =>
|
||||
h
|
||||
.nodes()
|
||||
.filter(
|
||||
(node) => node.type === 'input' && node.props.type === 'number',
|
||||
);
|
||||
assert.deepEqual(
|
||||
amounts().map((node) => node.props.value),
|
||||
['', '', '', ''],
|
||||
);
|
||||
h.button('Usar a soma').props.onClick();
|
||||
h.render();
|
||||
assert.match(h.text(), /montantes em falta/);
|
||||
assert.equal(
|
||||
h.changes.some(([key]) => key === 'total_investment'),
|
||||
false,
|
||||
);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
amounts()[i].props.onChange({
|
||||
target: { value: String((i + 1) * 1000) },
|
||||
});
|
||||
h.render();
|
||||
}
|
||||
assert.equal(
|
||||
h.changes.some(([key]) => key === 'total_investment'),
|
||||
false,
|
||||
);
|
||||
h.button('Usar a soma').props.onClick();
|
||||
h.render();
|
||||
assert.deepEqual(h.changes.at(-1), ['total_investment', '10000.00']);
|
||||
const saved = h.changes
|
||||
.filter(([key]) => key === 'initial_budget_snapshot')
|
||||
.at(-1)[1];
|
||||
const restored = harness('investment-initial-budget.tsx', saved);
|
||||
assert.deepEqual(
|
||||
restored
|
||||
.nodes()
|
||||
.filter(
|
||||
(node) => node.type === 'input' && node.props.type === 'number',
|
||||
)
|
||||
.map((node) => node.props.value),
|
||||
['1000', '2000', '3000', '4000'],
|
||||
);
|
||||
});
|
||||
|
||||
test('hotel estimate is selected deliberately, saved as assumptions, then adopted without replacing another field', () => {
|
||||
const h = harness('investment-operating-assistance.tsx');
|
||||
h.nodes()
|
||||
.find((node) => node.type === 'select')
|
||||
.props.onChange({ target: { value: 'hotel' } });
|
||||
h.render();
|
||||
const amounts = () =>
|
||||
h
|
||||
.nodes()
|
||||
.filter(
|
||||
(node) => node.type === 'input' && node.props.type === 'number',
|
||||
);
|
||||
for (const [i, value] of ['10', '5000', '50', '300'].entries()) {
|
||||
amounts()[i].props.onChange({ target: { value } });
|
||||
h.render();
|
||||
}
|
||||
assert.equal(
|
||||
h.changes.some(([key]) => key === 'annual_revenue'),
|
||||
false,
|
||||
);
|
||||
h.button('Usar esta estimativa de receitas').props.onClick();
|
||||
h.render();
|
||||
assert.deepEqual(h.changes.at(-1), ['annual_revenue', '7500000.00']);
|
||||
assert.equal(
|
||||
h.changes.some(
|
||||
([key]) =>
|
||||
key === 'total_investment' || key === 'investment_budget_max',
|
||||
),
|
||||
false,
|
||||
);
|
||||
const saved = h.changes
|
||||
.filter(([key]) => key === 'planning_assumptions_snapshot')
|
||||
.at(-1)[1];
|
||||
const restored = harness('investment-operating-assistance.tsx', saved);
|
||||
assert.equal(
|
||||
restored.nodes().find((node) => node.type === 'select').props.value,
|
||||
'hotel',
|
||||
);
|
||||
assert.match(restored.text(), /ocupação/);
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
getSimulationSections,
|
||||
simulationFieldsForSection,
|
||||
simulationFieldAvailableAtDetailLevel,
|
||||
simulationDraftFingerprint,
|
||||
validateSimulationDraft,
|
||||
partitionSimulationDraft,
|
||||
restoreSimulationDraft,
|
||||
} from '../../resources/js/lib/simulation-form.ts';
|
||||
import {
|
||||
emptyOperatingAssumptions,
|
||||
estimateOperatingRevenue,
|
||||
estimateOperatingCosts,
|
||||
restoreOperatingAssumptions,
|
||||
} from '../../resources/js/lib/investment-operating-assistance.ts';
|
||||
|
||||
test('confirmed nullable empty inputs match their HTTP-normalised recovery without accepting changed values', () => {
|
||||
const local = {
|
||||
purpose: 'own_investment',
|
||||
context_opportunity: '',
|
||||
total_investment: '2000000',
|
||||
secured_amount: '1000000',
|
||||
};
|
||||
const snapshots = partitionSimulationDraft(local);
|
||||
snapshots.economic_snapshot.context_opportunity = null;
|
||||
const saved = restoreSimulationDraft(
|
||||
snapshots.economic_snapshot,
|
||||
snapshots.personal_snapshot,
|
||||
);
|
||||
const versionedLocal = {
|
||||
...local,
|
||||
project_questionnaire_version: 'legacy-unversioned',
|
||||
};
|
||||
assert.equal(
|
||||
simulationDraftFingerprint(saved),
|
||||
simulationDraftFingerprint(versionedLocal),
|
||||
);
|
||||
assert.notEqual(
|
||||
simulationDraftFingerprint(saved),
|
||||
simulationDraftFingerprint({
|
||||
...versionedLocal,
|
||||
secured_amount: '250000',
|
||||
}),
|
||||
);
|
||||
assert.notEqual(
|
||||
simulationDraftFingerprint(saved),
|
||||
simulationDraftFingerprint({
|
||||
...versionedLocal,
|
||||
context_opportunity: 'another-opportunity',
|
||||
}),
|
||||
);
|
||||
assert.notEqual(
|
||||
simulationDraftFingerprint({ ...versionedLocal, secured_amount: '' }),
|
||||
simulationDraftFingerprint({ ...versionedLocal, secured_amount: '0' }),
|
||||
);
|
||||
});
|
||||
|
||||
test('Hotel and Agronegocio reuse a controlled stage contract without requiring adverts, zones or formal financing facts', () => {
|
||||
for (const project_title of ['Criar Hotel', 'Agronegócio em Matola Rio']) {
|
||||
const draft = {
|
||||
journey_type: 'investor',
|
||||
detail_level: 'simple',
|
||||
purpose: 'own_investment',
|
||||
preferred_language: 'pt-MZ',
|
||||
project_title,
|
||||
province_id: 'province-qa',
|
||||
district_id: 'boane-qa',
|
||||
locality_id: 'matola-rio-qa',
|
||||
currency: 'MZN',
|
||||
investment_budget_min: '1000000',
|
||||
investment_budget_max: '5000000',
|
||||
};
|
||||
const sections = getSimulationSections(draft);
|
||||
assert.equal(sections.length, 8);
|
||||
assert.ok(
|
||||
simulationFieldsForSection(draft, 'purpose').some(
|
||||
(field) => field.key === 'locality_id',
|
||||
),
|
||||
);
|
||||
for (const stage of [
|
||||
'market',
|
||||
'investment',
|
||||
'financial',
|
||||
'operating',
|
||||
'cashflow',
|
||||
'tax',
|
||||
])
|
||||
assert.deepEqual(
|
||||
validateSimulationDraft(draft, stage),
|
||||
{},
|
||||
`${stage} must permit unknown preparation facts`,
|
||||
);
|
||||
const finance = simulationFieldsForSection(draft, 'financial').map(
|
||||
(field) => field.key,
|
||||
);
|
||||
assert.ok(finance.includes('secured_amount'));
|
||||
assert.equal(finance.includes('annual_revenue'), false);
|
||||
assert.ok(
|
||||
simulationFieldsForSection(draft, 'operating').some(
|
||||
(field) => field.key === 'annual_revenue',
|
||||
),
|
||||
);
|
||||
const editableOperating = simulationFieldsForSection(
|
||||
draft,
|
||||
'operating',
|
||||
).filter((field) =>
|
||||
simulationFieldAvailableAtDetailLevel(
|
||||
draft,
|
||||
'operating',
|
||||
field.key,
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
editableOperating.some((field) => field.key === 'annual_revenue'),
|
||||
);
|
||||
assert.ok(
|
||||
editableOperating.some(
|
||||
(field) => field.key === 'annual_operating_costs',
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
simulationFieldAvailableAtDetailLevel(draft, 'operating', 'nuit'),
|
||||
false,
|
||||
);
|
||||
const snapshot = JSON.stringify({
|
||||
version: 1,
|
||||
data: {
|
||||
...emptyOperatingAssumptions(),
|
||||
model: 'hotel',
|
||||
capacity: '10',
|
||||
price: '5000',
|
||||
occupancy: '50',
|
||||
frequency: '300',
|
||||
source: 'Synthetic assumptions explicitly entered',
|
||||
},
|
||||
});
|
||||
const original = {
|
||||
...draft,
|
||||
preparation_step: 'operating',
|
||||
planning_assumptions_snapshot: snapshot,
|
||||
};
|
||||
const partitioned = partitionSimulationDraft(original);
|
||||
const recovered = restoreSimulationDraft(
|
||||
partitioned.economic_snapshot,
|
||||
partitioned.personal_snapshot,
|
||||
);
|
||||
for (const key of [
|
||||
'locality_id',
|
||||
'currency',
|
||||
'investment_budget_min',
|
||||
'investment_budget_max',
|
||||
'preparation_step',
|
||||
'planning_assumptions_snapshot',
|
||||
])
|
||||
assert.equal(recovered[key], original[key]);
|
||||
assert.equal(recovered.total_investment, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test('guided estimates require explicit assumptions, preserve the model and do not use population as revenue', () => {
|
||||
const empty = emptyOperatingAssumptions();
|
||||
assert.throws(() => estimateOperatingRevenue(empty), /Escolha/);
|
||||
const hotel = {
|
||||
...empty,
|
||||
model: 'hotel',
|
||||
capacity: '10',
|
||||
price: '5000',
|
||||
occupancy: '50',
|
||||
frequency: '300',
|
||||
};
|
||||
assert.equal(estimateOperatingRevenue(hotel), '7500000.00');
|
||||
assert.throws(
|
||||
() => estimateOperatingRevenue({ ...hotel, occupancy: '101' }),
|
||||
/100%/,
|
||||
);
|
||||
assert.throws(
|
||||
() => estimateOperatingRevenue({ ...hotel, price: '' }),
|
||||
/falta/,
|
||||
);
|
||||
assert.equal(
|
||||
estimateOperatingRevenue({
|
||||
...hotel,
|
||||
model: 'agriculture',
|
||||
capacity: '1200',
|
||||
price: '25.50',
|
||||
frequency: '2',
|
||||
}),
|
||||
'61200.00',
|
||||
);
|
||||
assert.throws(() => estimateOperatingCosts(empty), /não são zero/);
|
||||
assert.throws(
|
||||
() =>
|
||||
estimateOperatingCosts({
|
||||
...hotel,
|
||||
costs: [{ label: 'Energia', annual: '' }],
|
||||
}),
|
||||
/falta/,
|
||||
);
|
||||
const data = {
|
||||
...hotel,
|
||||
costs: [
|
||||
{ label: 'Energia', annual: '100.10' },
|
||||
{ label: 'Pessoal', annual: '200.20' },
|
||||
],
|
||||
};
|
||||
assert.equal(estimateOperatingCosts(data), '300.30');
|
||||
assert.deepEqual(
|
||||
restoreOperatingAssumptions(JSON.stringify({ version: 1, data })),
|
||||
data,
|
||||
);
|
||||
assert.deepEqual(restoreOperatingAssumptions('{broken'), empty);
|
||||
});
|
||||
@@ -108,7 +108,7 @@ test('conflict recovery reads current data without applying a write automaticall
|
||||
});
|
||||
test('validation shows each field message once and preserves its value', async () => {
|
||||
const h = harness();
|
||||
h.change(residence, 'ZZ', account);
|
||||
h.change(residence, 'ZA', account);
|
||||
const sent = h.submit(account);
|
||||
await h.fail(422, sent, {
|
||||
'payload.residence_country_code': ['SYNTHETIC invalid country'],
|
||||
@@ -117,7 +117,7 @@ test('validation shows each field message once and preserves its value', async (
|
||||
text(h.form(account)).split('SYNTHETIC invalid country').length - 1,
|
||||
1,
|
||||
);
|
||||
assert.equal(h.value(residence, account), 'ZZ');
|
||||
assert.equal(h.value(residence, account), 'ZA');
|
||||
assert.equal(h.field(residence, account).props['aria-invalid'], true);
|
||||
});
|
||||
test('one page leave guard covers multiple dirty profile declarations', () => {
|
||||
|
||||
@@ -138,6 +138,37 @@ function fixture() {
|
||||
};
|
||||
}
|
||||
|
||||
test('a planning budget remains an interval in the same dossier report without inventing an investment amount', () => {
|
||||
const input = fixture();
|
||||
input.context_opportunity = null;
|
||||
input.opportunity_options = [];
|
||||
input.preparation_report.opportunity = null;
|
||||
Object.assign(input.investment_context.fields, {
|
||||
investment_budget_min: '1000000',
|
||||
investment_budget_max: '5000000',
|
||||
currency: 'MZN',
|
||||
});
|
||||
const report = createInvestorDossierReport(input, '2026-11-15T12:00:00Z');
|
||||
const section = report.sections.find((section) => section.id === 'project');
|
||||
assert.equal(
|
||||
section.rows.find(
|
||||
(row) => row.field === 'Orçamento previsto — mínimo do intervalo',
|
||||
).value,
|
||||
'1000000',
|
||||
);
|
||||
assert.equal(
|
||||
section.rows.find(
|
||||
(row) => row.field === 'Orçamento previsto — máximo do intervalo',
|
||||
).value,
|
||||
'5000000',
|
||||
);
|
||||
assert.equal(
|
||||
section.rows.some((row) => row.field === 'Investimento previsto'),
|
||||
false,
|
||||
);
|
||||
assert.equal(input.context_opportunity, null);
|
||||
});
|
||||
|
||||
void test('one dossier groups stage evidence, SWOT, fiscal and all preserved APIEX versions without modifying sources', () => {
|
||||
const input = fixture();
|
||||
input.documents.push({ ...input.documents[0], id: 'second-link' });
|
||||
@@ -202,6 +233,7 @@ void test('financial results from a different opportunity do not enter the conso
|
||||
id: 'other',
|
||||
context_opportunity: 'op-b',
|
||||
financial_snapshot: 'OTHER-PRIVATE-INPUTS',
|
||||
preparation_snapshot: { annual_revenue: 'OTHER-PRIVATE-PREPARATION' },
|
||||
draft_id: 'other-draft',
|
||||
draft_version: 8,
|
||||
recorded_at: '2026-11-13',
|
||||
@@ -214,6 +246,7 @@ void test('financial results from a different opportunity do not enter the conso
|
||||
'OTHER-PRIVATE-INPUTS',
|
||||
),
|
||||
);
|
||||
assert.equal(JSON.stringify(createInvestorDossierReport(input)).includes('OTHER-PRIVATE-PREPARATION'), false);
|
||||
assert.ok(
|
||||
!investorDossierReportIndex(input).some(
|
||||
(entry) => entry.id === 'finance:other',
|
||||
@@ -249,6 +282,7 @@ void test('the consolidated report reuses loan, break-even, financing and budget
|
||||
input.results = [
|
||||
{
|
||||
id: 'finance-a',
|
||||
preparation_snapshot: { total_investment: '100000', investment_budget_min: '1000000', investment_budget_max: '5000000', annual_revenue: '7500000', planning_assumptions_snapshot: JSON.stringify({ version: 1, data: { model: 'hotel', capacity: '10', price: '5000', occupancy: '50', frequency: '300', source: 'Synthetic assumptions', costs: [{ label: 'Energia', annual: '' }] } }), initial_budget_snapshot: JSON.stringify({ version: 1, rows: [{ label: 'Equipamento', amount: '100000' }] }) },
|
||||
context_opportunity: 'op-a',
|
||||
context_revision: 2,
|
||||
context_state: 'review_required',
|
||||
@@ -287,6 +321,18 @@ void test('the consolidated report reuses loan, break-even, financing and budget
|
||||
);
|
||||
assert.match(rows[0].classification, /Histórico/);
|
||||
assert.equal(input.results[0].financial_snapshot, financial_snapshot);
|
||||
assert.equal(rows.find(item => item.field === 'Receitas anuais estimadas').value, '7500000 MZN');
|
||||
assert.equal(rows.find(item => item.field === 'Quartos disponíveis').value, '10');
|
||||
assert.equal(rows.find(item => item.field === 'Custo anual — Energia').value, 'Por confirmar');
|
||||
assert.equal(rows.find(item => item.field === 'Investimento inicial — Equipamento').value, '100000');
|
||||
});
|
||||
|
||||
test('funding remains calculable without presenting an unchosen empty loan or empty comparisons', () => {
|
||||
const input = fixture();
|
||||
input.results = [{ id: 'funding-only', context_opportunity: 'op-a', context_revision: 3, currency: 'MZN', draft_id: 'draft-a', draft_version: 1, recorded_at: '2026-11-15', engine: 'financial-calculators:v1', preparation_snapshot: { planning_loan: 'no' }, financial_snapshot: serializeFinancialToolsSnapshot({ budgetPeriod: 'Mensal', loan: { principal: '', rate: '', months: '', rateType: 'nominal', periodMonths: '1', gracePeriods: '', upfrontFee: '', recurringFee: '' }, breakEven: { fixed: '', price: '', variable: '' }, funding: { total: '1000000', secured: '1000000' }, incomes: [{ label: 'Receita', amount: '' }], expenses: [{ label: 'Custos', amount: '' }] }) }];
|
||||
const rows = createInvestorDossierReport(input).sections.find(section => section.id === 'finance').rows;
|
||||
assert.equal(rows.find(row => row.field === 'Financiamento — Diferença por financiar').value, '0.00 MZN');
|
||||
assert.equal(rows.some(row => /Empréstimo educativo|Ponto de equilíbrio|Orçamento —/.test(row.field)), false);
|
||||
});
|
||||
|
||||
void test('the existing Word and print exporters retain dossier identity, pending stages, source and history, escaping active HTML', async () => {
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
readNavigationFocus,
|
||||
rememberNavigationFocus,
|
||||
} from '../../resources/js/lib/navigation-focus.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const A = '15111500-0000-4000-8000-000000000001';
|
||||
const B = '15111500-0000-4000-8000-000000000002';
|
||||
|
||||
test('dossier provider retains tab focus across navigation/reload, honours explicit URLs and uses the current server version on deliberate change', async () => {
|
||||
const oldStorage = globalThis.sessionStorage,
|
||||
oldWindow = globalThis.window;
|
||||
const storage = new Map(),
|
||||
calls = [],
|
||||
visits = [];
|
||||
globalThis.sessionStorage = {
|
||||
getItem: (k) => storage.get(k),
|
||||
setItem: (k, v) => storage.set(k, v),
|
||||
removeItem: (k) => storage.delete(k),
|
||||
};
|
||||
globalThis.window = {
|
||||
location: { hash: '' },
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
let pageUrl = '/simulador',
|
||||
serverFocus = { case_id: B, step_code: null, version: 8 };
|
||||
rememberNavigationFocus(7, { case_id: A, step_code: 'S08', version: 1 });
|
||||
const code = ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
'resources/js/components/dossier-navigation-context.tsx',
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText;
|
||||
function mount() {
|
||||
const state = [],
|
||||
dependencies = [],
|
||||
pending = [];
|
||||
let cursor = 0,
|
||||
effectCursor = 0;
|
||||
const hooks = {
|
||||
createContext: () => ({ Provider: 'provider' }),
|
||||
useContext: () => ({}),
|
||||
useState(initial) {
|
||||
const i = cursor++;
|
||||
if (!(i in state))
|
||||
state[i] =
|
||||
typeof initial === 'function' ? initial() : initial;
|
||||
return [
|
||||
state[i],
|
||||
(n) =>
|
||||
(state[i] = typeof n === 'function' ? n(state[i]) : n),
|
||||
];
|
||||
},
|
||||
useEffect(callback, deps) {
|
||||
const i = effectCursor++;
|
||||
if (
|
||||
!dependencies[i] ||
|
||||
deps.some((v, n) => v !== dependencies[i][n])
|
||||
) {
|
||||
dependencies[i] = deps;
|
||||
pending.push(callback);
|
||||
}
|
||||
},
|
||||
};
|
||||
const module = { exports: {} };
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) => {
|
||||
if (id === 'react') return hooks;
|
||||
if (id === '@inertiajs/react')
|
||||
return {
|
||||
usePage: () => ({
|
||||
url: pageUrl,
|
||||
props: {
|
||||
auth: { user: { id: 7 } },
|
||||
investorPathEnabled: true,
|
||||
},
|
||||
}),
|
||||
router: { visit: (url) => visits.push(url) },
|
||||
Link: 'a',
|
||||
};
|
||||
if (id === '@/lib/navigation-focus')
|
||||
return { readNavigationFocus, rememberNavigationFocus };
|
||||
if (id === '@/lib/investor-context')
|
||||
return {
|
||||
contextApi: async (url, data, method) => {
|
||||
calls.push({ url, data, method });
|
||||
if (url === '/investimentos')
|
||||
return { contexts: [{ id: A }, { id: B }] };
|
||||
if (url === '/investimentos/contexto-atual') {
|
||||
if (method === 'PUT') {
|
||||
assert.equal(
|
||||
data.version,
|
||||
serverFocus.version,
|
||||
);
|
||||
serverFocus = {
|
||||
...data,
|
||||
version: serverFocus.version + 1,
|
||||
};
|
||||
}
|
||||
return { installed: true, focus: serverFocus };
|
||||
}
|
||||
return { case: { id: url.split('/').pop() } };
|
||||
},
|
||||
};
|
||||
return require(id);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const render = () => {
|
||||
cursor = effectCursor = 0;
|
||||
const tree = module.exports.NavigationContextProvider({
|
||||
children: null,
|
||||
});
|
||||
while (pending.length) pending.shift()();
|
||||
return tree.props.value;
|
||||
};
|
||||
return async () => {
|
||||
render();
|
||||
await new Promise(setImmediate);
|
||||
return render();
|
||||
};
|
||||
}
|
||||
try {
|
||||
let render = mount(),
|
||||
view = await render();
|
||||
assert.equal(view.active, A);
|
||||
assert.equal(view.view.case.id, A);
|
||||
assert.equal(
|
||||
calls.some((c) => c.method === 'PUT'),
|
||||
false,
|
||||
);
|
||||
render = mount();
|
||||
view = await render();
|
||||
assert.equal(
|
||||
view.active,
|
||||
A,
|
||||
'reload must not adopt the other tab server preference',
|
||||
);
|
||||
pageUrl = '/simulador?context=' + B;
|
||||
view = await render();
|
||||
assert.equal(view.active, B, 'explicit authorised dossier wins');
|
||||
assert.equal(readNavigationFocus(7, [A, B]).case_id, B);
|
||||
serverFocus = { case_id: A, step_code: null, version: 15 };
|
||||
view.choose(A, 'S02');
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(
|
||||
calls.filter((c) => c.method === 'PUT').at(-1).data.version,
|
||||
15,
|
||||
);
|
||||
assert.equal(visits.at(-1), '/investimentos/' + A + '#S02');
|
||||
} finally {
|
||||
globalThis.sessionStorage = oldStorage;
|
||||
globalThis.window = oldWindow;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
readNavigationFocus,
|
||||
rememberNavigationFocus,
|
||||
} from '../../resources/js/lib/navigation-focus.ts';
|
||||
|
||||
test('tab focus survives reload but is isolated by actor and rechecked against authorised dossiers', () => {
|
||||
const old = globalThis.sessionStorage,
|
||||
values = new Map();
|
||||
globalThis.sessionStorage = {
|
||||
getItem: (k) => values.get(k),
|
||||
setItem: (k, v) => values.set(k, v),
|
||||
removeItem: (k) => values.delete(k),
|
||||
};
|
||||
try {
|
||||
const focus = { case_id: 'synthetic-A', step_code: 'S08', version: 3 };
|
||||
rememberNavigationFocus(1, focus);
|
||||
assert.deepEqual(readNavigationFocus(1, ['synthetic-A']), focus);
|
||||
assert.equal(readNavigationFocus(2, ['synthetic-A']), null);
|
||||
assert.equal(readNavigationFocus(1, ['synthetic-B']), null);
|
||||
const firstTab = globalThis.sessionStorage;
|
||||
globalThis.sessionStorage = {
|
||||
getItem: () => null,
|
||||
setItem: (k, v) => values.set(k, v),
|
||||
removeItem: (k) => values.delete(k),
|
||||
};
|
||||
assert.equal(readNavigationFocus(1, ['synthetic-A']), null);
|
||||
globalThis.sessionStorage = firstTab;
|
||||
assert.deepEqual(readNavigationFocus(1, ['synthetic-A']), focus);
|
||||
rememberNavigationFocus(1, null);
|
||||
assert.equal(readNavigationFocus(1, ['synthetic-A']), null);
|
||||
} finally {
|
||||
globalThis.sessionStorage = old;
|
||||
}
|
||||
});
|
||||
test('corrupt, invalid and unavailable browser persistence cannot become authorisation or prevent use', () => {
|
||||
const old = globalThis.sessionStorage;
|
||||
try {
|
||||
for (const value of [
|
||||
'broken',
|
||||
'{"case_id":"A","step_code":"S99","version":1}',
|
||||
'{"case_id":"A","step_code":null,"version":-1}',
|
||||
]) {
|
||||
globalThis.sessionStorage = { getItem: () => value };
|
||||
assert.equal(readNavigationFocus(1, ['A']), null);
|
||||
}
|
||||
globalThis.sessionStorage = {
|
||||
getItem() {
|
||||
throw Error('blocked');
|
||||
},
|
||||
setItem() {
|
||||
throw Error('blocked');
|
||||
},
|
||||
removeItem() {
|
||||
throw Error('blocked');
|
||||
},
|
||||
};
|
||||
assert.equal(readNavigationFocus(1, ['A']), null);
|
||||
assert.doesNotThrow(() =>
|
||||
rememberNavigationFocus(1, {
|
||||
case_id: 'A',
|
||||
step_code: null,
|
||||
version: 1,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
globalThis.sessionStorage = old;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
samePlanningAmount,
|
||||
fundingDifferences,
|
||||
draftFundingDifferences,
|
||||
} from '../../resources/js/lib/planning-finance-context.ts';
|
||||
import {
|
||||
serializeFinancialToolsSnapshot,
|
||||
calculateFundingGap,
|
||||
} from '../../resources/js/lib/financial-calculators.ts';
|
||||
import { defaultCashflowDraftInputs } from '../../resources/js/lib/monthly-cashflow.ts';
|
||||
|
||||
test('funding reconciliation compares exact decimals without treating unknown as zero', () => {
|
||||
assert.equal(samePlanningAmount('1000000', '1000000.00'), true);
|
||||
assert.equal(samePlanningAmount('', '0'), false);
|
||||
assert.equal(samePlanningAmount('', ''), true);
|
||||
assert.equal(
|
||||
samePlanningAmount('9007199254740993', '9007199254740992'),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(
|
||||
fundingDifferences(
|
||||
{ total: '1000000', secured: '1000000' },
|
||||
{ total: '1000000', secured: '250000' },
|
||||
),
|
||||
['secured'],
|
||||
);
|
||||
assert.equal(calculateFundingGap('1000000', '1000000').gap, '0.00');
|
||||
});
|
||||
|
||||
test('a recovered snapshot retains deliberate values and reports conflicting funding origins', () => {
|
||||
const data = {
|
||||
budgetPeriod: 'Mensal',
|
||||
loan: {
|
||||
principal: '',
|
||||
rate: '',
|
||||
months: '',
|
||||
rateType: 'nominal',
|
||||
periodMonths: '1',
|
||||
gracePeriods: '',
|
||||
upfrontFee: '',
|
||||
recurringFee: '',
|
||||
},
|
||||
breakEven: { fixed: '', price: '', variable: '' },
|
||||
funding: { total: '2000000', secured: '250000' },
|
||||
incomes: [{ label: 'Receitas', amount: '' }],
|
||||
expenses: [{ label: 'Custos', amount: '' }],
|
||||
};
|
||||
const snapshot = serializeFinancialToolsSnapshot(data);
|
||||
const draft = {
|
||||
total_investment: '2000000',
|
||||
secured_amount: '1000000',
|
||||
financial_tools_snapshot: snapshot,
|
||||
};
|
||||
assert.deepEqual(draftFundingDifferences(draft), ['secured']);
|
||||
assert.equal(
|
||||
draft.financial_tools_snapshot,
|
||||
snapshot,
|
||||
'a check must not silently replace the restored calculator',
|
||||
);
|
||||
assert.deepEqual(
|
||||
draftFundingDifferences({ ...draft, secured_amount: '250000.00' }),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('fresh cashflow assumptions contain no demonstration amounts', () => {
|
||||
for (const [key, value] of Object.entries(defaultCashflowDraftInputs())) {
|
||||
if (typeof value === 'string' && /^\d/.test(value))
|
||||
assert.fail(`Unexpected automatic amount in ${key}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
currencyChoices,
|
||||
matchesChoice,
|
||||
} from '../../resources/js/lib/catalogue-choice.ts';
|
||||
import {
|
||||
createInvestmentHref,
|
||||
preparationSearch,
|
||||
} from '../../resources/js/lib/preparation-intent.ts';
|
||||
|
||||
test('an own investment carries explicit sector, geography and an interval, without an advert or corridor', () => {
|
||||
const path = [
|
||||
{ id: 'province-qa', location_type: 'province' },
|
||||
{ id: 'district-qa', location_type: 'district' },
|
||||
{ id: 'locality-qa', location_type: 'locality' },
|
||||
];
|
||||
const url = new URL(
|
||||
createInvestmentHref(
|
||||
{
|
||||
sector: 'agro',
|
||||
min_amount: '1000000',
|
||||
max_amount: '5000000',
|
||||
currency: 'MZN',
|
||||
q: 'Hotel',
|
||||
corridor_id: 'unrelated',
|
||||
opportunities: [42],
|
||||
},
|
||||
path,
|
||||
),
|
||||
'https://qa.example.test',
|
||||
);
|
||||
assert.equal(url.pathname, '/investimentos/iniciar');
|
||||
assert.equal(url.searchParams.get('investment_budget_min'), '1000000');
|
||||
assert.equal(url.searchParams.get('investment_budget_max'), '5000000');
|
||||
assert.equal(url.searchParams.get('currency'), 'MZN');
|
||||
assert.equal(url.searchParams.get('locality_id'), 'locality-qa');
|
||||
assert.equal(url.searchParams.get('sector'), 'agro');
|
||||
for (const key of [
|
||||
'q',
|
||||
'project_title',
|
||||
'corridor_id',
|
||||
'opportunities',
|
||||
'total_investment',
|
||||
])
|
||||
assert.equal(url.searchParams.has(key), false);
|
||||
const empty = new URL(createInvestmentHref({ q: 'Criar Hotel' }), url);
|
||||
assert.equal(
|
||||
empty.search,
|
||||
'',
|
||||
'a title does not assign a definitive activity or sector',
|
||||
);
|
||||
});
|
||||
|
||||
test('optional opportunity searches use only confirmed criteria and do not carry budget or private declarations', () => {
|
||||
const query = new URLSearchParams(
|
||||
preparationSearch('hotel', 'sector:7', [
|
||||
{ id: 'province-qa', location_type: 'province' },
|
||||
]),
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...query.entries()],
|
||||
[
|
||||
['q', 'hotel'],
|
||||
['sector_id', '7'],
|
||||
['province_id', 'province-qa'],
|
||||
],
|
||||
);
|
||||
assert.equal(preparationSearch('', '', []), '');
|
||||
});
|
||||
|
||||
test('country and currency search accepts names, three letters, accents, case and short codes', () => {
|
||||
for (const query of ['MOC', 'moç', 'MZ', 'mocambique'])
|
||||
assert.equal(matchesChoice(query, ['Moçambique — MZ']), true);
|
||||
const metical = currencyChoices().find((choice) => choice.value === 'MZN');
|
||||
assert.ok(metical);
|
||||
assert.match(metical.label, /metical/i);
|
||||
for (const query of ['MET', 'met', 'MZN'])
|
||||
assert.equal(
|
||||
matchesChoice(query, [metical.label, ...metical.keywords]),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(
|
||||
currencyChoices(['MZN', 'USD']).map((choice) => choice.value),
|
||||
['MZN', 'USD'],
|
||||
'preserve a consumer’s approved currency constraints',
|
||||
);
|
||||
assert.equal(matchesChoice('euro', [metical.label]), false);
|
||||
});
|
||||
@@ -0,0 +1,588 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const root = path.resolve('resources/js');
|
||||
function load(file, mocks = {}) {
|
||||
const absolute = path.resolve(root, file);
|
||||
const module = { exports: {} };
|
||||
const code = ts.transpileModule(fs.readFileSync(absolute, 'utf8'), {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) => {
|
||||
if (id in mocks) return mocks[id];
|
||||
if (id === '@inertiajs/react')
|
||||
return {
|
||||
Link: ({ children, ...props }) =>
|
||||
React.createElement('a', props, children),
|
||||
usePage: () => ({ url: '/sectores/test' }),
|
||||
};
|
||||
if (id.startsWith('.') || id.startsWith('@/')) {
|
||||
const base = id.startsWith('@/')
|
||||
? path.resolve(root, id.slice(2))
|
||||
: path.resolve(path.dirname(absolute), id);
|
||||
const found = [base, base + '.tsx', base + '.ts'].find(
|
||||
(p) => fs.existsSync(p) && fs.statSync(p).isFile(),
|
||||
);
|
||||
if (found) return load(path.relative(root, found), mocks);
|
||||
}
|
||||
return require(id);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return module.exports;
|
||||
}
|
||||
const render = (file, props) =>
|
||||
renderToStaticMarkup(React.createElement(load(file).default, props));
|
||||
|
||||
test('demographic comparison retains four saved places and requires a province before searching districts', () => {
|
||||
const Page = load('pages/investment/demography.tsx', {
|
||||
'./shared': {
|
||||
Frame: ({ children }) =>
|
||||
React.createElement('main', null, children),
|
||||
button: '',
|
||||
},
|
||||
'@/components/demographic-evidence': { default: () => null },
|
||||
}).default;
|
||||
const territories = [
|
||||
{
|
||||
id: 'p1',
|
||||
name: 'Província A',
|
||||
location_type: 'province',
|
||||
parent_id: null,
|
||||
},
|
||||
{
|
||||
id: 'p2',
|
||||
name: 'Província B',
|
||||
location_type: 'province',
|
||||
parent_id: null,
|
||||
},
|
||||
{
|
||||
id: 'd1',
|
||||
name: 'Distrito A',
|
||||
location_type: 'district',
|
||||
parent_id: 'p1',
|
||||
},
|
||||
{
|
||||
id: 'd2',
|
||||
name: 'Distrito B',
|
||||
location_type: 'district',
|
||||
parent_id: 'p2',
|
||||
},
|
||||
];
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Page, {
|
||||
evidence: { territories: [] },
|
||||
filters: {
|
||||
territories: territories.map((t) => t.id),
|
||||
start_year: 2026,
|
||||
end_year: 2027,
|
||||
},
|
||||
territories,
|
||||
sectors: { general: 'Geral' },
|
||||
}),
|
||||
);
|
||||
assert.match(html, /aria-label="Pesquisar Província da comparação"/);
|
||||
assert.match(
|
||||
html,
|
||||
/aria-label="Pesquisar Distrito da comparação \(opcional\)"[^>]*disabled/,
|
||||
);
|
||||
assert.doesNotMatch(html, /<select[^>]*multiple/);
|
||||
for (const t of territories)
|
||||
assert.ok(html.includes(`Retirar ${t.name} —`));
|
||||
assert.match(html, /disabled=""[^>]*>Acrescentar à comparação/);
|
||||
assert.match(html, /value="2026"/);
|
||||
assert.match(html, /value="2027"/);
|
||||
});
|
||||
|
||||
test('the real preparation editor opens an own idea with its budget and no mandatory advert or duplicate reference selector', () => {
|
||||
const Empty = () => null;
|
||||
const Editor = load('pages/investor-path/context.tsx', {
|
||||
'@/pages/investment/shared': {
|
||||
Frame: ({ children }) =>
|
||||
React.createElement('main', null, children),
|
||||
card: '',
|
||||
button: '',
|
||||
input: '',
|
||||
},
|
||||
'@/components/navigation-context': { useNavigationContext: () => ({}) },
|
||||
'@/components/investment-territory': { TerritoryFields: Empty },
|
||||
'@/components/private-investment-preparation': {
|
||||
PreparationEditor: Empty,
|
||||
PreparationImpact: Empty,
|
||||
},
|
||||
'@/components/investment-complements': {
|
||||
default: Empty,
|
||||
SelectedComplements: Empty,
|
||||
complementInput: (value) => value,
|
||||
},
|
||||
'@/components/context-documents': { default: Empty },
|
||||
'@/components/investment-opportunity-choices': { default: Empty },
|
||||
'@/components/investment-requirements': { default: Empty },
|
||||
'@/lib/operation-key': { createOperationKey: () => 'synthetic-key' },
|
||||
}).default;
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Editor, {
|
||||
initial: {
|
||||
case: {
|
||||
id: 'synthetic-hotel',
|
||||
title: 'Criar Hotel',
|
||||
version: 1,
|
||||
},
|
||||
context: {
|
||||
revision: 0,
|
||||
fields: { project_title: 'Criar Hotel' },
|
||||
selection: {},
|
||||
provenance: {},
|
||||
opportunity_choices: [],
|
||||
},
|
||||
private_investment: null,
|
||||
can_write: true,
|
||||
results: [],
|
||||
requests: [],
|
||||
preparation_documents: [],
|
||||
},
|
||||
source: null,
|
||||
options: {
|
||||
countries: [
|
||||
{ code: 'MZ', name: 'Moçambique', name_en: 'Mozambique' },
|
||||
],
|
||||
sectors: [{ id: 7, name: 'Turismo QA' }],
|
||||
parks: [],
|
||||
search_limited: false,
|
||||
opportunities: [
|
||||
{
|
||||
key: 'opportunity:2',
|
||||
title: 'Açúcar sem pertinência',
|
||||
kind: 'opportunity',
|
||||
},
|
||||
],
|
||||
},
|
||||
entryIdea: {
|
||||
sector_id: '7',
|
||||
currency: 'MZN',
|
||||
investment_budget_min: '1000000',
|
||||
investment_budget_max: '5000000',
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.match(html, /Criar Hotel/);
|
||||
assert.match(html, /value="1000000"/);
|
||||
assert.match(html, /value="5000000"/);
|
||||
assert.match(html, /value="sector:7" selected=""/);
|
||||
assert.match(html, /Oportunidades relacionadas \(opcional\)/);
|
||||
assert.doesNotMatch(html, /Referência individual|Açúcar sem pertinência/);
|
||||
if (process.env.INVESTMOZ_INTENT_PREVIEW === '1') {
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'public/build-qa-opportunities/manifest.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const css = fs.readFileSync(
|
||||
'public/build-qa-opportunities/' +
|
||||
manifest['resources/css/app.css'].file,
|
||||
'utf8',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
'outputs/investor-intent-20261115/editor-preview.html',
|
||||
`<!doctype html><html lang="pt"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>InvesteMoz — prévia sintética de preparação</title><style>${css}</style><body><div class="mx-auto max-w-4xl p-4"><p class="rounded border p-3">QA sintético: editor renderizado, sem autenticação, gravação ou consultas. A cartografia foi substituída no ensaio. Esta prévia não demonstra o percurso autenticado.</p>${html}</div></body></html>`,
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('changing the consulted territory remounts its evidence and aborts a late response', async () => {
|
||||
const state = [],
|
||||
refs = [];
|
||||
let cursor = 0,
|
||||
refCursor = 0,
|
||||
cleanup;
|
||||
const hooks = {
|
||||
useState(initial) {
|
||||
const index = cursor++;
|
||||
if (!(index in state)) state[index] = initial;
|
||||
return [
|
||||
state[index],
|
||||
(next) => {
|
||||
state[index] = next;
|
||||
},
|
||||
];
|
||||
},
|
||||
useRef(initial) {
|
||||
const index = refCursor++;
|
||||
refs[index] ??= { current: initial };
|
||||
return refs[index];
|
||||
},
|
||||
useEffect(callback) {
|
||||
cleanup = callback();
|
||||
},
|
||||
};
|
||||
const Component = load('components/demographic-context.tsx', {
|
||||
react: hooks,
|
||||
}).default;
|
||||
const a = Component({ territoryId: 'synthetic-A' });
|
||||
const b = Component({ territoryId: 'synthetic-B' });
|
||||
assert.notEqual(a.key, b.key);
|
||||
assert.equal(Component({ territoryId: null }), null);
|
||||
const tree = a.type(a.props);
|
||||
const nodes = (n) =>
|
||||
!n || typeof n !== 'object'
|
||||
? []
|
||||
: Array.isArray(n)
|
||||
? n.flatMap(nodes)
|
||||
: [n, ...nodes(n.props?.children)];
|
||||
const button = nodes(tree).find((n) => n.type === 'button');
|
||||
const originalFetch = globalThis.fetch;
|
||||
let resolve, signal;
|
||||
globalThis.fetch = (url, options) => {
|
||||
assert.match(url, /synthetic-A/);
|
||||
signal = options.signal;
|
||||
return new Promise((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
};
|
||||
try {
|
||||
const pending = button.props.onClick();
|
||||
cleanup();
|
||||
assert.equal(signal.aborted, true);
|
||||
resolve({ ok: true, json: async () => ({ territories: ['old A'] }) });
|
||||
await pending;
|
||||
assert.equal(
|
||||
state[0],
|
||||
null,
|
||||
'late evidence must not be attached to another territory',
|
||||
);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('shared evidence is closed by default, preserves content and wraps long references', () => {
|
||||
const html = render('components/evidence-details.tsx', {
|
||||
children: 'source-version-hash',
|
||||
title: 'Fonte',
|
||||
});
|
||||
assert.match(html, /<details[^>]*>/);
|
||||
assert.doesNotMatch(html, /<details[^>]*\bopen/);
|
||||
assert.match(html, /source-version-hash/);
|
||||
assert.match(html, /overflow-wrap:anywhere/);
|
||||
});
|
||||
test('public document keeps applicability, usage limitations and actions visible, with source metadata in detail', () => {
|
||||
const { PublicDocumentContent } = load(
|
||||
'components/public-document-content.tsx',
|
||||
);
|
||||
const resource = {
|
||||
id: 1,
|
||||
title: 'Diploma QA',
|
||||
description: 'Objecto documentado',
|
||||
issuer: null,
|
||||
document_number: null,
|
||||
document_date: null,
|
||||
applicable_from: '2025-01-01',
|
||||
applicable_until: null,
|
||||
source_url: null,
|
||||
source_confirmation: 'unknown',
|
||||
usage_notice: 'Confirmar o âmbito aplicável',
|
||||
view_url: null,
|
||||
download_url: '/documents/1',
|
||||
context_actions: [],
|
||||
};
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(PublicDocumentContent, { resource }),
|
||||
);
|
||||
assert.match(html, /2025-01-01/);
|
||||
assert.match(html, /Confirmar o âmbito aplicável/);
|
||||
assert.match(html, /href="\/documents\/1"/);
|
||||
assert.doesNotMatch(html, /Entidade emissora|Consultar ficha/);
|
||||
assert.ok(html.indexOf('Período indicado') > html.indexOf('</details>'));
|
||||
});
|
||||
test('territorial references retain exact citation and provenance without a primary internal-process block', () => {
|
||||
const source = {
|
||||
association: 'Corredor QA',
|
||||
role: 'Ligação',
|
||||
source_reference: 'Diploma QA §2',
|
||||
source_quote: 'Relação documentada',
|
||||
supports: '',
|
||||
traceability: 'original hash/version',
|
||||
official_source_accepted: true,
|
||||
existing_validation: 'validated',
|
||||
};
|
||||
const html = render('components/territorial-source-evidence.tsx', {
|
||||
sources: [source],
|
||||
});
|
||||
assert.match(html, /Diploma QA §2/);
|
||||
assert.match(html, /original hash\/version/);
|
||||
assert.doesNotMatch(
|
||||
html,
|
||||
/não retira a aceitação existente|campo específico/,
|
||||
);
|
||||
assert.equal(
|
||||
render('components/territorial-source-evidence.tsx', { sources: [] }),
|
||||
'',
|
||||
);
|
||||
});
|
||||
test('empty published catalogue does not claim absent companies, resources or economic potential', () => {
|
||||
const html = render('components/published-opportunities-empty.tsx', {
|
||||
href: '/oportunidades?sector=qa',
|
||||
});
|
||||
assert.match(html, /Sem anúncios publicados/);
|
||||
assert.match(
|
||||
html,
|
||||
/não indica ausência de empresas, recursos ou potencial/,
|
||||
);
|
||||
assert.match(html, /sector=qa/);
|
||||
});
|
||||
const value = (
|
||||
year,
|
||||
age_group = 'all',
|
||||
data_kind = 'projected',
|
||||
unit = 'pessoas',
|
||||
) => ({
|
||||
year,
|
||||
indicator: 'population',
|
||||
age_group,
|
||||
residence: 'all',
|
||||
value: '1234',
|
||||
original_value: '1 234',
|
||||
unit,
|
||||
data_kind,
|
||||
sheet: 'sheet',
|
||||
cell: 'B' + year,
|
||||
validation_status: 'valid',
|
||||
});
|
||||
test('demographic highlights never sum dimensions, mix units or silently replace a source/version', () => {
|
||||
const { demographicHighlights } = load(
|
||||
'components/demographic-evidence.tsx',
|
||||
);
|
||||
const values = [
|
||||
value(2024),
|
||||
value(2025),
|
||||
value(2026, '0-4'),
|
||||
value(2024, 'all', 'observed'),
|
||||
value(2023, 'all', 'projected', 'unspecified'),
|
||||
];
|
||||
assert.deepEqual(demographicHighlights(values), [
|
||||
values[1],
|
||||
values[3],
|
||||
values[4],
|
||||
]);
|
||||
assert.deepEqual(demographicHighlights([value(2025, '0-4')]), []);
|
||||
});
|
||||
test('demography shows original latest total, period, projection and decision warning; technical cells remain closed', () => {
|
||||
const evidence = {
|
||||
state: 'available',
|
||||
start_year: 2024,
|
||||
end_year: 2025,
|
||||
limitations: ['Não prova procura'],
|
||||
comparisons: [],
|
||||
differences: [],
|
||||
territories: [
|
||||
{
|
||||
id: 'qa',
|
||||
name: 'Território QA',
|
||||
level: 'province',
|
||||
factors_to_assess: [],
|
||||
series: [
|
||||
{
|
||||
import_id: 'qa',
|
||||
source: 'Fonte QA',
|
||||
version: 'Edição QA',
|
||||
sha256: '123abc',
|
||||
file_name: 'QA.xlsx',
|
||||
missing_years: [],
|
||||
issue_counts: {},
|
||||
values: [value(2024), value(2025)],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const html = render('components/demographic-evidence.tsx', { evidence });
|
||||
assert.match(html, /1 234/);
|
||||
assert.match(html, /não demonstram procura ou rentabilidade/);
|
||||
assert.match(html, /Projecção/);
|
||||
assert.match(html, /SHA256/);
|
||||
assert.ok(html.indexOf('SHA256') > html.indexOf('<summary'));
|
||||
assert.doesNotMatch(html, /<details[^>]*\bopen/);
|
||||
});
|
||||
test('cluster analysis omits empty field blocks but keeps documented evidence and uncertainty', () => {
|
||||
const { forces } = load('lib/cluster-competitiveness.ts');
|
||||
const rows = Object.fromEntries(
|
||||
forces.map((f) => [
|
||||
f,
|
||||
{
|
||||
pressure: '',
|
||||
evidence: 'Facto QA',
|
||||
source: '',
|
||||
period: '',
|
||||
rationale: '',
|
||||
limitations: 'Por confirmar',
|
||||
opportunity: '',
|
||||
},
|
||||
]),
|
||||
);
|
||||
const html = render('components/cluster-competitiveness-public.tsx', {
|
||||
analysis: {
|
||||
version: 1,
|
||||
at: '2026-11-15',
|
||||
draft: { sector: 'QA', region: 'Local QA', forces: rows },
|
||||
},
|
||||
});
|
||||
assert.match(html, /Facto QA/);
|
||||
assert.match(html, /Por confirmar/);
|
||||
assert.doesNotMatch(html, /<dt[^>]*>Fonte e referência/);
|
||||
});
|
||||
test('simulator keeps original calculation correspondence and source behind explicit details', () => {
|
||||
const { SimulationModeloA } = load('components/simulation-modelo-a.tsx');
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(SimulationModeloA, { draft: {} }),
|
||||
);
|
||||
assert.match(html, /Modelo A/);
|
||||
assert.match(html, /SHA256/);
|
||||
assert.ok(
|
||||
html.indexOf('SHA256') >
|
||||
html.indexOf('Exemplar e integridade da fonte'),
|
||||
);
|
||||
assert.match(html, /não é imposto final/);
|
||||
});
|
||||
|
||||
// Optional visual fixture: the real components with explicit synthetic data,
|
||||
// not an authenticated application or an operational publication.
|
||||
if (process.env.INVESTMOZ_RECONCILIATION_PREVIEW === '1') {
|
||||
const population = (year, age, amount, residence = 'all') => ({
|
||||
...value(year, age, 'projected', 'pessoas'),
|
||||
residence,
|
||||
value: String(amount),
|
||||
original_value: String(amount),
|
||||
cell: `${year}-${age}-${residence}`,
|
||||
});
|
||||
const values = [
|
||||
population(2026, 'all', 1000),
|
||||
population(2028, 'all', 1200),
|
||||
population(2028, 'all', 480, 'urban'),
|
||||
population(2028, 'all', 720, 'rural'),
|
||||
];
|
||||
for (const age of ['0-4', '5-9', '10-14'])
|
||||
values.push(population(2028, age, 120));
|
||||
for (const age of [
|
||||
'15-19',
|
||||
'20-24',
|
||||
'25-29',
|
||||
'30-34',
|
||||
'35-39',
|
||||
'40-44',
|
||||
'45-49',
|
||||
'50-54',
|
||||
'55-59',
|
||||
'60-64',
|
||||
])
|
||||
values.push(population(2028, age, 60));
|
||||
const evidence = {
|
||||
state: 'available',
|
||||
start_year: 2026,
|
||||
end_year: 2028,
|
||||
sector: 'general',
|
||||
limitations: [
|
||||
'Exclusivamente dados sintéticos. Não representam população real.',
|
||||
],
|
||||
comparisons: [],
|
||||
differences: [],
|
||||
territories: [
|
||||
{
|
||||
id: 'synthetic-qa',
|
||||
name: 'Território sintético QA',
|
||||
level: 'district',
|
||||
factors_to_assess: [],
|
||||
series: [
|
||||
{
|
||||
import_id: 'qa',
|
||||
source: 'Fonte sintética de ensaio',
|
||||
version: 'QA 2026',
|
||||
sha256: 'a'.repeat(64),
|
||||
file_name: 'exemplo-sintetico.xlsx',
|
||||
missing_years: [2027],
|
||||
issue_counts: {},
|
||||
values,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const demographicHtml = render('components/demographic-evidence.tsx', {
|
||||
evidence,
|
||||
});
|
||||
const emptyHtml = render('components/published-opportunities-empty.tsx', {
|
||||
href: '#demografia',
|
||||
label: 'Estudar a localização',
|
||||
});
|
||||
const { PublicDocumentContent } = load(
|
||||
'components/public-document-content.tsx',
|
||||
);
|
||||
const documentHtml = renderToStaticMarkup(
|
||||
React.createElement(PublicDocumentContent, {
|
||||
resource: {
|
||||
id: 1,
|
||||
title: 'Guia sintético QA',
|
||||
description:
|
||||
'Documento de ensaio para conferir a apresentação.',
|
||||
issuer: 'Entidade sintética',
|
||||
document_number: 'QA-1',
|
||||
document_date: '2026-11-15',
|
||||
applicable_from: '2026-11-15',
|
||||
applicable_until: null,
|
||||
source_url: null,
|
||||
source_confirmation: 'unknown',
|
||||
usage_notice:
|
||||
'Exemplo de limitação relevante, conservada junto do documento.',
|
||||
view_url: null,
|
||||
download_url: '#documento',
|
||||
context_actions: [],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const sourceHtml = render('components/territorial-source-evidence.tsx', {
|
||||
sources: [
|
||||
{
|
||||
association: 'Relação territorial sintética',
|
||||
role: 'Contexto',
|
||||
source_reference: 'Fonte sintética §1',
|
||||
source_quote: 'Relação apenas para ensaio.',
|
||||
supports: '',
|
||||
traceability: 'Versão QA e original conservados',
|
||||
official_source_accepted: false,
|
||||
existing_validation: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
const { SimulationModeloA } = load('components/simulation-modelo-a.tsx');
|
||||
const simulatorHtml = renderToStaticMarkup(
|
||||
React.createElement(SimulationModeloA, { draft: {} }),
|
||||
);
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync('public/build-qa-opportunities/manifest.json', 'utf8'),
|
||||
);
|
||||
const css = fs.readFileSync(
|
||||
'public/build-qa-opportunities/' +
|
||||
manifest['resources/css/app.css'].file,
|
||||
'utf8',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
'outputs/demography-reconciliation-20261115/visual-components.html',
|
||||
`<!doctype html><html lang="pt"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>InvesteMoz QA — conferência de componentes</title><style>${css}</style><body class="bg-slate-50 text-slate-900"><main class="mx-auto max-w-5xl space-y-8 p-4"><header><h1 class="text-2xl font-bold">InvesteMoz — prévia QA</h1><p>Componentes reais com dados sintéticos. Não é uma sessão autenticada nem publicação no portal.</p><nav class="flex flex-wrap gap-4 py-4"><a href="#demografia">Demografia</a><a href="#catalogo">Catálogo</a><a href="#territorio">Território</a><a href="#documento">Biblioteca</a><a href="#simulador">Simulador</a></nav></header><section id="demografia">${demographicHtml}</section><section id="catalogo"><h2 class="text-xl font-semibold">Catálogo — sem anúncios publicados</h2>${emptyHtml}</section><section id="territorio"><h2 class="text-xl font-semibold">Contexto territorial</h2>${sourceHtml}</section><section id="documento">${documentHtml}</section><section id="simulador">${simulatorHtml}</section></main></body></html>`,
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
@@ -193,7 +193,7 @@ void test('small business exploratory draft includes idea and finance without ma
|
||||
assert.deepEqual(validateSimulationDraft(draft, 'opportunity'), {});
|
||||
});
|
||||
|
||||
void test('project investment evaluation opens a direct project, location, finance, tax and analysis journey', () => {
|
||||
void test('simple investment preparation separates initial investment and funding and retains the full advanced journey', () => {
|
||||
const selected = replaceSimulationValue({}, 'journey_type', 'investor');
|
||||
assert.equal(selected.purpose, 'simulate_only');
|
||||
const sections = getSimulationSections(selected).map(
|
||||
@@ -201,14 +201,29 @@ void test('project investment evaluation opens a direct project, location, finan
|
||||
);
|
||||
assert.deepEqual(sections, [
|
||||
'purpose',
|
||||
'project',
|
||||
'location',
|
||||
'market',
|
||||
'investment',
|
||||
'financial',
|
||||
'operating',
|
||||
'cashflow',
|
||||
'tax',
|
||||
'scenarios',
|
||||
'procedures',
|
||||
'review',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
getSimulationSections({ ...selected, detail_level: 'advanced' }).map(
|
||||
(section) => section.id,
|
||||
),
|
||||
[
|
||||
'purpose',
|
||||
'project',
|
||||
'location',
|
||||
'financial',
|
||||
'tax',
|
||||
'scenarios',
|
||||
'procedures',
|
||||
'review',
|
||||
],
|
||||
);
|
||||
for (const sectionId of [
|
||||
'project',
|
||||
'location',
|
||||
|
||||
Reference in New Issue
Block a user