merge: integrate validated QA 1349952d for authorised public installation
tests / ci (push) Waiting to run
tests / ci (push) Waiting to run
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class BusinessPlanDraftContinuityTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
public function test_incomplete_plans_keep_exact_values_in_their_own_dossier_after_a_new_session(): void
|
||||
{
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
$this->assertSame('continuity_20261120_test', $identity->name);
|
||||
$this->assertSame(55441, (int) $identity->port);
|
||||
config(['investor-path.enabled' => true]);
|
||||
$owner = User::factory()->create();
|
||||
$cases = [];
|
||||
foreach (['Hotel sintético QA' => '250.50', 'Agronegócio sintético QA' => '375.25'] as $title => $price) {
|
||||
$case = app(VirtualDesk::class)->createCase($owner, ['title' => $title, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true]);
|
||||
$snapshot = json_encode(['version' => 17, 'plan' => ['currency' => 'MZN', 'annualGrowthPercent' => '250', 'products' => [['label' => $title, 'monthlyUnits' => '25', 'unitPrice' => $price, 'unitVariableCost' => '100.50']], 'monthlyOperatingExpenses' => '500.25', 'salesCollectionPercent' => '', 'openingReceivablesCollectionPercent' => '']], JSON_THROW_ON_ERROR);
|
||||
$this->actingAs($owner)->postJson('/api/v1/simulation-drafts', ['context' => $case->id, 'personal_snapshot' => [], 'economic_snapshot' => ['purpose' => 'simulate_only', 'journey_type' => 'small_business', 'business_plan_snapshot' => $snapshot]], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated();
|
||||
$cases[] = [$case->id, $snapshot];
|
||||
}
|
||||
$this->flushSession();
|
||||
foreach ($cases as [$caseId, $snapshot]) {
|
||||
$this->actingAs(User::findOrFail($owner->id))->getJson('/api/v1/simulation-drafts/current?context='.$caseId)->assertOk()->assertJsonPath('data.economic_snapshot.business_plan_snapshot', $snapshot);
|
||||
}
|
||||
$this->actingAs(User::factory()->create())->getJson('/api/v1/simulation-drafts/current?context='.$cases[0][0])->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,20 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\DemographicEvidence;
|
||||
use App\Services\DemographicImport;
|
||||
use App\Services\InvestmentPreparationWorkspace;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use App\Services\SectorContentAnalysis;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DemographyTest extends TestCase
|
||||
@@ -77,6 +81,35 @@ final class DemographyTest extends TestCase
|
||||
$this->assertSame([], app(DemographicEvidence::class)->analyse([$this->district], 2026, 2027)['territories']);
|
||||
}
|
||||
|
||||
public function test_tourism_is_explicit_and_comparisons_include_intermediate_years(): void
|
||||
{
|
||||
$this->assertSame('Turismo', DemographicEvidence::sectors()['tourism']);
|
||||
$response = $this->getJson('/api/v1/investment/demography?'.http_build_query(['territories' => [$this->district], 'start_year' => 2026, 'end_year' => 2028, 'sector' => 'tourism']))->assertOk();
|
||||
$response->assertJsonPath('sector', 'tourism')->assertJsonPath('territories.0.series.0.values.0.original_value', '100.125');
|
||||
$other = (array) DB::table('geo_locations')->where('id', $this->district)->first();
|
||||
$other['id'] = (string) Str::uuid();
|
||||
$other['code'] = $other['id'];
|
||||
$other['external_id'] = '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$other['id'];
|
||||
DB::table('geo_locations')->insert($other);
|
||||
foreach (DB::table('demographic_observations')->where('geo_location_id', $this->district)->get() as $row) {
|
||||
$row = (array) $row;
|
||||
unset($row['id']);
|
||||
DB::table('demographic_observations')->insert([...$row, 'geo_location_id' => $other['id']]);
|
||||
}
|
||||
$analysis = app(DemographicEvidence::class)->analyse([$this->district, $other['id']], 2026, 2028, 'commerce');
|
||||
$this->assertSame([2026, 2027], array_column($analysis['comparisons'], 'year'));
|
||||
$this->assertSame([], app(SectorContentAnalysis::class)->forTerritories([$this->district], 'commerce'));
|
||||
}
|
||||
|
||||
public function test_commerce_and_territory_reach_the_normal_investor_entry(): void
|
||||
{
|
||||
$sector = Sector::firstOrCreate(['slug' => 'comercio-e-servicos'], ['name' => 'Comércio e serviços', 'is_active' => true]);
|
||||
$this->get('/localizacoes/demografia?'.http_build_query(['territories' => [$this->district], 'sector' => 'commerce']))
|
||||
->assertOk()->assertInertia(fn ($page) => $page->component('investment/demography')->where('entrySector', $sector->slug)->where('sectorReadings', []));
|
||||
$this->actingAs(User::factory()->create())->get('/investimentos/iniciar?'.http_build_query(['source' => 'territory:'.$this->district, 'sector' => $sector->slug]))
|
||||
->assertOk()->assertInertia(fn ($page) => $page->component('investor-path/context-start')->where('entryQuery.sector_id', (string) $sector->id)->where('source.id', $this->district)->etc());
|
||||
}
|
||||
|
||||
public function test_new_editions_remain_separate_and_divergence_is_reported(): void
|
||||
{
|
||||
$other = $this->batch('approved');
|
||||
@@ -202,8 +235,10 @@ final class DemographyTest extends TestCase
|
||||
{
|
||||
Storage::fake('local');
|
||||
$disk = Storage::disk('local');
|
||||
$original = 'SYNTHETIC prepared original'; $sha = hash('sha256', $original);
|
||||
$directory = 'prepared/'.$sha; $disk->makeDirectory($directory);
|
||||
$original = 'SYNTHETIC prepared original';
|
||||
$sha = hash('sha256', $original);
|
||||
$directory = 'prepared/'.$sha;
|
||||
$disk->makeDirectory($directory);
|
||||
$disk->put('synthetic.xlsx', $original);
|
||||
$row = ['province' => 'SYNTHETIC province', 'territory' => 'SYNTHETIC province', 'level' => 'province',
|
||||
'year' => 2026, 'indicator' => 'population', 'sex' => 'all', 'residence' => 'all', 'age_group' => 'all', 'unit' => 'pessoas',
|
||||
@@ -214,10 +249,11 @@ final class DemographyTest extends TestCase
|
||||
$preview = json_encode($report, JSON_THROW_ON_ERROR);
|
||||
$receipt = ['sha256' => $sha, 'baseline_year' => null, 'parser_sha256' => hash_file('sha256', base_path('tools/demography_workbook.py')),
|
||||
'preview_sha256' => hash('sha256', $preview), 'records_sha256' => hash('sha256', $records), 'record_count' => 1];
|
||||
$disk->put($directory.'/preview.json', $preview); $disk->put($directory.'/records.ndjson', $records);
|
||||
$disk->put($directory.'/preview.json', $preview);
|
||||
$disk->put($directory.'/records.ndjson', $records);
|
||||
$disk->put($directory.'/preparation.json', json_encode($receipt, JSON_THROW_ON_ERROR));
|
||||
config(['demography.prepared_directory' => $disk->path('prepared'), 'demography.python' => '/missing-python-must-not-run']);
|
||||
$this->mock(\App\Services\Malware\MalwareScanner::class)->shouldReceive('scan')->once()->andReturn([
|
||||
$this->mock(MalwareScanner::class)->shouldReceive('scan')->once()->andReturn([
|
||||
'result' => 'clean', 'engine' => 'synthetic', 'engine_version' => 'test']);
|
||||
$service = app(DemographicImport::class);
|
||||
$this->assertTrue($service->preparedSourcesReady(['synthetic.xlsx' => ['sha256' => $sha, 'records' => 1]]));
|
||||
@@ -227,9 +263,14 @@ final class DemographyTest extends TestCase
|
||||
$this->assertSame('100.125', DB::table('demographic_observations')->where('import_id', $result['id'])->value('numeric_value'));
|
||||
$this->assertSame('imported', DB::table('demographic_imports')->where('id', $result['id'])->value('status'));
|
||||
$disk->put($directory.'/records.ndjson', 'TAMPERED');
|
||||
try { $service->preparedSource($sha, null); $this->fail('Changed prepared records must be refused.'); }
|
||||
catch (\Symfony\Component\HttpKernel\Exception\HttpException $error) { $this->assertSame(409, $error->getStatusCode()); }
|
||||
$receipt['parser_sha256'] = str_repeat('0', 64); $disk->put($directory.'/preparation.json', json_encode($receipt, JSON_THROW_ON_ERROR));
|
||||
try {
|
||||
$service->preparedSource($sha, null);
|
||||
$this->fail('Changed prepared records must be refused.');
|
||||
} catch (HttpException $error) {
|
||||
$this->assertSame(409, $error->getStatusCode());
|
||||
}
|
||||
$receipt['parser_sha256'] = str_repeat('0', 64);
|
||||
$disk->put($directory.'/preparation.json', json_encode($receipt, JSON_THROW_ON_ERROR));
|
||||
$this->assertFalse($service->preparedSourcesReady(['synthetic.xlsx' => ['sha256' => $sha, 'records' => 1]]));
|
||||
}
|
||||
|
||||
|
||||
@@ -14,21 +14,31 @@ 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();
|
||||
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]]);
|
||||
$this->assertContains($db->name, ['investor_intent_20261115_test', 'continuity_20261120_test']);
|
||||
$this->assertSame(55441, (int) $db->port);
|
||||
// Counts below concern this test's fixtures. Existing browser fixtures
|
||||
// remain unchanged after DatabaseTransactions rolls the test back.
|
||||
DB::table('funding_programmes')->update(['published_version_id' => null]);
|
||||
$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->geo[$type] = $id;
|
||||
$parent = $id;
|
||||
}
|
||||
$this->sector = Sector::create(['slug' => 'synthetic-funding-qa', 'name' => 'SYNTHETIC sector', 'is_active' => true, 'published_at' => now()])->id;
|
||||
}
|
||||
@@ -37,13 +47,16 @@ final class FundingCriteriaCoherenceTest extends TestCase
|
||||
{
|
||||
$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]]];
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -62,7 +75,9 @@ final class FundingCriteriaCoherenceTest extends TestCase
|
||||
$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);
|
||||
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');
|
||||
@@ -82,8 +97,12 @@ final class FundingCriteriaCoherenceTest extends TestCase
|
||||
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()); }
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Services\FundingProgrammes;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
/** Uses unchanged documentary institutions in the explicitly guarded QA fixture. */
|
||||
final class FundingLocalPresenceAcceptanceTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
private array $fixture;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->assertSame('continuity_20261120_test', DB::connection()->getDatabaseName());
|
||||
$this->fixture = json_decode(file_get_contents(base_path('outputs/funding-b03-b06-20261120/fixture.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
$this->assertSame($this->fixture['source_sha256'], hash_file('sha256', database_path('data/funding-institutions-nov2026.json')));
|
||||
}
|
||||
|
||||
private function ids(string $province, string $mode, string $certainty = 'include_unknown'): array
|
||||
{
|
||||
return app(FundingProgrammes::class)->catalogueQuery(['territory' => $this->fixture['provinces'][$province], 'location_mode' => $mode, 'kind' => 'institution', 'need' => 'investment', 'certainty' => $certainty])->pluck('p.id')->all();
|
||||
}
|
||||
|
||||
public function test_national_financing_is_not_a_physical_branch_and_unknowns_are_not_confirmed(): void
|
||||
{
|
||||
$moza = $this->fixture['records']['moza']['id'];
|
||||
$microbank = $this->fixture['records']['ac-microbanco']['id'];
|
||||
$this->assertContains($moza, $this->ids('Niassa', 'coverage'));
|
||||
$this->assertNotContains($moza, $this->ids('Niassa', 'physical'));
|
||||
$this->assertContains($moza, $this->ids('Maputo Cidade', 'physical'));
|
||||
$this->assertContains($this->fixture['records']['bci']['id'], $this->ids('Maputo Cidade', 'physical', 'documented'));
|
||||
$this->assertNotContains($microbank, $this->ids('Gaza', 'physical', 'documented'));
|
||||
$this->assertContains($microbank, $this->ids('Gaza', 'physical'));
|
||||
}
|
||||
|
||||
public function test_empty_local_result_does_not_fall_back_to_the_national_catalogue(): void
|
||||
{
|
||||
$district = DB::table('geo_locations')->where('parent_id', $this->fixture['provinces']['Niassa'])->where('location_type', 'district')->firstOrFail();
|
||||
$filters = ['territory' => $district->id, 'kind' => 'institution', 'need' => 'investment', 'location_mode' => 'physical', 'certainty' => 'documented'];
|
||||
$this->get('/fundos?'.http_build_query($filters))->assertOk()
|
||||
->assertInertia(fn ($page) => $page->component('funding/index')->has('items.data', 0)->where('filters.territory', $district->id)->where('filters.location_mode', 'physical')->etc());
|
||||
}
|
||||
|
||||
public function test_each_documentary_institution_selection_opens_its_own_record(): void
|
||||
{
|
||||
foreach ($this->fixture['records'] as $key => $record) {
|
||||
$this->get('/fundos/'.$record['id'].'?'.http_build_query(['location_mode' => 'physical', 'territory' => $this->fixture['provinces']['Maputo Cidade'], 'need' => 'investment']))->assertOk()
|
||||
->assertInertia(fn ($page) => $page->component('funding/show')->where('record.id', $record['id'])->where('record.payload.title', $record['title'])->where('record.payload.institution_key', $key)->where('selection.location_mode', 'physical')->etc());
|
||||
}
|
||||
$this->get('/fundos/00000000-0000-4000-8000-000000000000')->assertNotFound();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestorIntegralReportTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
public function test_private_report_snapshots_are_preserved_in_the_exact_result_version_without_exposing_them_in_events(): void
|
||||
{
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
$this->assertStringEndsWith('_test', $identity->name);
|
||||
$this->assertSame(55441, (int) $identity->port);
|
||||
$this->withoutVite();
|
||||
Http::fake();
|
||||
$owner = User::factory()->create();
|
||||
config(['investor-path.enabled' => true, 'portal.managers' => [$owner->email], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->actingAs($owner);
|
||||
if (! DB::table('desk_service_versions')->where('code', 'project-preparation')->exists()) {
|
||||
$this->postJson('/management/balcao/servicos', ['code' => 'project-preparation', 'confirm' => true])->assertCreated();
|
||||
}
|
||||
$case = $this->postJson('/investimentos', ['title' => 'QA synthetic report transport', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
// Transport contract only: no invented financial amounts or calculated results.
|
||||
$economic = [
|
||||
'purpose' => 'simulate_only',
|
||||
'financial_tools_snapshot' => json_encode(['version' => 1, 'data' => []], JSON_THROW_ON_ERROR),
|
||||
'business_plan_snapshot' => json_encode(['version' => 17, 'plan' => ['fixture' => 'synthetic transport only']], JSON_THROW_ON_ERROR),
|
||||
'project_team_snapshot' => json_encode([['competency' => 'QA role', 'state' => 'unknown', 'action' => '', 'estimated_cost' => '', 'due_date' => '']], JSON_THROW_ON_ERROR),
|
||||
'project_execution_snapshot' => json_encode([['title' => 'QA milestone', 'due_date' => '', 'status' => 'planned', 'planned_amount' => '', 'actual_amount' => '']], JSON_THROW_ON_ERROR),
|
||||
];
|
||||
$draft = $this->postJson('/api/v1/simulation-drafts', ['context' => $case, 'personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
|
||||
$view = $this->getJson('/investimentos/'.$case)->assertOk()->json();
|
||||
$request = ['version' => $view['case']['version'], 'draft_id' => $draft, 'draft_version' => 1];
|
||||
$result = $this->postJson('/investimentos/'.$case.'/resultados', $request)->assertOk()->json('result');
|
||||
foreach (['business_plan_snapshot', 'project_team_snapshot', 'project_execution_snapshot'] as $field) {
|
||||
$this->assertSame($economic[$field], $result['preparation_snapshot'][$field]);
|
||||
}
|
||||
$this->postJson('/investimentos/'.$case.'/resultados', $request)->assertOk()->assertJsonPath('result.id', $result['id']);
|
||||
$this->flushSession();
|
||||
$this->actingAs($owner)->getJson('/investimentos/'.$case)->assertOk()->assertJsonPath('results.0.preparation_snapshot', $result['preparation_snapshot']);
|
||||
$event = app(VirtualDesk::class)->decode(DB::table('desk_events')->where('case_id', $case)->where('action', 'tool_evidence_returned')->value('payload'));
|
||||
foreach (['business_plan_snapshot', 'project_team_snapshot', 'project_execution_snapshot'] as $field) {
|
||||
$this->assertArrayNotHasKey($field, $event['preparation_snapshot']);
|
||||
}
|
||||
$this->actingAs(User::factory()->create())->getJson('/investimentos/'.$case)->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\CorridorAgribusinessOpportunities;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
/** Existing documentary records and disclosure states only; never creates opportunities. */
|
||||
final class PortfolioOpportunityAcceptanceTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->assertSame('main_reference_20261104_test', DB::connection()->getDatabaseName());
|
||||
}
|
||||
|
||||
public function test_documentary_source_records_are_available_and_searchable_without_inventing_sites(): void
|
||||
{
|
||||
$entries = app(CorridorAgribusinessOpportunities::class)->entries();
|
||||
$this->assertCount(34, $entries);
|
||||
foreach ($entries as $entry) {
|
||||
$record = Opportunity::where('management_creation_key', $entry['key'])->firstOrFail();
|
||||
$this->assertTrue(Opportunity::published()->whereKey($record->id)->exists(), $entry['title']);
|
||||
$this->assertTrue(app(InvestmentCatalogue::class)->query(['q' => $entry['chain']])->whereKey($record->id)->exists(), $entry['title']);
|
||||
$this->assertNull($record->primary_territory_id);
|
||||
$this->assertNull($record->province);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_public_opportunities_are_embedded_even_without_matching_portfolio_fiches(): void
|
||||
{
|
||||
$record = Opportunity::published()->where('title', 'Soja — Corredor da Beira')->firstOrFail();
|
||||
$this->get('/carteira?q=Soja')->assertOk()->assertInertia(fn ($page) => $page->component('portfolio/index')
|
||||
->has('publishedOpportunities.data', 2)
|
||||
->where('publishedOpportunities.data', fn ($items) => collect($items)->contains('id', $record->id))->etc());
|
||||
$this->get('/carteira?kind=corridor&q=Beira')->assertOk()->assertInertia(fn ($page) => $page->component('portfolio/index')->has('publishedOpportunities.data', 7)->etc());
|
||||
}
|
||||
|
||||
public function test_province_does_not_promote_unsited_opportunities_or_fiches_from_another_province(): void
|
||||
{
|
||||
$geography = app(InvestmentGeography::class);
|
||||
$zambezia = $geography->publicReferences()->where('location_type', 'province')->where('name', 'Zambezia')->value('id');
|
||||
$maputo = $geography->publicReferences()->where('location_type', 'province')->where('name', 'Maputo Província')->value('id');
|
||||
$mocuba = InvestmentPortfolioController::visible()->where('title', 'Construção da Cidadela Parlamentar de Mocuba')->firstOrFail();
|
||||
foreach ([[$zambezia, true], [$maputo, false]] as [$province, $expected]) {
|
||||
$this->assertNotEmpty($province);
|
||||
$this->get('/carteira?'.http_build_query(['province_id' => $province, 'q' => 'Mocuba']))->assertOk()->assertInertia(fn ($page) => $page->component('portfolio/index')
|
||||
->where('records.data', fn ($items) => collect($items)->contains('id', $mocuba->id) === $expected)->etc());
|
||||
$this->get('/carteira?'.http_build_query(['province_id' => $province, 'q' => 'Soja']))->assertOk()->assertInertia(fn ($page) => $page->component('portfolio/index')->has('publishedOpportunities.data', 0)->etc());
|
||||
}
|
||||
}
|
||||
|
||||
public function test_real_published_opportunity_reaches_normal_private_entry_without_invented_territory(): void
|
||||
{
|
||||
$record = Opportunity::published()->where('title', 'Soja — Corredor da Beira')->firstOrFail();
|
||||
$actor = User::factory()->create(['name' => 'SINTÉTICO — verificação de percurso documental']);
|
||||
$this->actingAs($actor)->get('/investimentos/iniciar?source=opportunity:'.$record->id)->assertOk()
|
||||
->assertInertia(fn ($page) => $page->component('investor-path/context-start')->where('source.id', (string) $record->id)->etc());
|
||||
$this->assertNull($record->fresh()->primary_territory_id);
|
||||
}
|
||||
}
|
||||
@@ -131,7 +131,7 @@ final class SectorContentAnalysisTest extends TestCase
|
||||
'location_type' => $type, 'source_system' => 'cartografia-workbook', 'data_classification' => 'public',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
|
||||
}
|
||||
$readings = app(SectorContentAnalysis::class)->forTerritories([$district]);
|
||||
$readings = app(SectorContentAnalysis::class)->forTerritories([$district], 'tourism');
|
||||
$this->assertCount(1, $readings);
|
||||
$this->assertSame($article['href'], $readings[0]['href']);
|
||||
$this->assertSame('Maputo Província', $readings[0]['analysis']['region']);
|
||||
|
||||
@@ -1684,7 +1684,7 @@ void test('supplier order installments reconcile exact cents, cash dates and una
|
||||
];
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(malformedPlan),
|
||||
/declare encomendas/,
|
||||
/soma das percentagens.*excede 100%/,
|
||||
);
|
||||
const snapshot = JSON.parse(serializeBusinessPlanSnapshot(plan));
|
||||
snapshot.plan.products[0].productInventoryPurchasesByPeriod[0].paymentInstallments[1].lagMonths = 13;
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import * as business from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import {
|
||||
newAnnualReferencePlan,
|
||||
serializeAnnualExampleSnapshot,
|
||||
} from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
import * as contract from '../../resources/js/lib/simulation-contract.ts';
|
||||
import * as bridge from '../../resources/js/lib/financial-fiscal-bridge.ts';
|
||||
import { validateSimulationDraft } from '../../resources/js/lib/simulation-form.ts';
|
||||
|
||||
// Exercise the real input callbacks and the parent's snapshot echo, including
|
||||
// effects. No server, database or fiscal rates are used by this regression.
|
||||
function editor(initialSnapshot) {
|
||||
const values = [],
|
||||
dependencies = [];
|
||||
let cursor = 0,
|
||||
pending = [],
|
||||
changed = false,
|
||||
snapshot = initialSnapshot;
|
||||
const hooks = {
|
||||
...React,
|
||||
useState(initial) {
|
||||
const index = cursor++;
|
||||
if (!(index in values)) values[index] = initial;
|
||||
return [
|
||||
values[index],
|
||||
(next) => {
|
||||
const value =
|
||||
typeof next === 'function' ? next(values[index]) : next;
|
||||
if (!Object.is(value, values[index])) changed = true;
|
||||
values[index] = value;
|
||||
},
|
||||
];
|
||||
},
|
||||
useEffect(callback, deps) {
|
||||
const index = cursor++;
|
||||
if (
|
||||
!dependencies[index] ||
|
||||
deps.some(
|
||||
(value, i) => !Object.is(value, dependencies[index][i]),
|
||||
)
|
||||
) {
|
||||
dependencies[index] = deps;
|
||||
pending.push(callback);
|
||||
}
|
||||
},
|
||||
};
|
||||
const require = createRequire(import.meta.url),
|
||||
module = { exports: {} };
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/simulation-business-plan.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(name) =>
|
||||
(name === '@/components/integral-financial-plan'
|
||||
? { IntegralFinancialPlan: () => null }
|
||||
: undefined) ??
|
||||
(name === '@/components/business-plan-warnings'
|
||||
? { BusinessPlanWarnings: () => null }
|
||||
: name === '@/components/simulation-annual-example'
|
||||
? { SimulationAnnualExample: () => null }
|
||||
: undefined) ??
|
||||
{
|
||||
react: hooks,
|
||||
'@/components/currency-select': { CurrencySelect: () => null },
|
||||
'@/lib/business-financial-plan': business,
|
||||
'@/lib/simulation-contract': contract,
|
||||
'@/lib/financial-fiscal-bridge': bridge,
|
||||
'@/components/financial-plan-details': {
|
||||
FinancialPlanDetails: () => null,
|
||||
},
|
||||
'@/components/market-analysis-plan': {
|
||||
MarketAnalysisPlan: () => null,
|
||||
},
|
||||
'@/components/financial-ratios-plan': {
|
||||
FinancialRatiosPlan: () => null,
|
||||
},
|
||||
'@/components/plan-economic-classification': {
|
||||
PlanEconomicClassification: () => null,
|
||||
},
|
||||
}[name] ??
|
||||
require(name),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
let tree;
|
||||
function render() {
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
changed = false;
|
||||
cursor = 0;
|
||||
pending = [];
|
||||
tree = module.exports.SimulationBusinessPlan({
|
||||
currency: 'MZN',
|
||||
snapshot,
|
||||
onCurrencyChange() {},
|
||||
onSnapshotChange(value) {
|
||||
snapshot = value;
|
||||
changed = true;
|
||||
},
|
||||
});
|
||||
pending.forEach((callback) => callback());
|
||||
if (!changed) return;
|
||||
}
|
||||
throw new Error('Editor did not settle');
|
||||
}
|
||||
function walk(node, predicate) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (predicate(node)) return node;
|
||||
for (const child of React.Children.toArray(node.props?.children)) {
|
||||
const found = walk(child, predicate);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
function field(label) {
|
||||
const money = walk(
|
||||
tree,
|
||||
(node) =>
|
||||
node.props?.label === label &&
|
||||
typeof node.props.onChange === 'function',
|
||||
);
|
||||
if (money) return money.props;
|
||||
const container = walk(
|
||||
tree,
|
||||
(node) =>
|
||||
node.type === 'label' &&
|
||||
React.Children.toArray(node.props.children).some(
|
||||
(child) => typeof child === 'string' && child === label,
|
||||
),
|
||||
);
|
||||
const input = walk(container, (node) => node.type === 'input');
|
||||
assert.ok(input, `Missing field: ${label}`);
|
||||
return {
|
||||
value: input.props.value,
|
||||
onChange: (value) => input.props.onChange({ target: { value } }),
|
||||
};
|
||||
}
|
||||
render();
|
||||
return {
|
||||
field,
|
||||
edit(label, value) {
|
||||
field(label).onChange(value);
|
||||
render();
|
||||
},
|
||||
snapshot: () => snapshot,
|
||||
example() {
|
||||
const toggle = walk(
|
||||
tree,
|
||||
(node) =>
|
||||
node.type === 'button' &&
|
||||
React.Children.toArray(node.props.children).some(
|
||||
(child) =>
|
||||
child === 'Carregar cenário anual de exemplo',
|
||||
),
|
||||
);
|
||||
if (toggle) {
|
||||
toggle.props.onClick();
|
||||
render();
|
||||
}
|
||||
return walk(
|
||||
tree,
|
||||
(node) => typeof node.props?.onSnapshotChange === 'function',
|
||||
)?.props;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
void test('annual example snapshot is saved through the existing parent callback and recovered by a fresh editor', () => {
|
||||
const form = editor();
|
||||
const exampleSnapshot = serializeAnnualExampleSnapshot(
|
||||
newAnnualReferencePlan(),
|
||||
);
|
||||
form.example().onSnapshotChange(exampleSnapshot);
|
||||
const recovered = editor(form.snapshot());
|
||||
assert.equal(recovered.example().snapshot, exampleSnapshot);
|
||||
recovered.edit('Preço por unidade', '250.50');
|
||||
assert.equal(recovered.example().snapshot, exampleSnapshot);
|
||||
});
|
||||
|
||||
void test('monthly units, unit price, variable cost and operating expenses remain editable after snapshot echo', () => {
|
||||
const form = editor();
|
||||
for (const label of [
|
||||
'Unidades por mes',
|
||||
'Preço por unidade',
|
||||
'Custo variável por unidade',
|
||||
'Despesas operacionais reconhecidas',
|
||||
]) {
|
||||
for (const value of ['', '2', '25', '250.50']) {
|
||||
form.edit(label, value);
|
||||
assert.equal(
|
||||
form.field(label).value,
|
||||
value,
|
||||
`${label}: ${value}; saved=${form.snapshot()}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const restored = business.restoreBusinessPlanSnapshot(form.snapshot());
|
||||
assert.ok(restored, 'The edited plan must remain recoverable');
|
||||
assert.equal(restored.products[0].monthlyUnits, '250.50');
|
||||
assert.equal(restored.monthlyOperatingExpenses, '250.50');
|
||||
assert.equal(restored.salesCollectionPercent, '');
|
||||
assert.equal(restored.openingReceivablesCollectionPercent, '');
|
||||
const recovered = editor(form.snapshot());
|
||||
assert.equal(recovered.field('Preço por unidade').value, '250.50');
|
||||
recovered.edit('Despesas operacionais reconhecidas', '500');
|
||||
assert.equal(recovered.field('Preço por unidade').value, '250.50');
|
||||
assert.equal(
|
||||
recovered.field('Despesas operacionais reconhecidas').value,
|
||||
'500',
|
||||
);
|
||||
assert.throws(() => business.forecastBusinessPlan(restored));
|
||||
assert.ok(
|
||||
validateSimulationDraft(
|
||||
{ business_plan_snapshot: form.snapshot() },
|
||||
'financial',
|
||||
).business_plan_snapshot,
|
||||
);
|
||||
assert.equal(
|
||||
validateSimulationDraft({}, 'financial').business_plan_snapshot,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
void test('numeric entry messages distinguish missing, invalid, negative, fractional people and percentages', () => {
|
||||
assert.equal(
|
||||
business.businessPlanNumberError(''),
|
||||
'Preencha este campo para continuar.',
|
||||
);
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('abc'),
|
||||
'Introduza apenas números (ex.: 25.000).',
|
||||
);
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('-1'),
|
||||
'Este valor não pode ser negativo.',
|
||||
);
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('1.5', { integer: true }),
|
||||
'Introduza um número inteiro de pessoas.',
|
||||
);
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('101', { percent: true }),
|
||||
'Introduza uma percentagem entre 0% e 100%.',
|
||||
);
|
||||
assert.equal(business.businessPlanNumberError('0'), '');
|
||||
assert.equal(business.businessPlanNumberError('25.50'), '');
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('-25.50', { allowNegative: true }),
|
||||
'',
|
||||
);
|
||||
});
|
||||
|
||||
void test('invalid percentages remain editable after recovery without becoming valid calculation inputs', () => {
|
||||
const form = editor();
|
||||
form.edit('Preço por unidade', '250.50');
|
||||
const decoded = JSON.parse(form.snapshot());
|
||||
decoded.plan.salesCollectionPercent = '101';
|
||||
const snapshot = JSON.stringify(decoded);
|
||||
assert.equal(business.restoreBusinessPlanSnapshot(snapshot), null);
|
||||
const editable = business.restoreBusinessPlanSnapshot(snapshot, {
|
||||
editable: true,
|
||||
});
|
||||
assert.equal(editable.salesCollectionPercent, '101');
|
||||
assert.equal(editor(snapshot).field('Preço por unidade').value, '250.50');
|
||||
assert.ok(
|
||||
validateSimulationDraft(
|
||||
{ business_plan_snapshot: snapshot },
|
||||
'financial',
|
||||
).business_plan_snapshot,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,289 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
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 * as guidance from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
import * as business from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import * as catalogue from '../../resources/js/lib/catalogue-choice.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
function load(name, mocks) {
|
||||
const source = fs.readFileSync(
|
||||
new URL(`../../resources/js/components/${name}.tsx`, import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
const module = { exports: {} };
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(key) => mocks[key] ?? require(key),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return module.exports;
|
||||
}
|
||||
function nodes(tree) {
|
||||
if (Array.isArray(tree)) return tree.flatMap(nodes);
|
||||
return tree && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
}
|
||||
|
||||
void test('a saved catalogue choice retains its exact value without exposing an internal identifier', () => {
|
||||
const { default: Select } = load('catalogue-choice-select', {
|
||||
react: {
|
||||
useId: () => 'test-choice',
|
||||
useState: (initial) => [initial, () => {}],
|
||||
},
|
||||
'./territory-search-select': () => null,
|
||||
'@/lib/catalogue-choice': catalogue,
|
||||
});
|
||||
const id = 'a2000000-0000-4000-8000-000000000013';
|
||||
let chosen;
|
||||
const element = Select({
|
||||
label: 'Actividade a comparar',
|
||||
value: id,
|
||||
options: [],
|
||||
onChange: (value) => {
|
||||
chosen = value;
|
||||
},
|
||||
});
|
||||
assert.equal(element.props.selected.id, id);
|
||||
assert.equal(
|
||||
element.props.selected.name,
|
||||
'Escolha guardada — designação por recuperar',
|
||||
);
|
||||
assert.ok(!element.props.selected.name.includes(id));
|
||||
element.props.onChange({ id, name: 'Designação recuperada' });
|
||||
assert.equal(chosen, id);
|
||||
assert.equal(
|
||||
Select({
|
||||
label: 'Actividade',
|
||||
value: id,
|
||||
options: [{ value: id, label: 'Hotelaria documentada' }],
|
||||
onChange() {},
|
||||
}).props.selected.name,
|
||||
'Hotelaria documentada',
|
||||
);
|
||||
});
|
||||
|
||||
void test('warning dismissal is local, never blocks a form, and changed assumptions reveal the warning again', () => {
|
||||
let dismissed = [];
|
||||
const { BusinessPlanWarnings } = load('business-plan-warnings', {
|
||||
react: {
|
||||
...React,
|
||||
useState: () => [
|
||||
dismissed,
|
||||
(next) => {
|
||||
dismissed = next(dismissed);
|
||||
},
|
||||
],
|
||||
},
|
||||
'@/lib/business-plan-guidance': guidance,
|
||||
});
|
||||
const metrics = { fundingGap: 100, currency: 'MZN' };
|
||||
const tree = BusinessPlanWarnings({ metrics });
|
||||
assert.ok(nodes(tree).some((node) => node.props?.role === 'status'));
|
||||
assert.equal(
|
||||
nodes(tree).some((node) => node.props?.role === 'alert'),
|
||||
false,
|
||||
);
|
||||
const button = nodes(tree).find((node) => node.type === 'button');
|
||||
assert.equal(button.props.type, 'button');
|
||||
assert.equal(button.props.disabled, undefined);
|
||||
button.props.onClick();
|
||||
assert.equal(BusinessPlanWarnings({ metrics }), null);
|
||||
assert.ok(
|
||||
BusinessPlanWarnings({ metrics: { ...metrics, fundingGap: 200 } }),
|
||||
);
|
||||
});
|
||||
|
||||
void test('annual example renders expected results and source gaps without blocking errors or inferred monthly rows', () => {
|
||||
const warningModule = load('business-plan-warnings', {
|
||||
'@/lib/business-plan-guidance': guidance,
|
||||
});
|
||||
const { SimulationAnnualExample } = load('simulation-annual-example', {
|
||||
'@/lib/business-plan-guidance': guidance,
|
||||
'@/lib/business-financial-plan': business,
|
||||
'./business-plan-warnings': warningModule,
|
||||
});
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(SimulationAnnualExample, { currency: 'MZN' }),
|
||||
);
|
||||
assert.match(html, /Linhas mensais por reconciliar/);
|
||||
assert.match(html, /Avisos — pode continuar/);
|
||||
assert.match(html, /Neste ano o negócio dá prejuízo/);
|
||||
assert.match(
|
||||
html,
|
||||
/As vendas mensais médias não atingem o ponto de equilíbrio/,
|
||||
);
|
||||
assert.match(html, /não se distribuem valores pelos meses/);
|
||||
assert.match(html, /Balanço projectado/);
|
||||
assert.match(html, /Distribuição mensal ilustrativa/);
|
||||
assert.match(html, /Não é financiamento confirmado/);
|
||||
assert.equal((html.match(/Projecção mensal/g) ?? []).length, 3);
|
||||
assert.doesNotMatch(html, /role="alert"|aria-invalid="true"|disabled=/);
|
||||
assert.match(html.replace(/[\s\u00a0\u202f]/g, ''), /1325000[.,]00/);
|
||||
});
|
||||
|
||||
void test('annual example edits survive parent snapshot, draft storage, reload and reopening without changing investor forecast', async () => {
|
||||
const form = await import('../../resources/js/lib/simulation-form.ts');
|
||||
const { SimulationAnnualExample } = load('simulation-annual-example', {
|
||||
'@/lib/business-plan-guidance': guidance,
|
||||
'@/lib/business-financial-plan': business,
|
||||
'./business-plan-warnings': { BusinessPlanWarnings: () => null },
|
||||
});
|
||||
const input = {
|
||||
currency: 'MZN',
|
||||
openingCash: '0',
|
||||
assetInvestment: '0',
|
||||
products: [
|
||||
{
|
||||
label: 'Serviço de teste',
|
||||
monthlyUnits: '1',
|
||||
unitPrice: '100',
|
||||
unitVariableCost: '40',
|
||||
},
|
||||
],
|
||||
...Object.fromEntries(
|
||||
[
|
||||
'monthlyCollections',
|
||||
'monthlyVariableCostPayments',
|
||||
'monthlyInventoryPurchases',
|
||||
'monthlyOperatingExpenses',
|
||||
'monthlyOperatingPayments',
|
||||
'monthlyPayrollExpense',
|
||||
'monthlyPayrollPayments',
|
||||
'inventory',
|
||||
'receivables',
|
||||
'payables',
|
||||
'equity',
|
||||
'shareholderLoans',
|
||||
'bankLoanProceeds',
|
||||
'grants',
|
||||
'assetDepreciation',
|
||||
'monthlyInterestExpense',
|
||||
'monthlyInterestPayment',
|
||||
'monthlyPrincipalRepayment',
|
||||
].map((key) => [key, '0']),
|
||||
),
|
||||
depreciationLifeMonths: 60,
|
||||
periods: 12,
|
||||
};
|
||||
const investorBefore = business.forecastBusinessPlan(input);
|
||||
let snapshot;
|
||||
const render = () =>
|
||||
SimulationAnnualExample({
|
||||
currency: 'MZN',
|
||||
snapshot,
|
||||
onSnapshotChange: (value) => {
|
||||
snapshot = value;
|
||||
},
|
||||
});
|
||||
const field = (tree, label) =>
|
||||
nodes(tree).find(
|
||||
(node) =>
|
||||
node.props?.label === label &&
|
||||
typeof node.props.onChange === 'function',
|
||||
);
|
||||
field(render(), 'Vendas previstas').props.onChange('14537.25');
|
||||
const edited = guidance.restoreAnnualExampleSnapshot(snapshot);
|
||||
assert.equal(edited.years[0].sales, '14537.25');
|
||||
const before = guidance.calculateAnnualReferencePlan(edited);
|
||||
const saved = {
|
||||
purpose: 'simulate_only',
|
||||
business_plan_snapshot: business.serializeBusinessPlanSnapshot({
|
||||
...input,
|
||||
annualExampleSnapshot: snapshot,
|
||||
}),
|
||||
};
|
||||
const browserCopy = JSON.parse(
|
||||
JSON.stringify(form.getAutosaveSnapshot(saved)),
|
||||
);
|
||||
const serverCopy = JSON.parse(
|
||||
JSON.stringify(form.partitionSimulationDraft(saved, false)),
|
||||
);
|
||||
for (const recoveredDraft of [
|
||||
browserCopy,
|
||||
form.restoreSimulationDraft(serverCopy.economic_snapshot, {}),
|
||||
]) {
|
||||
const investorPlan = business.restoreBusinessPlanSnapshot(
|
||||
recoveredDraft.business_plan_snapshot,
|
||||
);
|
||||
assert.ok(investorPlan);
|
||||
snapshot = investorPlan.annualExampleSnapshot;
|
||||
assert.equal(
|
||||
field(render(), 'Vendas previstas').props.value,
|
||||
'14537.25',
|
||||
);
|
||||
const after = guidance.calculateAnnualReferencePlan(
|
||||
guidance.restoreAnnualExampleSnapshot(snapshot),
|
||||
);
|
||||
assert.deepEqual(after, before);
|
||||
assert.ok(
|
||||
after.years.every(
|
||||
(year) =>
|
||||
year.balanceDifference === '0.00' &&
|
||||
year.illustrativeMonths.every(
|
||||
(month) => month.balanceDifference === '0.00',
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(
|
||||
business.forecastBusinessPlan(investorPlan),
|
||||
investorBefore,
|
||||
);
|
||||
}
|
||||
field(render(), 'Vendas previstas').props.onChange('');
|
||||
assert.equal(
|
||||
guidance.restoreAnnualExampleSnapshot(snapshot).years[0].sales,
|
||||
'',
|
||||
);
|
||||
assert.equal(field(render(), 'Vendas previstas').props.value, '');
|
||||
assert.throws(
|
||||
() =>
|
||||
guidance.calculateAnnualReferencePlan(
|
||||
guidance.restoreAnnualExampleSnapshot(snapshot),
|
||||
),
|
||||
/Preencha/,
|
||||
);
|
||||
});
|
||||
|
||||
void test('annual example refuses unknown storage versions, extra investor fields and oversized snapshots without overwriting them', () => {
|
||||
const valid = guidance.serializeAnnualExampleSnapshot(
|
||||
guidance.newAnnualReferencePlan(),
|
||||
);
|
||||
for (const source of [
|
||||
'{',
|
||||
'x'.repeat(12001),
|
||||
valid.replace('"version":1', '"version":2'),
|
||||
valid.replace('"openingCash"', '"investorName"'),
|
||||
]) {
|
||||
assert.equal(guidance.restoreAnnualExampleSnapshot(source), null);
|
||||
const { SimulationAnnualExample } = load('simulation-annual-example', {
|
||||
'@/lib/business-plan-guidance': guidance,
|
||||
'@/lib/business-financial-plan': business,
|
||||
'./business-plan-warnings': { BusinessPlanWarnings: () => null },
|
||||
});
|
||||
let overwritten = false;
|
||||
const html = renderToStaticMarkup(
|
||||
SimulationAnnualExample({
|
||||
currency: 'MZN',
|
||||
snapshot: source,
|
||||
onSnapshotChange: () => {
|
||||
overwritten = true;
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.match(html, /conteúdo guardado foi preservado/);
|
||||
assert.equal(overwritten, false);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
businessPlanWarnings,
|
||||
defaultPlanWarningLimits,
|
||||
newAnnualReferencePlan,
|
||||
calculateAnnualReferencePlan,
|
||||
} from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { validateSimulationDraft } from '../../resources/js/lib/simulation-form.ts';
|
||||
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
function businessPlan() {
|
||||
const amounts = [
|
||||
'monthlyCollections',
|
||||
'monthlyVariableCostPayments',
|
||||
'monthlyInventoryPurchases',
|
||||
'monthlyOperatingExpenses',
|
||||
'monthlyOperatingPayments',
|
||||
'monthlyPayrollExpense',
|
||||
'monthlyPayrollPayments',
|
||||
'inventory',
|
||||
'receivables',
|
||||
'payables',
|
||||
'equity',
|
||||
'shareholderLoans',
|
||||
'bankLoanProceeds',
|
||||
'grants',
|
||||
'assetDepreciation',
|
||||
'monthlyInterestExpense',
|
||||
'monthlyInterestPayment',
|
||||
'monthlyPrincipalRepayment',
|
||||
];
|
||||
return {
|
||||
...Object.fromEntries(amounts.map((key) => [key, '0'])),
|
||||
currency: 'MZN',
|
||||
openingCash: '1000',
|
||||
assetInvestment: '200',
|
||||
products: [
|
||||
{
|
||||
label: 'Serviço sintético',
|
||||
monthlyUnits: '10',
|
||||
unitPrice: '100',
|
||||
unitVariableCost: '40',
|
||||
},
|
||||
],
|
||||
depreciationLifeMonths: 60,
|
||||
periods: 12,
|
||||
annualGrowthPercent: '250',
|
||||
};
|
||||
}
|
||||
|
||||
void test('insufficient funding and growth above 100 percent remain valid, saved assumptions with nonblocking warnings', () => {
|
||||
const plan = businessPlan();
|
||||
const snapshot = serializeBusinessPlanSnapshot(plan);
|
||||
const restored = restoreBusinessPlanSnapshot(snapshot);
|
||||
assert.equal(restored.annualGrowthPercent, '250');
|
||||
const result = forecastBusinessPlan(restored);
|
||||
assert.equal(result.fundingGap, '200.00');
|
||||
assert.equal(
|
||||
result.totalRevenue,
|
||||
'12000.00',
|
||||
'a growth target must not overwrite declared sales',
|
||||
);
|
||||
assert.equal(
|
||||
validateSimulationDraft(
|
||||
{ business_plan_snapshot: snapshot },
|
||||
'financial',
|
||||
).business_plan_snapshot,
|
||||
undefined,
|
||||
);
|
||||
const warnings = businessPlanWarnings({
|
||||
fundingGap: Number(result.fundingGap),
|
||||
growthPercent: Number(restored.annualGrowthPercent),
|
||||
currency: 'MZN',
|
||||
});
|
||||
assert.deepEqual(
|
||||
warnings.map((warning) => warning.id),
|
||||
['funding', 'growth'],
|
||||
);
|
||||
const report = createProjectDossierReport(
|
||||
{ business_plan_snapshot: snapshot },
|
||||
{
|
||||
selectedSections: new Set(['finance']),
|
||||
generatedAt: '2026-11-20T08:00:00Z',
|
||||
},
|
||||
);
|
||||
assert.match(JSON.stringify(report), /aviso não bloqueante/);
|
||||
assert.match(JSON.stringify(report), /Crescimento anual pretendido/);
|
||||
assert.match(JSON.stringify(report), /250%/);
|
||||
});
|
||||
|
||||
void test('owner annual reference reconciles exact startup, margins, profits, cash and unrounded break-even', () => {
|
||||
const source = newAnnualReferencePlan(),
|
||||
before = JSON.stringify(source);
|
||||
const result = calculateAnnualReferencePlan(source),
|
||||
first = result.years[0];
|
||||
assert.equal(result.startupExpenses, '1325000.00');
|
||||
assert.equal(result.assets, '500250.00');
|
||||
assert.equal(result.requiredFunding, '1825250.00');
|
||||
assert.equal(result.availableFunding, '0.00');
|
||||
assert.equal(result.fundingGap, '1825250.00');
|
||||
assert.equal(first.grossMargin, '1999.00');
|
||||
assert.equal(first.operatingExpenses, '2415.00');
|
||||
assert.equal(first.operatingProfit, '-416.00');
|
||||
assert.equal(first.netProfit, '-416.00');
|
||||
assert.equal(first.cashFlow, '756.00');
|
||||
assert.equal(first.closingCash, '90756.00');
|
||||
assert.equal(Math.round(first.monthlyBreakEven), 1464);
|
||||
assert.ok(
|
||||
Math.abs(first.monthlyBreakEven - 2415 / 12 / (1999 / 14537)) < 1e-10,
|
||||
);
|
||||
assert.equal(result.years[1].netProfit, '1456.00');
|
||||
assert.equal(result.years[2].netProfit, '1631.00');
|
||||
assert.equal(result.years[2].closingCash, '93498.00');
|
||||
assert.equal(result.monthlyStatus, 'por reconciliar');
|
||||
assert.equal('monthlyRows' in result, false);
|
||||
assert.deepEqual(
|
||||
result.years.map((year) => year.operatingLiabilities),
|
||||
['1641.00', '1417.00', '1598.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
result.years.map((year) => year.receivables),
|
||||
['469.00', '694.00', '771.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
result.years.map((year) => year.closingAssets),
|
||||
['501475.00', '502707.00', '504519.00'],
|
||||
);
|
||||
assert.equal(result.capitalToMobilise, '1825250.00');
|
||||
const cents = (value) => BigInt(value.replace('.', ''));
|
||||
for (const [index, year] of result.years.entries()) {
|
||||
assert.equal(year.balanceDifference, '0.00');
|
||||
assert.equal(year.illustrativeMonths.length, 12);
|
||||
for (const key of [
|
||||
'sales',
|
||||
'directCosts',
|
||||
'netProfit',
|
||||
'cashReceived',
|
||||
'cashSpent',
|
||||
]) {
|
||||
const expected =
|
||||
key === 'netProfit' ? year[key] : source.years[index][key];
|
||||
assert.equal(
|
||||
year.illustrativeMonths.reduce(
|
||||
(sum, row) => sum + cents(row[key]),
|
||||
0n,
|
||||
),
|
||||
cents(Number(expected).toFixed(2)),
|
||||
);
|
||||
}
|
||||
for (const month of year.illustrativeMonths)
|
||||
assert.equal(month.balanceDifference, '0.00');
|
||||
const last = year.illustrativeMonths.at(-1);
|
||||
for (const key of [
|
||||
'closingCash',
|
||||
'receivables',
|
||||
'operatingLiabilities',
|
||||
])
|
||||
assert.equal(last[key], year[key]);
|
||||
}
|
||||
const warnings = businessPlanWarnings({
|
||||
fundingGap: Number(result.fundingGap),
|
||||
netProfit: Number(first.netProfit),
|
||||
sales: Number(first.sales),
|
||||
directCosts: Number(first.directCosts),
|
||||
monthlyBreakEven: first.monthlyBreakEven,
|
||||
});
|
||||
assert.ok(warnings.some((warning) => warning.id === 'loss'));
|
||||
assert.ok(warnings.some((warning) => warning.id === 'break-even'));
|
||||
assert.equal(JSON.stringify(source), before);
|
||||
});
|
||||
|
||||
void test('derived ledger reconciles edited cents and surplus funding without altering annual inputs', () => {
|
||||
const plan = newAnnualReferencePlan();
|
||||
plan.ownerCapital = '2000000.01';
|
||||
plan.years[0].sales = '14537.01';
|
||||
plan.years[0].cashSpent = '15783.01';
|
||||
plan.years[0].payrollCharges = '315.01';
|
||||
plan.years[0].vatPaid = '2470.99';
|
||||
const before = JSON.stringify(plan);
|
||||
const result = calculateAnnualReferencePlan(plan);
|
||||
assert.equal(result.capitalToMobilise, '0.00');
|
||||
assert.equal(result.years[0].closingCash, '265506.00');
|
||||
assert.equal(result.years[0].receivables, '469.01');
|
||||
assert.equal(result.years[0].vatBalance, '0.01');
|
||||
for (const year of result.years) {
|
||||
assert.equal(year.balanceDifference, '0.00');
|
||||
for (const month of year.illustrativeMonths)
|
||||
assert.equal(month.balanceDifference, '0.00');
|
||||
assert.equal(
|
||||
year.illustrativeMonths.at(-1).closingCash,
|
||||
year.closingCash,
|
||||
);
|
||||
}
|
||||
assert.equal(JSON.stringify(plan), before);
|
||||
plan.years[0].vatReceived = '16539.01';
|
||||
assert.throws(() => calculateAnnualReferencePlan(plan), /IVA/);
|
||||
});
|
||||
|
||||
void test('reference edits update dependent totals and preserve data when an input is invalid', () => {
|
||||
const source = newAnnualReferencePlan();
|
||||
source.startupExpenses[0].amount = '25000.25';
|
||||
assert.equal(
|
||||
calculateAnnualReferencePlan(source).requiredFunding,
|
||||
'1825250.25',
|
||||
);
|
||||
source.years[0].sales = '';
|
||||
assert.throws(
|
||||
() => calculateAnnualReferencePlan(source),
|
||||
/Preencha este campo para continuar/,
|
||||
);
|
||||
assert.equal(source.startupExpenses[0].amount, '25000.25');
|
||||
source.years[0].sales = '0';
|
||||
assert.throws(
|
||||
() => calculateAnnualReferencePlan(source),
|
||||
/Indique as vendas previstas/,
|
||||
);
|
||||
source.years[0].sales = '100';
|
||||
assert.throws(() => calculateAnnualReferencePlan(source), /não há margem/);
|
||||
});
|
||||
|
||||
void test('warning limits are configurable and equality at the threshold is not a warning', () => {
|
||||
assert.deepEqual(businessPlanWarnings({ growthPercent: 100 }), []);
|
||||
assert.deepEqual(
|
||||
businessPlanWarnings(
|
||||
{ growthPercent: 250 },
|
||||
{ ...defaultPlanWarningLimits, annualGrowthPercent: 300 },
|
||||
),
|
||||
[],
|
||||
);
|
||||
assert.equal(businessPlanWarnings({ creditDays: 91 })[0].id, 'credit');
|
||||
assert.deepEqual(businessPlanWarnings({ creditDays: 90 }), []);
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
checkDecisionBalance,
|
||||
calculateDecisionRatios,
|
||||
} from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
|
||||
const supplied2025 = () => ({
|
||||
cash: '90756',
|
||||
receivables: '469',
|
||||
inventory: '0',
|
||||
otherCurrentAssets: '150000',
|
||||
longTermAssets: '260250',
|
||||
accumulatedDepreciation: '0',
|
||||
currentLiabilities: '1642',
|
||||
longTermLiabilities: '0',
|
||||
paidCapital: '1825250',
|
||||
retainedResults: '-1325000',
|
||||
periodResult: '-416',
|
||||
});
|
||||
|
||||
void test('the supplied 2025 balance is one currency unit out of balance and cannot produce decision ratios', () => {
|
||||
const source = supplied2025(),
|
||||
before = JSON.stringify(source);
|
||||
const balance = checkDecisionBalance(source);
|
||||
assert.equal(balance.assets, '501475.00');
|
||||
assert.equal(balance.liabilitiesAndCapital, '501476.00');
|
||||
assert.equal(balance.difference, '-1.00');
|
||||
assert.equal(balance.balanced, false);
|
||||
assert.match(balance.error, /não estão equilibrados/);
|
||||
assert.throws(
|
||||
() => calculateDecisionRatios(source, '14537'),
|
||||
/não estão equilibrados/,
|
||||
);
|
||||
assert.equal(JSON.stringify(source), before);
|
||||
});
|
||||
|
||||
void test('cent discrepancies are never hidden by a balancing entry or materiality tolerance', () => {
|
||||
const source = { ...supplied2025(), currentLiabilities: '1641.01' };
|
||||
assert.equal(checkDecisionBalance(source).difference, '-0.01');
|
||||
assert.equal(checkDecisionBalance(source).balanced, false);
|
||||
assert.equal(source.currentLiabilities, '1641.01');
|
||||
});
|
||||
|
||||
void test('a separately identified synthetic balanced scenario produces the approved ratios', () => {
|
||||
const synthetic = { ...supplied2025(), currentLiabilities: '1641' };
|
||||
const balance = checkDecisionBalance(synthetic);
|
||||
assert.equal(balance.balanced, true);
|
||||
const ratios = calculateDecisionRatios(synthetic, '14537', '10000');
|
||||
assert.equal(ratios.currentLiquidity, 241225 / 1641);
|
||||
assert.equal(ratios.debtAssets, 1641 / 501475);
|
||||
assert.equal(ratios.netMargin, -416 / 14537);
|
||||
assert.equal(ratios.returnOnEquity, -416 / 499834);
|
||||
assert.equal(ratios.salesGrowth, 14537 / 10000 - 1);
|
||||
});
|
||||
|
||||
void test('missing data remains missing and zero denominators do not become zero ratios', () => {
|
||||
assert.throws(
|
||||
() => checkDecisionBalance({ ...supplied2025(), receivables: '' }),
|
||||
/Preencha este campo/,
|
||||
);
|
||||
const zero = Object.fromEntries(
|
||||
Object.keys(supplied2025()).map((key) => [key, '0']),
|
||||
);
|
||||
assert.deepEqual(calculateDecisionRatios(zero, '0', '0'), {
|
||||
salesGrowth: null,
|
||||
currentLiquidity: null,
|
||||
debtAssets: null,
|
||||
netMargin: null,
|
||||
returnOnEquity: null,
|
||||
});
|
||||
assert.throws(
|
||||
() =>
|
||||
checkDecisionBalance({ ...zero, accumulatedDepreciation: '0.01' }),
|
||||
/depreciação acumulada/,
|
||||
);
|
||||
});
|
||||
@@ -333,3 +333,47 @@ await test('successful save recovers the saved dossier edition and history links
|
||||
assert.match(html, /dossier-a\/forma-juridica\?revision=event-a/);
|
||||
assert.match(html, /dossier-a\/forma-juridica\?history_before=100/);
|
||||
});
|
||||
await test('C07 keeps one eight-theme questionnaire and one introductory phrase without repeating the pending questions', () => {
|
||||
const h = harness();
|
||||
const intro =
|
||||
'Compare alternativas para discutir a constitui\u00e7\u00e3o; n\u00e3o existe uma forma universalmente prefer\u00edvel.';
|
||||
const keys = [
|
||||
'purpose',
|
||||
'participants',
|
||||
'participation',
|
||||
'capital',
|
||||
'management',
|
||||
'responsibility',
|
||||
'listing',
|
||||
'regulated',
|
||||
];
|
||||
const full = Object.fromEntries(
|
||||
keys.map((key) => [
|
||||
key,
|
||||
{
|
||||
label: 'SYNTHETIC question ' + key,
|
||||
options: { unknown: 'Por esclarecer' },
|
||||
},
|
||||
]),
|
||||
);
|
||||
const html = renderToStaticMarkup(
|
||||
h.render({
|
||||
definition: { version: 'v1', questions: full },
|
||||
answers: Object.fromEntries(keys.map((key) => [key, 'unknown'])),
|
||||
result: {
|
||||
...props.result,
|
||||
questions: full,
|
||||
pending: keys,
|
||||
route: intro,
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.equal(html.split(intro).length - 1, 1);
|
||||
assert.equal((html.match(/<form\b/g) || []).length, 1);
|
||||
for (const key of keys)
|
||||
assert.equal(html.split('name="answers[' + key + ']"').length - 1, 1);
|
||||
assert.ok(
|
||||
html.replace(/<[^>]*>/g, '').includes('H\u00e1 8 temas por esclarecer'),
|
||||
);
|
||||
assert.doesNotMatch(html, /Por esclarecer:/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||
import { buildComplementaryTables } from '../../resources/js/lib/complementary-report.ts';
|
||||
import {
|
||||
correctionGroupMatches,
|
||||
correctionFieldHints,
|
||||
} from '../../resources/js/lib/field-corrections.ts';
|
||||
|
||||
void test('V09 field routing distinguishes Marco 2 from Necessidade 2 and preserves personnel aliases', () => {
|
||||
assert.deepEqual(
|
||||
correctionFieldHints(
|
||||
'Função 2: «Departamento (mapa de pessoal)»: Preencha este campo.',
|
||||
[
|
||||
'Departamento (mapa de pessoal)',
|
||||
'Quantidade de pessoas (inteiro)',
|
||||
'Remuneração mensal por pessoa',
|
||||
],
|
||||
),
|
||||
['Departamento (mapa de pessoal)'],
|
||||
);
|
||||
assert.equal(
|
||||
correctionGroupMatches(
|
||||
'Marcos / Marco 2 / «Prazo previsto»: Preencha este campo.',
|
||||
'Marco 2',
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
correctionGroupMatches(
|
||||
'Marcos / Marco 2 / «Prazo previsto»: Preencha este campo.',
|
||||
'Necessidade 2',
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
correctionGroupMatches(
|
||||
'Função 2: «Mês final no plano»: inválido.',
|
||||
'Necessidade 2',
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
correctionGroupMatches('Função 2: inválido.', 'Marco 2'),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
correctionGroupMatches('Segmento 2: inválido.', 'Segmento 1'),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
correctionGroupMatches('Segmento 2: inválido.', 'Segmento 2'),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
void test('V09 milestone monetary diagnostics identify blank, format, negative and precision without changing acceptance or totals', () => {
|
||||
const { plan, draft, milestones } = complementaryFixture();
|
||||
for (const [value, message] of [
|
||||
['', 'Preencha este campo'],
|
||||
['abc', 'Introduza apenas números'],
|
||||
['-1', 'Este valor não pode ser negativo'],
|
||||
['1.234', 'até duas casas decimais'],
|
||||
[' 1 ', 'até duas casas decimais'],
|
||||
]) {
|
||||
const input = {
|
||||
...draft,
|
||||
project_execution_snapshot: JSON.stringify([
|
||||
{ ...milestones[0], planned_amount: value },
|
||||
]),
|
||||
};
|
||||
const before = JSON.stringify(input);
|
||||
const result = buildComplementaryTables(input, plan)[1];
|
||||
assert.ok(
|
||||
result.issues.some(
|
||||
(s) =>
|
||||
s.includes('Marco 1') &&
|
||||
s.includes('«Montante planeado»') &&
|
||||
s.includes(message),
|
||||
),
|
||||
);
|
||||
assert.equal(result.rows.at(-1)[5], 'Por determinar');
|
||||
assert.equal(JSON.stringify(input), before);
|
||||
}
|
||||
const optional = buildComplementaryTables(draft, plan)[1];
|
||||
assert.ok(!optional.issues.length);
|
||||
assert.equal(optional.rows.at(-1)[5], '100.25');
|
||||
assert.equal(optional.rows.at(-1)[6], 'Por determinar');
|
||||
const invalidActual = buildComplementaryTables(
|
||||
{
|
||||
...draft,
|
||||
project_execution_snapshot: JSON.stringify([
|
||||
{ ...milestones[0], actual_amount: '-1' },
|
||||
]),
|
||||
},
|
||||
plan,
|
||||
)[1];
|
||||
assert.ok(
|
||||
invalidActual.issues.some(
|
||||
(s) =>
|
||||
s.includes('«Montante realizado»') &&
|
||||
s.includes('não pode ser negativo'),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
void test('V09 required milestone fields and staff salary/months point to their real labels while valid rows stay unchanged', () => {
|
||||
const { plan, draft, team, milestones } = complementaryFixture();
|
||||
const fixed = buildComplementaryTables(draft, plan);
|
||||
for (const [field, label] of [
|
||||
['title', 'Marco ou resultado'],
|
||||
['responsible', 'Responsável pelo marco'],
|
||||
['department', 'Departamento do marco'],
|
||||
['start_date', 'Data de início'],
|
||||
['due_date', 'Prazo previsto'],
|
||||
]) {
|
||||
const result = buildComplementaryTables(
|
||||
{
|
||||
...draft,
|
||||
project_execution_snapshot: JSON.stringify([
|
||||
{ ...milestones[0], [field]: '' },
|
||||
]),
|
||||
},
|
||||
plan,
|
||||
)[1];
|
||||
assert.ok(
|
||||
result.issues.some(
|
||||
(s) =>
|
||||
s.includes(`«${label}»`) &&
|
||||
s.includes('Preencha este campo'),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(result.rows.at(-1), fixed[1].rows.at(-1));
|
||||
}
|
||||
for (const [field, value, label] of [
|
||||
['competency', '', 'Competência ou função'],
|
||||
['department', '', 'Departamento (mapa de pessoal)'],
|
||||
['monthly_salary', '-1', 'Remuneração mensal por pessoa'],
|
||||
['start_month', '0', 'Mês inicial no plano'],
|
||||
['end_month', '14', 'Mês final no plano'],
|
||||
]) {
|
||||
const input = {
|
||||
...draft,
|
||||
project_team_snapshot: JSON.stringify([
|
||||
{ ...team[0], [field]: value },
|
||||
]),
|
||||
};
|
||||
const result = buildComplementaryTables(input, plan)[2];
|
||||
assert.ok(
|
||||
result.issues.some(
|
||||
(s) => s.includes('Função 1') && s.includes(label),
|
||||
),
|
||||
);
|
||||
assert.equal(result.rows.at(-1)[1], 'Por determinar');
|
||||
}
|
||||
assert.deepEqual(buildComplementaryTables(draft, plan), fixed);
|
||||
});
|
||||
|
||||
void test('V09 market fields use exact labels and retain existing growth and integer boundaries', () => {
|
||||
const { plan, draft } = complementaryFixture();
|
||||
for (const [key, value, label] of [
|
||||
['baseYear', '', 'Ano-base de mercado'],
|
||||
['years', '1', 'Horizonte de mercado (anos)'],
|
||||
]) {
|
||||
const result = buildComplementaryTables(draft, {
|
||||
...plan,
|
||||
marketAnalysis: { ...plan.marketAnalysis, [key]: value },
|
||||
})[0];
|
||||
assert.ok(result.issues.some((s) => s.includes(`«${label}»`)));
|
||||
}
|
||||
for (const [key, value, label] of [
|
||||
['label', '', 'Nome do segmento'],
|
||||
['basis', '', 'Fonte e data'],
|
||||
['customers', '2.5', 'Clientes potenciais no ano-base'],
|
||||
['growthPercent', '-101', 'Crescimento anual do segmento (%)'],
|
||||
]) {
|
||||
const changed = {
|
||||
...plan,
|
||||
marketAnalysis: {
|
||||
...plan.marketAnalysis,
|
||||
segments: [
|
||||
{ ...plan.marketAnalysis.segments[0], [key]: value },
|
||||
],
|
||||
},
|
||||
};
|
||||
const before = JSON.stringify(changed),
|
||||
result = buildComplementaryTables(draft, changed)[0];
|
||||
assert.ok(
|
||||
result.issues.some(
|
||||
(s) => s.includes('Segmento 1') && s.includes(label),
|
||||
),
|
||||
);
|
||||
assert.equal(JSON.stringify(changed), before);
|
||||
}
|
||||
const growth = {
|
||||
...plan,
|
||||
marketAnalysis: {
|
||||
...plan.marketAnalysis,
|
||||
segments: [
|
||||
{ ...plan.marketAnalysis.segments[0], growthPercent: '101' },
|
||||
],
|
||||
},
|
||||
};
|
||||
assert.equal(buildComplementaryTables(draft, growth)[0].issues.length, 0);
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import JSZip from 'jszip';
|
||||
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||
import { buildComplementaryTables } from '../../resources/js/lib/complementary-report.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import {
|
||||
restoreBusinessPlanSnapshot,
|
||||
serializeBusinessPlanSnapshot,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import {
|
||||
partitionSimulationDraft,
|
||||
restoreSimulationDraft,
|
||||
} from '../../resources/js/lib/simulation-form.ts';
|
||||
import {
|
||||
createProjectDossierReport,
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
void test('personnel in a different currency remains unreconciled without automatic conversion', () => {
|
||||
const { plan, draft } = complementaryFixture();
|
||||
const staff = buildComplementaryTables(
|
||||
{ ...draft, currency: 'USD' },
|
||||
plan,
|
||||
)[2];
|
||||
assert.match(staff.issues.join(' '), /moeda/);
|
||||
assert.ok(
|
||||
!staff.rows.some(
|
||||
(r) => r[0] === 'Diferença face à despesa de pessoal no plano',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
void test('malformed rows never produce misleading partial totals or erase original data', () => {
|
||||
const { plan, draft, team, milestones } = complementaryFixture();
|
||||
const input = {
|
||||
...draft,
|
||||
project_team_snapshot: JSON.stringify([...team, { bad: 'row' }]),
|
||||
project_execution_snapshot: JSON.stringify([
|
||||
...milestones,
|
||||
{ ...milestones[0], responsible: 42 },
|
||||
]),
|
||||
};
|
||||
const before = JSON.stringify(input);
|
||||
const t = buildComplementaryTables(input, plan);
|
||||
assert.ok(t[1].issues.length);
|
||||
assert.equal(t[1].rows.at(-1).at(-2), 'Por determinar');
|
||||
assert.ok(t[2].issues.length);
|
||||
assert.equal(t[2].rows.at(-1)[1], 'Por determinar');
|
||||
assert.equal(JSON.stringify(input), before);
|
||||
plan.marketAnalysis.segments = [null];
|
||||
assert.ok(buildComplementaryTables(draft, plan)[0].issues.length);
|
||||
});
|
||||
|
||||
void test('market projects integer customers and CAGR, never replaces sales; high growth is a warning', () => {
|
||||
const { plan, draft } = complementaryFixture();
|
||||
const before = buildIntegralFinancialTables(plan);
|
||||
let t = buildComplementaryTables(draft, plan)[0];
|
||||
assert.deepEqual(t.rows[0], [
|
||||
'Segmento ilustrativo',
|
||||
'100',
|
||||
'110',
|
||||
'121',
|
||||
'10,00%',
|
||||
]);
|
||||
assert.equal(t.issues.length, 0);
|
||||
plan.marketAnalysis.segments[0].growthPercent = '150';
|
||||
t = buildComplementaryTables(draft, plan)[0];
|
||||
assert.deepEqual(t.rows[0].slice(1, 4), ['100', '250', '625']);
|
||||
assert.equal(t.issues.length, 0);
|
||||
assert.match(t.notes.join(' '), /não bloqueante/);
|
||||
assert.deepEqual(buildIntegralFinancialTables(plan), before);
|
||||
plan.marketAnalysis.segments[0].customers = '0';
|
||||
assert.equal(
|
||||
buildComplementaryTables(draft, plan)[0].rows[0].at(-1),
|
||||
'Por determinar',
|
||||
);
|
||||
plan.marketAnalysis.segments[0].growthPercent = '-100';
|
||||
assert.equal(buildComplementaryTables(draft, plan)[0].issues.length, 0);
|
||||
plan.marketAnalysis.segments[0].customers = '1.5';
|
||||
assert.ok(buildComplementaryTables(draft, plan)[0].issues.length);
|
||||
plan.marketAnalysis.segments[0].customers = '100';
|
||||
plan.marketAnalysis.segments[0].basis = '';
|
||||
assert.ok(buildComplementaryTables(draft, plan)[0].issues.length);
|
||||
});
|
||||
void test('milestone totals distinguish optional unknown actuals, invalid dates and exact centavos', () => {
|
||||
const { plan, draft, milestones } = complementaryFixture();
|
||||
let t = buildComplementaryTables(draft, plan)[1];
|
||||
assert.equal(t.issues.length, 0);
|
||||
assert.deepEqual(t.rows.at(-1).slice(-2), ['100.25', 'Por determinar']);
|
||||
milestones[0].actual_amount = '0';
|
||||
milestones[0].start_date = '2027-02-30';
|
||||
draft.project_execution_snapshot = JSON.stringify(milestones);
|
||||
t = buildComplementaryTables(draft, plan)[1];
|
||||
assert.ok(t.issues.length);
|
||||
assert.equal(t.rows.at(-1).at(-1), '0.00');
|
||||
milestones[0].start_date = '2027-03-01';
|
||||
assert.match(
|
||||
buildComplementaryTables(
|
||||
{
|
||||
...draft,
|
||||
project_execution_snapshot: JSON.stringify(milestones),
|
||||
},
|
||||
plan,
|
||||
)[1].issues.join(' '),
|
||||
/A data de término não pode ser anterior à data de início\./,
|
||||
);
|
||||
});
|
||||
void test('personnel reconciles 13 months and partial years, preserves financial figures on mismatch', () => {
|
||||
const { plan, draft, team } = complementaryFixture();
|
||||
const before = buildIntegralFinancialTables(plan);
|
||||
let t = buildComplementaryTables(draft, plan)[2];
|
||||
assert.equal(t.issues.length, 0);
|
||||
assert.deepEqual(
|
||||
t.rows.find((r) => r[0] === 'Folha salarial prevista').slice(-2),
|
||||
['2400.00', '200.00'],
|
||||
);
|
||||
assert.ok(
|
||||
t.rows
|
||||
.at(-1)
|
||||
.slice(1)
|
||||
.every((x) => x === '0.00'),
|
||||
);
|
||||
team[0].monthly_salary = '100.01';
|
||||
draft.project_team_snapshot = JSON.stringify(team);
|
||||
t = buildComplementaryTables(draft, plan)[2];
|
||||
assert.equal(t.rows.at(-1)[1], '0.02');
|
||||
assert.match(t.issues.join(' '), /diverge/);
|
||||
assert.deepEqual(buildIntegralFinancialTables(plan), before);
|
||||
team[0].quantity = '1.5';
|
||||
assert.ok(
|
||||
buildComplementaryTables(
|
||||
{ ...draft, project_team_snapshot: JSON.stringify(team) },
|
||||
plan,
|
||||
)[2].issues.length,
|
||||
);
|
||||
});
|
||||
void test('legacy rows remain preserved and missing supplements remain explicit, not zero', () => {
|
||||
const { plan, draft, team, milestones } = complementaryFixture();
|
||||
delete plan.marketAnalysis;
|
||||
for (const k of [
|
||||
'department',
|
||||
'quantity',
|
||||
'monthly_salary',
|
||||
'start_month',
|
||||
'end_month',
|
||||
])
|
||||
delete team[0][k];
|
||||
for (const k of ['department', 'responsible', 'start_date'])
|
||||
delete milestones[0][k];
|
||||
const old = {
|
||||
...draft,
|
||||
project_team_snapshot: JSON.stringify(team),
|
||||
project_execution_snapshot: JSON.stringify(milestones),
|
||||
};
|
||||
const t = buildComplementaryTables(old, plan);
|
||||
assert.ok(t.every((x) => x.issues.length));
|
||||
assert.equal(t[2].rows[0][1], 'Por determinar');
|
||||
assert.equal(team[0].estimated_cost, '');
|
||||
assert.equal(t[1].rows[0].at(-2), '100.25');
|
||||
});
|
||||
void test('economic draft roundtrip and existing Word/print exports include three complementary tables', async () => {
|
||||
const { plan, draft } = complementaryFixture();
|
||||
const parts = partitionSimulationDraft(draft);
|
||||
const restored = restoreSimulationDraft(
|
||||
parts.personal_snapshot,
|
||||
parts.economic_snapshot,
|
||||
);
|
||||
assert.equal(restored.project_team_snapshot, draft.project_team_snapshot);
|
||||
assert.equal(
|
||||
restored.project_execution_snapshot,
|
||||
draft.project_execution_snapshot,
|
||||
);
|
||||
const recovered = restoreBusinessPlanSnapshot(
|
||||
serializeBusinessPlanSnapshot(plan),
|
||||
);
|
||||
assert.deepEqual(recovered.marketAnalysis, plan.marketAnalysis);
|
||||
assert.deepEqual(
|
||||
buildComplementaryTables(restored, recovered),
|
||||
buildComplementaryTables(draft, plan),
|
||||
);
|
||||
const report = createProjectDossierReport(draft, {
|
||||
selectedSections: new Set(['market', 'team', 'execution', 'finance']),
|
||||
});
|
||||
assert.equal(report.sections.flatMap((s) => s.tables ?? []).length, 11);
|
||||
const html = await createProjectDossierPrintHtml(report, []);
|
||||
for (const title of ['Análise de Mercado', 'Marcos', 'Pessoal'])
|
||||
assert.ok(html.includes(title));
|
||||
const doc = await generateProjectDossierDocx(report, []);
|
||||
const zip = await JSZip.loadAsync(
|
||||
doc instanceof Blob ? await doc.arrayBuffer() : doc,
|
||||
);
|
||||
const xml = await zip.file('word/document.xml').async('string');
|
||||
for (const title of ['Análise de Mercado', 'Marcos', 'Pessoal'])
|
||||
assert.ok(xml.includes(title));
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import JSZip from 'jszip';
|
||||
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { serializeBusinessPlanSnapshot } from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import {
|
||||
createIntegralFinancialReport,
|
||||
createProjectDossierReport,
|
||||
integralFinancialTableIds,
|
||||
generateProjectDossierDocx,
|
||||
createProjectDossierPrintHtml,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
import {
|
||||
createInvestorDossierReport,
|
||||
createInvestorStageReport,
|
||||
investorFinancialReportChoices,
|
||||
} from '../../resources/js/lib/investor-dossier-report.ts';
|
||||
|
||||
export function consolidatedFixture() {
|
||||
const { plan, draft } = complementaryFixture(),
|
||||
balance = buildIntegralFinancialTables(plan).find(
|
||||
(t) => t.id === 'balance',
|
||||
);
|
||||
plan.ratioCurrentBalances = {
|
||||
assetsByMonth: balance.rows
|
||||
.find((r) => r[0] === 'Caixa líquida')
|
||||
.slice(1, 14),
|
||||
liabilitiesByMonth: balance.rows
|
||||
.find((r) => r[0] === 'Total do passivo')
|
||||
.slice(1, 14),
|
||||
};
|
||||
draft.business_plan_snapshot = serializeBusinessPlanSnapshot(plan);
|
||||
return { plan, draft };
|
||||
}
|
||||
const dossier = () => {
|
||||
const { draft } = consolidatedFixture();
|
||||
return {
|
||||
case: { id: 'synthetic-case', title: 'Hotel QA sintético', version: 3 },
|
||||
context_opportunity: null,
|
||||
opportunity_options: [],
|
||||
investment_context: { revision: 1, fields: {} },
|
||||
phases: {},
|
||||
steps: [
|
||||
{
|
||||
code: 'S03',
|
||||
title: 'Viabilidade',
|
||||
state: 'preparing',
|
||||
reason: '',
|
||||
phase: 1,
|
||||
detail: {},
|
||||
},
|
||||
],
|
||||
documents: [],
|
||||
results: [
|
||||
{
|
||||
id: 'saved-one',
|
||||
draft_id: 'synthetic-draft',
|
||||
draft_version: 1,
|
||||
recorded_at: '2026-11-20T12:00:00Z',
|
||||
currency: 'MZN',
|
||||
engine: 'financial-calculators:v1',
|
||||
financial_snapshot: '',
|
||||
preparation_snapshot: draft,
|
||||
context_revision: 1,
|
||||
context_state: 'current',
|
||||
},
|
||||
],
|
||||
};
|
||||
};
|
||||
void test('eleven tables and summary come from one immutable saved scenario and appear in both export formats', async () => {
|
||||
const { draft } = consolidatedFixture(),
|
||||
before = JSON.stringify(draft),
|
||||
report = createIntegralFinancialReport(draft, {
|
||||
version: 'QA v1',
|
||||
generatedAt: '2026-11-20T12:00:00Z',
|
||||
});
|
||||
assert.equal(report.sections.length, 1);
|
||||
assert.deepEqual(
|
||||
report.sections[0].tables.map((t) => t.id),
|
||||
[...integralFinancialTableIds],
|
||||
);
|
||||
assert.equal(new Set(report.sections[0].tables.map((t) => t.id)).size, 11);
|
||||
const original = createProjectDossierReport(draft, {
|
||||
selectedSections: new Set(['finance', 'market', 'team', 'execution']),
|
||||
});
|
||||
for (const t of report.sections[0].tables)
|
||||
assert.deepEqual(
|
||||
t,
|
||||
original.sections
|
||||
.flatMap((s) => s.tables ?? [])
|
||||
.find((r) => r.id === t.id),
|
||||
);
|
||||
const cash = report.sections[0].rows.find(
|
||||
(r) => r.field === 'Caixa final projectada',
|
||||
);
|
||||
assert.match(cash.value, /4 540,00/);
|
||||
assert.equal(JSON.stringify(draft), before);
|
||||
const html = await createProjectDossierPrintHtml(report, []),
|
||||
doc = await generateProjectDossierDocx(report, []),
|
||||
zip = await JSZip.loadAsync(
|
||||
doc instanceof Blob ? await doc.arrayBuffer() : doc,
|
||||
),
|
||||
xml = await zip.file('word/document.xml').async('string');
|
||||
for (const t of report.sections[0].tables) {
|
||||
assert.ok(html.includes(t.title));
|
||||
assert.ok(xml.includes(t.title));
|
||||
}
|
||||
});
|
||||
void test('dossier uses only the chosen preserved scenario, requires choice between versions and never leaks another opportunity', () => {
|
||||
const input = dossier();
|
||||
let report = createInvestorDossierReport(input);
|
||||
assert.equal(
|
||||
report.sections.find((s) => s.id === 'financial-report').tables.length,
|
||||
11,
|
||||
);
|
||||
const other = structuredClone(input.results[0]);
|
||||
other.id = 'other-opportunity';
|
||||
other.context_opportunity = 'foreign';
|
||||
other.preparation_snapshot.project_team_snapshot = 'FOREIGN PRIVATE DATA';
|
||||
input.results.push(other);
|
||||
assert.equal(investorFinancialReportChoices(input).length, 1);
|
||||
assert.ok(
|
||||
!JSON.stringify(createInvestorDossierReport(input)).includes(
|
||||
'FOREIGN PRIVATE DATA',
|
||||
),
|
||||
);
|
||||
const second = structuredClone(input.results[0]);
|
||||
second.id = 'saved-two';
|
||||
second.draft_version = 2;
|
||||
const snapshot = JSON.parse(
|
||||
second.preparation_snapshot.business_plan_snapshot,
|
||||
);
|
||||
snapshot.plan.reportAssumptions.startupExpenses[0].amount = '100.25';
|
||||
second.preparation_snapshot.business_plan_snapshot =
|
||||
JSON.stringify(snapshot);
|
||||
input.results.push(second);
|
||||
assert.throws(() => createInvestorDossierReport(input), /Escolha/);
|
||||
const chosen = createInvestorDossierReport(input, undefined, {
|
||||
financialResultId: 'saved-two',
|
||||
}).sections.find((s) => s.id === 'financial-report');
|
||||
assert.match(
|
||||
chosen.rows.find((r) => r.field === 'Caixa final projectada').value,
|
||||
/4 539,75/,
|
||||
);
|
||||
assert.equal(
|
||||
chosen.tables
|
||||
.find((t) => t.id === 'funding')
|
||||
.rows.find((r) => r[0] === 'Diferença por financiar')[1],
|
||||
'100.25',
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
createInvestorDossierReport(input, undefined, {
|
||||
financialResultId: other.id,
|
||||
}),
|
||||
/contexto/,
|
||||
);
|
||||
report = createInvestorDossierReport(input, undefined, {
|
||||
financialResultId: second.id,
|
||||
});
|
||||
assert.match(
|
||||
report.sections
|
||||
.find((s) => s.id === 'financial-report')
|
||||
.rows.find((r) => r.field === 'Caixa final projectada').value,
|
||||
/4 539,75/,
|
||||
);
|
||||
assert.equal(
|
||||
createInvestorStageReport(
|
||||
input,
|
||||
'S03',
|
||||
undefined,
|
||||
second.id,
|
||||
).sections.find((s) => s.id === 'financial-report').tables.length,
|
||||
11,
|
||||
);
|
||||
});
|
||||
void test('historical or absent snapshots are not silently reconstructed from another version', () => {
|
||||
const input = dossier();
|
||||
input.results[0].context_revision = 0;
|
||||
let report = createInvestorDossierReport(input);
|
||||
assert.match(
|
||||
report.sections
|
||||
.find((s) => s.id === 'financial-report')
|
||||
.paragraphs.join(' '),
|
||||
/histórica/,
|
||||
);
|
||||
delete input.results[0].preparation_snapshot.business_plan_snapshot;
|
||||
report = createInvestorDossierReport(input);
|
||||
assert.ok(!report.sections.some((s) => s.id === 'financial-report'));
|
||||
});
|
||||
|
||||
void test('currency differences remain explicit without relabelling or converting the saved plan', () => {
|
||||
const { draft } = consolidatedFixture();
|
||||
const report = createIntegralFinancialReport({ ...draft, currency: 'USD' });
|
||||
assert.match(report.sections[0].paragraphs.join(' '), /MZN.*USD/);
|
||||
assert.equal(
|
||||
report.sections[0].rows.find((r) => r.field === 'Moeda do plano').value,
|
||||
'MZN',
|
||||
);
|
||||
});
|
||||
@@ -24,10 +24,26 @@ function load(path, overrides = {}) {
|
||||
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;
|
||||
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);
|
||||
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);
|
||||
@@ -169,16 +185,23 @@ test('growth uses explicit comparable endpoints and does not fill missing interm
|
||||
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', () => {
|
||||
test('public dimensions round population and hide technical references without modifying evidence', () => {
|
||||
const original = base(),
|
||||
before = JSON.stringify(original);
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Component, { evidence: evidence([base()]) }),
|
||||
React.createElement(Component, { evidence: evidence([original]) }),
|
||||
);
|
||||
assert.ok(
|
||||
html.indexOf('Retrato da população') <
|
||||
html.indexOf('Valores originais por ano'),
|
||||
html.indexOf('Valores de apresentação por ano'),
|
||||
);
|
||||
assert.match(html, /1000.1234567890123/);
|
||||
assert.match(html, /Valores por dimensão, fonte e advertências/);
|
||||
assert.doesNotMatch(
|
||||
html,
|
||||
/1000.1234567890123|SHA256|source.xlsx|Referência/,
|
||||
);
|
||||
assert.match(html, /1\s000/);
|
||||
assert.match(html, /Valores por ano e dimensão/);
|
||||
assert.equal(JSON.stringify(original), before);
|
||||
assert.doesNotMatch(html, /<details[^>]*\bopen\b/);
|
||||
assert.match(html, /um único ano/);
|
||||
assert.match(html, /capacidade instalada/);
|
||||
@@ -233,3 +256,85 @@ test('Barue 2026 provided evidence produces the readable proportions without cha
|
||||
assert.equal(Number(r.age15to64Share.toFixed(1)), 51.3);
|
||||
assert.equal(JSON.stringify(s), before);
|
||||
});
|
||||
|
||||
test('annual comparisons format all populations and do not repeat technical explanations', () => {
|
||||
const data = evidence([base()]);
|
||||
data.comparisons = [2026, 2027, 2028].map((year) => ({
|
||||
year,
|
||||
left: 'Bilene',
|
||||
right: 'Funhalouro',
|
||||
left_value: '157982.9857834139',
|
||||
right_value: '46656.505898723823',
|
||||
difference: '111326.479884690077',
|
||||
left_import: 'a',
|
||||
right_import: 'b',
|
||||
explanation: 'INTERNAL REPEATED EXPLANATION',
|
||||
}));
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Component, { evidence: data }),
|
||||
);
|
||||
assert.match(html, /157\s983/);
|
||||
assert.match(html, /46\s657/);
|
||||
assert.match(html, /111\s326/);
|
||||
assert.match(html, /<h3[^>]*>2027<\/h3>/);
|
||||
assert.doesNotMatch(html, /111326\.479|INTERNAL REPEATED/);
|
||||
assert.equal(
|
||||
(
|
||||
html.match(/Os indicadores demográficos não demonstram procura/g) ||
|
||||
[]
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test('concurrent divergence remains visible without exposing reconciliation identifiers', () => {
|
||||
const data = evidence([base()]);
|
||||
data.differences = [
|
||||
{
|
||||
territory_id: 'INTERNAL-TERRITORY',
|
||||
dimension: '2026|population|all|all|pessoas',
|
||||
state: 'divergent_values',
|
||||
values: [
|
||||
{
|
||||
import_id: 'INTERNAL-IMPORT',
|
||||
value: '1000.1234567890123',
|
||||
data_kind: 'projected',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Component, { evidence: data }),
|
||||
);
|
||||
assert.match(html, /Há valores divergentes entre séries/);
|
||||
assert.doesNotMatch(
|
||||
html,
|
||||
/INTERNAL-TERRITORY|INTERNAL-IMPORT|2026\|population|1000\.1234567890123/,
|
||||
);
|
||||
});
|
||||
|
||||
test('commerce preparation carries the explicit sector and territory', () => {
|
||||
const Page = load('pages/investment/demography.tsx', {
|
||||
'@inertiajs/react': { router: {} },
|
||||
'./shared': {
|
||||
Frame: ({ children }) =>
|
||||
React.createElement('main', null, children),
|
||||
button: '',
|
||||
},
|
||||
}).default;
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Page, {
|
||||
evidence: evidence([base()]),
|
||||
filters: { territories: ['district-one'], sector: 'commerce' },
|
||||
territories: [],
|
||||
sectors: { commerce: 'Comércio e serviços', tourism: 'Turismo' },
|
||||
entrySector: 'comercio-e-servicos',
|
||||
}),
|
||||
);
|
||||
assert.match(
|
||||
html,
|
||||
/source=territory%3Adistrict-one&sector=comercio-e-servicos/,
|
||||
);
|
||||
assert.doesNotMatch(html, /Hotelaria e alojamento|sector=turismo/);
|
||||
assert.match(html, /Não há ideias documentadas compatíveis/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import JSZip from 'jszip';
|
||||
import {
|
||||
createProjectDossierReport,
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
const text =
|
||||
'Objectivos: testar uma procura declarada. Missao: prestar um servico local. Chaves para o sucesso: qualidade e cumprimento dos prazos.';
|
||||
const make = () =>
|
||||
createProjectDossierReport(
|
||||
{
|
||||
project_title: 'SYNTHETIC narrative QA',
|
||||
project_summary: text,
|
||||
competitor_assumption:
|
||||
'SYNTHETIC <script>alert(1)</script> & alternatives',
|
||||
},
|
||||
{
|
||||
selectedSections: new Set(['summary', 'project', 'market']),
|
||||
generatedAt: '2026-11-21T10:00:00Z',
|
||||
},
|
||||
);
|
||||
void test('F23 preserves investor executive objectives, mission and success keys without adopting TEMPO examples', () => {
|
||||
const r = make();
|
||||
assert.equal(
|
||||
r.sections.find((s) => s.id === 'summary').paragraphs[0],
|
||||
text,
|
||||
);
|
||||
assert.ok(
|
||||
!r.sections
|
||||
.find((s) => s.id === 'summary')
|
||||
.paragraphs[0].includes('TEMPO'),
|
||||
);
|
||||
});
|
||||
void test('F26 exports nonfinancial rows as escaped paragraphs in HTML and Word without losing values and provenance', async () => {
|
||||
const r = make(),
|
||||
before = JSON.stringify(r);
|
||||
const html = await createProjectDossierPrintHtml(r, [], true);
|
||||
assert.doesNotMatch(html, /<table\b/);
|
||||
assert.ok(html.includes(text));
|
||||
assert.ok(html.includes('<script>'));
|
||||
assert.ok(!html.includes('<script>alert'));
|
||||
const zip = await JSZip.loadAsync(
|
||||
await (await generateProjectDossierDocx(r, [], true)).arrayBuffer(),
|
||||
);
|
||||
const xml = await zip.file('word/document.xml').async('string');
|
||||
assert.doesNotMatch(xml, /<w:tbl\b/);
|
||||
assert.ok(xml.includes(text));
|
||||
assert.match(xml, /Classifica|Origem|origem|introduzido/);
|
||||
assert.equal(JSON.stringify(r), before);
|
||||
});
|
||||
void test('F26 keeps financial metadata tables and detailed financial tables intact alongside narrative paragraphs', async () => {
|
||||
const r = make();
|
||||
r.sections.push({
|
||||
id: 'finance',
|
||||
title: 'SYNTHETIC finance',
|
||||
private: true,
|
||||
paragraphs: [],
|
||||
rows: [
|
||||
{
|
||||
field: 'SYNTHETIC preserved amount',
|
||||
value: '100.00 MZN',
|
||||
classification: 'Declared',
|
||||
origin: 'Synthetic input',
|
||||
},
|
||||
],
|
||||
tables: [
|
||||
{
|
||||
id: 'synthetic-core',
|
||||
title: 'SYNTHETIC core table',
|
||||
headers: ['Month', 'Cash'],
|
||||
rows: [['1', '100.00']],
|
||||
notes: [],
|
||||
issues: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
const html = await createProjectDossierPrintHtml(r, [], true);
|
||||
assert.equal((html.match(/<table\b/g) || []).length, 2);
|
||||
assert.ok(html.includes('100.00 MZN'));
|
||||
const zip = await JSZip.loadAsync(
|
||||
await (await generateProjectDossierDocx(r, [], true)).arrayBuffer(),
|
||||
);
|
||||
const xml = await zip.file('word/document.xml').async('string');
|
||||
assert.equal((xml.match(/<w:tbl\b/g) || []).length, 2);
|
||||
assert.ok(xml.includes('100.00 MZN'));
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
exportBusinessPlanCsv,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { dayTermsFixture, operation } from './fixtures/financial-day-terms.mjs';
|
||||
|
||||
test('F20-A preserves explicitly classified independent other income when replacing sales collections', () => {
|
||||
const p = dayTermsFixture();
|
||||
p.monthlyCollections = '100';
|
||||
p.reportAssumptions.manualCollectionsKind = 'other_income';
|
||||
const r = forecastBusinessPlan(p);
|
||||
assert.deepEqual(
|
||||
r.rows.map((row) => row.otherCollections),
|
||||
['100.00', '100.00', '100.00'],
|
||||
);
|
||||
assert.equal(r.totalCashCollections, '1300.00');
|
||||
const tables = buildIntegralFinancialTables(p);
|
||||
assert.deepEqual(
|
||||
tables
|
||||
.find((t) => t.id === 'profit-loss')
|
||||
.rows.find((r) => r[0] === 'Outras receitas de caixa declaradas')
|
||||
.slice(1),
|
||||
['100.00', '100.00', '100.00', '300.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
tables
|
||||
.find((t) => t.id === 'balance')
|
||||
.rows.find((r) => r[0] === 'Diferença do balanço')
|
||||
.slice(1),
|
||||
['0.00', '0.00', '0.00', '0.00'],
|
||||
);
|
||||
});
|
||||
|
||||
test('F20-A replaces only opted-in cash agendas, preserves recognition and reconciles every monthly balance', () => {
|
||||
const p = dayTermsFixture();
|
||||
const before = structuredClone(p);
|
||||
const r = forecastBusinessPlan(p);
|
||||
assert.deepEqual(p, before);
|
||||
assert.deepEqual(
|
||||
r.rows.map((r) => r.salesCollections),
|
||||
['0.00', '0.00', '1000.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
r.rows.map((r) => r.variableCostPayments),
|
||||
['0.00', '0.00', '400.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
r.rows.map((r) => r.operatingPayments),
|
||||
['0.00', '0.00', '100.00'],
|
||||
);
|
||||
assert.equal(r.totalCashCollections, '1000.00');
|
||||
assert.equal(r.rows[0].revenue, '1000.00');
|
||||
assert.equal(r.rows[0].inventoryReceipts, '400.00');
|
||||
assert.equal(r.rows[0].operatingExpenses, '100.00');
|
||||
assert.equal(r.salesReceivablesAtEnd, '0.00');
|
||||
const tables = buildIntegralFinancialTables(p);
|
||||
const balance = tables.find((t) => t.id === 'balance');
|
||||
assert.deepEqual(
|
||||
balance.rows.find((r) => r[0] === 'Diferença do balanço').slice(1),
|
||||
['0.00', '0.00', '0.00', '0.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
balance.rows
|
||||
.find((r) => r[0] === 'Obrigações operacionais líquidas')
|
||||
.slice(1, 4),
|
||||
['500.00', '500.00', '0.00'],
|
||||
);
|
||||
assert.ok(
|
||||
tables.every((t) => t.issues.length === 0),
|
||||
JSON.stringify(tables.map((t) => t.issues)),
|
||||
);
|
||||
assert.match(
|
||||
tables.find((t) => t.id === 'cashflow').notes.join(' '),
|
||||
/2027-03-02.*aproximação/,
|
||||
);
|
||||
assert.match(exportBusinessPlanCsv(p), /2027-03-02/);
|
||||
});
|
||||
|
||||
test('F20-A calendar days cover zero, individual dates, leap February and year transition', () => {
|
||||
const p = dayTermsFixture();
|
||||
p.dayTerms.operations.forEach((o) => (o.termDays = '0'));
|
||||
assert.equal(forecastBusinessPlan(p).rows[0].salesCollections, '1000.00');
|
||||
const sale = p.dayTerms.operations[0];
|
||||
Object.assign(sale, {
|
||||
recognitionBasis: 'date',
|
||||
recognitionDate: '2027-01-20',
|
||||
termDays: '30',
|
||||
});
|
||||
let r = forecastBusinessPlan(p);
|
||||
assert.equal(r.dayTermEvents[0].due, '2027-02-19');
|
||||
assert.equal(r.dayTermEvents[0].approximate, false);
|
||||
sale.recognitionBasis = 'monthly';
|
||||
p.reportAssumptions.startYear = '2028';
|
||||
assert.equal(forecastBusinessPlan(p).dayTermEvents[0].due, '2028-03-01');
|
||||
p.reportAssumptions.startYear = '2027';
|
||||
sale.termDays = '365';
|
||||
assert.equal(forecastBusinessPlan(p).dayTermEvents[0].due, '2028-01-31');
|
||||
});
|
||||
|
||||
test('F20-A excludes early and unknown payments including within the same month, never silently normalizes them', () => {
|
||||
const p = dayTermsFixture();
|
||||
const o = p.dayTerms.operations[1];
|
||||
Object.assign(o, {
|
||||
recognitionBasis: 'date',
|
||||
recognitionDate: '2027-01-25',
|
||||
originBasis: 'date',
|
||||
originDate: '2027-01-01',
|
||||
termDays: '0',
|
||||
});
|
||||
assert.throws(() => forecastBusinessPlan(p), /antecipação excluída/);
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p)),
|
||||
null,
|
||||
);
|
||||
assert.ok(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p), {
|
||||
editable: true,
|
||||
}),
|
||||
);
|
||||
o.termDays = '30';
|
||||
assert.equal(forecastBusinessPlan(p).dayTermEvents[1].due, '2027-01-31');
|
||||
o.originBasis = 'unknown';
|
||||
assert.throws(() => forecastBusinessPlan(p), /origem.*insuficiente/);
|
||||
o.originBasis = 'recognition';
|
||||
o.recognitionBasis = 'unknown';
|
||||
assert.throws(() => forecastBusinessPlan(p), /reconhecimento insuficiente/);
|
||||
});
|
||||
|
||||
test('F20-A parcels reconcile to recognition and reject duplicates without merging distinct equal payments', () => {
|
||||
const p = dayTermsFixture();
|
||||
const original = p.dayTerms.operations[1];
|
||||
original.amount = '200';
|
||||
const second = { ...original, parcelId: '2' };
|
||||
p.dayTerms.operations.push(second);
|
||||
assert.equal(
|
||||
forecastBusinessPlan(p).rows[2].variableCostPayments,
|
||||
'400.00',
|
||||
);
|
||||
second.parcelId = '1';
|
||||
assert.throws(() => forecastBusinessPlan(p), /duplicada/);
|
||||
second.originId = 'another';
|
||||
assert.equal(
|
||||
forecastBusinessPlan(p).rows[2].variableCostPayments,
|
||||
'400.00',
|
||||
);
|
||||
second.amount = '201';
|
||||
assert.throws(() => forecastBusinessPlan(p), /soma dos montantes/);
|
||||
});
|
||||
|
||||
test('F20-A retains future receivables and payables at horizons 1 and 60 and restores manual schedules explicitly', () => {
|
||||
for (const periods of [1, 60]) {
|
||||
const p = dayTermsFixture(periods);
|
||||
p.dayTerms.operations.forEach((o) => {
|
||||
o.month = periods;
|
||||
o.originId += '-last';
|
||||
o.termDays = '365';
|
||||
});
|
||||
p.products[0].monthlyUnitsByPeriod = Array(periods).fill('0');
|
||||
p.products[0].monthlyUnitsByPeriod[periods - 1] = '1';
|
||||
p.inventoryPurchaseSchedule.forEach(
|
||||
(o, i) => (o.amount = i === periods - 1 ? '400' : '0'),
|
||||
);
|
||||
p.monthlyOperatingExpensesByPeriod = Array(periods).fill('0');
|
||||
p.monthlyOperatingExpensesByPeriod[periods - 1] = '100';
|
||||
const r = forecastBusinessPlan(p);
|
||||
assert.equal(r.totalCashCollections, '0.00');
|
||||
assert.equal(r.supplierPaymentsOutstandingAtEnd, '400.00');
|
||||
assert.equal(r.salesReceivablesAtEnd, '1000.00');
|
||||
assert.ok(r.dayTermEvents.every((e) => e.outsideHorizon));
|
||||
assert.equal(r.rows.at(-1).variableCostPayments, '0.00');
|
||||
}
|
||||
const p = dayTermsFixture();
|
||||
const legacy = { ...p, dayTerms: undefined };
|
||||
p.dayTerms.sales = p.dayTerms.purchases = p.dayTerms.services = false;
|
||||
assert.deepEqual(forecastBusinessPlan(p), forecastBusinessPlan(legacy));
|
||||
});
|
||||
|
||||
test('F20-A version 20 recovers dates, inactive manual inputs and outcomes; invalid terms and foreign versions are rejected', () => {
|
||||
const p = dayTermsFixture();
|
||||
const snapshot = serializeBusinessPlanSnapshot(p);
|
||||
assert.equal(JSON.parse(snapshot).version, 20);
|
||||
const recovered = restoreBusinessPlanSnapshot(snapshot);
|
||||
assert.ok(recovered);
|
||||
assert.deepEqual(recovered.dayTerms, p.dayTerms);
|
||||
assert.equal(recovered.monthlyCollections, '777');
|
||||
assert.deepEqual(forecastBusinessPlan(recovered), forecastBusinessPlan(p));
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(
|
||||
snapshot.replace('"version":20', '"version":19'),
|
||||
),
|
||||
null,
|
||||
);
|
||||
for (const termDays of ['', '-1', '366', '1.5', 'abc']) {
|
||||
p.dayTerms.operations[0].termDays = termDays;
|
||||
assert.throws(() => forecastBusinessPlan(p), /Prazo \(dias\)/);
|
||||
}
|
||||
p.dayTerms.operations[0] = operation('sales', '1000');
|
||||
Object.assign(p.dayTerms.operations[0], {
|
||||
recognitionBasis: 'date',
|
||||
recognitionDate: '2027-02-30',
|
||||
});
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/reconhecimento insuficiente ou inválida/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import JSZip from 'jszip';
|
||||
import * as presentation from '../../resources/js/lib/financial-issue-presentation.ts';
|
||||
import * as integral from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { serializeBusinessPlanSnapshot } from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { buildComplementaryTables } from '../../resources/js/lib/complementary-report.ts';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||
import {
|
||||
createProjectDossierReport,
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
const mismatch = () => ({
|
||||
...financialReportFixture(12),
|
||||
fundingBreakdown: {
|
||||
ownerCapital: '700',
|
||||
investorCapital: '0',
|
||||
additionalCapital: '0',
|
||||
},
|
||||
});
|
||||
|
||||
void test('deduplication never hides a forecast error behind an unreadable report snapshot or the annual example', () => {
|
||||
const plan = mismatch();
|
||||
const error = integral.buildIntegralFinancialTables(plan)[0].issues[0];
|
||||
assert.equal(presentation.forecastErrorShownInReport(plan, error), true);
|
||||
assert.equal(
|
||||
presentation.forecastErrorShownInReport(plan, 'Other error'),
|
||||
false,
|
||||
);
|
||||
plan.reportAssumptions.startupExpenses = 'invalid structure';
|
||||
assert.equal(presentation.forecastErrorShownInReport(plan, error), false);
|
||||
delete plan.reportAssumptions;
|
||||
plan.reportSource = 'annual_example';
|
||||
assert.equal(presentation.forecastErrorShownInReport(plan, error), false);
|
||||
});
|
||||
|
||||
void test('capital mismatch names the exact compared controls once and preserves all seven validity flags', () => {
|
||||
const plan = mismatch(),
|
||||
tables = integral.buildIntegralFinancialTables(plan),
|
||||
before = JSON.stringify({ plan, tables });
|
||||
assert.equal(tables.filter((t) => t.issues.length).length, 7);
|
||||
const issues = presentation.financialIssuesForDisplay(tables);
|
||||
assert.equal(issues.length, 1);
|
||||
assert.equal(issues[0].tables.length, 7);
|
||||
for (const field of [
|
||||
'Capital próprio',
|
||||
'Capital do proprietário',
|
||||
'Capital do investidor',
|
||||
'Capital adicional angariado',
|
||||
])
|
||||
assert.ok(issues[0].message.includes(field));
|
||||
assert.equal(JSON.stringify({ plan, tables }), before);
|
||||
plan.fundingBreakdown.ownerCapital = '600';
|
||||
assert.deepEqual(
|
||||
presentation.financialIssuesForDisplay(
|
||||
integral.buildIntegralFinancialTables(plan),
|
||||
),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
void test('opening imbalance identifies original fields and exact difference without guessing the responsible balance', () => {
|
||||
const plan = financialReportFixture(12);
|
||||
plan.reportAssumptions.openingEquity = '999';
|
||||
const issues = presentation.financialIssuesForDisplay(
|
||||
integral.buildIntegralFinancialTables(plan),
|
||||
);
|
||||
assert.equal(issues.length, 1);
|
||||
const message = issues[0].message;
|
||||
assert.match(message, /diferença 1,00/);
|
||||
assert.match(message, /Capital e resultados anteriores/);
|
||||
assert.match(message, /não permite identificar automaticamente/);
|
||||
});
|
||||
|
||||
void test('personnel mismatch points to both tables and quantity, salary and active months; correction removes it', () => {
|
||||
const { plan, draft, team } = complementaryFixture();
|
||||
team[0].monthly_salary = '100.01';
|
||||
draft.project_team_snapshot = JSON.stringify(team);
|
||||
const tables = buildComplementaryTables(draft, plan);
|
||||
const before = JSON.stringify({ plan, draft, tables });
|
||||
const message = presentation
|
||||
.financialIssuesForDisplay(tables)
|
||||
.find((i) => i.message.includes('Mapa de pessoal')).message;
|
||||
for (const field of [
|
||||
'Folha salarial prevista',
|
||||
'Pessoal',
|
||||
'quantidade',
|
||||
'remuneração mensal',
|
||||
'meses activos',
|
||||
])
|
||||
assert.ok(message.includes(field));
|
||||
assert.equal(JSON.stringify({ plan, draft, tables }), before);
|
||||
team[0].monthly_salary = '100.00';
|
||||
draft.project_team_snapshot = JSON.stringify(team);
|
||||
assert.ok(
|
||||
!presentation
|
||||
.financialIssuesForDisplay(buildComplementaryTables(draft, plan))
|
||||
.some((i) => i.message.includes('Mapa de pessoal')),
|
||||
);
|
||||
});
|
||||
|
||||
void test('inventory and startup messages identify their controls; unknown diagnostics remain visible without invented attribution', () => {
|
||||
assert.match(
|
||||
presentation.financialIssueMessage(
|
||||
'A soma das existencias iniciais por produto deve coincidir com as existencias iniciais do plano.',
|
||||
),
|
||||
/Planear stock por produto/,
|
||||
);
|
||||
assert.match(
|
||||
presentation.financialIssueMessage(
|
||||
'As aquisições do cenário não correspondem às necessidades de activos. Confira os valores e adopte as aquisições calculadas.',
|
||||
),
|
||||
/Aquisição de activos/,
|
||||
);
|
||||
const raw = 'Diagnóstico específico não mapeado';
|
||||
const tables = [
|
||||
{ id: 'a', title: 'Tabela A', issues: [raw, raw] },
|
||||
{ id: 'b', title: 'Tabela B', issues: [raw] },
|
||||
];
|
||||
assert.deepEqual(presentation.financialIssuesForDisplay(tables), [
|
||||
{ message: raw, tables: ['Tabela A', 'Tabela B'] },
|
||||
]);
|
||||
});
|
||||
|
||||
void test('real table component presents one issue panel while retaining every table and calculated row', () => {
|
||||
const code = ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/investment-report-tables.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText;
|
||||
const module = { exports: {} },
|
||||
require = createRequire(import.meta.url);
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(name) =>
|
||||
name === '@/lib/integral-financial-report'
|
||||
? integral
|
||||
: name === '@/lib/financial-issue-presentation'
|
||||
? presentation
|
||||
: require(name),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const tables = integral.buildIntegralFinancialTables(mismatch()),
|
||||
message = presentation.financialIssuesForDisplay(tables)[0].message;
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(module.exports.InvestmentReportTables, { tables }),
|
||||
);
|
||||
assert.equal(html.split(message).length - 1, 1);
|
||||
assert.equal(
|
||||
(html.match(/aria-label="Dados financeiros a corrigir"/g) ?? []).length,
|
||||
1,
|
||||
);
|
||||
assert.ok(tables.every((t) => html.includes(t.title)));
|
||||
const valid = integral.buildIntegralFinancialTables(
|
||||
financialReportFixture(12),
|
||||
);
|
||||
assert.ok(
|
||||
!renderToStaticMarkup(
|
||||
React.createElement(module.exports.InvestmentReportTables, {
|
||||
tables: valid,
|
||||
}),
|
||||
).includes('Dados financeiros a corrigir'),
|
||||
);
|
||||
});
|
||||
|
||||
void test('print and Word present the same capital correction only once, without mutating report tables', async () => {
|
||||
const report = createProjectDossierReport(
|
||||
{
|
||||
project_title: 'SINTÉTICO V12',
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(mismatch()),
|
||||
},
|
||||
{
|
||||
selectedSections: new Set(['finance']),
|
||||
generatedAt: '2026-11-20T12:00:00Z',
|
||||
},
|
||||
);
|
||||
const before = JSON.stringify(report),
|
||||
message = presentation.financialIssuesForDisplay(
|
||||
report.sections.find((s) => s.id === 'finance').tables,
|
||||
)[0].message;
|
||||
const html = await createProjectDossierPrintHtml(report, []);
|
||||
assert.equal(html.split(message).length - 1, 1);
|
||||
const blob = await generateProjectDossierDocx(report, []),
|
||||
zip = await JSZip.loadAsync(
|
||||
blob instanceof Blob ? await blob.arrayBuffer() : blob,
|
||||
),
|
||||
xml = await zip.file('word/document.xml').async('string');
|
||||
assert.equal(xml.split(message).length - 1, 1);
|
||||
assert.equal(JSON.stringify(report), before);
|
||||
});
|
||||
@@ -0,0 +1,442 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import JSZip from 'jszip';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import ts from 'typescript';
|
||||
import * as guidance from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
import { selectPlanCae } from '../../resources/js/lib/cae-mozambique.ts';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
monthlyProjectedSales,
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
compareBusinessScenarios,
|
||||
exportBusinessPlanCsv,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { financialPlanWarnings } from '../../resources/js/lib/financial-plan-warnings.ts';
|
||||
import { buildAnnualExampleTables } from '../../resources/js/lib/annual-example-report.ts';
|
||||
import {
|
||||
newAnnualReferencePlan,
|
||||
serializeAnnualExampleSnapshot,
|
||||
} from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
import {
|
||||
createProjectDossierReport,
|
||||
createIntegralFinancialReport,
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
const cell = (tables, id, label, index) =>
|
||||
tables.find((t) => t.id === id).rows.find((r) => r[0] === label)[index];
|
||||
const reload = (p) =>
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p));
|
||||
|
||||
void test('annual growth is explicit, reaches all dependent forecasts and preserves declared monthly overrides', () => {
|
||||
const p = financialReportFixture(36);
|
||||
p.annualGrowthPercent = '150';
|
||||
const unchanged = forecastBusinessPlan(p);
|
||||
assert.equal(unchanged.rows[12].revenue, '1000.00');
|
||||
p.applyAnnualGrowth = true;
|
||||
const result = forecastBusinessPlan(reload(p));
|
||||
assert.equal(result.rows[12].revenue, '2500.00');
|
||||
assert.equal(result.rows[24].revenue, '6250.00');
|
||||
assert.equal(result.rows[12].variableCost, '1000.00');
|
||||
assert.deepEqual(
|
||||
monthlyProjectedSales(p),
|
||||
result.rows.map((r) => r.revenue),
|
||||
);
|
||||
p.products[0].monthlyUnitsByPeriod = Array(36).fill('7');
|
||||
assert.equal(forecastBusinessPlan(p).rows[24].revenue, '700.00');
|
||||
const tables = buildIntegralFinancialTables({
|
||||
...p,
|
||||
products: [{ ...p.products[0], monthlyUnitsByPeriod: undefined }],
|
||||
});
|
||||
assert.equal(cell(tables, 'sales', 'Vendas totais', 37), '12000.00');
|
||||
assert.equal(cell(tables, 'sales', 'Vendas totais', 38), '30000.00');
|
||||
assert.equal(cell(tables, 'sales', 'Vendas totais', 39), '75000.00');
|
||||
});
|
||||
|
||||
void test('dividends reduce cash and capital equally, never profit; monthly and annual balances stay exact', () => {
|
||||
const p = financialReportFixture(13),
|
||||
base = buildIntegralFinancialTables(p);
|
||||
p.dividendsByPeriod = Array(13).fill('25.25');
|
||||
const updated = reload(p),
|
||||
tables = buildIntegralFinancialTables(updated);
|
||||
assert.equal(forecastBusinessPlan(updated).rows[0].dividends, '25.25');
|
||||
for (let col = 1; col <= 13; col++) {
|
||||
assert.equal(
|
||||
cell(tables, 'profit-loss', 'Lucro líquido', col),
|
||||
cell(base, 'profit-loss', 'Lucro líquido', col),
|
||||
);
|
||||
const cents = (s) => BigInt(s.replace('.', ''));
|
||||
assert.equal(
|
||||
cents(cell(base, 'balance', 'Capital e resultados', col)) -
|
||||
cents(cell(tables, 'balance', 'Capital e resultados', col)),
|
||||
2525n * BigInt(col),
|
||||
);
|
||||
assert.equal(
|
||||
cents(cell(base, 'cashflow', 'Caixa final', col)) -
|
||||
cents(cell(tables, 'cashflow', 'Caixa final', col)),
|
||||
2525n * BigInt(col),
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'balance', 'Diferença do balanço', col),
|
||||
'0.00',
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
cell(tables, 'cashflow', 'Dividendos distribuídos', 14),
|
||||
'303.00',
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'cashflow', 'Dividendos distribuídos', 15),
|
||||
'25.25',
|
||||
);
|
||||
p.dividendsByPeriod[0] = '-1';
|
||||
assert.throws(() => forecastBusinessPlan(p));
|
||||
p.dividendsByPeriod = ['25'];
|
||||
assert.throws(() => forecastBusinessPlan(p));
|
||||
});
|
||||
|
||||
void test('operating components replace rather than add the old aggregate; capital splits reconcile and survive recovery', () => {
|
||||
const p = financialReportFixture(13);
|
||||
p.operatingExpenseLines = [
|
||||
{ label: 'Rendas', monthlyAmount: '10.25' },
|
||||
{ label: 'Seguros', monthlyAmount: '20.75' },
|
||||
];
|
||||
p.fundingBreakdown = {
|
||||
ownerCapital: '200.25',
|
||||
investorCapital: '300.25',
|
||||
additionalCapital: '99.50',
|
||||
};
|
||||
const recovered = reload(p);
|
||||
assert.deepEqual(recovered.operatingExpenseLines, p.operatingExpenseLines);
|
||||
assert.deepEqual(recovered.fundingBreakdown, p.fundingBreakdown);
|
||||
const tables = buildIntegralFinancialTables(recovered);
|
||||
assert.equal(
|
||||
forecastBusinessPlan(recovered).rows[0].operatingExpenses,
|
||||
'31.00',
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'profit-loss', 'Despesas operacionais', 14),
|
||||
'372.00',
|
||||
);
|
||||
assert.equal(cell(tables, 'profit-loss', 'Despesa: Rendas', 14), '123.00');
|
||||
assert.equal(cell(tables, 'funding', 'Capital do investidor', 1), '300.25');
|
||||
assert.equal(cell(tables, 'balance', 'Diferença do balanço', 13), '0.00');
|
||||
recovered.monthlyOperatingExpenses = '';
|
||||
recovered.monthlyOperatingExpensesByPeriod = [''];
|
||||
assert.equal(
|
||||
forecastBusinessPlan(recovered).rows[0].operatingExpenses,
|
||||
'31.00',
|
||||
);
|
||||
p.equity = '601';
|
||||
assert.throws(() => forecastBusinessPlan(p), /capital discriminado/);
|
||||
p.equity = '600';
|
||||
p.operatingExpenseLines[0].monthlyAmount = '';
|
||||
assert.throws(() => forecastBusinessPlan(p));
|
||||
assert.equal(reload({ ...p, dividendsByPeriod: [5] }), null);
|
||||
});
|
||||
|
||||
void test('the full example shares the saved snapshot and its eleven tables and exports change together, leaving investor inputs untouched', async () => {
|
||||
const p = financialReportFixture(13),
|
||||
annual = newAnnualReferencePlan();
|
||||
annual.years[0].sales = '14537.25';
|
||||
p.annualExampleSnapshot = serializeAnnualExampleSnapshot(annual);
|
||||
p.reportSource = 'annual_example';
|
||||
const before = forecastBusinessPlan(p),
|
||||
recovered = reload(p);
|
||||
const tables = buildAnnualExampleTables(recovered);
|
||||
assert.equal(tables.length, 11);
|
||||
assert.equal(cell(tables, 'sales', 'Vendas totais', 37), '14537.25');
|
||||
assert.equal(cell(tables, 'balance', 'Diferença do balanço', 1), '0.00');
|
||||
assert.equal(
|
||||
cell(tables, 'personnel', 'Folha de pagamento agregada', 37),
|
||||
'2100.00',
|
||||
);
|
||||
assert.deepEqual(forecastBusinessPlan(recovered), before);
|
||||
const report = createProjectDossierReport(
|
||||
{
|
||||
project_title: 'QA sintético',
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(recovered),
|
||||
},
|
||||
{
|
||||
selectedSections: new Set([
|
||||
'finance',
|
||||
'market',
|
||||
'execution',
|
||||
'team',
|
||||
]),
|
||||
generatedAt: '2026-11-20T12:00:00Z',
|
||||
},
|
||||
);
|
||||
const all = report.sections.flatMap((s) => s.tables ?? []);
|
||||
assert.equal(all.length, 11);
|
||||
assert.deepEqual(
|
||||
all.find((t) => t.id === 'sales'),
|
||||
tables.find((t) => t.id === 'sales'),
|
||||
);
|
||||
const html = await createProjectDossierPrintHtml(report, []);
|
||||
assert.match(html, /14 537,25/);
|
||||
assert.match(html, /Exemplo sintético/);
|
||||
const blob = await generateProjectDossierDocx(report, []),
|
||||
zip = await JSZip.loadAsync(
|
||||
blob instanceof Blob ? await blob.arrayBuffer() : blob,
|
||||
),
|
||||
xml = await zip.file('word/document.xml').async('string');
|
||||
assert.match(xml, /14 537,25/);
|
||||
assert.match(xml, /Capital por mobilizar/);
|
||||
recovered.reportSource = 'investor';
|
||||
assert.equal(
|
||||
buildIntegralFinancialTables(recovered)
|
||||
.find((t) => t.id === 'sales')
|
||||
.rows.find((r) => r[0] === 'Vendas totais')[1],
|
||||
'1000.00',
|
||||
);
|
||||
});
|
||||
|
||||
void test('financial warnings use the actual report metrics, remain non-blocking and reach print exports', async () => {
|
||||
const p = financialReportFixture(12);
|
||||
p.products[0].unitVariableCost = '90';
|
||||
p.bankLoanProceeds = '30000';
|
||||
p.equity = '0';
|
||||
p.salesCollectionLagMonths = 4;
|
||||
p.applyAnnualGrowth = false;
|
||||
p.annualGrowthPercent = '150';
|
||||
p.monthlyInventoryPurchases = '900';
|
||||
p.monthlyVariableCostPayments = '900';
|
||||
const tables = buildIntegralFinancialTables(p);
|
||||
assert.ok(
|
||||
tables.every((t) => !t.issues.length),
|
||||
JSON.stringify(tables.flatMap((t) => t.issues)),
|
||||
);
|
||||
const warnings = financialPlanWarnings(p, tables),
|
||||
ids = warnings.map((w) => w.id);
|
||||
for (const id of [
|
||||
'loss',
|
||||
'margin',
|
||||
'break-even',
|
||||
'cash',
|
||||
'growth',
|
||||
'credit',
|
||||
'debt',
|
||||
'capital',
|
||||
]) {
|
||||
// Cash may be abundant because the declared loan is large; test that condition separately.
|
||||
if (id !== 'cash')
|
||||
assert.ok(
|
||||
ids.some((s) => s.endsWith('-' + id)),
|
||||
id,
|
||||
);
|
||||
}
|
||||
const low = structuredClone(tables);
|
||||
low
|
||||
.find((t) => t.id === 'cashflow')
|
||||
.rows.find((r) => r[0] === 'Caixa final')[13] = '0.00';
|
||||
assert.ok(
|
||||
financialPlanWarnings(p, low).some((w) => w.id.endsWith('-cash')),
|
||||
);
|
||||
const report = createProjectDossierReport(
|
||||
{ business_plan_snapshot: serializeBusinessPlanSnapshot(p) },
|
||||
{
|
||||
selectedSections: new Set(['finance']),
|
||||
generatedAt: '2026-11-20T12:00:00Z',
|
||||
},
|
||||
);
|
||||
const html = await createProjectDossierPrintHtml(report, []);
|
||||
assert.match(html, /Aviso não bloqueante/);
|
||||
assert.match(html, /margem bruta é baixa/);
|
||||
const integral = createIntegralFinancialReport({
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(p),
|
||||
});
|
||||
assert.match(
|
||||
await createProjectDossierPrintHtml(integral, []),
|
||||
/margem bruta é baixa/,
|
||||
);
|
||||
});
|
||||
|
||||
void test('new declarations retain strict recovery boundaries and scenario adjustments reach operating components', () => {
|
||||
const p = financialReportFixture(12);
|
||||
p.operatingExpenseLines = [{ label: 'Renda', monthlyAmount: '10.25' }];
|
||||
p.dividendsByPeriod = Array(12).fill('2.25');
|
||||
const adjustment = {
|
||||
unitVolumePercent: '0',
|
||||
unitPricePercent: '0',
|
||||
unitCostPercent: '0',
|
||||
operatingCostsPercent: '100',
|
||||
cashCollectionsPercent: '0',
|
||||
};
|
||||
p.scenarioAdjustments = {
|
||||
favorable: adjustment,
|
||||
unfavorable: { ...adjustment, operatingCostsPercent: '-50' },
|
||||
};
|
||||
const scenarios = compareBusinessScenarios(p);
|
||||
assert.equal(scenarios.favorable.result.rows[0].operatingExpenses, '20.50');
|
||||
assert.equal(
|
||||
scenarios.unfavorable.result.rows[0].operatingExpenses,
|
||||
'5.13',
|
||||
);
|
||||
assert.match(exportBusinessPlanCsv(p), /Dividendos distribuídos/);
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(
|
||||
serializeBusinessPlanSnapshot({
|
||||
...p,
|
||||
dividendsByPeriod: ['0', null],
|
||||
}),
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(
|
||||
serializeBusinessPlanSnapshot({
|
||||
...p,
|
||||
fundingBreakdown: { ownerCapital: 0 },
|
||||
}),
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(
|
||||
serializeBusinessPlanSnapshot({ ...p, reportSource: 'foreign' }),
|
||||
),
|
||||
null,
|
||||
);
|
||||
p.fundingBreakdown = {
|
||||
ownerCapital: '1',
|
||||
investorCapital: '0',
|
||||
additionalCapital: '0',
|
||||
};
|
||||
assert.throws(() => forecastBusinessPlan(p), /capital discriminado/);
|
||||
});
|
||||
|
||||
void test('version 18 protects the added financial semantics and preserves prior payables, CAE and the legacy version 17 inputs', () => {
|
||||
const legacy = financialReportFixture(12);
|
||||
legacy.economicClassification = selectPlanCae('55111');
|
||||
legacy.openingPayablesInstallments = [{ month: 2, percent: '50' }];
|
||||
assert.equal(JSON.parse(serializeBusinessPlanSnapshot(legacy)).version, 17);
|
||||
const p = { ...legacy, dividendsByPeriod: Array(12).fill('0') };
|
||||
const snapshot = serializeBusinessPlanSnapshot(p);
|
||||
assert.equal(JSON.parse(snapshot).version, 18);
|
||||
const recovered = restoreBusinessPlanSnapshot(snapshot);
|
||||
assert.deepEqual(
|
||||
recovered.economicClassification,
|
||||
legacy.economicClassification,
|
||||
);
|
||||
assert.deepEqual(
|
||||
recovered.openingPayablesInstallments,
|
||||
legacy.openingPayablesInstallments,
|
||||
);
|
||||
const downgraded = JSON.parse(snapshot);
|
||||
downgraded.version = 17;
|
||||
assert.equal(restoreBusinessPlanSnapshot(JSON.stringify(downgraded)), null);
|
||||
assert.deepEqual(
|
||||
forecastBusinessPlan(recovered),
|
||||
forecastBusinessPlan({ ...legacy, dividendsByPeriod: undefined }),
|
||||
);
|
||||
});
|
||||
|
||||
void test('actual editor controls preserve declarations through snapshot reload and an explicit return from example to investor report', () => {
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/financial-plan-details.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
const module = { exports: {} },
|
||||
require = createRequire(import.meta.url);
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(name) =>
|
||||
name === '@/lib/business-plan-guidance' ? guidance : require(name),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
let plan = financialReportFixture(13);
|
||||
const render = () =>
|
||||
module.exports.FinancialPlanDetails({
|
||||
plan,
|
||||
onChange: (next) => {
|
||||
plan = reload(next);
|
||||
assert.ok(plan);
|
||||
},
|
||||
});
|
||||
const nodes = (n) =>
|
||||
Array.isArray(n)
|
||||
? n.flatMap(nodes)
|
||||
: n && typeof n === 'object'
|
||||
? [n, ...nodes(n.props?.children)]
|
||||
: [];
|
||||
const text = (n) =>
|
||||
typeof n === 'string'
|
||||
? n
|
||||
: Array.isArray(n)
|
||||
? n.map(text).join('')
|
||||
: n && typeof n === 'object'
|
||||
? text(n.props?.children)
|
||||
: '';
|
||||
const field = (label) => {
|
||||
const node = nodes(render()).find(
|
||||
(n) => n.type === 'label' && text(n).includes(label),
|
||||
);
|
||||
assert.ok(node, label);
|
||||
return nodes(node).find(
|
||||
(n) => n.type === 'input' || n.type === 'select',
|
||||
);
|
||||
};
|
||||
field('Projectar os anos seguintes').props.onChange({
|
||||
target: { checked: true },
|
||||
});
|
||||
assert.equal(plan.applyAnnualGrowth, true);
|
||||
field('Prazo de recebimento a crédito').props.onChange({
|
||||
target: { value: '91' },
|
||||
});
|
||||
assert.equal(plan.creditTermDays, '91');
|
||||
field('Planear dividendos').props.onChange({ target: { checked: true } });
|
||||
field('Dividendos, mês 1').props.onChange({ target: { value: '12.25' } });
|
||||
assert.equal(plan.dividendsByPeriod[0], '12.25');
|
||||
const select = () => nodes(render()).find((n) => n.type === 'select');
|
||||
select().props.onChange({ target: { value: 'annual_example' } });
|
||||
assert.equal(plan.reportSource, 'annual_example');
|
||||
assert.ok(plan.annualExampleSnapshot);
|
||||
assert.equal(buildAnnualExampleTables(plan).length, 11);
|
||||
select().props.onChange({ target: { value: 'investor' } });
|
||||
assert.equal(plan.reportSource, 'investor');
|
||||
assert.equal(plan.dividendsByPeriod[0], '12.25');
|
||||
assert.equal(plan.products[0].monthlyUnits, '10');
|
||||
});
|
||||
|
||||
void test('the credit warning uses the declared 90-day boundary without converting or changing monthly cash flows', () => {
|
||||
const p = financialReportFixture(12),
|
||||
baseline = forecastBusinessPlan(p);
|
||||
for (const days of ['0', '30', '90', '91', '365']) {
|
||||
p.creditTermDays = days;
|
||||
const restored = reload(p);
|
||||
assert.equal(restored.creditTermDays, days);
|
||||
assert.deepEqual(forecastBusinessPlan(restored), baseline);
|
||||
assert.equal(
|
||||
financialPlanWarnings(
|
||||
restored,
|
||||
buildIntegralFinancialTables(restored),
|
||||
).some((w) => w.id.endsWith('-credit')),
|
||||
Number(days) > 90,
|
||||
);
|
||||
}
|
||||
for (const invalid of ['-1', '366', '30.5', 'abc']) {
|
||||
p.creditTermDays = invalid;
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/prazo entre 0 e 365 dias/,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import JSZip from 'jszip';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import { buildFinancialRatiosTable } from '../../resources/js/lib/financial-ratios-report.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import {
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { calculateDecisionRatios } from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
import {
|
||||
createProjectDossierReport,
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
const fixture = () => {
|
||||
const plan = financialReportFixture(13),
|
||||
source = buildIntegralFinancialTables(plan),
|
||||
b = source.find((t) => t.id === 'balance');
|
||||
plan.ratioCurrentBalances = {
|
||||
assetsByMonth: b.rows
|
||||
.find((r) => r[0] === 'Caixa líquida')
|
||||
.slice(1, 14),
|
||||
liabilitiesByMonth: b.rows
|
||||
.find((r) => r[0] === 'Total do passivo')
|
||||
.slice(1, 14),
|
||||
};
|
||||
return { plan, source };
|
||||
};
|
||||
const get = (t, label) => t.rows.find((r) => r[0] === label);
|
||||
|
||||
void test('a missing classification in later months does not erase an available earlier liquidity ratio', () => {
|
||||
const { plan, source } = fixture();
|
||||
plan.ratioCurrentBalances = {
|
||||
assetsByMonth: ['1180'],
|
||||
liabilitiesByMonth: ['10'],
|
||||
};
|
||||
const table = buildFinancialRatiosTable(plan, source);
|
||||
assert.equal(get(table, 'Liquidez corrente')[1], '118,00×');
|
||||
assert.equal(get(table, 'Liquidez corrente')[2], 'Por determinar');
|
||||
assert.equal(table.issues.length, 24);
|
||||
assert.equal(new Set(table.issues).size, 24);
|
||||
assert.ok(
|
||||
table.issues.every((issue) =>
|
||||
/corrente — mês (?:[2-9]|1[0-3]):/.test(issue),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
void test('annual comparison uses two complete years and permits growth above 100 percent', () => {
|
||||
const plan = financialReportFixture(24);
|
||||
plan.products[0].monthlyUnitsByPeriod = [
|
||||
...Array(12).fill('10'),
|
||||
...Array(12).fill('25'),
|
||||
];
|
||||
const table = buildFinancialRatiosTable(plan);
|
||||
assert.equal(get(table, 'Crescimento das vendas').at(-1), '150,00%');
|
||||
assert.equal(get(table, 'Crescimento das vendas')[13], '150,00%');
|
||||
});
|
||||
void test('approved formulas are presented from the same monthly and annual statements, without summing ratios', () => {
|
||||
const { plan, source } = fixture();
|
||||
const t = buildFinancialRatiosTable(plan, source);
|
||||
assert.equal(t.issues.length, 0);
|
||||
const approved = calculateDecisionRatios(
|
||||
{
|
||||
cash: '1180',
|
||||
receivables: '0',
|
||||
inventory: '0',
|
||||
otherCurrentAssets: '0',
|
||||
longTermAssets: '590',
|
||||
accumulatedDepreciation: '0',
|
||||
currentLiabilities: '10',
|
||||
longTermLiabilities: '0',
|
||||
paidCapital: '1600',
|
||||
retainedResults: '-100',
|
||||
periodResult: '260',
|
||||
},
|
||||
'1000',
|
||||
);
|
||||
assert.equal(
|
||||
get(t, 'Liquidez corrente')[1],
|
||||
approved.currentLiquidity.toFixed(2).replace('.', ',') + '×',
|
||||
);
|
||||
assert.equal(
|
||||
get(t, 'Endividamento (passivo/activo)')[1],
|
||||
(approved.debtAssets * 100).toFixed(2).replace('.', ',') + '%',
|
||||
);
|
||||
assert.equal(get(t, 'Margem líquida')[1], '26,00%');
|
||||
assert.equal(get(t, 'Retorno do capital')[1], '14,77%');
|
||||
assert.equal(get(t, 'Margem líquida')[14], '26,00%');
|
||||
assert.equal(get(t, 'Retorno do capital')[14], '67,53%');
|
||||
assert.equal(get(t, 'Liquidez corrente')[14], '35,50×');
|
||||
assert.equal(get(t, 'Crescimento das vendas')[1], 'Por determinar');
|
||||
assert.equal(get(t, 'Crescimento das vendas')[2], '0,00%');
|
||||
assert.equal(get(t, 'Crescimento das vendas').at(-1), 'Por determinar');
|
||||
});
|
||||
void test('inconsistent balance blocks only dependent indicators; missing liquidity does not invent maturity', () => {
|
||||
const { plan, source } = fixture();
|
||||
delete plan.ratioCurrentBalances;
|
||||
let t = buildFinancialRatiosTable(plan, source);
|
||||
assert.equal(get(t, 'Liquidez corrente')[1], 'Por determinar');
|
||||
assert.equal(get(t, 'Margem líquida')[1], '26,00%');
|
||||
assert.equal(get(t, 'Retorno do capital')[1], '14,77%');
|
||||
source
|
||||
.find((t) => t.id === 'balance')
|
||||
.rows.find((r) => r[0] === 'Diferença do balanço')[1] = '0.01';
|
||||
t = buildFinancialRatiosTable(plan, source);
|
||||
assert.equal(get(t, 'Retorno do capital')[1], 'Por determinar');
|
||||
assert.equal(get(t, 'Endividamento (passivo/activo)')[1], 'Por determinar');
|
||||
assert.equal(get(t, 'Margem líquida')[1], '26,00%');
|
||||
assert.equal(get(t, 'Crescimento das vendas')[2], '0,00%');
|
||||
source
|
||||
.find((t) => t.id === 'profit-loss')
|
||||
.issues.push('Imposto indeterminado');
|
||||
assert.equal(
|
||||
get(buildFinancialRatiosTable(plan, source), 'Margem líquida')[1],
|
||||
'Por determinar',
|
||||
);
|
||||
});
|
||||
void test('zero denominators, invalid classification and malformed snapshots remain indeterminate; inputs unchanged', () => {
|
||||
const { plan, source } = fixture();
|
||||
const before = JSON.stringify(source);
|
||||
plan.ratioCurrentBalances.assetsByMonth[0] = '999999';
|
||||
let t = buildFinancialRatiosTable(plan, source);
|
||||
assert.equal(get(t, 'Liquidez corrente')[1], 'Por determinar');
|
||||
assert.equal(JSON.stringify(source), before);
|
||||
plan.ratioCurrentBalances.assetsByMonth[0] = '1180';
|
||||
plan.ratioCurrentBalances.liabilitiesByMonth[0] = '0';
|
||||
assert.equal(
|
||||
get(buildFinancialRatiosTable(plan, source), 'Liquidez corrente')[1],
|
||||
'Por determinar',
|
||||
);
|
||||
plan.ratioCurrentBalances.assetsByMonth[0] = { bad: true };
|
||||
assert.doesNotThrow(() => buildFinancialRatiosTable(plan, source));
|
||||
source
|
||||
.find((t) => t.id === 'sales')
|
||||
.rows.find((r) => r[0] === 'Vendas totais')[1] = '0.00';
|
||||
t = buildFinancialRatiosTable(plan, source);
|
||||
assert.equal(get(t, 'Margem líquida')[1], 'Por determinar');
|
||||
assert.equal(get(t, 'Crescimento das vendas')[2], 'Por determinar');
|
||||
});
|
||||
void test('ratio classifications persist in the existing snapshot and export as the final financial table', async () => {
|
||||
const { plan } = fixture(),
|
||||
snapshot = serializeBusinessPlanSnapshot(plan),
|
||||
recovered = restoreBusinessPlanSnapshot(snapshot);
|
||||
assert.deepEqual(recovered.ratioCurrentBalances, plan.ratioCurrentBalances);
|
||||
assert.deepEqual(
|
||||
buildFinancialRatiosTable(recovered),
|
||||
buildFinancialRatiosTable(plan),
|
||||
);
|
||||
const report = createProjectDossierReport(
|
||||
{ business_plan_snapshot: snapshot },
|
||||
{ selectedSections: new Set(['finance']) },
|
||||
);
|
||||
assert.equal(report.sections[0].tables.length, 8);
|
||||
assert.equal(report.sections[0].tables.at(-1).id, 'ratios');
|
||||
assert.match(
|
||||
await createProjectDossierPrintHtml(report, []),
|
||||
/Rácios financeiros/,
|
||||
);
|
||||
const doc = await generateProjectDossierDocx(report, []),
|
||||
zip = await JSZip.loadAsync(
|
||||
doc instanceof Blob ? await doc.arrayBuffer() : doc,
|
||||
);
|
||||
assert.match(
|
||||
await zip.file('word/document.xml').async('string'),
|
||||
/Rácios financeiros/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
printedCents,
|
||||
reconcileFinancialReference,
|
||||
} from '../../tools/financial-reference-reconciliation.mjs';
|
||||
import { newAnnualReferencePlan } from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
|
||||
const source = fs.readFileSync(
|
||||
new URL('./fixtures/financial-reference-2025.txt', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const report = reconcileFinancialReference(source);
|
||||
const item = (id) => {
|
||||
const record = report.checks.find((check) => check.id === id);
|
||||
assert.ok(record, id);
|
||||
return record;
|
||||
};
|
||||
|
||||
void test('printed amounts retain thousands, decimal cents and parentheses without floating-point rounding', () => {
|
||||
assert.equal(printedCents('1.234,56'), 123456n);
|
||||
assert.equal(printedCents('(416)'), -41600n);
|
||||
assert.equal(printedCents('0,01'), 1n);
|
||||
assert.equal(printedCents('501.475'), 50147500n);
|
||||
for (const invalid of ['', '1,234', '1.00', 'unknown', '17%'])
|
||||
assert.throws(() => printedCents(invalid));
|
||||
});
|
||||
|
||||
void test('the one-unit imbalance is traced through the printed cash-spending subtotal without changing annual data', () => {
|
||||
const approvedBefore = JSON.stringify(newAnnualReferencePlan());
|
||||
assert.deepEqual(report.oneUnitTrace, {
|
||||
approvedCashSpent: '15783.00',
|
||||
componentCashSpent: '15782.00',
|
||||
approvedClosingCash: '90756.00',
|
||||
componentOnlyClosingCash: '90757.00',
|
||||
approvedAssets: '501475.00',
|
||||
componentOnlyAssets: '501476.00',
|
||||
liabilitiesAndCapital: '501476.00',
|
||||
componentOnlyIsDiagnosticNotCorrection: true,
|
||||
});
|
||||
assert.equal(item('cash.2025_spending_components').difference, '-1.00');
|
||||
assert.equal(
|
||||
item('balance.2025_assets_vs_liabilities_capital').difference,
|
||||
'-1.00',
|
||||
);
|
||||
assert.equal(report.annualTotalsChanged, false);
|
||||
assert.equal(report.applicationFormulasChanged, false);
|
||||
assert.equal(JSON.stringify(newAnnualReferencePlan()), approvedBefore);
|
||||
});
|
||||
|
||||
void test('sales, direct costs, gross margin and payroll reconcile at total level but listed revenue and cost lines are incomplete', () => {
|
||||
for (const id of [
|
||||
'sales.months_to_2025',
|
||||
'direct_costs.months_to_2025',
|
||||
'gross_margin.months_to_2025',
|
||||
'payroll.months_to_2025',
|
||||
])
|
||||
assert.equal(item(id).matches, true);
|
||||
assert.equal(item('sales.listed_lines.2025').difference, '-3652.00');
|
||||
assert.equal(item('costs.listed_lines.2025').difference, '-2243.00');
|
||||
assert.equal(item('sales.listed_lines.2026').difference, '-8250.00');
|
||||
assert.equal(item('sales.listed_lines.2027').difference, '-9350.00');
|
||||
for (const record of report.checks.filter(
|
||||
(check) =>
|
||||
check.id.startsWith('sales.line.') ||
|
||||
check.id.startsWith('costs.line.'),
|
||||
))
|
||||
assert.equal(record.matches, true);
|
||||
});
|
||||
|
||||
void test('the stated reference rate reconstructs cent precision and preserves annual payroll charges and profit', () => {
|
||||
const precise = report.payrollRecomposition;
|
||||
assert.equal(precise.rate, '15%');
|
||||
assert.deepEqual(precise.monthlyCharges, Array(12).fill('26.25'));
|
||||
assert.deepEqual(precise.monthlyOperating, Array(12).fill('201.25'));
|
||||
assert.equal(precise.monthlyNetProfit[8], '-0.25');
|
||||
assert.equal(precise.chargesAnnualCheck.calculated, '315.00');
|
||||
assert.equal(precise.operatingAnnualCheck.calculated, '2415.00');
|
||||
assert.equal(precise.profitAnnualCheck.calculated, '-416.00');
|
||||
assert.ok(
|
||||
precise.chargesAnnualCheck.matches &&
|
||||
precise.operatingAnnualCheck.matches &&
|
||||
precise.profitAnnualCheck.matches,
|
||||
);
|
||||
assert.equal(precise.scope, 'reference_arithmetic_only_not_a_fiscal_rule');
|
||||
assert.equal(
|
||||
item('net_profit.printed_months_to_2025').calculated,
|
||||
'-413.00',
|
||||
);
|
||||
});
|
||||
|
||||
void test('cash discrepancies and ambiguous duplicate labels remain explicit rather than being reclassified as investment', () => {
|
||||
assert.equal(
|
||||
item('cash.Caixa proveniente de contas a receber').difference,
|
||||
'2.00',
|
||||
);
|
||||
assert.equal(item('cash.Subtotal de Dinheiro Gasto').difference, '-1.00');
|
||||
assert.equal(item('cash.Fluxo de Caixa Líquido').calculated, '755.00');
|
||||
assert.equal(report.balanceMonths.at(-1).componentDifference, '-1.00');
|
||||
assert.deepEqual(
|
||||
report.ambiguousCashLabel.map((row) => row.sum),
|
||||
['0.00', '16538.00'],
|
||||
);
|
||||
assert.equal(report.status, 'BLOCKED_SOURCE_PRECISION_OR_COMPLETENESS');
|
||||
assert.equal(report.missing.length, 4);
|
||||
});
|
||||
|
||||
void test('normalised labels preserve the same numerical conclusions and missing source rows do not become zeros', () => {
|
||||
assert.deepEqual(
|
||||
reconcileFinancialReference(source.normalize('NFD')).checks,
|
||||
report.checks,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
reconcileFinancialReference(
|
||||
source.replaceAll(
|
||||
'Caixa proveniente de contas a receber',
|
||||
'Rubrica retirada',
|
||||
),
|
||||
),
|
||||
/Rubrica em falta/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { financialReportFixture } from './integral-financial-plan.mjs';
|
||||
import { serializeBusinessPlanSnapshot } from '../../../resources/js/lib/business-financial-plan.ts';
|
||||
export function complementaryFixture() {
|
||||
const plan=financialReportFixture(13);
|
||||
plan.marketAnalysis={baseYear:'2027',years:'3',segments:[{label:'Segmento ilustrativo',customers:'100',growthPercent:'10',basis:'Hipótese sintética de QA; não é procura observada.'}]};
|
||||
const team=[{competency:'Operação',department:'Operações',quantity:'2',monthly_salary:'100.00',start_month:'1',end_month:'13',state:'gap',action:'',estimated_cost:'',due_date:''}];
|
||||
const milestones=[{title:'Preparação ilustrativa',start_date:'2027-01-01',due_date:'2027-02-01',responsible:'Responsável sintético',department:'Operações',status:'planned',planned_amount:'100.25',actual_amount:''}];
|
||||
return {plan,team,milestones,draft:{currency:'MZN',project_title:'QA complementar sintético',business_plan_snapshot:serializeBusinessPlanSnapshot(plan),project_team_snapshot:JSON.stringify(team),project_execution_snapshot:JSON.stringify(milestones)}};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { financialReportFixture } from './integral-financial-plan.mjs';
|
||||
|
||||
export function dayTermsFixture(periods = 3) {
|
||||
const p = financialReportFixture(periods);
|
||||
const schedule = amount => Array.from({ length: periods }, (_, i) => i === 0 ? amount : '0');
|
||||
p.products = [{ label: 'Serviço sintético F20-A', monthlyUnits: '0', unitPrice: '1000', unitVariableCost: '0', monthlyUnitsByPeriod: schedule('1') }];
|
||||
p.useInventoryPurchaseSchedule = true;
|
||||
p.inventoryPurchaseSchedule = schedule('400').map(amount => ({ amount, leadMonths: 0 }));
|
||||
p.monthlyOperatingExpensesByPeriod = schedule('100');
|
||||
p.monthlyPayrollExpense = '0';
|
||||
p.monthlyPayrollPayments = '0';
|
||||
p.monthlyCollections = '777'; // Kept, never added to the opted-in sales agenda.
|
||||
p.reportAssumptions.manualCollectionsKind = 'sales';
|
||||
p.dayTerms = { sales: true, purchases: true, services: true, operations: [
|
||||
operation('sales', '1000'), operation('purchases', '400'), operation('services', '100'),
|
||||
] };
|
||||
return p;
|
||||
}
|
||||
|
||||
export function operation(kind, amount) {
|
||||
return { kind, month: 1, originId: kind + '-1', parcelId: '1', amount, termDays: '30',
|
||||
recognitionBasis: 'monthly', recognitionDate: '', originBasis: 'recognition', originDate: '' };
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
# Extract of user-supplied financial reference; no operational data.
|
||||
# NFC labels; original printed amounts preserved. No unrounded amounts available.
|
||||
# Original SHA256: 93630807245726aa782825c7ee8d3b744ca413eb9500f6374ba3ce5d801d75a8
|
||||
|
||||
Tabela: Previsão de Vendas
|
||||
Vendas 2025 2026 2027
|
||||
Publicidade 2.137 3.000 3.500
|
||||
Intermediação Comercial 5.336 6.000 6.500
|
||||
Comercialização de Commodities 3.211 4.000 4.250
|
||||
Formação 201 250 275
|
||||
Vendas Totais 14.537 21.500 23.875
|
||||
Custo Direto das Vendas 2025 2026 2027
|
||||
Publicidade 1.595 2.500 3.000
|
||||
Intermediação Comercial 4.273 5.500 6.000
|
||||
Comercialização de Commodities 3.211 3.750 4.000
|
||||
Formação 139 450 475
|
||||
Marketing 1.077 1.100 1.200
|
||||
Subtotal Direct Cost of Sales 12.538 16.200 18.325
|
||||
|
||||
Tabela: Previsão de Vendas
|
||||
Publicidade 100 110 121 133 140 161 177 195 215 237 261 287
|
||||
Intermediação Comercial 250 275 302 332 365 402 442 486 535 588 647 712
|
||||
Comercialização de Commodities 150 165 182 200 220 242 266 293 322 354 389 428
|
||||
Formação 10 11 12 13 14 15 16 18 20 22 24 26
|
||||
Vendas Totais 680 748 824 905 990 1.095 1.203 1.324 1.458 1.604 1.765 1.941
|
||||
Publicidade 75 82 90 99 109 120 132 145 160 176 194 213
|
||||
Intermediação Comercial 200 220 242 266 293 322 354 389 428 471 518 570
|
||||
Comercialização de Commodities 150 165 182 200 220 242 266 293 322 354 389 428
|
||||
Formação 6 7 8 9 10 11 12 13 14 15 16 18
|
||||
Subtotal Custo Direto das Vendas 586 644 710 781 860 945 1.038 1.142 1.257 1.383 1.520 1.672
|
||||
|
||||
Tabela: Lucros e Perdas
|
||||
2025 2026 2027
|
||||
Vendas 14.537 21.500 23.875
|
||||
Custo Direto das Vendas 12.538 16.200 18.325
|
||||
Outros custos de vendas 0 0 0
|
||||
Custo Total das Vendas 12.538 16.200 18.325
|
||||
Margem bruta 1.999 5.300 5.550
|
||||
Folha de pagamento 2.100 2.800 2.800
|
||||
Marketing/Promoção 0 0 0
|
||||
Depreciação 0 0 0
|
||||
Rendas 0 0 0
|
||||
Utilidades 0 0 0
|
||||
Seguros 0 0 0
|
||||
Impostos sobre Folhas de Pagamento 315 420 420
|
||||
Outros 0 0 0
|
||||
Despesas Operacionais Totais 2.415 3.220 3.220
|
||||
Lucro antes de juros e impostos (416) 2.080 2.330
|
||||
EBITDA (416) 2.080 2.330
|
||||
Despesa com juros 0 0 0
|
||||
Impostos Incorridos 0 624 699
|
||||
Lucro Líquido (416) 1.456 1.631
|
||||
|
||||
Tabela: Lucros e Perdas
|
||||
Vendas 680 748 824 905 990 1.095 1.203 1.324 1.458 1.604 1.765 1.941
|
||||
Custo Direto das Vendas 586 644 710 781 860 945 1.038 1.142 1.257 1.383 1.520 1.672
|
||||
Outros custos de vendas 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Custo Total das Vendas 586 644 710 781 860 945 1.038 1.142 1.257 1.383 1.520 1.672
|
||||
Margem bruta 94 104 114 124 130 150 165 182 201 221 245 269
|
||||
Folha de pagamento 175 175 175 175 175 175 175 175 175 175 175 175
|
||||
Marketing/Promoção 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Depreciação 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Aluguer 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Serviços públicos 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Seguros 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Impostos sobre Folhas de Pagamento 15% 26 26 26 26 26 26 26 26 26 26 26 26
|
||||
Outros 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Despesas Operacionais Totais 201 201 201 201 201 201 201 201 201 201 201 201
|
||||
Lucro antes de juros e impostos (107) (97) (87) (77) (71) (51) (36) (19) (0) 20 44 68
|
||||
EBITDA (107) (97) (87) (77) (71) (51) (36) (19) (0) 20 44 68
|
||||
Despesa com juros 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Impostos Incorridos 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Lucro Líquido (107) (97) (87) (77) (71) (51) (36) (19) (0) 20 44 68
|
||||
|
||||
Tabela: Fluxo de Caixa
|
||||
2025 2026 2027
|
||||
Vendas em Dinheiro 10.903 16.125 17.906
|
||||
Caixa proveniente de contas a receber 3.165 5.150 5.892
|
||||
Subtotal de Caixa Proveniente das Operações 14.068 21.275 23.798
|
||||
Imposto sobre vendas, IVA, HST/GST recebidos 2.471 3.655 4.059
|
||||
Novo Endividamento Corrente 0 0 0
|
||||
Novos Outros Passivos (sem juros) 0 0 0
|
||||
Novos Passivos de Longo Prazo 0 0 0
|
||||
Vendas de Outros Activos Correntes 0 0 0
|
||||
Vendas de Activos de Longo Prazo 0 0 0
|
||||
Novo Investimento Recebido 0 0 0
|
||||
Subtotal de Dinheiro Recebido 16.539 24.930 27.857
|
||||
Despesas 2025 2026 2027
|
||||
Gastos em Dinheiro 2.100 2.800 2.800
|
||||
Pagamentos de Contas 11.211 17.468 19.263
|
||||
Subtotal gasto em operações 13.311 20.268 22.063
|
||||
Imposto sobre vendas, IVA, HST/GST pagos 2.471 3.655 4.059
|
||||
Reembolso do principal de empréstimos correntes 0 0 0
|
||||
Reembolso do principal de outros passivos 0 0 0
|
||||
Reembolso do principal de passivos de longo prazo 0 0 0
|
||||
Comprar Outros Activos Correntes 0 0 0
|
||||
Comprar Activos de longo prazo 0 0 0
|
||||
Dividends 0 0 0
|
||||
Subtotal de Dinheiro Gasto 15.783 23.923 26.122
|
||||
Fluxo de Caixa Líquido 756 1.007 1.735
|
||||
Cash Balance 90.756 91.763 93.498
|
||||
|
||||
Tabela: Fluxo de Caixa
|
||||
Vendas em Dinheiro 510 561 618 679 742 821 902 993 1.094 1.203 1.324 1.456
|
||||
Caixa proveniente de contas a receber 6 171 188 207 227 248 275 302 332 366 402 443
|
||||
Subtotal de Caixa Proveniente das Operações 516 732 806 885 969 1.070 1.177 1.295 1.426 1.569 1.726 1.898
|
||||
Imposto sobre vendas, IVA, HST/GST recebidos 17,00% 116 127 140 154 168 186 205 225 248 273 300 330
|
||||
Novo Endividamento Corrente 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Novos Outros Passivos (sem juros) 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Novos Passivos de Longo Prazo 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Vendas de Outros Activos Correntes 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Vendas de Activos de Longo Prazo 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Novo Investimento Recebido 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Novo Investimento Recebido 631 859 946 1.039 1.138 1.256 1.381 1.520 1.673 1.841 2.026 2.228
|
||||
Despesas provenientes das Operações 175 175 175 175 175 175 175 175 175 175 175 175
|
||||
Pagamentos de Contas 20 614 672 739 810 889 974 1.068 1.172 1.287 1.414 1.551
|
||||
Subtotal gasto em operações 195 789 847 914 985 1.064 1.149 1.243 1.347 1.462 1.589 1.726
|
||||
Imposto sobre vendas, IVA, HST/GST pagos 116 127 140 154 168 186 205 225 248 273 300 330
|
||||
Reembolso do principal do empréstimo corrente 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Outros passivos Reembolso do principal 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Reembolso de Principal de Passivos a Longo Prazo 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Reembolso de Principal de Passivos a Longo Prazo 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Comprar Activos de longo prazo 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Dividendos 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Subtotal de Dinheiro Gasto 311 916 988 1.067 1.153 1.250 1.354 1.468 1.595 1.735 1.889 2.056
|
||||
Fluxo de Caixa Líquido 320 (58) (42) (28) (16) 5 28 52 79 106 137 172
|
||||
Saldo de Caixa 90.320 90.263 90.221 90.193 90.177 90.183 90.210 90.262 90.341 90.447 90.584 90.756
|
||||
|
||||
Tabela: Balanço
|
||||
Ativos 2025 2026 2027
|
||||
Dinheiro 90.756 91.763 93.498
|
||||
Contas a receber 469 694 770
|
||||
Outros ativos correntes 150.000 150.000 150.000
|
||||
Total de ativos correntes 241.225 242.457 244.269
|
||||
Ativos de Longo Prazo 260.250 260.250 260.250
|
||||
Depreciação acumulada 0 0 0
|
||||
Total de Activos a Longo Prazo 260.250 260.250 260.250
|
||||
Total de Activos 501.475 502.707 504.519
|
||||
Passivos e Capital 2025 2026 2027
|
||||
Contas a pagar 1.642 1.417 1.598
|
||||
Empréstimos Correntes 0 0 0
|
||||
Outros passivos correntes 0 0 0
|
||||
Subtotais Passivos Correntes 1.642 1.417 1.598
|
||||
Passivos de Longo Prazo 0 0 0
|
||||
Total de Passivos 1.642 1.417 1.598
|
||||
Capital pago 1.825.250 1.825.250 1.825.250
|
||||
Lucros Retidos (1.325.000) (1.325.416) (1.323.960)
|
||||
Rendimentos (416) 1.456 1.631
|
||||
Total Capital 499.834 501.290 502.921
|
||||
Total de Passivos e Capital 501.475 502.707 504.519
|
||||
Património Líquido 499.834 501.290 502.921
|
||||
|
||||
Tabela: Balanço
|
||||
Dinheiro 90.000 90.320 90.263 90.221 90.193 90.177 90.183 90.210 90.262 90.341 90.447 90.584 90.756
|
||||
Contas a receber 0 164 181 199 219 239 265 291 320 352 388 427 469
|
||||
Outros Activos correntes 150.000 150.000 150.000 150.000 150.000 150.000 150.000 150.000 150.000 150.000 150.000 150.000 150.000
|
||||
Total de activos correntes 240.000 240.485 240.443 240.420 240.411 240.416 240.447 240.501 240.582 240.693 240.835 241.011 241.225
|
||||
Activos de Longo Prazo 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250
|
||||
Activos de Longo Prazo 0 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Total de Activos a Longo Prazo 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250 260.250
|
||||
Total de Activos 500.250 500.735 500.693 500.670 500.661 500.666 500.697 500.751 500.832 500.943 501.085 501.261 501.475
|
||||
Contas a pagar 0 592 648 712 780 857 939 1.029 1.129 1.240 1.362 1.495 1.642
|
||||
Empréstimos Correntes 0 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Outros passivos correntes 0 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Subtotais Passivos Correntes 0 592 648 712 780 857 939 1.029 1.129 1.240 1.362 1.495 1.642
|
||||
Passivos de Longo Prazo 0 0 0 0 0 0 0 0 0 0 0 0 0
|
||||
Total de Passivos 0 592 648 712 780 857 939 1.029 1.129 1.240 1.362 1.495 1.642
|
||||
Capital pago 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250 1.825.250
|
||||
Lucros Retidos (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000) (1.325.000)
|
||||
Rendimentos 0 (107) (205) (292) (369) (440) (492) (528) (547) (547) (528) (484) (416)
|
||||
Total Capital 500.250 500.143 500.046 499.958 499.881 499.810 499.758 499.722 499.703 499.703 499.722 499.766 499.834
|
||||
Total de Passivos e Capital Próprio 500.250 500.735 500.693 500.670 500.661 500.666 500.697 500.751 500.832 500.943 501.085 501.261 501.475
|
||||
Património Líquido 500.250 500.143 500.046 499.958 499.881 499.810 499.758 499.722 499.703 499.703 499.722 499.766 499.834
|
||||
@@ -0,0 +1,65 @@
|
||||
import { newReportAssumptions } from '../../../resources/js/lib/integral-financial-report.ts';
|
||||
|
||||
export function financialReportFixture(periods = 24) {
|
||||
const value = {
|
||||
currency: 'MZN',
|
||||
openingCash: '1000',
|
||||
assetInvestment: '600',
|
||||
equity: '600',
|
||||
products: [
|
||||
{
|
||||
label: 'Serviço declarado',
|
||||
monthlyUnits: '10',
|
||||
unitPrice: '100',
|
||||
unitVariableCost: '40',
|
||||
},
|
||||
],
|
||||
depreciationLifeMonths: 60,
|
||||
periods,
|
||||
...Object.fromEntries(
|
||||
[
|
||||
'monthlyCollections',
|
||||
'monthlyVariableCostPayments',
|
||||
'monthlyInventoryPurchases',
|
||||
'monthlyOperatingExpenses',
|
||||
'monthlyOperatingPayments',
|
||||
'monthlyPayrollExpense',
|
||||
'monthlyPayrollPayments',
|
||||
'inventory',
|
||||
'receivables',
|
||||
'payables',
|
||||
'shareholderLoans',
|
||||
'bankLoanProceeds',
|
||||
'grants',
|
||||
'assetDepreciation',
|
||||
'monthlyInterestExpense',
|
||||
'monthlyInterestPayment',
|
||||
'monthlyPrincipalRepayment',
|
||||
].map((key) => [key, '0']),
|
||||
),
|
||||
};
|
||||
Object.assign(value, {
|
||||
monthlyVariableCostPayments: '400',
|
||||
monthlyInventoryPurchases: '400',
|
||||
monthlyOperatingExpenses: '100',
|
||||
monthlyOperatingPayments: '100',
|
||||
monthlyPayrollExpense: '200',
|
||||
monthlyPayrollPayments: '200',
|
||||
assetDepreciation: '600',
|
||||
salesCollectionLagMonths: 0,
|
||||
salesCollectionPercent: '100',
|
||||
openingReceivablesCollectionPercent: '0',
|
||||
});
|
||||
value.reportAssumptions = {
|
||||
...newReportAssumptions(periods),
|
||||
startYear: '2027',
|
||||
openingFixedAssets: '0',
|
||||
openingOtherAssets: '0',
|
||||
openingEquity: '1000',
|
||||
startupExpenses: [{ label: 'Constituição', amount: '100' }],
|
||||
taxExpenseByMonth: Array(periods).fill('30'),
|
||||
taxPaymentByMonth: Array(periods).fill('20'),
|
||||
taxSource: 'Hipótese sintética de teste; não é taxa legal',
|
||||
};
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import {financialReportFixture} from './integral-financial-plan.mjs';
|
||||
export function periodInvestmentsFixture(periods=7,regime='PGC-PE'){
|
||||
const p=financialReportFixture(periods);p.accountingRegime=regime;
|
||||
p.products[0].monthlyUnits='0';
|
||||
for(const k of ['monthlyCollections','monthlyInventoryPurchases','monthlyVariableCostPayments','monthlyOperatingExpenses','monthlyOperatingPayments','monthlyPayrollExpense','monthlyPayrollPayments'])p[k]='0';
|
||||
p.reportAssumptions.taxExpenseByMonth=Array(periods).fill('0');p.reportAssumptions.taxPaymentByMonth=Array(periods).fill('0');
|
||||
const agenda=()=>Array.from({length:periods},(_,i)=>({month:i+1,interestExpense:'0',interestPaid:'0',principal:'0'}));
|
||||
const bank={id:'BANK-1',label:'Empréstimo sintético',kind:'bank',drawdowns:[{id:'D1',date:'2027-02-10',amount:'500'}],agenda:agenda()};
|
||||
const shareholder={id:'SHARE-1',label:'Suprimento sintético',kind:'shareholder',drawdowns:[{id:'D1',date:'2027-03-05',amount:'200'}],agenda:agenda()};
|
||||
if(periods>=2)bank.agenda[1].interestExpense='5';
|
||||
if(periods>=3)Object.assign(bank.agenda[2],{interestExpense:'5',interestPaid:'10',principal:'100'});
|
||||
if(periods>=4){bank.agenda[3].principal='400';shareholder.agenda[3].principal='200';}
|
||||
p.periodInvestments={enabled:true,financings:[bank,shareholder],assets:[{id:'A1',label:'Activo sintético',recognitionDate:'2027-04-01',paymentDate:'2027-04-02',cost:'100',depreciable:true,base:'100',lifeMonths:'3',availableDate:'2027-04-16',linearBasis:regime==='PGC-NIRF'?'Consumo uniforme declarado no cenário sintético':''}]};
|
||||
return p;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
||||
import {financialReportFixture} from './integral-financial-plan.mjs';
|
||||
export function advanceFixture({kind='purchases',amount='100000',recognition='2027-02-15',invoice='2027-03-01',periods=4}={}) {
|
||||
const p=financialReportFixture(periods);
|
||||
p.products=[{label:'Sintético F20-B',monthlyUnits:'0',unitPrice:'0',unitVariableCost:'0'}];
|
||||
p.monthlyOperatingExpenses='0';p.monthlyOperatingExpensesByPeriod=Array(periods).fill('0');
|
||||
p.monthlyPayrollExpense=p.monthlyPayrollPayments=p.monthlyInterestExpense=p.monthlyInterestPayment=p.monthlyPrincipalRepayment='0';
|
||||
p.monthlyVariableCostPayments='999';p.monthlyOperatingPayments='888';
|
||||
p.useInventoryPurchaseSchedule=true;
|
||||
p.inventoryPurchaseSchedule=Array.from({length:periods},()=>({amount:'0',leadMonths:0}));
|
||||
if(recognition) {
|
||||
const m=(Number(recognition.slice(0,4))-2027)*12+Number(recognition.slice(5,7))-1;
|
||||
if(m<periods) {
|
||||
if(kind==='purchases')p.inventoryPurchaseSchedule[m].amount=amount;
|
||||
else p.monthlyOperatingExpensesByPeriod[m]=amount;
|
||||
}
|
||||
}
|
||||
// Both agendas explicitly selected; zero-recognition category has no operations.
|
||||
p.supplierAdvances={regime:'PGC-PE',purchases:true,services:true,operations:[{
|
||||
kind,originId:'OP-1',parcelId:'P-1',supplier:'Fornecedor sintético',amount,
|
||||
recognitionDate:recognition,invoiceDate:invoice,ordinaryContract:true,events:[],
|
||||
}]};
|
||||
return p;
|
||||
}
|
||||
export const event=(id,kind,date,amount)=>({id,kind,date,amount});
|
||||
@@ -1,29 +1,29 @@
|
||||
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";
|
||||
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 && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
const text = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.map(text).join("")
|
||||
? tree.map(text).join('')
|
||||
: tree?.props
|
||||
? text(tree.props.children)
|
||||
: typeof tree === "string"
|
||||
: typeof tree === 'string'
|
||||
? tree
|
||||
: "";
|
||||
: '';
|
||||
|
||||
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
|
||||
function harness(filters, errors = {}) {
|
||||
function harness(filters, errors = {}, items = []) {
|
||||
const memory = [];
|
||||
let cursor = 0;
|
||||
const state = (initial) => {
|
||||
@@ -32,7 +32,8 @@ function harness(filters, errors = {}) {
|
||||
return [
|
||||
memory[id],
|
||||
(next) => {
|
||||
memory[id] = typeof next === "function" ? next(memory[id]) : next;
|
||||
memory[id] =
|
||||
typeof next === 'function' ? next(memory[id]) : next;
|
||||
},
|
||||
];
|
||||
};
|
||||
@@ -40,7 +41,10 @@ function harness(filters, errors = {}) {
|
||||
let form;
|
||||
const TerritoryFields = () => null;
|
||||
const module = { exports: {} };
|
||||
const source = fs.readFileSync("resources/js/pages/funding/index.tsx", "utf8");
|
||||
const source = fs.readFileSync(
|
||||
'resources/js/pages/funding/index.tsx',
|
||||
'utf8',
|
||||
);
|
||||
compileFunction(
|
||||
ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
@@ -48,10 +52,10 @@ function harness(filters, errors = {}) {
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText,
|
||||
["require", "module", "exports"],
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(id) => {
|
||||
if (id === "react")
|
||||
if (id === 'react')
|
||||
return {
|
||||
...React,
|
||||
useState: state,
|
||||
@@ -60,9 +64,9 @@ function harness(filters, errors = {}) {
|
||||
return value;
|
||||
},
|
||||
};
|
||||
if (id === "@inertiajs/react")
|
||||
if (id === '@inertiajs/react')
|
||||
return {
|
||||
Link: "a",
|
||||
Link: 'a',
|
||||
useForm(initial) {
|
||||
const [data, set] = state(initial);
|
||||
form = {
|
||||
@@ -70,7 +74,11 @@ function harness(filters, errors = {}) {
|
||||
errors: {},
|
||||
processing: false,
|
||||
setData(key, value) {
|
||||
set(typeof key === "string" ? { ...data, [key]: value } : key);
|
||||
set(
|
||||
typeof key === 'string'
|
||||
? { ...data, [key]: value }
|
||||
: key,
|
||||
);
|
||||
},
|
||||
get(url) {
|
||||
submitted = { url, data };
|
||||
@@ -79,22 +87,25 @@ function harness(filters, errors = {}) {
|
||||
return form;
|
||||
},
|
||||
};
|
||||
if (id === "@/pages/investment/shared") return { Frame: "main", card: "", button: "" };
|
||||
if (id === "@/components/funding-classification")
|
||||
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",
|
||||
banking: 'Banca',
|
||||
insurance_intermediation: 'Mediação de seguros',
|
||||
},
|
||||
financialTypes: {
|
||||
commercial_bank: "Banco comercial",
|
||||
broker: "Corretora",
|
||||
other: "Outro",
|
||||
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: {} };
|
||||
if (id === '@/components/investment-territory')
|
||||
return { TerritoryFields };
|
||||
if (id === '@/components/funding-institution')
|
||||
return { InstitutionView: 'article' };
|
||||
if (id === './shared') return { windowLabels: {} };
|
||||
return require(id);
|
||||
},
|
||||
module,
|
||||
@@ -103,13 +114,13 @@ function harness(filters, errors = {}) {
|
||||
const props = {
|
||||
filters,
|
||||
criteriaErrors: errors,
|
||||
items: { data: [], links: [] },
|
||||
items: { data: items, links: [] },
|
||||
options: { sectors: [], territories: [] },
|
||||
kinds: { institution: "Instituição", fund: "Fundo" },
|
||||
kinds: { institution: 'Instituição', fund: 'Fundo' },
|
||||
management: false,
|
||||
categoryTypes: {
|
||||
banking: ["commercial_bank"],
|
||||
insurance_intermediation: ["broker"],
|
||||
banking: ['commercial_bank'],
|
||||
insurance_intermediation: ['broker'],
|
||||
},
|
||||
};
|
||||
let tree;
|
||||
@@ -120,9 +131,11 @@ function harness(filters, errors = {}) {
|
||||
return tree;
|
||||
}
|
||||
const select = (label) =>
|
||||
nodes(nodes(tree).find((n) => n.type === "label" && text(n).startsWith(label))).find(
|
||||
(n) => n.type === "select",
|
||||
);
|
||||
nodes(
|
||||
nodes(tree).find(
|
||||
(n) => n.type === 'label' && text(n).startsWith(label),
|
||||
),
|
||||
).find((n) => n.type === 'select');
|
||||
render();
|
||||
return {
|
||||
render,
|
||||
@@ -134,92 +147,259 @@ function harness(filters, errors = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
test("institution category restricts types and removes only an incompatible dependent choice", () => {
|
||||
test('B03 broad coverage remains explicit and physical choice requests documented presence', () => {
|
||||
const h = harness({
|
||||
category: "insurance_intermediation",
|
||||
institution_type: "broker",
|
||||
sector: "7",
|
||||
need: "investment",
|
||||
territory: "district-qa",
|
||||
need: 'investment',
|
||||
territory: '7d908cf8-6e52-5141-8832-b1193985e39f',
|
||||
});
|
||||
h.select("Categoria da instituição").props.onChange({
|
||||
target: { value: "banking" },
|
||||
assert.equal(h.select('Localização a pesquisar').props.value, 'coverage');
|
||||
h.select('Localização a pesquisar').props.onChange({
|
||||
target: { value: 'physical' },
|
||||
});
|
||||
h.render();
|
||||
assert.equal(h.form().data.institution_type, "");
|
||||
assert.equal(h.form().data.location_mode, 'physical');
|
||||
assert.equal(h.form().data.certainty, 'documented');
|
||||
assert.match(
|
||||
text(h.tree()),
|
||||
/a cobertura indica onde o financiamento se aplica/,
|
||||
);
|
||||
});
|
||||
|
||||
test('B06 empty results omit institution alternatives and real result links keep exact identities', () => {
|
||||
const filters = {
|
||||
need: 'investment',
|
||||
territory: '4aa31470-997e-5c63-8fe0-ff2f62586f56',
|
||||
location_mode: 'physical',
|
||||
};
|
||||
const empty = harness(filters);
|
||||
assert.match(text(empty.tree()), /Não foram encontradas instituições/);
|
||||
assert.equal(
|
||||
nodes(empty.tree()).filter(
|
||||
(n) =>
|
||||
n.props?.href?.startsWith('/fundos/') &&
|
||||
n.props.href !== '/fundos/guardados',
|
||||
).length,
|
||||
0,
|
||||
);
|
||||
const fixture = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'outputs/funding-b03-b06-20261120/fixture.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const originals = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'database/data/funding-institutions-nov2026.json',
|
||||
'utf8',
|
||||
),
|
||||
).references;
|
||||
const items = Object.entries(fixture.records).map(([key, r]) => ({
|
||||
id: r.id,
|
||||
payload: originals[key].draft,
|
||||
}));
|
||||
const h = harness(filters, {}, items);
|
||||
for (const item of items) {
|
||||
const link = nodes(h.tree()).find(
|
||||
(n) =>
|
||||
text(n) === item.payload.title &&
|
||||
n.props?.href?.startsWith('/fundos/'),
|
||||
);
|
||||
assert.ok(link, item.payload.title);
|
||||
assert.ok(link.props.href.startsWith('/fundos/' + item.id + '?'));
|
||||
assert.match(link.props.href, /location_mode=physical/);
|
||||
}
|
||||
});
|
||||
|
||||
void test('searching another province resets only the search location and preserves the investment scope', () => {
|
||||
const filters = {
|
||||
category: 'banking',
|
||||
institution_type: 'commercial_bank',
|
||||
need: 'investment',
|
||||
context: 'case-qa',
|
||||
opportunity: 'opportunity-qa',
|
||||
province_id: 'province-qa',
|
||||
district_id: 'district-qa',
|
||||
territory: 'district-qa',
|
||||
location_mode: 'physical',
|
||||
certainty: 'documented',
|
||||
};
|
||||
const h = harness(filters);
|
||||
const action = nodes(h.tree()).find(
|
||||
(n) =>
|
||||
n.type === 'button' &&
|
||||
text(n) === 'Procurar instituição noutra província',
|
||||
);
|
||||
assert.ok(action);
|
||||
action.props.onClick();
|
||||
h.render();
|
||||
for (const key of [
|
||||
'territory',
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
])
|
||||
assert.equal(h.form().data[key], '');
|
||||
for (const key of [
|
||||
'category',
|
||||
'institution_type',
|
||||
'need',
|
||||
'context',
|
||||
'opportunity',
|
||||
'location_mode',
|
||||
'certainty',
|
||||
])
|
||||
assert.equal(h.form().data[key], filters[key]);
|
||||
assert.deepEqual(h.territory().props.initial, []);
|
||||
assert.equal(h.submitted(), undefined);
|
||||
assert.match(
|
||||
text(h.tree()),
|
||||
/a localização do investimento no dossier mantém-se/,
|
||||
);
|
||||
});
|
||||
|
||||
void 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",
|
||||
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")
|
||||
nodes(h.select('Tipo de instituição'))
|
||||
.filter((n) => n.type === 'option')
|
||||
.map((n) => n.props.value),
|
||||
["", "commercial_bank", "other"],
|
||||
['', 'commercial_bank', 'other'],
|
||||
);
|
||||
assert.match(text(h.tree()), /tipo anterior não pertence/);
|
||||
const results = nodes(h.tree()).find((n) => n.type === "details");
|
||||
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", () => {
|
||||
void 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: 'fund',
|
||||
category: 'banking',
|
||||
institution_type: 'commercial_bank',
|
||||
location_mode: 'physical',
|
||||
province_id: 'province-qa',
|
||||
sector: '8',
|
||||
state: 'closed',
|
||||
certainty: 'documented',
|
||||
need: 'investment',
|
||||
},
|
||||
{ kind: ["Combinação incompatível."] },
|
||||
{ kind: ['Combinação incompatível.'] },
|
||||
);
|
||||
assert.match(text(h.tree()), /A pesquisa não foi executada/);
|
||||
assert.equal(h.form().data.kind, "fund");
|
||||
assert.equal(h.form().data.kind, 'fund');
|
||||
const action = nodes(h.tree()).find(
|
||||
(n) => n.type === "button" && /Manter o fundo/.test(text(n)),
|
||||
(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");
|
||||
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",
|
||||
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")
|
||||
.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");
|
||||
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',
|
||||
);
|
||||
});
|
||||
|
||||
test("local search defaults to documented presence and keeps the explicit unknown option and chosen territory", () => {
|
||||
const h = harness({ territory: "district-qa", sector: "7" });
|
||||
h.select("Localização a pesquisar").props.onChange({ target: { value: "physical" } });
|
||||
h.render();
|
||||
assert.equal(h.form().data.certainty, "documented");
|
||||
assert.equal(h.form().data.territory, "district-qa");
|
||||
assert.equal(h.form().data.sector, "7");
|
||||
h.select("Informação por confirmar").props.onChange({ target: { value: "include_unknown" } });
|
||||
h.render();
|
||||
assert.equal(h.form().data.certainty, "include_unknown");
|
||||
const resumed = harness({
|
||||
location_mode: "physical",
|
||||
territory: "district-qa",
|
||||
certainty: "include_unknown",
|
||||
});
|
||||
assert.equal(resumed.form().data.certainty, "include_unknown");
|
||||
assert.equal(harness({ location_mode: "physical" }).form().data.certainty, "documented");
|
||||
void test('search needs both location and purpose; Enter and missing criteria cannot submit', () => {
|
||||
for (const filters of [
|
||||
{},
|
||||
{ need: 'investment' },
|
||||
{ province_id: 'province-qa' },
|
||||
]) {
|
||||
const h = harness(filters);
|
||||
const submit = nodes(h.tree()).find(
|
||||
(n) => n.type === 'button' && text(n) === 'Pesquisar',
|
||||
);
|
||||
assert.equal(submit.props.disabled, true);
|
||||
nodes(h.tree())
|
||||
.find((n) => n.type === 'form')
|
||||
.props.onSubmit({ preventDefault() {} });
|
||||
assert.equal(h.submitted(), undefined);
|
||||
assert.match(
|
||||
text(h.tree()),
|
||||
/Escolha a localização a pesquisar e a necessidade/,
|
||||
);
|
||||
}
|
||||
for (const location of [
|
||||
{ province_id: 'province-qa' },
|
||||
{ territory: 'district-qa' },
|
||||
]) {
|
||||
const h = harness({
|
||||
...location,
|
||||
need: 'investment',
|
||||
context: 'dossier-qa',
|
||||
opportunity: 'opportunity-qa',
|
||||
});
|
||||
assert.equal(
|
||||
nodes(h.tree()).find(
|
||||
(n) => n.type === 'button' && text(n) === 'Pesquisar',
|
||||
).props.disabled,
|
||||
false,
|
||||
);
|
||||
nodes(h.tree())
|
||||
.find((n) => n.type === 'form')
|
||||
.props.onSubmit({ preventDefault() {} });
|
||||
assert.equal(h.submitted().data.need, 'investment');
|
||||
assert.equal(h.submitted().data.context, 'dossier-qa');
|
||||
assert.equal(h.submitted().data.opportunity, 'opportunity-qa');
|
||||
}
|
||||
});
|
||||
|
||||
void test('local search defaults to documented presence and keeps the explicit unknown option and chosen territory', () => {
|
||||
const h = harness({ territory: 'district-qa', sector: '7' });
|
||||
h.select('Localização a pesquisar').props.onChange({
|
||||
target: { value: 'physical' },
|
||||
});
|
||||
h.render();
|
||||
assert.equal(h.form().data.certainty, 'documented');
|
||||
assert.equal(h.form().data.territory, 'district-qa');
|
||||
assert.equal(h.form().data.sector, '7');
|
||||
h.select('Informação por confirmar').props.onChange({
|
||||
target: { value: 'include_unknown' },
|
||||
});
|
||||
h.render();
|
||||
assert.equal(h.form().data.certainty, 'include_unknown');
|
||||
const resumed = harness({
|
||||
location_mode: 'physical',
|
||||
territory: 'district-qa',
|
||||
certainty: 'include_unknown',
|
||||
});
|
||||
assert.equal(resumed.form().data.certainty, 'include_unknown');
|
||||
assert.equal(
|
||||
harness({ location_mode: 'physical' }).form().data.certainty,
|
||||
'documented',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import * as report from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import * as warnings from '../../resources/js/lib/financial-plan-warnings.ts';
|
||||
import * as annual from '../../resources/js/lib/annual-example-report.ts';
|
||||
import {
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
|
||||
void test('one startup editor retains all rows and persists an edit without duplicating controls or changing reconciliation', () => {
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/integral-financial-plan.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
const module = { exports: {} },
|
||||
require = createRequire(import.meta.url);
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(name) =>
|
||||
name === '@/lib/integral-financial-report'
|
||||
? report
|
||||
: name === './investment-report-tables'
|
||||
? { InvestmentReportTables: () => null }
|
||||
: name === '@/lib/financial-plan-warnings'
|
||||
? warnings
|
||||
: name === '@/lib/annual-example-report'
|
||||
? annual
|
||||
: name === './business-plan-warnings'
|
||||
? { BusinessPlanWarnings: () => null }
|
||||
: name === './startup-asset-requirements'
|
||||
? { StartupAssetRequirements: () => null }
|
||||
: require(name),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
let plan = financialReportFixture(12);
|
||||
const render = () =>
|
||||
module.exports.IntegralFinancialPlan({
|
||||
plan,
|
||||
onChange: (next) => {
|
||||
plan = next;
|
||||
},
|
||||
});
|
||||
const html = renderToStaticMarkup(render());
|
||||
assert.equal(
|
||||
(html.match(/Adicionar despesa de arranque/g) ?? []).length,
|
||||
1,
|
||||
);
|
||||
assert.equal((html.match(/Remover despesa/g) ?? []).length, 1);
|
||||
const nodes = (node) =>
|
||||
Array.isArray(node)
|
||||
? node.flatMap(nodes)
|
||||
: node && typeof node === 'object'
|
||||
? [node, ...nodes(node.props?.children)]
|
||||
: [];
|
||||
const label = nodes(render()).find(
|
||||
(node) =>
|
||||
node.type === 'label' &&
|
||||
React.Children.toArray(node.props.children).includes(
|
||||
'Montante de arranque 1',
|
||||
),
|
||||
);
|
||||
nodes(label)
|
||||
.find((node) => node.type === 'input')
|
||||
.props.onChange({ target: { value: '100.25' } });
|
||||
plan = restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(plan));
|
||||
assert.equal(plan.reportAssumptions.startupExpenses[0].amount, '100.25');
|
||||
assert.match(renderToStaticMarkup(render()), /value="100.25"/);
|
||||
const balance = report
|
||||
.buildIntegralFinancialTables(plan)
|
||||
.find((table) => table.id === 'balance');
|
||||
assert.ok(
|
||||
balance.rows
|
||||
.find((row) => row[0] === 'Diferença do balanço')
|
||||
.slice(1)
|
||||
.every((value) => value === '0.00'),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
import { financialReportFixture as plan } from './fixtures/integral-financial-plan.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import JSZip from 'jszip';
|
||||
import {
|
||||
buildIntegralFinancialTables,
|
||||
displayReportMoney,
|
||||
} from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import {
|
||||
createProjectDossierReport,
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
import {
|
||||
partitionSimulationDraft,
|
||||
restoreSimulationDraft,
|
||||
} from '../../resources/js/lib/simulation-form.ts';
|
||||
|
||||
void test('acceptance regression: summary uses the same cash, tax payments and startup funding gap as its seven tables', () => {
|
||||
const input = plan(13);
|
||||
const make = () =>
|
||||
createProjectDossierReport(
|
||||
{
|
||||
project_title: 'QA',
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
|
||||
},
|
||||
{ selectedSections: new Set(['finance']) },
|
||||
).sections[0];
|
||||
const finance = make();
|
||||
const value = (field) =>
|
||||
finance.rows.find((row) => row.field === field)?.value;
|
||||
assert.equal(value('Caixa final projectada'), '4 540,00 MZN');
|
||||
assert.equal(value('Pagamentos no horizonte'), '9 360,00 MZN');
|
||||
assert.equal(value('Resultado antes de impostos'), '3 770,00 MZN');
|
||||
assert.equal(value('Resultado líquido no horizonte'), '3 380,00 MZN');
|
||||
assert.equal(value('Diferença entre usos e fontes'), '100,00 MZN');
|
||||
assert.match(
|
||||
value('Reconciliação do financiamento'),
|
||||
/insuficiente.*não bloqueante/,
|
||||
);
|
||||
assert.equal(get(finance.tables, 'cashflow', 'Caixa final')[13], '4540.00');
|
||||
input.reportAssumptions.taxExpenseByMonth[0] = '';
|
||||
assert.match(
|
||||
make().rows.find((row) => row.field === 'Caixa final projectada').value,
|
||||
/Por determinar/,
|
||||
);
|
||||
});
|
||||
|
||||
void test('review regression: cash deficit does not create an undeclared loan or inflate projected liabilities', () => {
|
||||
const input = plan(12);
|
||||
input.reportAssumptions.startupExpenses[0].amount = '10000';
|
||||
const tables = buildIntegralFinancialTables(input);
|
||||
assert.equal(get(tables, 'cashflow', 'Caixa inicial')[1], '-9000.00');
|
||||
assert.equal(get(tables, 'balance', 'Caixa líquida')[1], '-8720.00');
|
||||
assert.equal(
|
||||
get(tables, 'balance', 'Total do passivo')[1],
|
||||
'10.00',
|
||||
'only the declared accrued tax, without a fabricated overdraft',
|
||||
);
|
||||
assert.equal(
|
||||
get(tables, 'balance', 'Empréstimos e suprimentos por reembolsar')[1],
|
||||
'0.00',
|
||||
);
|
||||
assert.equal(get(tables, 'balance', 'Total do activo')[1], '-8130.00');
|
||||
assert.equal(get(tables, 'balance', 'Diferença do balanço')[1], '0.00');
|
||||
assert.match(
|
||||
tables.find((table) => table.id === 'balance').notes.join(' '),
|
||||
/não cria dívida/,
|
||||
);
|
||||
});
|
||||
|
||||
void test('review regression: print export repeats rubrics in readable slices without losing any of sixty months or five annual periods', async () => {
|
||||
const input = plan(60);
|
||||
const report = createProjectDossierReport(
|
||||
{
|
||||
project_title: 'QA 60 meses',
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
|
||||
},
|
||||
{
|
||||
selectedSections: new Set(['finance']),
|
||||
generatedAt: '2026-11-20T12:00:00Z',
|
||||
},
|
||||
);
|
||||
const html = await createProjectDossierPrintHtml(report, []);
|
||||
const heads = [...html.matchAll(/<thead>([\s\S]*?)<\/thead>/g)];
|
||||
assert.ok(heads.length > 7);
|
||||
for (const [, head] of heads)
|
||||
assert.ok(
|
||||
(head.match(/<th>/g) ?? []).length <= 5,
|
||||
'four periods plus rubric maximum',
|
||||
);
|
||||
for (const table of report.sections[0].tables)
|
||||
for (const header of table.headers)
|
||||
assert.ok(html.includes(header), header);
|
||||
assert.match(html, /2031-12/);
|
||||
assert.doesNotMatch(html, /overflow-x:auto/);
|
||||
});
|
||||
|
||||
const get = (tables, id, label) =>
|
||||
tables
|
||||
.find((table) => table.id === id)
|
||||
.rows.find((row) => row[0] === label);
|
||||
|
||||
void test('seven integrated statements reconcile monthly flows, annual totals and closing stocks without changing the existing engine', () => {
|
||||
const input = plan(),
|
||||
before = JSON.stringify(input),
|
||||
forecast = forecastBusinessPlan(input),
|
||||
tables = buildIntegralFinancialTables(input);
|
||||
assert.equal(tables.length, 7);
|
||||
assert.ok(
|
||||
tables.every((table) => table.issues.length === 0),
|
||||
JSON.stringify(tables.map((t) => [t.id, t.issues])),
|
||||
);
|
||||
assert.equal(get(tables, 'startup', 'Despesas de arranque')[1], '100.00');
|
||||
assert.equal(
|
||||
get(tables, 'funding', 'Caixa após financiamento e arranque')[1],
|
||||
'900.00',
|
||||
);
|
||||
assert.deepEqual(get(tables, 'sales', 'Vendas totais').slice(-2), [
|
||||
'12000.00',
|
||||
'12000.00',
|
||||
]);
|
||||
assert.deepEqual(get(tables, 'profit-loss', 'Lucro líquido').slice(-2), [
|
||||
'3120.00',
|
||||
'3120.00',
|
||||
]);
|
||||
assert.deepEqual(get(tables, 'cashflow', 'Caixa inicial').slice(-2), [
|
||||
'900.00',
|
||||
'4260.00',
|
||||
]);
|
||||
assert.deepEqual(get(tables, 'cashflow', 'Caixa final').slice(-2), [
|
||||
'4260.00',
|
||||
'7620.00',
|
||||
]);
|
||||
assert.deepEqual(get(tables, 'balance', 'Total do activo').slice(-2), [
|
||||
'4740.00',
|
||||
'7980.00',
|
||||
]);
|
||||
assert.ok(
|
||||
get(tables, 'balance', 'Diferença do balanço')
|
||||
.slice(1)
|
||||
.every((value) => value === '0.00'),
|
||||
);
|
||||
assert.equal(
|
||||
get(tables, 'break-even', 'Vendas de equilíbrio')[1],
|
||||
'516.67',
|
||||
);
|
||||
assert.equal(JSON.stringify(input), before);
|
||||
const withoutSupplement = { ...input };
|
||||
delete withoutSupplement.reportAssumptions;
|
||||
assert.deepEqual(
|
||||
forecastBusinessPlan(withoutSupplement),
|
||||
forecast,
|
||||
'no changes to approved base forecast',
|
||||
);
|
||||
const draft = {
|
||||
purpose: 'own_investment',
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
|
||||
};
|
||||
const stored = JSON.parse(
|
||||
JSON.stringify(partitionSimulationDraft(draft, false)),
|
||||
);
|
||||
const recovered = restoreBusinessPlanSnapshot(
|
||||
restoreSimulationDraft(stored.economic_snapshot, {})
|
||||
.business_plan_snapshot,
|
||||
);
|
||||
assert.deepEqual(buildIntegralFinancialTables(recovered), tables);
|
||||
});
|
||||
|
||||
void test('missing inputs, insufficient inventory and inconsistent opening capital remain explicit, never balancing plugs', () => {
|
||||
const input = plan(12);
|
||||
input.reportAssumptions.openingEquity = '999.99';
|
||||
let tables = buildIntegralFinancialTables(input);
|
||||
assert.match(
|
||||
tables.find((t) => t.id === 'balance').issues.join(' '),
|
||||
/abertura/,
|
||||
);
|
||||
assert.equal(get(tables, 'balance', 'Diferença do balanço')[1], '0.01');
|
||||
input.reportAssumptions.openingEquity = '1000';
|
||||
input.monthlyInventoryPurchases = '';
|
||||
tables = buildIntegralFinancialTables(input);
|
||||
assert.match(
|
||||
tables.find((t) => t.id === 'balance').issues.join(' '),
|
||||
/agenda/,
|
||||
);
|
||||
assert.equal(
|
||||
get(tables, 'balance', 'Diferença do balanço')[1],
|
||||
'Por determinar',
|
||||
);
|
||||
input.monthlyInventoryPurchases = '0';
|
||||
assert.match(
|
||||
buildIntegralFinancialTables(input)
|
||||
.find((t) => t.id === 'balance')
|
||||
.issues.join(' '),
|
||||
/insuficientes/,
|
||||
);
|
||||
input.reportAssumptions.taxExpenseByMonth[0] = '';
|
||||
assert.ok(
|
||||
buildIntegralFinancialTables(input).every((t) => t.issues.length > 0),
|
||||
);
|
||||
});
|
||||
|
||||
void test('partial years, changing product schedules and negative cash keep exact amounts and disclosed assumptions', () => {
|
||||
const input = plan(13);
|
||||
input.products[0].unitPriceByPeriod = Array(13).fill('100.01');
|
||||
input.reportAssumptions.startupExpenses[0].amount = '10000.01';
|
||||
const tables = buildIntegralFinancialTables(input);
|
||||
assert.ok(
|
||||
tables
|
||||
.find((t) => t.id === 'sales')
|
||||
.headers.at(-1)
|
||||
.endsWith('(parcial)'),
|
||||
);
|
||||
assert.equal(get(tables, 'sales', 'Vendas totais').at(-1), '1000.10');
|
||||
assert.equal(get(tables, 'cashflow', 'Caixa inicial')[1], '-9000.01');
|
||||
assert.ok(
|
||||
get(tables, 'balance', 'Diferença do balanço')
|
||||
.slice(1)
|
||||
.every((value) => value === '0.00'),
|
||||
);
|
||||
assert.equal(displayReportMoney('-1234567.89'), '-1 234 567,89');
|
||||
});
|
||||
|
||||
void test('dossier print and Word exports include the seven statements and approved ratios, escape labels and split wide tables', async () => {
|
||||
const input = plan(13);
|
||||
input.products[0].label = '<script>não executar</script>';
|
||||
const report = createProjectDossierReport(
|
||||
{
|
||||
project_title: 'Teste QA',
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
|
||||
},
|
||||
{
|
||||
selectedSections: new Set(['finance']),
|
||||
generatedAt: '2026-11-20T12:00:00Z',
|
||||
},
|
||||
);
|
||||
assert.equal(report.sections[0].tables.length, 8);
|
||||
const html = await createProjectDossierPrintHtml(report, []);
|
||||
assert.match(html, /Balanço Projectado/);
|
||||
assert.match(html, /<script>/);
|
||||
assert.doesNotMatch(html, /<script>não executar/);
|
||||
const output = await generateProjectDossierDocx(report, []);
|
||||
const zip = await JSZip.loadAsync(
|
||||
output instanceof Blob ? await output.arrayBuffer() : output,
|
||||
);
|
||||
const xml = await zip.file('word/document.xml').async('string');
|
||||
assert.match(xml, /Balanço Projectado/);
|
||||
assert.match(xml, /Lucros e Perdas/);
|
||||
assert.doesNotMatch(xml, /<\/w:tbl>\s*<w:tbl>/);
|
||||
assert.match(xml, /7 620,00|7620,00|4 540,00|4540,00/);
|
||||
});
|
||||
@@ -188,6 +188,15 @@ test('summary focus and click wait for the native open toggle; closing a stage d
|
||||
};
|
||||
try {
|
||||
let tree = render();
|
||||
const action = new Target(false);
|
||||
tree.props.children.props.onPointerDownCapture();
|
||||
tree.props.children.props.onFocusCapture({ target: action });
|
||||
assert.equal(
|
||||
render().props.value.active,
|
||||
null,
|
||||
'pointer focus must not insert help before the action receives its click',
|
||||
);
|
||||
tree.props.children.props.onPointerUpCapture();
|
||||
const summary = new Target(true);
|
||||
tree.props.children.props.onFocusCapture({ target: summary });
|
||||
tree.props.children.props.onClickCapture({ target: summary });
|
||||
@@ -200,6 +209,12 @@ test('summary focus and click wait for the native open toggle; closing a stage d
|
||||
target: new Disclosure(false, false),
|
||||
});
|
||||
assert.equal(render().props.value.active, null);
|
||||
tree.props.children.props.onClickCapture({ target: action });
|
||||
assert.equal(
|
||||
render().props.value.active,
|
||||
'S02',
|
||||
'the completed click may open automatic help',
|
||||
);
|
||||
listeners.toggle({
|
||||
target: new Disclosure(false, true),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import {
|
||||
correctionFieldHints,
|
||||
fieldLabelMatches,
|
||||
} from '../../resources/js/lib/field-corrections.ts';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||
import { buildComplementaryTables } from '../../resources/js/lib/complementary-report.ts';
|
||||
import { financialPlanWarnings } from '../../resources/js/lib/financial-plan-warnings.ts';
|
||||
void test('V09 P0078 identifies the actual personnel quantity field with literal guidance without changing totals or input', () => {
|
||||
const { plan, draft, team } = complementaryFixture();
|
||||
const bad = {
|
||||
...draft,
|
||||
project_team_snapshot: JSON.stringify([
|
||||
{ ...team[0], quantity: '2.5' },
|
||||
]),
|
||||
};
|
||||
const before = JSON.stringify(bad);
|
||||
const report = buildComplementaryTables(bad, plan)[2];
|
||||
assert.match(
|
||||
report.issues.join(' '),
|
||||
/Introduza um n\u00famero inteiro de pessoas\./,
|
||||
);
|
||||
assert.match(report.issues.join(' '), /Quantidade de pessoas/);
|
||||
assert.equal(JSON.stringify(bad), before);
|
||||
const hints = correctionFieldHints(
|
||||
report.issues.find((i) => i.includes('n\u00famero inteiro de pessoas')),
|
||||
);
|
||||
assert.ok(
|
||||
hints.some((h) =>
|
||||
fieldLabelMatches('Quantidade de pessoas (inteiro)', h),
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
!hints.some((h) =>
|
||||
fieldLabelMatches('Remunera\u00e7\u00e3o mensal', h),
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
report.rows.find((r) => r[0] === 'Folha salarial prevista')[1],
|
||||
'Por determinar',
|
||||
);
|
||||
const good = buildComplementaryTables(
|
||||
{
|
||||
...bad,
|
||||
project_team_snapshot: JSON.stringify([
|
||||
{ ...team[0], quantity: '2' },
|
||||
]),
|
||||
},
|
||||
plan,
|
||||
)[2];
|
||||
assert.ok(
|
||||
!good.issues.some((i) => i.includes('n\u00famero inteiro de pessoas')),
|
||||
);
|
||||
});
|
||||
void test('V09 P0079/P0080 messages use calculated monthly values, group periods once, and never change tables', () => {
|
||||
const plan = { currency: 'MZN', periods: 3 };
|
||||
const tables = [
|
||||
{
|
||||
id: 'sales',
|
||||
headers: ['Rubrica', '2027-01', '2027-02', '2027-03'],
|
||||
rows: [['Vendas totais', '0.00', '100.00', '100.00']],
|
||||
issues: [],
|
||||
notes: [],
|
||||
},
|
||||
{
|
||||
id: 'profit-loss',
|
||||
headers: ['Rubrica', '2027-01', '2027-02', '2027-03'],
|
||||
rows: [
|
||||
['Custo directo', '0.00', '100.00', '150.00'],
|
||||
['Despesas operacionais', '10.00', '10.00', '10.00'],
|
||||
],
|
||||
issues: [],
|
||||
notes: [],
|
||||
},
|
||||
];
|
||||
tables.push({
|
||||
id: 'cashflow',
|
||||
headers: ['Rubrica', '2027-01', '2027-02', '2027-03'],
|
||||
rows: [['Caixa final', '-1.00', '0.00', '0.00']],
|
||||
issues: [],
|
||||
notes: [],
|
||||
});
|
||||
const before = JSON.stringify(tables);
|
||||
const w = financialPlanWarnings(plan, tables);
|
||||
assert.equal(w.filter((w) => w.id === 'cash-negative-2027-01').length, 1);
|
||||
assert.equal(
|
||||
w.filter((x) =>
|
||||
x.message.includes(
|
||||
'Com este custo vari\u00e1vel n\u00e3o h\u00e1 margem para cobrir os custos fixos. Reveja o custo vari\u00e1vel ou o pre\u00e7o.',
|
||||
),
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
assert.equal(
|
||||
w.filter((x) =>
|
||||
x.message.includes(
|
||||
'Indique as vendas previstas para calcular a margem e o ponto de equil\u00edbrio.',
|
||||
),
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
assert.equal(JSON.stringify(tables), before);
|
||||
const clear = structuredClone(tables);
|
||||
clear[0].rows[0] = ['Vendas totais', '100.00', '200.00', '200.00'];
|
||||
assert.ok(
|
||||
!financialPlanWarnings(plan, clear).some(
|
||||
(x) =>
|
||||
x.id === 'period-no-contribution' ||
|
||||
x.id === 'period-sales-required',
|
||||
),
|
||||
);
|
||||
const missing = structuredClone(tables);
|
||||
missing[0].rows[0][1] = 'Por determinar';
|
||||
assert.ok(
|
||||
!financialPlanWarnings(plan, missing).some(
|
||||
(x) => x.id === 'period-sales-required',
|
||||
),
|
||||
);
|
||||
const invalidTable = structuredClone(tables);
|
||||
invalidTable[0].issues = ['SYNTHETIC unresolved input'];
|
||||
assert.ok(
|
||||
!financialPlanWarnings(plan, invalidTable).some(
|
||||
(x) =>
|
||||
x.id === 'period-no-contribution' ||
|
||||
x.id === 'period-sales-required',
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||
import { buildComplementaryTables } from '../../resources/js/lib/complementary-report.ts';
|
||||
const message =
|
||||
'A data de t\u00e9rmino n\u00e3o pode ser anterior \u00e0 data de in\u00edcio.';
|
||||
void test('V09 P0077 diagnoses only reversed valid milestone dates with exact requested text and actual field', () => {
|
||||
const { plan, draft, milestones } = complementaryFixture();
|
||||
const rows = [
|
||||
{ ...milestones[0], start_date: '2027-03-10', due_date: '2027-03-01' },
|
||||
];
|
||||
const input = {
|
||||
...draft,
|
||||
project_execution_snapshot: JSON.stringify(rows),
|
||||
},
|
||||
before = JSON.stringify(input);
|
||||
const bad = buildComplementaryTables(input, plan)[1];
|
||||
assert.equal(bad.issues.filter((i) => i.includes(message)).length, 1);
|
||||
assert.match(bad.issues.join(' '), /Marco 1/);
|
||||
assert.match(bad.issues.join(' '), /Prazo previsto/);
|
||||
assert.equal(JSON.stringify(input), before);
|
||||
const fixed = buildComplementaryTables(
|
||||
{
|
||||
...input,
|
||||
project_execution_snapshot: JSON.stringify([
|
||||
{ ...rows[0], due_date: '2027-03-20' },
|
||||
]),
|
||||
},
|
||||
plan,
|
||||
)[1];
|
||||
assert.equal(fixed.issues.filter((i) => i.includes(message)).length, 0);
|
||||
assert.deepEqual(fixed.rows.at(-1), bad.rows.at(-1));
|
||||
const missing = buildComplementaryTables(
|
||||
{
|
||||
...input,
|
||||
project_execution_snapshot: JSON.stringify([
|
||||
{ ...rows[0], start_date: '' },
|
||||
]),
|
||||
},
|
||||
plan,
|
||||
)[1];
|
||||
assert.ok(missing.issues.length);
|
||||
assert.ok(!missing.issues.some((i) => i.includes(message)));
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { financialPlanWarnings } from '../../resources/js/lib/financial-plan-warnings.ts';
|
||||
import {
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
const monthly = (plan, tables = buildIntegralFinancialTables(plan)) =>
|
||||
financialPlanWarnings(plan, tables).filter((w) =>
|
||||
w.id.startsWith('cash-negative-'),
|
||||
);
|
||||
const e15 = () => {
|
||||
const plan = financialReportFixture(12);
|
||||
plan.monthlyOperatingPaymentsByPeriod = ['3000', ...Array(11).fill('0')];
|
||||
return plan;
|
||||
};
|
||||
|
||||
void test('E15: exactly five monthly deficits remain visible despite a positive annual closing, without changing tables or inputs', () => {
|
||||
const plan = e15(),
|
||||
tables = buildIntegralFinancialTables(plan);
|
||||
const before = JSON.stringify({ plan, tables });
|
||||
const warnings = monthly(plan, tables);
|
||||
const expected = [
|
||||
['2027-01', 'Janeiro', '-1 720,00'],
|
||||
['2027-02', 'Fevereiro', '-1 340,00'],
|
||||
['2027-03', 'Março', '-960,00'],
|
||||
['2027-04', 'Abril', '-580,00'],
|
||||
['2027-05', 'Maio', '-200,00'],
|
||||
];
|
||||
assert.deepEqual(
|
||||
warnings.map((w) => w.id),
|
||||
expected.map(([date]) => `cash-negative-${date}`),
|
||||
);
|
||||
expected.forEach(([, month, value], index) => {
|
||||
assert.ok(
|
||||
warnings[index].message.includes(`${month} de 2027: ${value} MZN`),
|
||||
);
|
||||
});
|
||||
assert.equal(
|
||||
tables
|
||||
.find((t) => t.id === 'cashflow')
|
||||
.rows.find((r) => r[0] === 'Caixa final')[13],
|
||||
'2460.00',
|
||||
);
|
||||
assert.equal(JSON.stringify({ plan, tables }), before);
|
||||
assert.deepEqual(
|
||||
monthly(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(plan)),
|
||||
),
|
||||
warnings,
|
||||
);
|
||||
});
|
||||
|
||||
void test('nonnegative, zero, undetermined and invalid cash balances do not invent monthly deficits or dates', () => {
|
||||
const plan = financialReportFixture(12);
|
||||
assert.deepEqual(monthly(plan), []);
|
||||
const tables = buildIntegralFinancialTables(plan);
|
||||
const row = tables
|
||||
.find((t) => t.id === 'cashflow')
|
||||
.rows.find((r) => r[0] === 'Caixa final');
|
||||
row[1] = '0.00';
|
||||
row[2] = '-0.00';
|
||||
row[3] = 'Por determinar';
|
||||
assert.deepEqual(monthly(plan, tables), []);
|
||||
const invalid = e15();
|
||||
invalid.reportAssumptions.taxSource = '';
|
||||
assert.deepEqual(monthly(invalid), []);
|
||||
});
|
||||
|
||||
void test('all sixty negative months use the calendar headers once, excluding annual summary columns', () => {
|
||||
const plan = financialReportFixture(60);
|
||||
plan.monthlyOperatingPayments = '2000';
|
||||
const warnings = monthly(plan);
|
||||
assert.equal(warnings.length, 60);
|
||||
assert.equal(new Set(warnings.map((w) => w.id)).size, 60);
|
||||
assert.match(warnings[0].message, /Janeiro de 2027/);
|
||||
assert.match(warnings[12].message, /Janeiro de 2028/);
|
||||
assert.match(warnings[59].message, /Dezembro de 2031/);
|
||||
});
|
||||
|
||||
void test('dossier report includes each monthly warning once, without copying it into individual tables', () => {
|
||||
const plan = e15();
|
||||
const report = createProjectDossierReport(
|
||||
{
|
||||
project_title: 'SINTÉTICO V11',
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(plan),
|
||||
},
|
||||
{
|
||||
selectedSections: new Set(['finance']),
|
||||
generatedAt: '2026-11-20T12:00:00Z',
|
||||
},
|
||||
);
|
||||
const section = report.sections.find((s) => s.id === 'finance');
|
||||
for (const warning of monthly(plan)) {
|
||||
assert.equal(
|
||||
section.paragraphs.filter((p) => p.includes(warning.message))
|
||||
.length,
|
||||
1,
|
||||
);
|
||||
assert.ok(
|
||||
section.tables.every(
|
||||
(t) => !JSON.stringify(t).includes(warning.message),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -112,7 +112,12 @@ test('dossier provider retains tab focus across navigation/reload, honours expli
|
||||
}
|
||||
return { installed: true, focus: serverFocus };
|
||||
}
|
||||
return { case: { id: url.split('/').pop() } };
|
||||
const request = new URL(url, 'https://qa.invalid');
|
||||
return {
|
||||
case: { id: request.pathname.split('/').pop() },
|
||||
context_opportunity:
|
||||
request.searchParams.get('opportunity'),
|
||||
};
|
||||
},
|
||||
};
|
||||
return require(id);
|
||||
@@ -128,11 +133,13 @@ test('dossier provider retains tab focus across navigation/reload, honours expli
|
||||
while (pending.length) pending.shift()();
|
||||
return tree.props.value;
|
||||
};
|
||||
return async () => {
|
||||
const settle = async () => {
|
||||
render();
|
||||
await new Promise(setImmediate);
|
||||
return render();
|
||||
};
|
||||
settle.immediate = render;
|
||||
return settle;
|
||||
}
|
||||
try {
|
||||
let render = mount(),
|
||||
@@ -151,6 +158,11 @@ test('dossier provider retains tab focus across navigation/reload, honours expli
|
||||
'reload must not adopt the other tab server preference',
|
||||
);
|
||||
pageUrl = '/simulador?context=' + B;
|
||||
assert.equal(
|
||||
render.immediate().view,
|
||||
null,
|
||||
'the pending explicit dossier cannot display the previous dossier',
|
||||
);
|
||||
view = await render();
|
||||
assert.equal(view.active, B, 'explicit authorised dossier wins');
|
||||
assert.equal(readNavigationFocus(7, [A, B]).case_id, B);
|
||||
@@ -162,6 +174,71 @@ test('dossier provider retains tab focus across navigation/reload, honours expli
|
||||
15,
|
||||
);
|
||||
assert.equal(visits.at(-1), '/investimentos/' + A + '#S02');
|
||||
|
||||
pageUrl = '/fundos?context=' + A + '&opportunity=opportunity%3Ahotel';
|
||||
assert.equal(
|
||||
render.immediate().view,
|
||||
null,
|
||||
'a pending opportunity cannot be labelled with the previous scope',
|
||||
);
|
||||
view = await render();
|
||||
assert.equal(view.view.context_opportunity, 'opportunity:hotel');
|
||||
pageUrl = '/documentos';
|
||||
view = await render();
|
||||
assert.equal(view.active, A);
|
||||
assert.equal(
|
||||
view.view.context_opportunity,
|
||||
'opportunity:hotel',
|
||||
'general menus retain this tab opportunity',
|
||||
);
|
||||
render = mount();
|
||||
view = await render();
|
||||
assert.equal(
|
||||
view.view.context_opportunity,
|
||||
'opportunity:hotel',
|
||||
'reload retains the scope',
|
||||
);
|
||||
view.choose(A, 'S08');
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(
|
||||
visits.at(-1),
|
||||
'/investimentos/' + A + '?opportunity=opportunity%3Ahotel#S08',
|
||||
);
|
||||
|
||||
pageUrl = '/investimentos/' + A;
|
||||
view = await render();
|
||||
assert.equal(
|
||||
view.view.context_opportunity,
|
||||
null,
|
||||
'explicit whole dossier clears the previous opportunity',
|
||||
);
|
||||
pageUrl = '/fundos?context=' + A + '&opportunity=opportunity%3Ahotel';
|
||||
view = await render();
|
||||
view.choose(B);
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(
|
||||
visits.at(-1),
|
||||
'/investimentos/' + B,
|
||||
'deliberate dossier switch does not carry the other opportunity',
|
||||
);
|
||||
pageUrl = '/fundos?context=' + B;
|
||||
view = await render();
|
||||
assert.equal(view.active, B);
|
||||
assert.equal(view.view.context_opportunity, null);
|
||||
|
||||
calls.length = 0;
|
||||
pageUrl = '/fundos?context=15111500-0000-4000-8000-000000000099';
|
||||
view = await render();
|
||||
assert.equal(
|
||||
view.active,
|
||||
'',
|
||||
'unavailable explicit dossier must not show an old dossier',
|
||||
);
|
||||
assert.equal(view.view, null);
|
||||
assert.equal(
|
||||
calls.some((c) => c.url.startsWith('/investimentos/15111500')),
|
||||
false,
|
||||
);
|
||||
} finally {
|
||||
globalThis.sessionStorage = oldStorage;
|
||||
globalThis.window = oldWindow;
|
||||
|
||||
@@ -17,6 +17,21 @@ test('tab focus survives reload but is isolated by actor and rechecked against a
|
||||
const focus = { case_id: 'synthetic-A', step_code: 'S08', version: 3 };
|
||||
rememberNavigationFocus(1, focus);
|
||||
assert.deepEqual(readNavigationFocus(1, ['synthetic-A']), focus);
|
||||
rememberNavigationFocus(1, {
|
||||
...focus,
|
||||
opportunity: 'opportunity:hotel',
|
||||
});
|
||||
assert.equal(
|
||||
readNavigationFocus(1, ['synthetic-A']).opportunity,
|
||||
'opportunity:hotel',
|
||||
);
|
||||
assert.equal(readNavigationFocus(1, ['synthetic-B']), null);
|
||||
rememberNavigationFocus(1, {
|
||||
...focus,
|
||||
opportunity: { invalid: true },
|
||||
});
|
||||
assert.deepEqual(readNavigationFocus(1, ['synthetic-A']), focus);
|
||||
rememberNavigationFocus(1, focus);
|
||||
assert.equal(readNavigationFocus(2, ['synthetic-A']), null);
|
||||
assert.equal(readNavigationFocus(1, ['synthetic-B']), null);
|
||||
const firstTab = globalThis.sessionStorage;
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { businessPlanWarnings } from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
void test('V14 optional narratives emit the exact requested guidance once, without altering inputs or existing financial warnings', () => {
|
||||
const metrics = {
|
||||
optionalTexts: [
|
||||
{ label: 'Concorrência', value: ' ' },
|
||||
{ label: 'SWOT', value: '' },
|
||||
],
|
||||
netProfit: -1,
|
||||
};
|
||||
const before = JSON.stringify(metrics);
|
||||
const warnings = businessPlanWarnings(metrics);
|
||||
assert.equal(warnings.filter((w) => w.id === 'optional-texts').length, 1);
|
||||
assert.equal(
|
||||
warnings.find((w) => w.id === 'optional-texts').message,
|
||||
'Pode completar estas secções para um relatório mais convincente.',
|
||||
);
|
||||
assert.ok(warnings.some((w) => w.id === 'loss'));
|
||||
assert.equal(JSON.stringify(metrics), before);
|
||||
assert.deepEqual(businessPlanWarnings({}), []);
|
||||
assert.deepEqual(
|
||||
businessPlanWarnings({
|
||||
optionalTexts: [
|
||||
{
|
||||
label: 'Concorrência',
|
||||
value: 'Existem alternativas identificadas.',
|
||||
},
|
||||
{ label: 'SWOT', value: 'Risco descrito pelo investidor.' },
|
||||
],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
});
|
||||
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 * as guidance from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
void test('V14 real notice lists missing optional sections once and disappears when completed', () => {
|
||||
const source=fs.readFileSync(new URL('../../resources/js/components/business-plan-warnings.tsx',import.meta.url),'utf8');
|
||||
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
|
||||
const module={exports:{}};
|
||||
compileFunction(code,['require','module','exports'])(key=>key==='@/lib/business-plan-guidance'?guidance:require(key),module,module.exports);
|
||||
const render=optionalTexts=>renderToStaticMarkup(React.createElement(module.exports.BusinessPlanWarnings,{metrics:{optionalTexts}}));
|
||||
const html=render([{label:'SWOT',value:''},{label:'Marketing',value:'definido'}]);
|
||||
assert.equal((html.match(/role="status"/g)||[]).length,1);assert.match(html,/SWOT/);assert.doesNotMatch(html,/Marketing/);
|
||||
assert.match(html,/type="button"/);assert.doesNotMatch(html,/aria-invalid|required=/);
|
||||
assert.equal(render([{label:'SWOT',value:'Forcas e riscos descritos.'}]),'');
|
||||
});
|
||||
import * as investorReports from '../../resources/js/lib/investor-dossier-report.ts';
|
||||
import * as projectReports from '../../resources/js/lib/project-dossier-report.ts';
|
||||
void test('V14 dossier SWOT notice uses the selected context, removes when text exists, and does not leak across ambiguous contexts', () => {
|
||||
function load(name){const module={exports:{}};const code=ts.transpileModule(fs.readFileSync(new URL('../../resources/js/components/'+name+'.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;compileFunction(code,['require','module','exports'])(id=>id==='@/lib/business-plan-guidance'?guidance:id==='@/lib/investor-dossier-report'?investorReports:id==='@/lib/project-dossier-report'?projectReports:id==='./business-plan-warnings'?load('business-plan-warnings'):id==='./dossier-report-preview'?{DossierReportPreview:()=>null}:require(id),module,module.exports);return module.exports;}
|
||||
const Component=load('investor-dossier-reports').InvestorDossierReports;
|
||||
const dossier={case:{id:'synthetic',title:'SYNTHETIC',version:1},context_opportunity:null,opportunity_options:[],investment_context:null,phases:{},steps:[],results:[],documents:[]};
|
||||
const render=()=>renderToStaticMarkup(React.createElement(Component,{dossier}));
|
||||
assert.match(render(),/Pode completar/);
|
||||
dossier.preparation_report={case_id:'synthetic',opportunity:null,version:1,context_revision:1,href:'/synthetic',api_state:'not_started',api_issues:[],exports:[],external:[],swot_review_required:false,swot:{object_key:'synthetic',scope:null,source_fingerprint:'',actions:[],rows:[{id:'r',dimension:'strength',text:'SYNTHETIC documented capability',reference:'',source_key:null,date:null,classification:'hypothesis'}]}};
|
||||
assert.doesNotMatch(render(),/Pode completar/);
|
||||
dossier.opportunity_options=['one','two'];dossier.preparation_report=null;assert.doesNotMatch(render(),/Pode completar/);
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
exportBusinessPlanCsv,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { buildFinancialFiscalBridge } from '../../resources/js/lib/financial-fiscal-bridge.ts';
|
||||
import { periodInvestmentsFixture as fixture } from './fixtures/period-investments.mjs';
|
||||
|
||||
test('F22 unfinished regime selection remains editable without losing the new contract', () => {
|
||||
const p = fixture();
|
||||
p.accountingRegime = undefined;
|
||||
const raw = serializeBusinessPlanSnapshot(p);
|
||||
assert.ok(restoreBusinessPlanSnapshot(raw, { editable: true }));
|
||||
assert.equal(restoreBusinessPlanSnapshot(raw), null);
|
||||
p.periodInvestments.enabled = false;
|
||||
const inactive = restoreBusinessPlanSnapshot(
|
||||
serializeBusinessPlanSnapshot(p),
|
||||
{ editable: true },
|
||||
);
|
||||
assert.ok(inactive);
|
||||
assert.deepEqual(inactive.periodInvestments, p.periodInvestments);
|
||||
});
|
||||
|
||||
test('F22 year transition retains the asset before readiness and carries only the identified financing debt', () => {
|
||||
const p = fixture(14);
|
||||
const f = p.periodInvestments.financings[0];
|
||||
p.periodInvestments.financings = [f];
|
||||
f.drawdowns[0].date = '2027-12-15';
|
||||
f.agenda.forEach((a) =>
|
||||
Object.assign(a, {
|
||||
interestExpense: '0',
|
||||
interestPaid: '0',
|
||||
principal: '0',
|
||||
}),
|
||||
);
|
||||
f.agenda[12].principal = '200';
|
||||
f.agenda[13].principal = '300';
|
||||
Object.assign(p.periodInvestments.assets[0], {
|
||||
recognitionDate: '2027-12-20',
|
||||
paymentDate: '2027-12-21',
|
||||
availableDate: '2028-01-16',
|
||||
lifeMonths: '1',
|
||||
});
|
||||
const r = forecastBusinessPlan(p),
|
||||
a = r.periodInvestmentLedger.assets[0];
|
||||
assert.equal(r.periodInvestmentLedger.monthly[11].bankBalance, '500.00');
|
||||
assert.equal(r.periodInvestmentLedger.monthly[12].bankBalance, '300.00');
|
||||
assert.equal(a.monthly[11].net, '100.00');
|
||||
assert.equal(a.monthly[11].depreciation, '0.00');
|
||||
assert.equal(a.monthly[12].depreciation, '51.61');
|
||||
assert.equal(a.monthly[13].depreciation, '48.39');
|
||||
const tables = buildIntegralFinancialTables(p);
|
||||
assert.ok(tables.every((t) => !t.issues.length));
|
||||
});
|
||||
|
||||
test('F22 bank and shareholder funding remain separate, enter cash on disbursement, and never become sales', () => {
|
||||
const p = fixture(),
|
||||
r = forecastBusinessPlan(p),
|
||||
m = r.periodInvestmentLedger.monthly;
|
||||
assert.deepEqual(
|
||||
m.map((r) => r.borrowings),
|
||||
['0.00', '500.00', '200.00', '0.00', '0.00', '0.00', '0.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
m.slice(0, 4).map((r) => r.bankBalance),
|
||||
['0.00', '500.00', '400.00', '0.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
m.slice(0, 4).map((r) => r.shareholderBalance),
|
||||
['0.00', '0.00', '200.00', '0.00'],
|
||||
);
|
||||
assert.equal(r.totalRevenue, '0.00');
|
||||
assert.equal(r.totalCashCollections, '0.00');
|
||||
assert.equal(r.rows[1].closingCash, '1500.00');
|
||||
assert.equal(r.rows[2].closingCash, '1590.00');
|
||||
assert.equal(r.rows[3].closingCash, '890.00');
|
||||
assert.equal(
|
||||
r.periodInvestmentLedger.financings[0].monthly[1].interestBalance,
|
||||
'5.00',
|
||||
);
|
||||
const before = structuredClone(p);
|
||||
forecastBusinessPlan(p);
|
||||
assert.deepEqual(p, before);
|
||||
});
|
||||
test('F22 recognition, cash, debt, interest and asset balances reconcile monthly and annually in both regimes', () => {
|
||||
for (const regime of ['PGC-PE', 'PGC-NIRF']) {
|
||||
const p = fixture(7, regime),
|
||||
r = forecastBusinessPlan(p),
|
||||
tables = buildIntegralFinancialTables(p);
|
||||
assert.ok(
|
||||
tables.every((t) => !t.issues.length),
|
||||
JSON.stringify(tables.map((t) => t.issues)),
|
||||
);
|
||||
const balance = tables.find((t) => t.id === 'balance');
|
||||
assert.deepEqual(
|
||||
balance.rows.find((r) => r[0] === 'Diferença do balanço').slice(1),
|
||||
Array(8).fill('0.00'),
|
||||
);
|
||||
assert.equal(r.periodInvestmentLedger.assets[0].firstFraction, '15/30');
|
||||
assert.deepEqual(
|
||||
r.periodInvestmentLedger.assets[0].monthly.map(
|
||||
(r) => r.depreciation,
|
||||
),
|
||||
['0.00', '0.00', '0.00', '16.67', '33.33', '33.33', '16.67'],
|
||||
);
|
||||
assert.equal(
|
||||
r.periodInvestmentLedger.assets[0].remainingDepreciation,
|
||||
'0.00',
|
||||
);
|
||||
assert.doesNotThrow(() => buildFinancialFiscalBridge(r));
|
||||
assert.match(exportBusinessPlanCsv(p), /BANK-1/);
|
||||
assert.match(exportBusinessPlanCsv(p), /2027-04-16/);
|
||||
}
|
||||
});
|
||||
test('F22 rejects cross-financing overpayments, duplicate origins, unknown agendas and invalid amounts', () => {
|
||||
const p = fixture();
|
||||
p.periodInvestments.financings[0].agenda[2].principal = '501';
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/dívida disponível deste financiamento/,
|
||||
);
|
||||
p.periodInvestments.financings[0].agenda[2].principal = '100';
|
||||
p.periodInvestments.financings[1].id = 'BANK-1';
|
||||
assert.throws(() => forecastBusinessPlan(p), /duplicado/);
|
||||
p.periodInvestments.financings[1].id = 'SHARE-1';
|
||||
p.periodInvestments.financings[0].agenda.pop();
|
||||
assert.throws(() => forecastBusinessPlan(p), /agenda completa/);
|
||||
p.periodInvestments.financings[0].agenda.push({
|
||||
month: 7,
|
||||
interestExpense: '',
|
||||
interestPaid: '0',
|
||||
principal: '0',
|
||||
});
|
||||
assert.throws(() => forecastBusinessPlan(p), /Juros reconhecidos/);
|
||||
});
|
||||
test('F22 excludes advances even in the same month and excludes asset purchase credit', () => {
|
||||
const p = fixture(),
|
||||
a = p.periodInvestments.assets[0];
|
||||
a.paymentDate = '2027-03-31';
|
||||
assert.throws(() => forecastBusinessPlan(p), /antecipado excluído/);
|
||||
a.paymentDate = '2027-05-01';
|
||||
assert.throws(() => forecastBusinessPlan(p), /mesmo período/);
|
||||
a.paymentDate = '2027-04-02';
|
||||
a.recognitionDate = '2027-04-03';
|
||||
assert.throws(() => forecastBusinessPlan(p), /antecipado excluído/);
|
||||
a.recognitionDate = '2027-04-01';
|
||||
a.availableDate = '';
|
||||
assert.throws(() => forecastBusinessPlan(p), /Disponibilidade para uso/);
|
||||
});
|
||||
test('F22 explicit regime and linear justification are required, and non-depreciable cost is retained', () => {
|
||||
const p = fixture(7, 'PGC-NIRF'),
|
||||
a = p.periodInvestments.assets[0];
|
||||
a.linearBasis = '';
|
||||
assert.throws(() => forecastBusinessPlan(p), /Fundamentação linear/);
|
||||
p.accountingRegime = undefined;
|
||||
assert.throws(() => forecastBusinessPlan(p), /Regime/);
|
||||
p.accountingRegime = 'PGC-PE';
|
||||
a.depreciable = false;
|
||||
a.base = '0';
|
||||
a.lifeMonths = '';
|
||||
a.availableDate = '';
|
||||
const r = forecastBusinessPlan(p);
|
||||
assert.equal(
|
||||
r.periodInvestmentLedger.assets[0].monthly.at(-1).net,
|
||||
'100.00',
|
||||
);
|
||||
assert.ok(
|
||||
r.periodInvestmentLedger.assets[0].monthly.every(
|
||||
(r) => r.depreciation === '0.00',
|
||||
),
|
||||
);
|
||||
});
|
||||
test('F22 full first month, leap February, cent rounding and horizons 1/60 retain the approved closing rule', () => {
|
||||
for (const available of ['2027-04-01', '2028-02-29']) {
|
||||
const p = fixture(4);
|
||||
p.periodInvestments.financings = [];
|
||||
const a = p.periodInvestments.assets[0];
|
||||
a.recognitionDate = available;
|
||||
a.paymentDate = available;
|
||||
a.availableDate = available;
|
||||
a.base = '0.01';
|
||||
a.cost = '0.01';
|
||||
a.lifeMonths = '1';
|
||||
p.reportAssumptions.startYear = available.slice(0, 4);
|
||||
const r = forecastBusinessPlan(p);
|
||||
assert.equal(
|
||||
r.periodInvestmentLedger.assets[0].monthly.at(-1).accumulated,
|
||||
'0.01',
|
||||
);
|
||||
}
|
||||
for (const periods of [1, 60]) {
|
||||
const p = fixture(periods);
|
||||
p.periodInvestments.financings = [];
|
||||
const a = p.periodInvestments.assets[0];
|
||||
a.recognitionDate = '2027-01-01';
|
||||
a.paymentDate = '2027-01-01';
|
||||
a.availableDate = '2027-01-16';
|
||||
a.lifeMonths = '600';
|
||||
const r = forecastBusinessPlan(p),
|
||||
end = r.periodInvestmentLedger.assets[0];
|
||||
assert.ok(Number(end.remainingDepreciation) > 0);
|
||||
assert.ok(Number(end.monthly.at(-1).net) > 0);
|
||||
}
|
||||
const future = fixture(1),
|
||||
r = forecastBusinessPlan(future);
|
||||
assert.ok(r.periodInvestmentLedger.assets[0].outsideHorizon);
|
||||
assert.equal(r.periodInvestmentLedger.monthly[0].acquisitions, '0.00');
|
||||
assert.equal(r.periodInvestmentLedger.monthly[0].borrowings, '0.00');
|
||||
});
|
||||
test('F22 snapshot 23 recovers the complete contract and inactive mode preserves every legacy result', () => {
|
||||
const p = fixture(),
|
||||
snapshot = serializeBusinessPlanSnapshot(p);
|
||||
assert.equal(JSON.parse(snapshot).version, 23);
|
||||
const restored = restoreBusinessPlanSnapshot(snapshot);
|
||||
assert.ok(restored);
|
||||
assert.deepEqual(restored.periodInvestments, p.periodInvestments);
|
||||
assert.deepEqual(forecastBusinessPlan(restored), forecastBusinessPlan(p));
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(
|
||||
snapshot.replace('"version":23', '"version":22'),
|
||||
),
|
||||
null,
|
||||
);
|
||||
p.periodInvestments.enabled = false;
|
||||
assert.deepEqual(
|
||||
forecastBusinessPlan(p),
|
||||
forecastBusinessPlan({ ...p, periodInvestments: undefined }),
|
||||
);
|
||||
p.periodInvestments.enabled = true;
|
||||
p.periodInvestments.assets[0].paymentDate = '2027-05-01';
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p)),
|
||||
null,
|
||||
);
|
||||
assert.ok(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p), {
|
||||
editable: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { mozambiqueCaeSubclasses } from '../../resources/js/lib/cae-mozambique-data.ts';
|
||||
import { describePlanCae, selectPlanCae, mozambiqueCaeSource } from '../../resources/js/lib/cae-mozambique.ts';
|
||||
import { serializeBusinessPlanSnapshot, restoreBusinessPlanSnapshot } from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { createIntegralFinancialReport, createProjectDossierPrintHtml, generateProjectDossierDocx } from '../../resources/js/lib/project-dossier-report.ts';
|
||||
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||
import JSZip from 'jszip';
|
||||
import { matchesChoice } from '../../resources/js/lib/catalogue-choice.ts';
|
||||
import { planCaeChoices } from '../../resources/js/lib/cae-mozambique.ts';
|
||||
|
||||
void test('searching Hotel includes the official plural Hotéis without assigning a code', () => {
|
||||
const hotel = planCaeChoices.find(n => n.value === '55111');
|
||||
assert.equal(matchesChoice('hotel', [hotel.label, ...hotel.keywords]), true);
|
||||
assert.equal(describePlanCae(undefined).value, 'Não documentado');
|
||||
});
|
||||
|
||||
void test('official structure preserves 579 unique five digit subclasses and source pages', () => {
|
||||
assert.equal(mozambiqueCaeSubclasses.length, 579);
|
||||
assert.equal(new Set(mozambiqueCaeSubclasses.map(n => n.code)).size, 579);
|
||||
for (const n of mozambiqueCaeSubclasses) {
|
||||
assert.match(n.code, /^\d{5}$/);
|
||||
assert.ok(n.label && n.page >= 38 && n.page <= 65);
|
||||
assert.doesNotMatch(n.label, /Secção\*|NÍVEL|\s[Pp]\d{4}$/);
|
||||
}
|
||||
assert.equal(describePlanCae(selectPlanCae('01120')).value, '01120 — Cultura de arroz');
|
||||
assert.match(describePlanCae(selectPlanCae('55111')).value, /Hotéis com restaurante/);
|
||||
assert.match(describePlanCae(selectPlanCae('90000')).value, /ACTIVIDADES/i);
|
||||
});
|
||||
|
||||
void test('official reference does not silently reuse divergent eBAU entries', () => {
|
||||
const existing = JSON.parse(fs.readFileSync(new URL('../../database/data/proactive-supply-classification.json', import.meta.url))).nodes;
|
||||
const normalize = s => s.toLocaleLowerCase('pt').replace(/[^\p{L}\p{N}]/gu, '');
|
||||
for (const n of mozambiqueCaeSubclasses.filter(n => n.code !== '96090'))
|
||||
assert.ok(existing.some(e => e.code === n.code && normalize(e.label) === normalize(n.label)), n.code);
|
||||
assert.match(describePlanCae(selectPlanCae('96090')).value, /Outras actividades de serviços pessoais/);
|
||||
for (const code of ['47210', '23962', 'hotel', 'turismo']) assert.throws(() => selectPlanCae(code));
|
||||
assert.equal(describePlanCae(undefined).value, 'Não documentado');
|
||||
assert.equal(selectPlanCae(''), undefined);
|
||||
});
|
||||
|
||||
void test('classification survives existing snapshot persistence without changing financial tables', () => {
|
||||
const { plan } = complementaryFixture();
|
||||
const before = buildIntegralFinancialTables(plan);
|
||||
const changed = { ...plan, economicClassification: selectPlanCae('55111') };
|
||||
const recovered = restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(changed));
|
||||
assert.deepEqual(recovered.economicClassification, changed.economicClassification);
|
||||
assert.deepEqual(buildIntegralFinancialTables(recovered), before);
|
||||
assert.equal(restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(plan)).economicClassification, undefined);
|
||||
});
|
||||
|
||||
void test('mismatched source or unknown selection remains unconfirmed without suppressing financial values', () => {
|
||||
for (const selection of [selectPlanCae('55111'), { ...selectPlanCae('55111'), sourceSha256: 'different' }, { ...selectPlanCae('55111'), code: '47210' }, {}]) {
|
||||
const { plan, draft } = complementaryFixture();
|
||||
const snapshot = serializeBusinessPlanSnapshot({ ...plan, economicClassification: selection });
|
||||
const report = createIntegralFinancialReport({ ...draft, business_plan_snapshot: snapshot });
|
||||
assert.equal(report.sections[0].tables.length, 11);
|
||||
assert.equal(describePlanCae(selection).confirmed, selection.sourceSha256 === mozambiqueCaeSource.sha256 && selection.code === '55111');
|
||||
assert.deepEqual(report.sections[0].tables.filter(t => !['ratios','market-analysis','personnel','milestones'].includes(t.id)), buildIntegralFinancialTables(plan));
|
||||
}
|
||||
});
|
||||
|
||||
void test('consolidated report and both existing exports carry canonical CAE and source without inventing a twelfth table', async () => {
|
||||
const { plan, draft } = complementaryFixture();
|
||||
const report = createIntegralFinancialReport({ ...draft, business_plan_snapshot: serializeBusinessPlanSnapshot({ ...plan, economicClassification: selectPlanCae('01120') }) });
|
||||
assert.equal(report.sections[0].tables.length, 11);
|
||||
const row = report.sections[0].rows.find(r => r.field === 'Classificação CAE do plano');
|
||||
assert.equal(row.value, '01120 — Cultura de arroz');
|
||||
assert.match(row.origin, /INE, 2008, página PDF 38/);
|
||||
const html = await createProjectDossierPrintHtml(report, []);
|
||||
assert.match(html, /01120/);
|
||||
const file = await generateProjectDossierDocx(report, []), zip = await JSZip.loadAsync(file instanceof Blob ? await file.arrayBuffer() : file);
|
||||
assert.match(await zip.file('word/document.xml').async('string'), /01120/);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
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 { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
import * as catalogue from '../../resources/js/lib/catalogue-context.ts';
|
||||
import * as territory from '../../resources/js/lib/search-territory.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const Frame = ({ children }) => React.createElement('main', null, children);
|
||||
const shared = {
|
||||
Layout: Frame,
|
||||
Management: Frame,
|
||||
Field: ({ children }) => React.createElement('label', null, children),
|
||||
control: '',
|
||||
button: '',
|
||||
Pagination: () => null,
|
||||
kind: () => '',
|
||||
};
|
||||
const module = { exports: {} };
|
||||
compileFunction(
|
||||
ts.transpileModule(
|
||||
fs.readFileSync('resources/js/pages/portfolio/index.tsx', 'utf8'),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText,
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(name) => {
|
||||
if (name === '@inertiajs/react')
|
||||
return {
|
||||
Link: ({ href, children }) =>
|
||||
React.createElement('a', { href }, children),
|
||||
useForm: (data) => ({ data, setData() {}, get() {} }),
|
||||
usePage: () => ({ url: '/carteira?q=Soja' }),
|
||||
};
|
||||
if (name === '@/lib/catalogue-context') return catalogue;
|
||||
if (name === '@/lib/search-territory') return territory;
|
||||
if (name === '@/components/investment-territory')
|
||||
return { TerritoryFields: () => null };
|
||||
if (name === '../management/shared' || name === './shared')
|
||||
return shared;
|
||||
return require(name);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const page = (data) =>
|
||||
renderToStaticMarkup(
|
||||
React.createElement(module.exports.default, {
|
||||
management: false,
|
||||
records: { data: [] },
|
||||
filters: { q: 'Soja' },
|
||||
publishedOpportunities: { data },
|
||||
territorySelection: [],
|
||||
sectors: [],
|
||||
}),
|
||||
);
|
||||
test('real documentary opportunity appears within the empty portfolio consultation with its own detail link', () => {
|
||||
// Existing public QA record, from the unchanged documentary corridor source.
|
||||
const source = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'database/data/corridor-investment-opportunities.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const summary = source.groups
|
||||
.find((g) => g.name === 'Corredor da Beira')
|
||||
.opportunities.find((o) => o.chain === 'Soja').description;
|
||||
const html = page([
|
||||
{
|
||||
id: 287,
|
||||
slug: 'inv-mz-gen-5563232446855414',
|
||||
title: 'Soja — Corredor da Beira',
|
||||
summary,
|
||||
location: 'Localização não indicada',
|
||||
},
|
||||
]);
|
||||
assert.match(html, /Oportunidades publicadas nesta consulta/);
|
||||
assert.match(html, /Soja — Corredor da Beira/);
|
||||
assert.match(
|
||||
html,
|
||||
/href="\/oportunidades\/inv-mz-gen-5563232446855414\?catalogue_query=q%3DSoja"/,
|
||||
);
|
||||
assert.match(html, /Localização não indicada/);
|
||||
});
|
||||
test('no matching public observations produce an explicit empty state rather than invented cards', () => {
|
||||
const html = page([]);
|
||||
assert.match(
|
||||
html,
|
||||
/Não há oportunidades publicadas com correspondência documentada/,
|
||||
);
|
||||
assert.doesNotMatch(html, /inv-mz-gen-/);
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
correctionFieldHints,
|
||||
fieldLabelMatches,
|
||||
} from '../../resources/js/lib/field-corrections.ts';
|
||||
import {
|
||||
publicReference,
|
||||
publicSourceHref,
|
||||
publicLocation,
|
||||
uniquePresentation,
|
||||
publicPortfolioText,
|
||||
} from '../../resources/js/lib/public-presentation.ts';
|
||||
import {
|
||||
catalogueFilterHref,
|
||||
catalogueDetailHref,
|
||||
catalogueReturnHref,
|
||||
} from '../../resources/js/lib/catalogue-context.ts';
|
||||
|
||||
test('existing diagnostics point to matching labels without inventing fields for unknown messages', () => {
|
||||
const hints = correctionFieldHints(
|
||||
'O capital discriminado não coincide com o capital próprio.',
|
||||
);
|
||||
assert.ok(
|
||||
hints.some((h) => fieldLabelMatches('Capital do proprietário', h)),
|
||||
);
|
||||
assert.ok(hints.some((h) => fieldLabelMatches('Capital próprio (MZN)', h)));
|
||||
assert.ok(
|
||||
correctionFieldHints(
|
||||
'Confira «Preço por unidade»: valor em falta.',
|
||||
).some((h) => fieldLabelMatches('Preço por unidade', h)),
|
||||
);
|
||||
assert.equal(
|
||||
correctionFieldHints('Situação não prevista').some((h) =>
|
||||
fieldLabelMatches('Capital próprio', h),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
fieldLabelMatches('Capital do investidor', 'Capital do proprietário'),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('public sources retain legal references and official PHP links, excluding local paths and executable schemes', () => {
|
||||
for (const value of [
|
||||
'C:\\laragon\\www\\portal\\app.php',
|
||||
'docs/auditoria/e25.json',
|
||||
'QA-20261121',
|
||||
'http://127.0.0.3:18724/private',
|
||||
'javascript:alert(1)',
|
||||
'https://example.org/resources/js/report.ts',
|
||||
])
|
||||
assert.equal(publicReference(value), null, value);
|
||||
assert.equal(publicReference('Decreto n.º 70/2009'), 'Decreto n.º 70/2009');
|
||||
assert.equal(
|
||||
publicSourceHref('https://example.gov.mz/documento.php?id=70'),
|
||||
'https://example.gov.mz/documento.php?id=70',
|
||||
);
|
||||
assert.equal(publicSourceHref('Decreto n.º 70/2009'), undefined);
|
||||
});
|
||||
|
||||
test('presentation deduplicates identical editions and preserves source records and full location', () => {
|
||||
const rows = Object.freeze([
|
||||
Object.freeze({ ref: 'Lei', date: '2020' }),
|
||||
Object.freeze({ ref: 'Lei', date: '2020' }),
|
||||
Object.freeze({ ref: 'Lei', date: '2024' }),
|
||||
]);
|
||||
assert.equal(uniquePresentation(rows, (r) => r.ref + r.date).length, 2);
|
||||
assert.equal(rows.length, 3);
|
||||
assert.equal(
|
||||
publicLocation([
|
||||
{ name: 'Cabo Delgado' },
|
||||
{ name: 'Balama' },
|
||||
{ name: 'Balama' },
|
||||
]),
|
||||
'Cabo Delgado · Balama · Balama',
|
||||
);
|
||||
});
|
||||
|
||||
test('published names replace internal cross-reference codes without replacing a code inside a word or altering originals', () => {
|
||||
const names = Object.freeze({
|
||||
A06: 'Projecto de arroz',
|
||||
'CLU-01': 'Cluster industrial',
|
||||
'A.1': 'Nome pontuado',
|
||||
});
|
||||
assert.equal(
|
||||
publicPortfolioText(
|
||||
'A06 e CLU-01; A.1. CA06 e A060 permanecem.',
|
||||
names,
|
||||
),
|
||||
'Projecto de arroz e Cluster industrial; Nome pontuado. CA06 e A060 permanecem.',
|
||||
);
|
||||
assert.equal(names.A06, 'Projecto de arroz');
|
||||
});
|
||||
|
||||
test('filter removal clears actual indexed arrays and dependent geography without losing deliberate criteria', () => {
|
||||
assert.equal(
|
||||
catalogueFilterHref(
|
||||
'/oportunidades?q=arroz&facets%5B0%5D=a&facets%5B1%5D=b&page=3',
|
||||
['q', 'facets'],
|
||||
'facets',
|
||||
),
|
||||
'/oportunidades?q=arroz',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueFilterHref(
|
||||
'/zonas?category=zee&province_id=p&district_id=d&locality_id=l&activity=energia&page=2',
|
||||
[],
|
||||
'province_id',
|
||||
),
|
||||
'/zonas?category=zee&activity=energia',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueFilterHref('/zonas?category=zee&q=arroz&page=2', [
|
||||
'category',
|
||||
'q',
|
||||
]),
|
||||
'/zonas',
|
||||
);
|
||||
const detail = catalogueDetailHref(
|
||||
'/zonas/zone',
|
||||
'category=industrial_park&activity=energia&q=Balama&page=2',
|
||||
);
|
||||
const back = new URL(
|
||||
catalogueReturnHref('/zonas', detail),
|
||||
'https://portal.invalid',
|
||||
);
|
||||
assert.equal(back.searchParams.get('activity'), 'energia');
|
||||
assert.equal(back.searchParams.get('category'), 'industrial_park');
|
||||
assert.equal(back.searchParams.get('q'), 'Balama');
|
||||
assert.equal(back.searchParams.get('page'), '2');
|
||||
});
|
||||
@@ -8,6 +8,32 @@ import {
|
||||
import { getSimulationSections } from '../../resources/js/lib/simulation-form.ts';
|
||||
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
void test('readiness explains stored answer codes in Portuguese without changing the draft', () => {
|
||||
const draft = {
|
||||
target_customers: 'Clientes sintéticos',
|
||||
market_assumption: 'Hipótese por testar',
|
||||
customer_validation_status: 'partial',
|
||||
cost_estimate_status: 'unknown',
|
||||
location_assessment_status: 'no',
|
||||
funding_status: 'in_process',
|
||||
receivables_timing_status: 'not_started',
|
||||
annual_revenue: '12000',
|
||||
};
|
||||
const before = JSON.stringify(draft);
|
||||
const origins = getProjectReadiness(draft)
|
||||
.map((item) => item.origin)
|
||||
.join('\n');
|
||||
assert.match(origins, /Parcialmente/);
|
||||
assert.match(origins, /Por confirmar/);
|
||||
assert.match(origins, /Estado declarado: Não/);
|
||||
assert.match(origins, /Em curso/);
|
||||
assert.doesNotMatch(
|
||||
origins,
|
||||
/\b(?:partial|unknown|in_process|not_started)\b/,
|
||||
);
|
||||
assert.equal(JSON.stringify(draft), before);
|
||||
});
|
||||
|
||||
void test('idea journey reuses one dossier and exposes the six requested stages', () => {
|
||||
const sections = getSimulationSections({
|
||||
purpose: 'simulate_only',
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
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 ts from 'typescript';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import * as publicPresentation from '../../resources/js/lib/public-presentation.ts';
|
||||
import { displayReportMoney } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
function component(name) {
|
||||
const module = { exports: {} };
|
||||
const code = ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
new URL(
|
||||
`../../resources/js/components/${name}.tsx`,
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) =>
|
||||
id === '@/lib/public-presentation'
|
||||
? publicPresentation
|
||||
: id.startsWith('./')
|
||||
? component(id.slice(2))
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return module.exports;
|
||||
}
|
||||
test('real public source list separates links, merges duplicate notes, retains different editions and original data', () => {
|
||||
const sources = [
|
||||
{
|
||||
title: 'Lei de investimento',
|
||||
url: 'https://example.gov.mz/lei.php',
|
||||
source_date: '2020-01-01',
|
||||
supports: 'Âmbito territorial',
|
||||
},
|
||||
{
|
||||
title: 'Lei de investimento',
|
||||
url: 'https://example.gov.mz/lei.php',
|
||||
source_date: '2020-01-01',
|
||||
supports: 'Âmbito territorial',
|
||||
},
|
||||
{
|
||||
title: 'Lei de investimento',
|
||||
url: 'https://example.gov.mz/lei.php',
|
||||
source_date: '2024-01-01',
|
||||
supports: 'Edição posterior',
|
||||
},
|
||||
{
|
||||
title: 'docs/interno.json',
|
||||
url: 'C:\\portal\\app.php',
|
||||
supports: 'QA-20261121',
|
||||
},
|
||||
];
|
||||
const before = JSON.stringify(sources);
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(component('public-source-list').default, {
|
||||
sources,
|
||||
}),
|
||||
);
|
||||
assert.equal((html.match(/<li>/g) || []).length, 2);
|
||||
assert.equal((html.match(/Âmbito territorial/g) || []).length, 1);
|
||||
assert.match(html, /2020-01-01/);
|
||||
assert.match(html, /2024-01-01/);
|
||||
assert.match(html, /href="https:\/\/example.gov.mz\/lei.php"/);
|
||||
assert.doesNotMatch(html, /docs\/interno|QA-20261121|C:\\portal/);
|
||||
assert.equal(JSON.stringify(sources), before);
|
||||
});
|
||||
test('real report tables expose existing message for navigation without changing their rows or values', () => {
|
||||
const module = { exports: {} };
|
||||
const code = ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/investment-report-tables.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) =>
|
||||
id === '@/lib/integral-financial-report'
|
||||
? { displayReportMoney }
|
||||
: id === '@/lib/financial-issue-presentation'
|
||||
? {
|
||||
financialIssuesForDisplay: () => [
|
||||
{
|
||||
message: 'Confira «Capital próprio».',
|
||||
tables: ['Quadro'],
|
||||
},
|
||||
],
|
||||
}
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const tables = [
|
||||
{
|
||||
id: 'synthetic',
|
||||
title: 'Quadro',
|
||||
headers: ['Rubrica', 'Janeiro'],
|
||||
rows: [['Saldo declarado', '123.45']],
|
||||
notes: [],
|
||||
issues: ['Confira «Capital próprio».'],
|
||||
},
|
||||
];
|
||||
const before = JSON.stringify(tables);
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(module.exports.InvestmentReportTables, { tables }),
|
||||
);
|
||||
assert.match(html, /data-correction-message="Confira «Capital próprio»."/);
|
||||
assert.doesNotMatch(html, /href="#portal-corrections"/); // Read-only report consumers need no dead editor link.
|
||||
assert.match(html, /Saldo declarado/);
|
||||
assert.equal(JSON.stringify(tables), before);
|
||||
});
|
||||
|
||||
test('real territorial presentation removes identical geometry editions but preserves distinct dates and full hierarchy', () => {
|
||||
const module = { exports: {} };
|
||||
const code = ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/structure-geography.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) =>
|
||||
id === '@/lib/public-presentation'
|
||||
? publicPresentation
|
||||
: id === './public-reference'
|
||||
? component('public-reference')
|
||||
: id === '@inertiajs/react'
|
||||
? {
|
||||
Link: ({ children, ...p }) =>
|
||||
React.createElement('a', p, children),
|
||||
}
|
||||
: id.startsWith('./')
|
||||
? { default: () => null }
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const point = {
|
||||
geometry_id: 'point-1',
|
||||
source_reference: 'Decreto 70/2009',
|
||||
source_date: '2020-01-01',
|
||||
geometry: { coordinates: [32, -25] },
|
||||
};
|
||||
const boundary = {
|
||||
geometry_id: 'boundary-1',
|
||||
source_reference: 'Decreto 70/2009',
|
||||
source_date: '2020-01-01',
|
||||
geometry: { type: 'Polygon', coordinates: [] },
|
||||
};
|
||||
const locations = [
|
||||
{
|
||||
id: 'location',
|
||||
name: 'Balama sintético',
|
||||
role: 'primary',
|
||||
location_type: 'district',
|
||||
path: [
|
||||
{ id: 'p', name: 'Cabo Delgado', location_type: 'province' },
|
||||
{ id: 'd', name: 'Balama', location_type: 'district' },
|
||||
],
|
||||
coordinates: [
|
||||
point,
|
||||
{ ...point },
|
||||
{ ...point, source_date: '2024-01-01' },
|
||||
],
|
||||
boundaries: [
|
||||
boundary,
|
||||
{ ...boundary },
|
||||
{ ...boundary, source_date: '2024-01-01' },
|
||||
],
|
||||
},
|
||||
];
|
||||
const before = JSON.stringify(locations);
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(module.exports.LocationList, { locations }),
|
||||
);
|
||||
assert.equal((html.match(/Coordenadas documentadas/g) || []).length, 2);
|
||||
assert.equal((html.match(/Polígono cadastrado/g) || []).length, 2);
|
||||
assert.match(html, /Cabo Delgado/);
|
||||
assert.match(html, /Balama/);
|
||||
assert.match(html, /2024-01-01/);
|
||||
assert.equal(JSON.stringify(locations), before);
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
void test('V09 missing year in an existing F22 snapshot uses the same literal without changing financial modules', () => {
|
||||
const p = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'docs/investmoz/v2/auditoria-portal/e32-f22-20261121/saved-plan.json',
|
||||
'utf8',
|
||||
),
|
||||
).plan;
|
||||
p.reportAssumptions.startYear = '';
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/«Ano inicial»: Preencha este campo para continuar\./,
|
||||
);
|
||||
});
|
||||
void test('V09 report year and fiscal source use required-field literal with actual labels', () => {
|
||||
const p = financialReportFixture(12);
|
||||
for (const [key, label] of [
|
||||
['startYear', 'Ano inicial'],
|
||||
['taxSource', 'Fonte ou pressuposto dos impostos estimados'],
|
||||
]) {
|
||||
const next = structuredClone(p);
|
||||
next.reportAssumptions[key] = '';
|
||||
assert.ok(
|
||||
buildIntegralFinancialTables(next)[0].issues.some(
|
||||
(x) =>
|
||||
x.includes(`«${label}»`) &&
|
||||
x.includes('Preencha este campo para continuar.'),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
import { fieldLabelMatches } from '../../resources/js/lib/field-corrections.ts';
|
||||
import { forecastBusinessPlan } from '../../resources/js/lib/business-financial-plan.ts';
|
||||
void test('V09 exact capital field does not link to another prefix field', () => {
|
||||
const names = ['Capital', 'Capital e resultados anteriores'];
|
||||
assert.equal(
|
||||
fieldLabelMatches('Capital', 'Capital e resultados anteriores', names),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
fieldLabelMatches(
|
||||
'Capital e resultados anteriores',
|
||||
'Capital e resultados anteriores',
|
||||
names,
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
void test('V09 shared numeric consumers and bounded percentages retain rejection with literal guidance', () => {
|
||||
const base = financialReportFixture(12);
|
||||
for (const [value, message] of [
|
||||
['', 'Preencha este campo'],
|
||||
['abc', 'Introduza apenas números'],
|
||||
['-1', 'Este valor não pode ser negativo'],
|
||||
])
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan({ ...base, equity: value }),
|
||||
new RegExp(message),
|
||||
);
|
||||
for (const patch of [
|
||||
{ salesCollectionPercent: '101' },
|
||||
{ openingReceivablesCollectionPercent: '101' },
|
||||
{ openingReceivablesInstallments: [{ month: 1, percent: '101' }] },
|
||||
{ openingPayablesInstallments: [{ month: 1, percent: '101' }] },
|
||||
{ salesRecoverySchedule: [{ month: 1, percent: '101' }] },
|
||||
])
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan({ ...base, ...patch }),
|
||||
/Introduza uma percentagem entre 0% e 100%\./,
|
||||
);
|
||||
});
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
void test('V09 report opening balances and startup amounts use literal diagnostics without changing valid tables', () => {
|
||||
const base = financialReportFixture(12),
|
||||
original = buildIntegralFinancialTables(base);
|
||||
for (const [key, label] of [
|
||||
['openingFixedAssets', 'Activos fixos anteriores'],
|
||||
['openingOtherAssets', 'Outros activos anteriores'],
|
||||
['openingEquity', 'Capital e resultados anteriores'],
|
||||
])
|
||||
for (const [value, message] of [
|
||||
['', 'Preencha este campo'],
|
||||
['abc', 'Introduza apenas números'],
|
||||
['-1', 'Este valor não pode ser negativo'],
|
||||
['1.234', 'duas casas decimais'],
|
||||
]) {
|
||||
const plan = structuredClone(base);
|
||||
plan.reportAssumptions[key] = value;
|
||||
const input = JSON.stringify(plan),
|
||||
t = buildIntegralFinancialTables(plan);
|
||||
assert.ok(
|
||||
t.every((x) =>
|
||||
x.issues.some(
|
||||
(s) => s.includes(label) && s.includes(message),
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.equal(JSON.stringify(plan), input);
|
||||
}
|
||||
for (const [key, value, label, message] of [
|
||||
['amount', '', 'Montante de arranque 1', 'Preencha este campo'],
|
||||
['amount', 'abc', 'Montante de arranque 1', 'Introduza apenas números'],
|
||||
['amount', '-1', 'Montante de arranque 1', 'não pode ser negativo'],
|
||||
['label', '', 'Despesa 1', 'Preencha este campo'],
|
||||
]) {
|
||||
const p = structuredClone(base);
|
||||
p.reportAssumptions.startupExpenses[0][key] = value;
|
||||
assert.ok(
|
||||
buildIntegralFinancialTables(p)[0].issues.some(
|
||||
(s) => s.includes(label) && s.includes(message),
|
||||
),
|
||||
);
|
||||
}
|
||||
assert.deepEqual(buildIntegralFinancialTables(base), original);
|
||||
});
|
||||
void test('V09 monthly tax diagnostics distinguish absent, malformed, negative and precision with exact month label', () => {
|
||||
const base = financialReportFixture(12);
|
||||
for (const [key, label] of [
|
||||
['taxExpenseByMonth', 'Imposto reconhecido'],
|
||||
['taxPaymentByMonth', 'Pagamento fiscal previsto'],
|
||||
])
|
||||
for (const [value, message] of [
|
||||
['', 'Preencha este campo'],
|
||||
['abc', 'Introduza apenas números'],
|
||||
['-1', 'Este valor não pode ser negativo'],
|
||||
['0.001', 'duas casas decimais'],
|
||||
]) {
|
||||
const p = structuredClone(base);
|
||||
p.reportAssumptions[key][1] = value;
|
||||
const t = buildIntegralFinancialTables(p);
|
||||
assert.ok(
|
||||
t.every((x) =>
|
||||
x.issues.some(
|
||||
(s) =>
|
||||
s.includes(`«${label} — mês 2»`) &&
|
||||
s.includes(message),
|
||||
),
|
||||
),
|
||||
);
|
||||
p.reportAssumptions[key][1] = base.reportAssumptions[key][1];
|
||||
assert.deepEqual(
|
||||
buildIntegralFinancialTables(p),
|
||||
buildIntegralFinancialTables(base),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,432 @@
|
||||
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 JSZip from 'jszip';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import {
|
||||
buildIntegralFinancialTables,
|
||||
newReportAssumptions,
|
||||
} from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import * as requirements from '../../resources/js/lib/startup-asset-requirements.ts';
|
||||
import {
|
||||
newAnnualReferencePlan,
|
||||
serializeAnnualExampleSnapshot,
|
||||
calculateAnnualReferencePlan,
|
||||
} from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
import { buildAnnualExampleTables } from '../../resources/js/lib/annual-example-report.ts';
|
||||
import { annualExampleOriginalDetail as original } from '../../resources/js/lib/annual-example-original-detail.ts';
|
||||
import { reconcileOriginalExample } from '../../resources/js/lib/annual-example-reconciliation.ts';
|
||||
import {
|
||||
createIntegralFinancialReport,
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
import { selectPlanCae } from '../../resources/js/lib/cae-mozambique.ts';
|
||||
const cell = (ts, id, label, col) =>
|
||||
ts.find((t) => t.id === id).rows.find((r) => r[0] === label)[col];
|
||||
const cents = (s) => BigInt(s.replace('.', ''));
|
||||
const reload = (p) =>
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p));
|
||||
function startup() {
|
||||
const p = financialReportFixture(12);
|
||||
for (const key of [
|
||||
'monthlyPayrollExpense',
|
||||
'monthlyPayrollPayments',
|
||||
'monthlyOperatingExpenses',
|
||||
'monthlyOperatingPayments',
|
||||
'monthlyInventoryPurchases',
|
||||
'monthlyVariableCostPayments',
|
||||
'assetDepreciation',
|
||||
'monthlyInterestExpense',
|
||||
'monthlyInterestPayment',
|
||||
'monthlyPrincipalRepayment',
|
||||
])
|
||||
p[key] = '0';
|
||||
Object.assign(p, {
|
||||
openingCash: '20000',
|
||||
inventory: '10000',
|
||||
receivables: '5000',
|
||||
assetInvestment: '600',
|
||||
equity: '0',
|
||||
economicClassification: selectPlanCae('55111'),
|
||||
startupAssetRequirements: {
|
||||
cashRequired: '90000',
|
||||
otherCurrentAssetsRequired: '150000',
|
||||
longTermAssetsRequired: '260250',
|
||||
priorAssetInvestment: '600',
|
||||
},
|
||||
});
|
||||
p.products = [
|
||||
{
|
||||
label: 'Sem vendas no ensaio de arranque',
|
||||
monthlyUnits: '0',
|
||||
unitPrice: '1',
|
||||
unitVariableCost: '0',
|
||||
},
|
||||
];
|
||||
Object.assign(p.reportAssumptions, {
|
||||
openingOtherAssets: '10000',
|
||||
openingFixedAssets: '55000',
|
||||
openingEquity: '85000',
|
||||
startYear: '2025',
|
||||
startupExpenses: newAnnualReferencePlan().startupExpenses,
|
||||
taxExpenseByMonth: Array(12).fill('0'),
|
||||
taxPaymentByMonth: Array(12).fill('0'),
|
||||
});
|
||||
return p;
|
||||
}
|
||||
void test('F16 distinguishes required and available cash/assets without treating planned equity as received funding', () => {
|
||||
const p = startup(),
|
||||
budget = requirements.calculateStartupAssetRequirements(p);
|
||||
assert.equal(
|
||||
requirements.startupAmount(budget.grossRequirements),
|
||||
'1825250.00',
|
||||
);
|
||||
assert.equal(
|
||||
requirements.startupAmount(budget.currentAcquisition),
|
||||
'125000.00',
|
||||
);
|
||||
assert.equal(
|
||||
requirements.startupAmount(budget.fixedAcquisition),
|
||||
'205250.00',
|
||||
);
|
||||
assert.throws(() => forecastBusinessPlan(p), /aquisições/);
|
||||
p.assetInvestment = requirements.startupAmount(budget.assetInvestment);
|
||||
let tables = buildIntegralFinancialTables(p);
|
||||
assert.ok(
|
||||
tables.every((t) => !t.issues.length),
|
||||
JSON.stringify(tables.flatMap((t) => t.issues)),
|
||||
);
|
||||
assert.equal(cell(tables, 'startup', 'Caixa', 1), '90000.00');
|
||||
assert.equal(cell(tables, 'startup', 'Caixa', 2), '20000.00');
|
||||
assert.equal(
|
||||
cell(
|
||||
tables,
|
||||
'funding',
|
||||
'Falta para a reserva requerida (projecção)',
|
||||
1,
|
||||
),
|
||||
'1740250.00',
|
||||
);
|
||||
p.equity = '1740250';
|
||||
tables = buildIntegralFinancialTables(p);
|
||||
assert.equal(
|
||||
cell(
|
||||
tables,
|
||||
'funding',
|
||||
'Caixa projectada após arranque com fontes planeadas',
|
||||
1,
|
||||
),
|
||||
'90000.00',
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'funding', 'Caixa disponível antes de financiamento', 1),
|
||||
'20000.00',
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'balance', 'Activos fixos líquidos', 1),
|
||||
'260250.00',
|
||||
);
|
||||
assert.equal(cell(tables, 'balance', 'Total do activo', 1), '500250.00');
|
||||
for (const v of tables
|
||||
.find((t) => t.id === 'balance')
|
||||
.rows.find((r) => r[0] === 'Diferença do balanço')
|
||||
.slice(1))
|
||||
assert.equal(v, '0.00');
|
||||
assert.match(
|
||||
tables.find((t) => t.id === 'funding').notes.join(' '),
|
||||
/não financiamento realizado/,
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'funding', 'Total de fontes planeadas', 1),
|
||||
'1740250.00',
|
||||
);
|
||||
assert.ok(
|
||||
!tables
|
||||
.find((t) => t.id === 'funding')
|
||||
.rows.some((r) => r[0] === 'Capital introduzido'),
|
||||
);
|
||||
});
|
||||
void test('F16 preserves legacy formulas and guards missing data, double counting, snapshot version and CAE', () => {
|
||||
const old = financialReportFixture(12),
|
||||
before = forecastBusinessPlan(old);
|
||||
assert.deepEqual(forecastBusinessPlan(reload(old)), before);
|
||||
const p = startup();
|
||||
p.assetInvestment = requirements.startupAmount(
|
||||
requirements.calculateStartupAssetRequirements(p).assetInvestment,
|
||||
);
|
||||
const s = serializeBusinessPlanSnapshot(p);
|
||||
assert.equal(JSON.parse(s).version, 19);
|
||||
const saved = reload(p);
|
||||
assert.deepEqual(saved.economicClassification, p.economicClassification);
|
||||
assert.deepEqual(
|
||||
saved.startupAssetRequirements,
|
||||
p.startupAssetRequirements,
|
||||
);
|
||||
assert.deepEqual(
|
||||
buildIntegralFinancialTables(saved),
|
||||
buildIntegralFinancialTables(p),
|
||||
);
|
||||
const bad = JSON.parse(s);
|
||||
bad.version = 18;
|
||||
assert.equal(restoreBusinessPlanSnapshot(JSON.stringify(bad)), null);
|
||||
p.startupAssetRequirements.cashRequired = '';
|
||||
assert.throws(
|
||||
() => requirements.calculateStartupAssetRequirements(p),
|
||||
/caixa requerida/,
|
||||
);
|
||||
p.startupAssetRequirements.cashRequired = '90000';
|
||||
p.reportAssumptions.openingOtherAssets = '';
|
||||
assert.throws(
|
||||
() => requirements.calculateStartupAssetRequirements(p),
|
||||
/disponíveis/,
|
||||
);
|
||||
});
|
||||
void test('F16 real editor adopts only acquisitions on explicit action and can restore the earlier investment', () => {
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/startup-asset-requirements.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
const module = { exports: {} },
|
||||
require = createRequire(import.meta.url);
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(name) =>
|
||||
name === '@/lib/startup-asset-requirements'
|
||||
? requirements
|
||||
: name === '@/lib/integral-financial-report'
|
||||
? { newReportAssumptions }
|
||||
: require(name),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
let p = startup();
|
||||
delete p.startupAssetRequirements;
|
||||
const nodes = (n) =>
|
||||
Array.isArray(n)
|
||||
? n.flatMap(nodes)
|
||||
: n && typeof n === 'object'
|
||||
? [n, ...nodes(n.props?.children)]
|
||||
: [];
|
||||
const text = (n) =>
|
||||
typeof n === 'string'
|
||||
? n
|
||||
: Array.isArray(n)
|
||||
? n.map(text).join('')
|
||||
: n && typeof n === 'object'
|
||||
? text(n.props?.children)
|
||||
: '';
|
||||
const render = () =>
|
||||
module.exports.StartupAssetRequirements({
|
||||
plan: p,
|
||||
onChange: (n) => {
|
||||
p = reload(n);
|
||||
assert.ok(p);
|
||||
},
|
||||
});
|
||||
nodes(render())
|
||||
.find((n) => n.type === 'button')
|
||||
.props.onClick();
|
||||
assert.equal(p.assetInvestment, '600');
|
||||
for (const [label, value] of [
|
||||
['Caixa requerida após o arranque', '90000'],
|
||||
['Outros activos correntes requeridos', '150000'],
|
||||
['Activos de longo prazo requeridos', '260250'],
|
||||
]) {
|
||||
const l = nodes(render()).find(
|
||||
(n) => n.type === 'label' && text(n).startsWith(label),
|
||||
);
|
||||
nodes(l)
|
||||
.find((n) => n.type === 'input')
|
||||
.props.onChange({ target: { value } });
|
||||
}
|
||||
nodes(render())
|
||||
.find((n) => n.type === 'button' && text(n).includes('Adoptar'))
|
||||
.props.onClick();
|
||||
assert.equal(p.assetInvestment, '330250.00');
|
||||
assert.equal(p.equity, '0');
|
||||
assert.equal(p.openingCash, '20000');
|
||||
nodes(render())
|
||||
.find((n) => n.type === 'button' && text(n).includes('Retirar'))
|
||||
.props.onClick();
|
||||
assert.equal(p.assetInvestment, '600');
|
||||
assert.equal(p.startupAssetRequirements, undefined);
|
||||
});
|
||||
void test('F31 recovers seven documented departments and identifies the exact unsolved source discrepancies', () => {
|
||||
const reconciled = reconcileOriginalExample(newAnnualReferencePlan());
|
||||
assert.equal(original.sales.length, 4);
|
||||
assert.equal(original.costs.length, 5);
|
||||
assert.equal(original.departments.length, 7);
|
||||
assert.deepEqual(
|
||||
reconciled.years.map((y) => y.salesDifference),
|
||||
['3652.00', '8250.00', '9350.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
reconciled.years.map((y) => y.costDifference),
|
||||
['2243.00', '2900.00', '3650.00'],
|
||||
);
|
||||
assert.equal(reconciled.months[0].knownSales, '510.00');
|
||||
assert.equal(reconciled.months[0].sourceSales, '680.00');
|
||||
assert.equal(reconciled.months[0].knownCosts, '431.00');
|
||||
assert.equal(reconciled.months[0].sourceCosts, '586.00');
|
||||
assert.equal(reconciled.years[0].payrollDifference, '0.00');
|
||||
assert.equal(reconciled.years[0].missingDepartments.length, 0);
|
||||
for (const y of reconciled.years.slice(1)) {
|
||||
assert.equal(y.missingDepartments.length, 4);
|
||||
assert.equal(y.payrollDifference, '1600.00');
|
||||
}
|
||||
assert.equal(original.departments[3].annual[1], null);
|
||||
});
|
||||
void test('F31 carries all 36 calculated months, original service/department rows and unchanged annual totals into one eleven-table report', () => {
|
||||
const annual = newAnnualReferencePlan(),
|
||||
p = financialReportFixture(12);
|
||||
p.annualExampleSnapshot = serializeAnnualExampleSnapshot(annual);
|
||||
p.reportSource = 'annual_example';
|
||||
const source = calculateAnnualReferencePlan(annual),
|
||||
tables = buildAnnualExampleTables(reload(p));
|
||||
assert.equal(tables.length, 11);
|
||||
const sales = tables.find((t) => t.id === 'sales');
|
||||
assert.equal(sales.headers.length, 40);
|
||||
assert.equal(sales.headers[1], '2025-01');
|
||||
assert.equal(sales.headers[36], '2027-12');
|
||||
for (let year = 0; year < 3; year++) {
|
||||
const start = year * 12 + 1,
|
||||
end = start + 12,
|
||||
col = 37 + year;
|
||||
for (const [id, label] of [
|
||||
['sales', 'Vendas totais'],
|
||||
['sales', 'Custo directo'],
|
||||
['profit-loss', 'Lucro líquido'],
|
||||
['cashflow', 'Caixa recebida'],
|
||||
['cashflow', 'Caixa gasta'],
|
||||
['cashflow', 'Fluxo líquido'],
|
||||
['personnel', 'Folha de pagamento agregada'],
|
||||
]) {
|
||||
const row = tables
|
||||
.find((t) => t.id === id)
|
||||
.rows.find((r) => r[0] === label);
|
||||
assert.equal(
|
||||
row.slice(start, end).reduce((sum, v) => sum + cents(v), 0n),
|
||||
cents(row[col]),
|
||||
`${id}/${label}/${year}`,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
cell(tables, 'cashflow', 'Caixa final', col),
|
||||
cell(tables, 'cashflow', 'Caixa final', end - 1),
|
||||
);
|
||||
}
|
||||
for (const amount of tables
|
||||
.find((t) => t.id === 'balance')
|
||||
.rows.find((r) => r[0] === 'Diferença do balanço')
|
||||
.slice(1))
|
||||
assert.equal(amount, '0.00');
|
||||
assert.equal(
|
||||
cell(
|
||||
tables,
|
||||
'sales',
|
||||
'Vendas documentadas no original — Publicidade',
|
||||
1,
|
||||
),
|
||||
'100.00',
|
||||
);
|
||||
assert.equal(
|
||||
cell(
|
||||
tables,
|
||||
'sales',
|
||||
'Vendas documentadas no original — Publicidade',
|
||||
37,
|
||||
),
|
||||
'2137.00',
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'sales', 'Custo documentado no original — Marketing', 1),
|
||||
'Não documentado',
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'personnel', 'Departamento documentado — Marketing', 37),
|
||||
'300.00',
|
||||
);
|
||||
assert.equal(
|
||||
cell(tables, 'personnel', 'Departamento documentado — Marketing', 38),
|
||||
'Não documentado',
|
||||
);
|
||||
assert.equal(source.years[0].closingAssets, '501475.00');
|
||||
assert.equal(source.years[0].closingLiabilities, '1641.00');
|
||||
assert.equal(source.years[0].closingCapital, '499834.00');
|
||||
assert.equal(
|
||||
cell(
|
||||
tables,
|
||||
'funding',
|
||||
'Caixa efectivamente disponível antes do financiamento',
|
||||
1,
|
||||
),
|
||||
'Não documentado no exemplo original',
|
||||
);
|
||||
});
|
||||
void test('F16/F31 persistence and existing Word/print exports preserve the same requirements, all months and source gaps', async () => {
|
||||
const p = startup();
|
||||
p.assetInvestment = requirements.startupAmount(
|
||||
requirements.calculateStartupAssetRequirements(p).assetInvestment,
|
||||
);
|
||||
p.equity = '1740250';
|
||||
const annual = newAnnualReferencePlan();
|
||||
annual.years[0].sales = '14537.25';
|
||||
p.annualExampleSnapshot = serializeAnnualExampleSnapshot(annual);
|
||||
for (const mode of ['investor', 'annual_example']) {
|
||||
p.reportSource = mode;
|
||||
const restored = reload(p),
|
||||
before = JSON.stringify(p);
|
||||
const report = createIntegralFinancialReport(
|
||||
{
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(restored),
|
||||
project_title: 'QA F16/F31',
|
||||
},
|
||||
{ generatedAt: '2026-11-20T12:00:00Z' },
|
||||
);
|
||||
assert.equal(report.sections[0].tables.length, 11);
|
||||
assert.equal(JSON.stringify(p), before);
|
||||
const html = await createProjectDossierPrintHtml(report, []),
|
||||
doc = await generateProjectDossierDocx(report, []),
|
||||
zip = await JSZip.loadAsync(
|
||||
doc instanceof Blob ? await doc.arrayBuffer() : doc,
|
||||
),
|
||||
xml = await zip.file('word/document.xml').async('string');
|
||||
for (const s of mode === 'investor'
|
||||
? [
|
||||
'Disponível antes de financiamento',
|
||||
'Caixa requerida',
|
||||
'não financiamento realizado',
|
||||
]
|
||||
: [
|
||||
'2025-01',
|
||||
'2027-12',
|
||||
'Vendas documentadas no original',
|
||||
'Departamento documentado',
|
||||
'Não documentado',
|
||||
]) {
|
||||
assert.ok((html + xml).includes(s), s);
|
||||
}
|
||||
if (mode === 'annual_example') {
|
||||
assert.match(xml, /14 537,25/);
|
||||
assert.match(xml, /documental/);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
exportBusinessPlanCsv,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { buildFinancialFiscalBridge } from '../../resources/js/lib/financial-fiscal-bridge.ts';
|
||||
import { advanceFixture, event } from './fixtures/supplier-advances.mjs';
|
||||
function nirf() {
|
||||
const p = advanceFixture();
|
||||
p.accountingRegime = 'PGC-NIRF';
|
||||
p.supplierAdvances.regime = 'PGC-NIRF';
|
||||
Object.assign(p.supplierAdvances.operations[0], {
|
||||
formalAgreement: {
|
||||
date: '2027-02-10',
|
||||
reference: 'ACORDO-SINTETICO-01',
|
||||
},
|
||||
events: [
|
||||
event('A', 'advance', '2027-01-10', '30000'),
|
||||
event('B', 'apply', '2027-02-15', '30000'),
|
||||
event('C', 'settle', '2027-04-01', '70000'),
|
||||
],
|
||||
});
|
||||
return p;
|
||||
}
|
||||
test('PGC-NIRF applies on recognized supply and dated formal agreement before invoice, no duplicate cash', () => {
|
||||
const p = nirf(),
|
||||
r = forecastBusinessPlan(p),
|
||||
l = r.supplierAdvanceLedger;
|
||||
assert.deepEqual(
|
||||
l.monthly.map((m) => [m.obligation, m.advance]),
|
||||
[
|
||||
['0.00', '30000.00'],
|
||||
['70000.00', '0.00'],
|
||||
['70000.00', '0.00'],
|
||||
['0.00', '0.00'],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
r.rows.map((m) => m.variableCostPayments),
|
||||
['30000.00', '0.00', '0.00', '70000.00'],
|
||||
);
|
||||
assert.deepEqual(l.operations[0].events[1].applicationBasis, {
|
||||
kind: 'formal_agreement',
|
||||
date: '2027-02-10',
|
||||
reference: 'ACORDO-SINTETICO-01',
|
||||
});
|
||||
assert.equal(
|
||||
l.operations[0].monthly[1].documentaryStatus,
|
||||
'formal_agreement',
|
||||
);
|
||||
assert.equal(l.operations[0].monthly[2].documentaryStatus, 'invoice');
|
||||
const tables = buildIntegralFinancialTables(p);
|
||||
assert.ok(tables.every((t) => t.issues.length === 0));
|
||||
assert.ok(
|
||||
tables
|
||||
.find((t) => t.id === 'balance')
|
||||
.rows.find((r) => r[0] === 'Diferença do balanço')
|
||||
.slice(1)
|
||||
.every((v) => v === '0.00'),
|
||||
);
|
||||
assert.match(
|
||||
tables.flatMap((t) => t.notes).join(' '),
|
||||
/ACORDO-SINTETICO-01/,
|
||||
);
|
||||
assert.match(exportBusinessPlanCsv(p), /PGC-NIRF/);
|
||||
assert.match(exportBusinessPlanCsv(p), /ACORDO-SINTETICO-01/);
|
||||
assert.equal(
|
||||
buildFinancialFiscalBridge(r).accountingLines.find(
|
||||
(l) => l.code === 'revenue',
|
||||
).total,
|
||||
'0.00',
|
||||
);
|
||||
});
|
||||
test('PGC-NIRF still requires recognition and sufficient dated basis; agreement is not a receipt', () => {
|
||||
const p = nirf(),
|
||||
o = p.supplierAdvances.operations[0];
|
||||
o.events[1].date = '2027-02-09';
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/aplicação exige reconhecimento/,
|
||||
);
|
||||
o.events[1].date = '2027-02-15';
|
||||
o.formalAgreement.date = '2027-02-16';
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/acordo formal correspondente/,
|
||||
);
|
||||
o.formalAgreement.date = '2027-02-10';
|
||||
o.formalAgreement.reference = ' ';
|
||||
assert.throws(() => forecastBusinessPlan(p), /referência identificada/);
|
||||
o.formalAgreement.reference = 'A';
|
||||
o.formalAgreement.date = '2027-02-30';
|
||||
assert.throws(() => forecastBusinessPlan(p), /data válida/);
|
||||
delete o.formalAgreement;
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/acordo formal correspondente/,
|
||||
);
|
||||
o.events[1].date = '2027-03-01';
|
||||
assert.equal(
|
||||
forecastBusinessPlan(p).supplierAdvanceLedger.operations[0].events[1]
|
||||
.applicationBasis.kind,
|
||||
'invoice',
|
||||
);
|
||||
});
|
||||
test('PGC-PE never uses agreement to apply before invoice, even in explicit-regime plans', () => {
|
||||
const p = nirf();
|
||||
p.accountingRegime = p.supplierAdvances.regime = 'PGC-PE';
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/aplicação exige reconhecimento e factura/,
|
||||
);
|
||||
p.supplierAdvances.operations[0].events[1].date = '2027-03-01';
|
||||
assert.equal(
|
||||
forecastBusinessPlan(p).supplierAdvanceLedger.monthly[1].advance,
|
||||
'30000.00',
|
||||
);
|
||||
});
|
||||
test('PGC-NIRF identity includes agreement across parcels; no shared balance or future settlement', () => {
|
||||
const p = nirf(),
|
||||
o = p.supplierAdvances.operations[0];
|
||||
o.amount = '50000';
|
||||
o.events[2].amount = '20000';
|
||||
p.supplierAdvances.operations.push({
|
||||
...structuredClone(o),
|
||||
parcelId: 'P-2',
|
||||
events: [],
|
||||
formalAgreement: { date: '2027-02-10', reference: 'DIFFERENT' },
|
||||
});
|
||||
assert.throws(() => forecastBusinessPlan(p), /parcelas da mesma operação/);
|
||||
p.supplierAdvances.operations[1].formalAgreement = {
|
||||
reference: o.formalAgreement.reference,
|
||||
date: o.formalAgreement.date,
|
||||
};
|
||||
assert.doesNotThrow(() => forecastBusinessPlan(p)); // JSON property order is not a different agreement.
|
||||
p.supplierAdvances.operations.pop();
|
||||
o.amount = '100000';
|
||||
o.events[1].amount = '30001';
|
||||
assert.throws(() => forecastBusinessPlan(p), /excede o saldo/);
|
||||
o.events[1].amount = '30000';
|
||||
o.events[2].date = '2027-02-20';
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/remanescente exige reconhecimento e factura/,
|
||||
);
|
||||
});
|
||||
test('snapshot 22 requires explicit consistent regime, carries agreement and permits editing incomplete basis', () => {
|
||||
const p = nirf(),
|
||||
s = serializeBusinessPlanSnapshot(p),
|
||||
r = restoreBusinessPlanSnapshot(s);
|
||||
assert.equal(JSON.parse(s).version, 22);
|
||||
assert.ok(r);
|
||||
assert.equal(r.accountingRegime, 'PGC-NIRF');
|
||||
assert.deepEqual(r.supplierAdvances, p.supplierAdvances);
|
||||
assert.deepEqual(forecastBusinessPlan(r), forecastBusinessPlan(p));
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(s.replace('"version":22', '"version":21')),
|
||||
null,
|
||||
);
|
||||
p.accountingRegime = 'PGC-PE';
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/identificação explícita|diverge/,
|
||||
);
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p)),
|
||||
null,
|
||||
);
|
||||
delete p.accountingRegime;
|
||||
assert.throws(() => forecastBusinessPlan(p), /identificação explícita/);
|
||||
p.accountingRegime = 'PGC-NIRF';
|
||||
p.supplierAdvances.operations[0].formalAgreement.reference = '';
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p)),
|
||||
null,
|
||||
);
|
||||
assert.ok(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p), {
|
||||
editable: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
test('accepted snapshot 21 stays PGC-PE locally without inferring plan regime or changing output/tables', () => {
|
||||
for (const name of ['saved-active.json', 'saved-refund.json']) {
|
||||
const s = JSON.parse(
|
||||
fs.readFileSync(
|
||||
new URL(
|
||||
'../../docs/investmoz/v2/auditoria-portal/e26-f20-b-20261121/' +
|
||||
name,
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const r = restoreBusinessPlanSnapshot(JSON.stringify(s));
|
||||
assert.ok(r);
|
||||
assert.equal(r.accountingRegime, undefined);
|
||||
assert.equal(r.supplierAdvances.regime, 'PGC-PE');
|
||||
assert.equal(JSON.parse(serializeBusinessPlanSnapshot(r)).version, 21);
|
||||
const baselineFile = new URL(
|
||||
'./fixtures/supplier-advances-pgc-pe-baseline.json',
|
||||
import.meta.url,
|
||||
);
|
||||
{
|
||||
const b = JSON.parse(fs.readFileSync(baselineFile, 'utf8')).find(
|
||||
(b) => b.name === name,
|
||||
);
|
||||
assert.deepEqual(forecastBusinessPlan(r), b.forecast);
|
||||
assert.deepEqual(buildIntegralFinancialTables(r), b.tables);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
exportBusinessPlanCsv,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { advanceFixture, event } from './fixtures/supplier-advances.mjs';
|
||||
import { buildFinancialFiscalBridge } from '../../resources/js/lib/financial-fiscal-bridge.ts';
|
||||
|
||||
test('F20-B refund reconciles in the editor fiscal bridge without becoming taxable revenue or other collections', () => {
|
||||
const p = advanceFixture({
|
||||
kind: 'services',
|
||||
amount: '12000',
|
||||
recognition: '2027-02-05',
|
||||
invoice: '2027-02-08',
|
||||
});
|
||||
p.supplierAdvances.operations[0].events = [
|
||||
event('A', 'advance', '2027-01-10', '20000'),
|
||||
event('B', 'apply', '2027-02-08', '12000'),
|
||||
event('C', 'refund', '2027-03-01', '8000'),
|
||||
];
|
||||
const bridge = buildFinancialFiscalBridge(forecastBusinessPlan(p));
|
||||
assert.equal(bridge.cashSchedule[2].supplierAdvanceRefunds, '8000.00');
|
||||
assert.equal(bridge.cashSchedule[2].otherCollections, '0.00');
|
||||
assert.equal(
|
||||
bridge.accountingLines.find((l) => l.code === 'revenue').total,
|
||||
'0.00',
|
||||
);
|
||||
});
|
||||
|
||||
test('F20-B accepts a prior documentary invoice without inferring an opening balance; horizon 60 retains future events', () => {
|
||||
const p = advanceFixture({
|
||||
recognition: '2031-12-20',
|
||||
invoice: '2026-12-01',
|
||||
periods: 60,
|
||||
});
|
||||
p.supplierAdvances.operations[0].events = [
|
||||
event('A', 'advance', '2027-01-01', '30000'),
|
||||
event('B', 'apply', '2031-12-20', '30000'),
|
||||
event('C', 'settle', '2032-01-01', '70000'),
|
||||
];
|
||||
const r = forecastBusinessPlan(p);
|
||||
assert.equal(r.supplierAdvanceLedger.monthly[0].advance, '30000.00');
|
||||
assert.equal(r.supplierAdvanceLedger.monthly[59].obligation, '70000.00');
|
||||
assert.equal(r.rows[59].variableCostPayments, '0.00');
|
||||
assert.equal(
|
||||
r.supplierAdvanceLedger.operations[0].events[2].outsideHorizon,
|
||||
true,
|
||||
);
|
||||
});
|
||||
const ledger = (p) => forecastBusinessPlan(p).supplierAdvanceLedger;
|
||||
function reconciled(p) {
|
||||
const tables = buildIntegralFinancialTables(p);
|
||||
assert.ok(
|
||||
tables.every((t) => t.issues.length === 0),
|
||||
JSON.stringify(tables.map((t) => [t.id, t.issues])),
|
||||
);
|
||||
const row = tables
|
||||
.find((t) => t.id === 'balance')
|
||||
.rows.find((r) => r[0] === 'Diferença do balanço');
|
||||
assert.ok(
|
||||
row.slice(1).every((v) => v === '0.00'),
|
||||
JSON.stringify(row),
|
||||
);
|
||||
return tables;
|
||||
}
|
||||
test('F20-B reception before invoice: gross obligation and asset separated, no second payment on application', () => {
|
||||
const p = advanceFixture();
|
||||
p.supplierAdvances.operations[0].events = [
|
||||
event('A', 'advance', '2027-01-10', '30000'),
|
||||
event('B', 'apply', '2027-03-01', '30000'),
|
||||
event('C', 'settle', '2027-04-01', '70000'),
|
||||
];
|
||||
const before = structuredClone(p),
|
||||
r = forecastBusinessPlan(p),
|
||||
l = r.supplierAdvanceLedger;
|
||||
assert.deepEqual(p, before);
|
||||
assert.deepEqual(
|
||||
l.monthly.map((m) => [m.obligation, m.advance, m.netDue]),
|
||||
[
|
||||
['0.00', '30000.00', '0.00'],
|
||||
['100000.00', '30000.00', '70000.00'],
|
||||
['70000.00', '0.00', '70000.00'],
|
||||
['0.00', '0.00', '0.00'],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
r.rows.map((m) => m.variableCostPayments),
|
||||
['30000.00', '0.00', '0.00', '70000.00'],
|
||||
);
|
||||
assert.equal(r.totalPayments, '100000.00');
|
||||
const tables = reconciled(p),
|
||||
b = tables.find((t) => t.id === 'balance');
|
||||
assert.equal(
|
||||
b.rows.find((r) => r[0] === 'Obrigações operacionais brutas')[2],
|
||||
'100000.00',
|
||||
);
|
||||
assert.equal(
|
||||
b.rows.find(
|
||||
(r) => r[0] === 'Adiantamentos identificados a fornecedores',
|
||||
)[2],
|
||||
'30000.00',
|
||||
);
|
||||
assert.equal(exportBusinessPlanCsv(p).includes('OP-1'), true);
|
||||
});
|
||||
test('F20-B invoice before reception does not recognize goods or expenses early', () => {
|
||||
const p = advanceFixture({
|
||||
recognition: '2027-03-10',
|
||||
invoice: '2027-01-10',
|
||||
});
|
||||
p.supplierAdvances.operations[0].events = [
|
||||
event('A', 'advance', '2027-02-01', '30000'),
|
||||
event('B', 'apply', '2027-03-10', '30000'),
|
||||
event('C', 'settle', '2027-04-01', '70000'),
|
||||
];
|
||||
const r = forecastBusinessPlan(p);
|
||||
assert.deepEqual(
|
||||
r.rows.map((m) => m.inventoryReceipts),
|
||||
['0.00', '0.00', '100000.00', '0.00'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
ledger(p).monthly.map((m) => m.obligation),
|
||||
['0.00', '0.00', '70000.00', '0.00'],
|
||||
);
|
||||
reconciled(p);
|
||||
});
|
||||
test('F20-B service partial use and refund: no new income or expenditure', () => {
|
||||
const p = advanceFixture({
|
||||
kind: 'services',
|
||||
amount: '12000',
|
||||
recognition: '2027-02-05',
|
||||
invoice: '2027-02-08',
|
||||
});
|
||||
p.supplierAdvances.operations[0].events = [
|
||||
event('A', 'advance', '2027-01-10', '20000'),
|
||||
event('B', 'apply', '2027-02-08', '12000'),
|
||||
event('C', 'refund', '2027-03-01', '8000'),
|
||||
];
|
||||
const r = forecastBusinessPlan(p);
|
||||
assert.deepEqual(
|
||||
ledger(p).monthly.map((m) => m.advance),
|
||||
['20000.00', '8000.00', '0.00', '0.00'],
|
||||
);
|
||||
assert.equal(r.rows[2].cashCollections, '8000.00');
|
||||
assert.equal(r.rows[2].revenue, '0.00');
|
||||
assert.equal(r.totalProfitBeforeTax, '-12040.00'); // accepted fixture depreciation: 10/month
|
||||
const tables = reconciled(p);
|
||||
assert.ok(
|
||||
tables
|
||||
.find((t) => t.id === 'profit-loss')
|
||||
.rows.find((r) => r[0] === 'Outras receitas de caixa declaradas')
|
||||
.slice(1)
|
||||
.every((v) => v === '0.00'),
|
||||
);
|
||||
assert.equal(
|
||||
tables
|
||||
.find((t) => t.id === 'balance')
|
||||
.rows.find((r) => r[0] === 'Recebíveis líquidos')[3],
|
||||
'0.00',
|
||||
);
|
||||
});
|
||||
test('F20-B different operations of same supplier never offset each other', () => {
|
||||
const p = advanceFixture({
|
||||
amount: '20000',
|
||||
recognition: '2027-03-01',
|
||||
invoice: '2027-03-01',
|
||||
});
|
||||
const a = p.supplierAdvances.operations[0];
|
||||
a.events = [event('A', 'advance', '2027-01-01', '20000')];
|
||||
p.supplierAdvances.operations.push({
|
||||
...structuredClone(a),
|
||||
originId: 'OP-2',
|
||||
amount: '12000',
|
||||
recognitionDate: '2027-02-01',
|
||||
invoiceDate: '2027-02-01',
|
||||
events: [],
|
||||
});
|
||||
p.inventoryPurchaseSchedule[1].amount = '12000';
|
||||
const l = ledger(p);
|
||||
assert.equal(l.monthly[1].advance, '20000.00');
|
||||
assert.equal(l.monthly[1].obligation, '12000.00');
|
||||
assert.equal(l.monthly[1].netDue, '12000.00');
|
||||
reconciled(p);
|
||||
p.supplierAdvances.operations[1].events = [
|
||||
event('B', 'apply', '2027-02-01', '12000'),
|
||||
];
|
||||
assert.throws(() => forecastBusinessPlan(p), /excede o saldo/);
|
||||
});
|
||||
test('F20-B application, refunds and remaining payments are bounded by same-parcel balances', () => {
|
||||
const p = advanceFixture(),
|
||||
o = p.supplierAdvances.operations[0];
|
||||
o.events = [
|
||||
event('A', 'advance', '2027-01-10', '30000'),
|
||||
event('B', 'apply', '2027-02-15', '30000'),
|
||||
];
|
||||
assert.throws(() => forecastBusinessPlan(p), /reconhecimento e factura/);
|
||||
o.events[1].date = '2027-03-01';
|
||||
o.events[1].amount = '30000.01';
|
||||
assert.throws(() => forecastBusinessPlan(p), /excede o saldo/);
|
||||
o.events[1] = event('B', 'refund', '2027-01-11', '30000.01');
|
||||
assert.throws(() => forecastBusinessPlan(p), /devolução excede/);
|
||||
o.events[1] = event('B', 'settle', '2027-03-01', '100000');
|
||||
assert.throws(() => forecastBusinessPlan(p), /líquido por liquidar/);
|
||||
o.events[1] = event('B', 'advance', '2027-03-01', '1');
|
||||
assert.throws(() => forecastBusinessPlan(p), /após reconhecimento/);
|
||||
});
|
||||
test('F20-B rejects special contracts, missing regime, invalid dates, duplicate parcels and inconsistent allocations', () => {
|
||||
const p = advanceFixture(),
|
||||
o = p.supplierAdvances.operations[0];
|
||||
o.ordinaryContract = false;
|
||||
assert.throws(() => forecastBusinessPlan(p), /contratos especiais/);
|
||||
o.ordinaryContract = true;
|
||||
p.supplierAdvances.regime = '';
|
||||
assert.throws(() => forecastBusinessPlan(p), /seleccione explicitamente/);
|
||||
p.supplierAdvances.regime = 'PGC-PE';
|
||||
o.recognitionDate = '2027-02-30';
|
||||
assert.throws(() => forecastBusinessPlan(p), /reconhecimento inválida/);
|
||||
o.recognitionDate = '2027-02-15';
|
||||
o.events = [event('A', 'advance', '', '1')];
|
||||
assert.throws(() => forecastBusinessPlan(p), /data de movimento/);
|
||||
o.events = [];
|
||||
p.supplierAdvances.operations.push(structuredClone(o));
|
||||
assert.throws(() => forecastBusinessPlan(p), /duplicada/);
|
||||
p.supplierAdvances.operations.pop();
|
||||
o.amount = '99999';
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(p),
|
||||
/exactamente o reconhecimento/,
|
||||
);
|
||||
});
|
||||
test('F20-B missing or future recognition preserves advances, no inferred opening allocation or last-month cash', () => {
|
||||
for (const recognition of ['', '2028-02-01']) {
|
||||
const p = advanceFixture({ recognition, invoice: '', periods: 1 });
|
||||
p.supplierAdvances.operations[0].events = [
|
||||
event('A', 'advance', '2027-01-01', '20000'),
|
||||
event('B', 'refund', '2027-02-01', '8000'),
|
||||
];
|
||||
assert.equal(ledger(p).monthly[0].advance, '20000.00');
|
||||
assert.equal(ledger(p).operations[0].events[1].outsideHorizon, true);
|
||||
assert.equal(forecastBusinessPlan(p).rows[0].cashCollections, '0.00');
|
||||
reconciled(p);
|
||||
}
|
||||
const p = advanceFixture();
|
||||
p.supplierAdvances.operations[0].events = [
|
||||
event('A', 'advance', '2026-12-31', '1'),
|
||||
];
|
||||
assert.throws(() => forecastBusinessPlan(p), /anterior ao plano/);
|
||||
});
|
||||
test('F20-B snapshot 21 round-trips inactive agendas, rejects foreign versions and invalid active ledgers', () => {
|
||||
const p = advanceFixture();
|
||||
p.supplierAdvances.operations[0].events = [
|
||||
event('A', 'advance', '2027-01-01', '30000'),
|
||||
];
|
||||
const s = serializeBusinessPlanSnapshot(p);
|
||||
assert.equal(JSON.parse(s).version, 21);
|
||||
const r = restoreBusinessPlanSnapshot(s);
|
||||
assert.ok(r);
|
||||
assert.equal(r.monthlyVariableCostPayments, '999');
|
||||
assert.deepEqual(r.supplierAdvances, p.supplierAdvances);
|
||||
assert.deepEqual(forecastBusinessPlan(r), forecastBusinessPlan(p));
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(s.replace('"version":21', '"version":20')),
|
||||
null,
|
||||
);
|
||||
p.supplierAdvances.operations[0].events.push(
|
||||
event('A', 'refund', '2027-01-02', '1'),
|
||||
);
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p)),
|
||||
null,
|
||||
);
|
||||
assert.ok(
|
||||
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p), {
|
||||
editable: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
test('F20-B inactive mode preserves every old value and F20-A can coexist only on unselected categories', () => {
|
||||
const p = advanceFixture(),
|
||||
legacy = { ...p, supplierAdvances: undefined };
|
||||
p.supplierAdvances.purchases = p.supplierAdvances.services = false;
|
||||
assert.deepEqual(forecastBusinessPlan(p), forecastBusinessPlan(legacy));
|
||||
p.supplierAdvances.purchases = true;
|
||||
p.dayTerms = {
|
||||
sales: true,
|
||||
purchases: true,
|
||||
services: false,
|
||||
operations: [],
|
||||
};
|
||||
assert.doesNotThrow(() => forecastBusinessPlan(p)); // inactive purchase day agenda isn't added or validated
|
||||
const l = ledger(p);
|
||||
assert.ok(l);
|
||||
assert.equal(forecastBusinessPlan(p).rows[0].variableCostPayments, '0.00');
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
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 * as presentation from '../../resources/js/lib/public-presentation.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
function load(name) {
|
||||
const module = { exports: {} };
|
||||
const code = ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/' + name + '.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) =>
|
||||
id === '@/lib/public-presentation'
|
||||
? presentation
|
||||
: id === '@inertiajs/react'
|
||||
? {
|
||||
Link: ({ children, ...props }) =>
|
||||
React.createElement('a', props, children),
|
||||
}
|
||||
: id === './public-reference'
|
||||
? load('public-reference')
|
||||
: id.startsWith('./')
|
||||
? { default: () => null }
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return module.exports;
|
||||
}
|
||||
const LocationList = load('structure-geography').LocationList;
|
||||
const base = () => ({
|
||||
id: 'synthetic',
|
||||
name: 'SYNTHETIC province',
|
||||
role: 'primary',
|
||||
location_type: 'province',
|
||||
path: [{ id: 'p', name: 'SYNTHETIC province', location_type: 'province' }],
|
||||
coordinates: [],
|
||||
boundaries: [],
|
||||
source_reference:
|
||||
'upgrade do portal de investimentos v4 programacao.docx — 6.1 / 6.6',
|
||||
});
|
||||
void test('P16 shows every required unknown field without inventing territorial values or exposing internal source paths', () => {
|
||||
const row = base(),
|
||||
before = JSON.stringify(row);
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(LocationList, { locations: [row] }),
|
||||
);
|
||||
assert.match(html, /Posto administrativo<\/dt><dd>N\u00e3o documentado/);
|
||||
assert.match(html, /Localidade<\/dt><dd>N\u00e3o documentado/);
|
||||
assert.match(html, /Coordenadas n\u00e3o documentadas/);
|
||||
assert.match(html, /Pol\u00edgono n\u00e3o documentado/);
|
||||
assert.match(html, /Data da fonte: N\u00e3o documentada/);
|
||||
assert.ok(!html.includes('programacao.docx'));
|
||||
assert.equal(JSON.stringify(row), before);
|
||||
});
|
||||
void test('P16 shows a confirmed source date once and treats empty dates as undocumented while preserving inputs', () => {
|
||||
for (const value of ['2026-11-01', '', ' ']) {
|
||||
const row = {
|
||||
...base(),
|
||||
source_reference: 'https://example.gov.mz/reference.pdf',
|
||||
source_date: value,
|
||||
};
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(LocationList, { locations: [row] }),
|
||||
);
|
||||
if (value.trim()) {
|
||||
assert.equal((html.match(/2026-11-01/g) || []).length, 1);
|
||||
assert.ok(!html.includes('Data da fonte: N\u00e3o documentada'));
|
||||
} else assert.match(html, /Data da fonte: N\u00e3o documentada/);
|
||||
assert.equal(row.source_date, value);
|
||||
}
|
||||
});
|
||||
|
||||
void test('P16 internal office filenames stay administrative while official document links and legal citations remain useful', () => {
|
||||
for (const v of [
|
||||
'upgrade do portal de investimentos v4 programacao.docx - 6.1',
|
||||
'Anexo.xlsm',
|
||||
'Mapa.xlsx',
|
||||
'Captura.emf',
|
||||
])
|
||||
assert.equal(presentation.publicReference(v), null);
|
||||
assert.equal(
|
||||
presentation.publicReference('Decreto n. 70/2009'),
|
||||
'Decreto n. 70/2009',
|
||||
);
|
||||
const url = 'https://example.gov.mz/Decreto70.docx';
|
||||
assert.equal(presentation.publicReference(url), url);
|
||||
});
|
||||
@@ -0,0 +1,204 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import * as business from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import * as integral from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import * as startup from '../../resources/js/lib/startup-asset-requirements.ts';
|
||||
import * as presentation from '../../resources/js/lib/financial-issue-presentation.ts';
|
||||
import * as annual from '../../resources/js/lib/annual-example-report.ts';
|
||||
import * as warnings from '../../resources/js/lib/financial-plan-warnings.ts';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const modules = {
|
||||
'@/lib/business-financial-plan': business,
|
||||
'@/lib/integral-financial-report': integral,
|
||||
'@/lib/startup-asset-requirements': startup,
|
||||
'@/lib/financial-issue-presentation': presentation,
|
||||
'@/lib/annual-example-report': annual,
|
||||
'@/lib/financial-plan-warnings': warnings,
|
||||
'./business-plan-warnings': { BusinessPlanWarnings: () => null },
|
||||
};
|
||||
function component(name) {
|
||||
if (modules[`./${name}`]) return modules[`./${name}`];
|
||||
const code = ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
new URL(
|
||||
`../../resources/js/components/${name}.tsx`,
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText;
|
||||
const module = { exports: {} };
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) =>
|
||||
modules[id] ??
|
||||
(id.startsWith('./') ? component(id.slice(2)) : require(id)),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
modules[`./${name}`] = module.exports;
|
||||
return module.exports;
|
||||
}
|
||||
const { StartupAssetRequirements } = component('startup-asset-requirements');
|
||||
const { IntegralFinancialPlan } = component('integral-financial-plan');
|
||||
const planWithStartup = () => ({
|
||||
...financialReportFixture(2),
|
||||
startupAssetRequirements: {
|
||||
cashRequired: '',
|
||||
otherCurrentAssetsRequired: '0',
|
||||
longTermAssetsRequired: '600',
|
||||
priorAssetInvestment: '600',
|
||||
},
|
||||
});
|
||||
|
||||
test('D1: one startup diagnostic across real local and report components; standalone and unreadable report retain it', () => {
|
||||
const plan = planWithStartup(),
|
||||
error = presentation.startupErrorMessage(plan);
|
||||
const render = () =>
|
||||
renderToStaticMarkup(
|
||||
React.createElement(
|
||||
React.Fragment,
|
||||
null,
|
||||
React.createElement(StartupAssetRequirements, {
|
||||
plan,
|
||||
onChange() {},
|
||||
showError: !presentation.forecastErrorShownInReport(
|
||||
plan,
|
||||
presentation.startupErrorMessage(plan),
|
||||
),
|
||||
}),
|
||||
React.createElement(IntegralFinancialPlan, {
|
||||
plan,
|
||||
onChange() {},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.ok(error.includes('caixa requerida'));
|
||||
assert.equal(render().split(error).length - 1, 1);
|
||||
assert.equal(
|
||||
renderToStaticMarkup(
|
||||
React.createElement(StartupAssetRequirements, {
|
||||
plan,
|
||||
onChange() {},
|
||||
}),
|
||||
).split(error).length - 1,
|
||||
1,
|
||||
);
|
||||
plan.reportAssumptions.startupExpenses = 'invalid';
|
||||
assert.equal(render().split(error).length - 1, 1);
|
||||
plan.reportSource = 'annual_example';
|
||||
assert.equal(presentation.forecastErrorShownInReport(plan, error), false);
|
||||
plan.startupAssetRequirements.cashRequired = '0';
|
||||
plan.reportAssumptions = financialReportFixture(2).reportAssumptions;
|
||||
assert.equal(presentation.startupErrorMessage(plan), '');
|
||||
delete plan.reportSource;
|
||||
plan.reportAssumptions = financialReportFixture(2).reportAssumptions;
|
||||
assert.ok(!render().includes(error));
|
||||
});
|
||||
|
||||
test('D2: depreciation and principal diagnostics are independent, both retained, and disappear on correction', () => {
|
||||
const plan = financialReportFixture(2);
|
||||
plan.bankLoanProceeds = '100';
|
||||
plan.depreciationLifeMonths = 1;
|
||||
const issues = () =>
|
||||
integral.buildIntegralFinancialTables(plan).flatMap((t) => t.issues);
|
||||
plan.assetDepreciation = '700';
|
||||
assert.equal(
|
||||
issues().filter((x) => x.includes('Base depreciável contabilística'))
|
||||
.length,
|
||||
2,
|
||||
);
|
||||
assert.ok(!issues().some((x) => x.includes('Reembolso de capital')));
|
||||
plan.assetDepreciation = '600';
|
||||
plan.monthlyPrincipalRepayment = '200';
|
||||
assert.equal(
|
||||
issues().filter((x) => x.includes('Reembolso de capital')).length,
|
||||
2,
|
||||
);
|
||||
assert.ok(
|
||||
!issues().some((x) => x.includes('Base depreciável contabilística')),
|
||||
);
|
||||
plan.assetDepreciation = '700';
|
||||
assert.equal(issues().length, 4);
|
||||
plan.assetDepreciation = '600';
|
||||
plan.monthlyPrincipalRepayment = '0';
|
||||
assert.deepEqual(issues(), []);
|
||||
const recovered = business.restoreBusinessPlanSnapshot(
|
||||
business.serializeBusinessPlanSnapshot(plan),
|
||||
);
|
||||
assert.deepEqual(
|
||||
business.forecastBusinessPlan(recovered),
|
||||
business.forecastBusinessPlan(plan),
|
||||
);
|
||||
});
|
||||
|
||||
function supplier() {
|
||||
const plan = financialReportFixture(2);
|
||||
plan.useProductInventorySchedule = true;
|
||||
plan.useSupplierPaymentTerms = true;
|
||||
plan.products[0] = {
|
||||
...plan.products[0],
|
||||
label: 'Fornecedor sintético V12',
|
||||
monthlyUnits: '0',
|
||||
productInventoryOpening: '0',
|
||||
productInventoryPurchasesByPeriod: [
|
||||
{
|
||||
amount: '200',
|
||||
leadMonths: 0,
|
||||
paymentInstallments: [
|
||||
{ lagMonths: 0, percent: '60' },
|
||||
{ lagMonths: 1, percent: '40' },
|
||||
],
|
||||
},
|
||||
{ amount: '0', leadMonths: 0, paymentInstallments: [] },
|
||||
],
|
||||
};
|
||||
return plan;
|
||||
}
|
||||
test('D3: 110% rejects with product, order month and percentage; 100% restores exact payments and unrelated validation remains', () => {
|
||||
const plan = supplier(),
|
||||
valid = business.forecastBusinessPlan(plan);
|
||||
const parts =
|
||||
plan.products[0].productInventoryPurchasesByPeriod[0]
|
||||
.paymentInstallments;
|
||||
parts[1].percent = '50';
|
||||
assert.throws(
|
||||
() => business.forecastBusinessPlan(plan),
|
||||
/Fornecedor sintético V12 — encomenda do mês 1:.*excede 100%/,
|
||||
);
|
||||
assert.equal(
|
||||
business.restoreBusinessPlanSnapshot(
|
||||
business.serializeBusinessPlanSnapshot(plan),
|
||||
),
|
||||
null,
|
||||
);
|
||||
parts[1].percent = '40';
|
||||
assert.deepEqual(business.forecastBusinessPlan(plan), valid);
|
||||
assert.deepEqual(
|
||||
business.forecastBusinessPlan(
|
||||
business.restoreBusinessPlanSnapshot(
|
||||
business.serializeBusinessPlanSnapshot(plan),
|
||||
),
|
||||
),
|
||||
valid,
|
||||
);
|
||||
plan.products[0].productInventoryPurchasesByPeriod[0].leadMonths = 13;
|
||||
assert.throws(
|
||||
() => business.forecastBusinessPlan(plan),
|
||||
/declare purchases and lead times/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
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 ts from 'typescript';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import { complementaryFixture } from './fixtures/complementary-plan.mjs';
|
||||
import * as business from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import * as dossier from '../../resources/js/lib/project-dossier.ts';
|
||||
import * as complementary from '../../resources/js/lib/complementary-report.ts';
|
||||
|
||||
test('V12 final: supplier import without product stock identifies the incompatible controls without weakening rejection', () => {
|
||||
const plan = financialReportFixture(2);
|
||||
plan.useSupplierPaymentTerms = true;
|
||||
plan.useProductInventorySchedule = false;
|
||||
const raw = JSON.stringify({ version: 17, plan });
|
||||
assert.equal(business.restoreBusinessPlanSnapshot(raw), null);
|
||||
assert.match(
|
||||
business.financialPlanImportMessage(raw),
|
||||
/Fluxo de Caixa \/ Calcular pagamentos pelo prazo do fornecedor/,
|
||||
);
|
||||
assert.match(
|
||||
business.financialPlanImportMessage(raw),
|
||||
/Active o stock por produto ou desactive os prazos/,
|
||||
);
|
||||
});
|
||||
|
||||
test('V12 final: imported out-of-horizon recovery identifies exact line and range; correction restores calculation', () => {
|
||||
const plan = financialReportFixture(2);
|
||||
const before = business.forecastBusinessPlan(plan);
|
||||
plan.salesRecoverySchedule = [{ month: 3, percent: '0' }];
|
||||
const imported = business.restoreBusinessPlanSnapshot(
|
||||
business.serializeBusinessPlanSnapshot(plan),
|
||||
);
|
||||
assert.ok(imported);
|
||||
assert.throws(
|
||||
() => business.forecastBusinessPlan(imported),
|
||||
/linha 1 \/ Mês \(3\): seleccione um mês inteiro entre 1 e 2/,
|
||||
);
|
||||
imported.salesRecoverySchedule[0].month = 1;
|
||||
assert.deepEqual(business.forecastBusinessPlan(imported), before);
|
||||
});
|
||||
|
||||
test('V12 final: quantity cell diagnostic retains exact calculation and rejection rules', () => {
|
||||
const plan = financialReportFixture(2);
|
||||
plan.products[0].monthlyUnitsByPeriod = ['0', '0'];
|
||||
const valid = business.forecastBusinessPlan(plan);
|
||||
for (const value of ['', '-1', '1.0001']) {
|
||||
plan.products[0].monthlyUnitsByPeriod[1] = value;
|
||||
assert.throws(
|
||||
() => business.forecastBusinessPlan(plan),
|
||||
/Previsão de Vendas \/ Unidades do produto 1, mês 2: preencha/,
|
||||
);
|
||||
}
|
||||
plan.products[0].monthlyUnitsByPeriod[1] = '0';
|
||||
assert.deepEqual(business.forecastBusinessPlan(plan), valid);
|
||||
});
|
||||
|
||||
test('V12 final: rejected short import names original agenda and never relaxes strict restore', () => {
|
||||
const plan = financialReportFixture(2);
|
||||
const valid = business.serializeBusinessPlanSnapshot(plan);
|
||||
const snapshot = JSON.parse(valid);
|
||||
snapshot.plan.products[0].monthlyUnitsByPeriod = ['0'];
|
||||
const short = JSON.stringify(snapshot);
|
||||
assert.equal(business.restoreBusinessPlanSnapshot(short), null);
|
||||
assert.match(
|
||||
business.financialPlanImportMessage(short),
|
||||
/Previsão de Vendas \/ Unidades do produto 1: a agenda contém 1 meses; deve cobrir os 2/,
|
||||
);
|
||||
assert.match(
|
||||
business.financialPlanImportMessage(short),
|
||||
/plano actual foi conservado/,
|
||||
);
|
||||
assert.ok(business.restoreBusinessPlanSnapshot(valid));
|
||||
assert.match(business.financialPlanImportMessage('{'), /JSON reconhecido/);
|
||||
});
|
||||
|
||||
test('V12 final: actual personnel component receives currency, withholds reconciliation and removes warning after correction', () => {
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/project-planning.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
const require = createRequire(import.meta.url),
|
||||
module = { exports: {} };
|
||||
const mocks = {
|
||||
'@/lib/project-dossier': dossier,
|
||||
'@/lib/business-financial-plan': business,
|
||||
'@/lib/complementary-report': complementary,
|
||||
'./investment-report-tables': {
|
||||
InvestmentReportTables: ({ tables }) =>
|
||||
React.createElement('div', null, JSON.stringify(tables)),
|
||||
},
|
||||
};
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(key) => mocks[key] ?? require(key),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const { plan, team } = complementaryFixture();
|
||||
const snapshot = business.serializeBusinessPlanSnapshot(plan);
|
||||
const props = {
|
||||
value: JSON.stringify(team),
|
||||
onChange: () => {},
|
||||
financialPlanSnapshot: snapshot,
|
||||
projectCurrency: 'USD',
|
||||
};
|
||||
const bad = renderToStaticMarkup(
|
||||
React.createElement(module.exports.ProjectTeamPlanner, props),
|
||||
);
|
||||
assert.match(bad, /Moeda das remunerações \(USD\).*Moeda \(MZN\)/);
|
||||
assert.match(bad, /sem conversão automática/);
|
||||
assert.ok(!bad.includes('Diferença face à despesa de pessoal no plano'));
|
||||
const fixed = renderToStaticMarkup(
|
||||
React.createElement(module.exports.ProjectTeamPlanner, {
|
||||
...props,
|
||||
projectCurrency: 'MZN',
|
||||
}),
|
||||
);
|
||||
assert.ok(!fixed.includes('difere de Plano financeiro'));
|
||||
assert.ok(fixed.includes('Diferença face à despesa de pessoal no plano'));
|
||||
assert.equal(business.serializeBusinessPlanSnapshot(plan), snapshot);
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { buildFinancialRatiosTable } from '../../resources/js/lib/financial-ratios-report.ts';
|
||||
import {
|
||||
financialIssueMessage,
|
||||
financialIssuesForDisplay,
|
||||
} from '../../resources/js/lib/financial-issue-presentation.ts';
|
||||
import {
|
||||
serializeBusinessPlanSnapshot,
|
||||
restoreBusinessPlanSnapshot,
|
||||
forecastBusinessPlan,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
|
||||
test('V12: current classification identifies each invalid field once without changing ratio rows or statements', () => {
|
||||
const plan = financialReportFixture(2);
|
||||
const source = buildIntegralFinancialTables(plan);
|
||||
const original = structuredClone(source);
|
||||
plan.ratioCurrentBalances = {
|
||||
assetsByMonth: ['0', '0'],
|
||||
liabilitiesByMonth: ['0', '0'],
|
||||
};
|
||||
const valid = buildFinancialRatiosTable(plan, source);
|
||||
for (const [key, label] of [
|
||||
['assetsByMonth', 'Activo corrente'],
|
||||
['liabilitiesByMonth', 'Passivo corrente'],
|
||||
]) {
|
||||
for (const value of ['', '999999']) {
|
||||
plan.ratioCurrentBalances[key][0] = value;
|
||||
const table = buildFinancialRatiosTable(plan, source);
|
||||
assert.equal(table.issues.length, 1);
|
||||
assert.ok(table.issues[0].includes(label + ' — mês 1:'));
|
||||
assert.match(
|
||||
table.issues[0],
|
||||
value === '' ? /preencha um montante/ : /excede o total/,
|
||||
);
|
||||
assert.equal(
|
||||
table.rows.find((row) => row[0] === 'Liquidez corrente')[1],
|
||||
'Por determinar',
|
||||
);
|
||||
}
|
||||
plan.ratioCurrentBalances[key][0] = '0';
|
||||
assert.deepEqual(buildFinancialRatiosTable(plan, source), valid);
|
||||
}
|
||||
assert.deepEqual(source, original);
|
||||
});
|
||||
|
||||
test('V12: missing or negative tax cells identify exact field and month; correction removes diagnostic', () => {
|
||||
const plan = financialReportFixture(2);
|
||||
const valid = buildIntegralFinancialTables(plan);
|
||||
for (const [key, label, original] of [
|
||||
['taxExpenseByMonth', 'Imposto reconhecido', '30'],
|
||||
['taxPaymentByMonth', 'Pagamento fiscal previsto', '20'],
|
||||
]) {
|
||||
for (const value of ['', '-1']) {
|
||||
plan.reportAssumptions[key][1] = value;
|
||||
const issues = financialIssuesForDisplay(
|
||||
buildIntegralFinancialTables(plan),
|
||||
);
|
||||
assert.equal(issues.length, 1);
|
||||
assert.ok(issues[0].message.includes(`«${label} — mês 2»`));
|
||||
assert.match(
|
||||
issues[0].message,
|
||||
value === ''
|
||||
? /Preencha este campo para continuar\./
|
||||
: /Este valor não pode ser negativo\./,
|
||||
);
|
||||
}
|
||||
plan.reportAssumptions[key][1] = original;
|
||||
assert.deepEqual(buildIntegralFinancialTables(plan), valid);
|
||||
}
|
||||
});
|
||||
|
||||
test('V12: stock and period reconciliation messages identify original controls without altering issues or rows', () => {
|
||||
const raw = [
|
||||
'Mês 2: existências insuficientes para as vendas declaradas.',
|
||||
'Existem períodos não reconciliados; reveja as rubricas indicadas.',
|
||||
];
|
||||
const tables = [
|
||||
{
|
||||
id: 'balance',
|
||||
title: 'Balanço Projectado',
|
||||
issues: raw,
|
||||
rows: [['Diferença do balanço', '-200.00']],
|
||||
},
|
||||
];
|
||||
const before = JSON.stringify(tables);
|
||||
const messages = financialIssuesForDisplay(tables);
|
||||
assert.equal(messages.length, 2);
|
||||
for (const field of [
|
||||
'mês 2',
|
||||
'Existências iniciais',
|
||||
'Encomenda',
|
||||
'Unidades por mes',
|
||||
])
|
||||
assert.ok(messages[0].message.includes(field));
|
||||
assert.match(messages[1].message, /Diferença do balanço/);
|
||||
assert.match(messages[1].message, /não identifica um único campo errado/);
|
||||
assert.equal(JSON.stringify(tables), before);
|
||||
});
|
||||
|
||||
test('V12: opening installment overflow names the right percentage fields and never attributes a false unique culprit', () => {
|
||||
for (const [kind, text] of [
|
||||
[
|
||||
'receivables',
|
||||
'A soma das cobranças declaradas de recebíveis de abertura não pode exceder 100%.',
|
||||
],
|
||||
[
|
||||
'payables',
|
||||
'A soma das liquidações declaradas de valores a pagar não pode exceder 100%.',
|
||||
],
|
||||
]) {
|
||||
const message = financialIssueMessage(text);
|
||||
assert.match(message, /Fluxo de Caixa/);
|
||||
assert.match(message, /Percentagem do saldo inicial/);
|
||||
assert.match(
|
||||
message,
|
||||
kind === 'receivables' ? /recebíveis/ : /valores a pagar/,
|
||||
);
|
||||
const plan = financialReportFixture(2);
|
||||
const key =
|
||||
kind === 'receivables'
|
||||
? 'openingReceivablesInstallments'
|
||||
: 'openingPayablesInstallments';
|
||||
plan[key] = [
|
||||
{ month: 1, percent: '60' },
|
||||
{ month: 2, percent: '50' },
|
||||
];
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan(plan),
|
||||
/não pode exceder 100%/,
|
||||
);
|
||||
plan[key][1].percent = '40';
|
||||
assert.doesNotThrow(() => forecastBusinessPlan(plan));
|
||||
}
|
||||
});
|
||||
|
||||
test('V12 regression: duplicate recovery months remain editable without blanking a saved plan; strict restore and forecast still reject', () => {
|
||||
const plan = financialReportFixture(2);
|
||||
plan.salesRecoverySchedule = [
|
||||
{ month: 1, percent: '0' },
|
||||
{ month: 1, percent: '0' },
|
||||
];
|
||||
const snapshot = serializeBusinessPlanSnapshot(plan);
|
||||
assert.equal(restoreBusinessPlanSnapshot(snapshot), null);
|
||||
const editable = restoreBusinessPlanSnapshot(snapshot, { editable: true });
|
||||
assert.ok(editable);
|
||||
assert.equal(editable.products[0].unitPrice, '100');
|
||||
assert.deepEqual(
|
||||
editable.salesRecoverySchedule,
|
||||
plan.salesRecoverySchedule,
|
||||
);
|
||||
assert.throws(() => forecastBusinessPlan(editable), /mês único/);
|
||||
assert.match(
|
||||
financialIssueMessage(
|
||||
'Cada recuperação deve ter um mês único dentro do horizonte.',
|
||||
),
|
||||
/campos «Mês»/,
|
||||
);
|
||||
editable.salesRecoverySchedule[1].month = 2;
|
||||
const recovered = restoreBusinessPlanSnapshot(
|
||||
serializeBusinessPlanSnapshot(editable),
|
||||
);
|
||||
assert.ok(recovered);
|
||||
assert.doesNotThrow(() => forecastBusinessPlan(recovered));
|
||||
});
|
||||
@@ -0,0 +1,260 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import {
|
||||
defaultPlanWarningLimits,
|
||||
isPlanWarningLimits,
|
||||
businessPlanWarnings,
|
||||
} from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
import {
|
||||
restoreBusinessPlanSnapshot,
|
||||
serializeBusinessPlanSnapshot,
|
||||
forecastBusinessPlan,
|
||||
exportBusinessPlanCsv,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||
import { financialPlanWarnings } from '../../resources/js/lib/financial-plan-warnings.ts';
|
||||
void test('V07 accepts finite warning thresholds without inventing percentage caps and rejects incomplete or invalid units', () => {
|
||||
assert.ok(isPlanWarningLimits(defaultPlanWarningLimits));
|
||||
assert.ok(
|
||||
isPlanWarningLimits({
|
||||
...defaultPlanWarningLimits,
|
||||
grossMarginPercent: -5,
|
||||
debtAssetsPercent: 200,
|
||||
}),
|
||||
);
|
||||
for (const v of [
|
||||
null,
|
||||
{},
|
||||
{ ...defaultPlanWarningLimits, creditDays: -1 },
|
||||
{ ...defaultPlanWarningLimits, cashExpenseMonths: -1 },
|
||||
{ ...defaultPlanWarningLimits, creditDays: NaN },
|
||||
{ ...defaultPlanWarningLimits, creditDays: Infinity },
|
||||
{ ...defaultPlanWarningLimits, extra: 1 },
|
||||
])
|
||||
assert.equal(isPlanWarningLimits(v), false);
|
||||
const metrics = {
|
||||
sales: 100,
|
||||
directCosts: 80,
|
||||
cash: 200,
|
||||
monthlyExpenses: 100,
|
||||
creditDays: 60,
|
||||
};
|
||||
assert.deepEqual(businessPlanWarnings(metrics), []);
|
||||
const adjusted = businessPlanWarnings(metrics, {
|
||||
...defaultPlanWarningLimits,
|
||||
grossMarginPercent: 25,
|
||||
cashExpenseMonths: 3,
|
||||
creditDays: 30,
|
||||
});
|
||||
assert.deepEqual(
|
||||
adjusted.map((w) => w.id),
|
||||
['margin', 'cash', 'credit'],
|
||||
);
|
||||
assert.match(adjusted.find((w) => w.id === 'cash').message, /3 meses/);
|
||||
});
|
||||
for (const source of [
|
||||
'e25-f20-a-20261121/saved.json',
|
||||
'e26-f20-b-20261121/saved-active.json',
|
||||
'e29-f20-b-nirf-20261121/saved-plan.json',
|
||||
'e32-f22-20261121/saved-plan.json',
|
||||
])
|
||||
void test(
|
||||
'V07 snapshot 24 roundtrip preserves financial schedules and amounts: ' +
|
||||
source,
|
||||
() => {
|
||||
const old = restoreBusinessPlanSnapshot(
|
||||
fs.readFileSync(
|
||||
'docs/investmoz/v2/auditoria-portal/' + source,
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.ok(old);
|
||||
const before = serializeBusinessPlanSnapshot(old),
|
||||
configured = {
|
||||
...old,
|
||||
warningLimits: {
|
||||
...defaultPlanWarningLimits,
|
||||
creditDays: 200,
|
||||
},
|
||||
};
|
||||
const raw = serializeBusinessPlanSnapshot(configured);
|
||||
assert.equal(JSON.parse(raw).version, 24);
|
||||
const restored = restoreBusinessPlanSnapshot(raw);
|
||||
assert.ok(restored);
|
||||
assert.deepEqual(restored.warningLimits, configured.warningLimits);
|
||||
assert.deepEqual(
|
||||
forecastBusinessPlan(restored),
|
||||
forecastBusinessPlan(old),
|
||||
);
|
||||
assert.deepEqual(
|
||||
buildIntegralFinancialTables(restored),
|
||||
buildIntegralFinancialTables(old),
|
||||
);
|
||||
assert.equal(
|
||||
exportBusinessPlanCsv(restored, '2026-11-21T10:00:00Z'),
|
||||
exportBusinessPlanCsv(old, '2026-11-21T10:00:00Z'),
|
||||
);
|
||||
delete restored.warningLimits;
|
||||
assert.equal(serializeBusinessPlanSnapshot(restored), before);
|
||||
const missing = JSON.parse(raw);
|
||||
delete missing.plan.warningLimits;
|
||||
assert.equal(
|
||||
restoreBusinessPlanSnapshot(JSON.stringify(missing)),
|
||||
null,
|
||||
);
|
||||
},
|
||||
);
|
||||
void test('V07 financial warning consumer applies saved limits while V11 monthly negative cash stays visible', () => {
|
||||
const p = restoreBusinessPlanSnapshot(
|
||||
fs.readFileSync(
|
||||
'docs/investmoz/v2/auditoria-portal/e32-f22-20261121/saved-plan.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
p.creditTermDays = '91';
|
||||
const tables = buildIntegralFinancialTables(p);
|
||||
assert.ok(
|
||||
financialPlanWarnings(p, tables).some((w) => w.id.endsWith('-credit')),
|
||||
);
|
||||
p.warningLimits = { ...defaultPlanWarningLimits, creditDays: 200 };
|
||||
assert.ok(
|
||||
!financialPlanWarnings(p, tables).some((w) => w.id.endsWith('-credit')),
|
||||
);
|
||||
const cash = [
|
||||
{
|
||||
id: 'cashflow',
|
||||
title: 'Synthetic cash',
|
||||
headers: [
|
||||
'Month',
|
||||
'2027-01',
|
||||
'2027-02',
|
||||
'2027-03',
|
||||
'2027-04',
|
||||
'2027-05',
|
||||
'2027-06',
|
||||
'2027-07',
|
||||
],
|
||||
rows: [
|
||||
[
|
||||
'Caixa final',
|
||||
'-1.00',
|
||||
'0.00',
|
||||
'0.00',
|
||||
'0.00',
|
||||
'0.00',
|
||||
'0.00',
|
||||
'0.00',
|
||||
],
|
||||
],
|
||||
notes: [],
|
||||
issues: [],
|
||||
},
|
||||
];
|
||||
assert.equal(
|
||||
financialPlanWarnings(p, cash).filter(
|
||||
(w) => w.id === 'cash-negative-2027-01',
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
void test('V07 reset to snapshot 23 preserves valid periodized unit schedules when F22 data is retained', () => {
|
||||
const plan = restoreBusinessPlanSnapshot(
|
||||
fs.readFileSync(
|
||||
'docs/investmoz/v2/auditoria-portal/e25-f20-a-20261121/saved.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
plan.periodInvestments = { enabled: false, financings: [], assets: [] };
|
||||
const raw = serializeBusinessPlanSnapshot(plan);
|
||||
assert.equal(JSON.parse(raw).version, 23);
|
||||
const restored = restoreBusinessPlanSnapshot(raw);
|
||||
assert.ok(restored);
|
||||
assert.deepEqual(
|
||||
restored.products[0].monthlyUnitsByPeriod,
|
||||
plan.products[0].monthlyUnitsByPeriod,
|
||||
);
|
||||
assert.deepEqual(
|
||||
forecastBusinessPlan(restored),
|
||||
forecastBusinessPlan(plan),
|
||||
);
|
||||
});
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
import * as guidance from '../../resources/js/lib/business-plan-guidance.ts';
|
||||
void test('V07 real limit editor applies only valid explicit settings, retains financial values and resets without mutating the plan', () => {
|
||||
const require = createRequire(import.meta.url),
|
||||
source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/warning-limits-editor.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
const values = { ...defaultPlanWarningLimits, creditDays: 200 };
|
||||
let error = '',
|
||||
saved;
|
||||
const module = { exports: {} };
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) =>
|
||||
id === 'react'
|
||||
? {
|
||||
...React,
|
||||
useRef: () => ({
|
||||
current: {
|
||||
querySelector: (selector) => ({
|
||||
valueAsNumber:
|
||||
values[
|
||||
/name="([^"]+)"/.exec(selector)[1]
|
||||
],
|
||||
}),
|
||||
},
|
||||
}),
|
||||
useState: () => ['', (value) => (error = value)],
|
||||
}
|
||||
: id === '@/lib/business-plan-guidance'
|
||||
? guidance
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const plan = Object.freeze({
|
||||
currency: 'MZN',
|
||||
openingCash: '1000',
|
||||
warningLimits: Object.freeze({ ...defaultPlanWarningLimits }),
|
||||
});
|
||||
const before = JSON.stringify(plan);
|
||||
const tree = module.exports.WarningLimitsEditor({
|
||||
plan,
|
||||
onChange: (value) => (saved = value),
|
||||
});
|
||||
const nodes = (t) =>
|
||||
Array.isArray(t)
|
||||
? t.flatMap(nodes)
|
||||
: t && typeof t === 'object'
|
||||
? [t, ...nodes(t.props?.children)]
|
||||
: [];
|
||||
const buttons = nodes(tree).filter((n) => n.type === 'button');
|
||||
values.creditDays = NaN;
|
||||
buttons[0].props.onClick();
|
||||
assert.equal(saved, undefined);
|
||||
assert.ok(error);
|
||||
values.creditDays = 200;
|
||||
buttons[0].props.onClick();
|
||||
assert.equal(error, '');
|
||||
assert.equal(saved.warningLimits.creditDays, 200);
|
||||
assert.equal(saved.openingCash, '1000');
|
||||
buttons[1].props.onClick();
|
||||
assert.equal(saved.warningLimits, undefined);
|
||||
assert.equal(JSON.stringify(plan), before);
|
||||
});
|
||||
Reference in New Issue
Block a user