Consolida rastreabilidade territorial e plano autenticado V2

This commit is contained in:
2026-10-09 02:05:44 +02:00
parent 30acdc9934
commit 6a71aa47e3
33 changed files with 2555 additions and 49 deletions
+52 -3
View File
@@ -12,6 +12,7 @@ use App\Services\InvestmentCatalogue;
use App\Services\InvestmentRelations;
use App\Services\InvestmentRelationshipRepair;
use App\Services\InvestmentTerritorialValidation;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -104,7 +105,7 @@ class InvestmentRelationshipTest extends TestCase
$this->get('/carteira/'.$f['dossier']->id)->assertNotFound();
}
public function test_ambiguous_multiple_sites_do_not_choose_an_arbitrary_opportunity_marker(): void
public function test_multiple_documented_sites_are_shown_separately_without_choosing_one(): void
{
$f = $this->fixture();
$id = (string) Str::uuid();
@@ -112,11 +113,59 @@ class InvestmentRelationshipTest extends TestCase
DB::table('project_locations')->insert(['id' => (string) Str::uuid(), 'project_id' => $f['project']->id, 'geo_location_id' => $id, 'role' => 'secondary', 'data_classification' => 'public']);
DB::table('geo_geometries')->insert(['id' => (string) Str::uuid(), 'geo_location_id' => $id, 'geometry_type' => 'point', 'data_classification' => 'public', 'geom' => DB::raw('ST_SetSRID(ST_MakePoint(32.6,-25.8),4326)')]);
$map = app(InvestmentCatalogue::class)->map([]);
$this->assertSame(0, $map['georeferenced_count']);
$this->assertCount(1, $map['unlocated']);
$this->assertSame(1, $map['georeferenced_count']);
$this->assertCount(0, $map['unlocated']);
$this->assertCount(2, $map['features']);
$this->assertSame(2, $map['marker_count']);
$this->assertCount(2, app(InvestmentRelations::class)->projectLocations($f['project']->id));
}
public function test_direct_context_impact_and_missing_geography_remain_distinct(): void
{
$f = $this->fixture();
$catalogue = app(InvestmentCatalogue::class);
$this->assertEmpty($catalogue->context($f['opportunity']->id)['opportunity_locations']);
$this->assertSame([$f['opportunity']->id], $catalogue->query(['territory_basis' => 'context'])->pluck('id')->all());
$this->assertSame([], $catalogue->query(['territory_basis' => 'direct'])->pluck('id')->all());
DB::table('opportunity_locations')->insert(['opportunity_id' => $f['opportunity']->id, 'geo_location_id' => $f['ids']['district']]);
$location = $catalogue->context($f['opportunity']->id)['opportunity_locations'][0];
$this->assertSame('opportunity', $location['role']);
$this->assertSame([$f['opportunity']->id], $catalogue->query(['q' => 'QA district'])->pluck('id')->all());
$this->assertNull($location['source_reference']);
$this->assertEmpty($location['coordinates']);
$this->assertSame([], $catalogue->query(['territory_basis' => 'context'])->pluck('id')->all());
$this->assertSame([$f['opportunity']->id], $catalogue->query(['territory_basis' => 'direct', 'geo_location_id' => $f['ids']['district']])->pluck('id')->all());
$this->assertSame([], $catalogue->query(['territory_basis' => 'direct', 'geo_location_id' => $f['ids']['site']])->pluck('id')->all());
DB::table('project_locations')->update(['role' => 'impact']);
$this->assertSame('impact', $catalogue->context($f['opportunity']->id)['projects'][0]->geography['locations'][0]['role']);
$this->assertSame(0, $catalogue->map([])['georeferenced_count']);
DB::table('opportunity_locations')->delete();
DB::table('opportunity_projects')->delete();
$this->assertEmpty($catalogue->context($f['opportunity']->id)['opportunity_locations']);
$this->assertSame(1, $catalogue->query([])->count());
$this->assertCount(1, $catalogue->map([])['unlocated']);
}
public function test_invalid_coordinates_are_rejected_and_polygon_provenance_is_preserved(): void
{
$f = $this->fixture();
DB::table('opportunity_locations')->insert(['opportunity_id' => $f['opportunity']->id, 'geo_location_id' => $f['ids']['site']]);
DB::table('geo_geometries')->insert(['id' => (string) Str::uuid(), 'geo_location_id' => $f['ids']['site'], 'geometry_type' => 'polygon', 'data_classification' => 'public',
'geom' => DB::raw("ST_GeomFromText('POLYGON((32 -26,33 -26,33 -25,32 -25,32 -26))',4326)"), 'source_system' => 'QA boundary', 'properties' => json_encode(['source_date' => '2026-10-08'])]);
$context = app(InvestmentCatalogue::class)->context($f['opportunity']->id);
$this->assertSame('2026-10-08', $context['opportunity_locations'][0]['boundaries'][0]['source_date']);
$this->assertSame('opportunity_site', app(InvestmentCatalogue::class)->map([])['features'][0]['properties']['location_basis']);
$this->assertCount(1, app(InvestmentCatalogue::class)->map([])['areas']);
try {
DB::transaction(fn () => DB::table('geo_geometries')->where('geo_location_id', $f['ids']['site'])->where('geometry_type', 'point')->update(['geom' => DB::raw('ST_SetSRID(ST_MakePoint(32.7,95),4326)')]));
$this->fail('Invalid coordinates must be rejected by the existing database guard.');
} catch (QueryException $error) {
$this->assertSame('23514', $error->getCode());
}
$this->assertSame(1, app(InvestmentCatalogue::class)->map([])['georeferenced_count']);
$this->assertCount(1, app(InvestmentCatalogue::class)->context($f['opportunity']->id)['opportunity_locations'][0]['coordinates']);
}
public function test_repair_requires_authenticated_management_is_transactional_and_replays_without_duplicates(): void
{
$f = $this->fixture();
@@ -0,0 +1,106 @@
<?php
namespace Tests\Feature;
use App\Models\EconomicCluster;
use App\Models\InvestmentDossier;
use App\Models\Project;
use App\Models\User;
use App\Services\InvestmentTerritorialTraceability;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class InvestmentTerritorialTraceabilityTest extends TestCase
{
use RefreshDatabase;
private string $directory;
protected function setUp(): void
{
parent::setUp();
$this->directory = storage_path('framework/testing/territorial-'.Str::uuid());
mkdir($this->directory, 0700, true);
config(['investment.traceability_directory' => $this->directory]);
}
protected function tearDown(): void
{
foreach (glob($this->directory.'/*') ?: [] as $file) {
unlink($file);
}
rmdir($this->directory);
parent::tearDown();
}
private function fixture(): array
{
$project = Project::factory()->create();
$cluster = EconomicCluster::create(['code' => 'QA-TRACE', 'name' => 'Synthetic QA cluster', 'sector' => 'QA', 'status' => 'planned']);
$dossier = InvestmentDossier::create(['cluster_id' => $cluster->id, 'title' => 'QA synthetic source', 'source' => 'Synthetic fixture only', 'content' => [], 'publication_status' => 'published', 'published_at' => now()->subMinute(), 'approval_basis' => 'document_owner', 'approval_evidence' => 'QA synthetic disclosure']);
$id = (string) Str::uuid();
DB::table('cluster_projects')->insert(['id' => $id, 'cluster_id' => $cluster->id, 'project_id' => $project->id, 'role' => 'anchor', 'source_system' => 'QA']);
$row = DB::table('cluster_projects')->where('id', $id)->first();
$plan = ['schema' => 1, 'target' => ['database' => config('database.connections.pgsql.database'), 'port' => 55441], 'code_hash' => app(InvestmentTerritorialTraceability::class)->fingerprint(),
'rows' => [['kind' => 'economic_clusters', 'record_id' => $cluster->id, 'association' => $project->id, 'role' => 'context', 'public' => true, 'dossier_id' => $dossier->id, 'source_reference' => 'QA synthetic source', 'source_quote' => 'QA anchor', 'supports' => 'Existing membership only', 'traceability' => 'quote recovered', 'official_source_accepted' => false, 'existing_validation' => $row->validation_status]],
'guards' => [['table' => 'cluster_projects', 'id' => $id, 'expected' => ['version_no' => $row->version_no, 'validation_status' => $row->validation_status, 'source_reference' => null]]],
'updates' => [['table' => 'cluster_projects', 'id' => $id, 'values' => ['source_reference' => 'QA synthetic source', 'evidence_reference' => $dossier->id]]]];
$bytes = json_encode($plan, JSON_THROW_ON_ERROR);
file_put_contents($this->directory.'/territory-activation-plan.json', $bytes);
file_put_contents($this->directory.'/qa-backup-fixture', 'QA fixture, not active backup evidence');
$hash = hash('sha256', $bytes);
$proof = ['restore_verified' => true, 'reversal_verified' => true, 'target' => $plan['target'], 'plan_hash' => $hash, 'code_hash' => $plan['code_hash'], 'verified_at' => gmdate('c'), 'dump_path' => $this->directory.'/qa-backup-fixture', 'sha256' => hash_file('sha256', $this->directory.'/qa-backup-fixture')];
file_put_contents($this->directory.'/territory-backup-proof.json', json_encode($proof, JSON_THROW_ON_ERROR));
$manager = User::factory()->create(['email' => 'territory-manager@example.invalid']);
config(['portal.managers' => [$manager->email]]);
return compact('hash', 'manager', 'id', 'cluster', 'dossier', 'row');
}
public function test_authenticated_application_is_idempotent_and_reversible_without_revalidating_sources(): void
{
$f = $this->fixture();
$payload = ['operation' => 'traceability', 'hash' => $f['hash'], 'reverse' => false];
$this->actingAs($f['manager'])->postJson('/management/relationship-repair', $payload)->assertOk()->assertJsonPath('changed', 1);
$this->postJson('/management/relationship-repair', $payload)->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('changed', 0);
$service = app(InvestmentTerritorialTraceability::class);
$this->assertCount(1, $service->sources('economic_clusters', $f['cluster']->id));
$this->assertDatabaseHas('cluster_projects', ['id' => $f['id'], 'validation_status' => $f['row']->validation_status, 'source_reference' => 'QA synthetic source']);
$f['dossier']->update(['publication_status' => 'draft']);
$this->assertSame([], $service->sources('economic_clusters', $f['cluster']->id));
$this->postJson('/management/relationship-repair', [...$payload, 'reverse' => true])->assertOk()->assertJsonPath('changed', 1);
$this->assertDatabaseHas('cluster_projects', ['id' => $f['id'], 'version_no' => $f['row']->version_no + 2, 'source_reference' => null, 'evidence_reference' => null, 'validation_status' => $f['row']->validation_status]);
$this->assertSame([], $service->sources('economic_clusters', $f['cluster']->id));
$this->assertSame(2, DB::table('audit_events')->where('source_system', 'territory-traceability-v2')->count());
$this->postJson('/management/relationship-repair', $payload)->assertConflict();
}
public function test_permissions_and_conflicting_snapshot_prevent_writes_and_show_field_error(): void
{
$f = $this->fixture();
$payload = ['operation' => 'traceability', 'hash' => $f['hash'], 'reverse' => false];
$this->actingAs(User::factory()->create())->postJson('/management/relationship-repair', $payload)->assertForbidden();
DB::table('cluster_projects')->where('id', $f['id'])->increment('version_no');
$this->actingAs($f['manager'])->postJson('/management/relationship-repair', $payload)->assertConflict();
$this->from('/management/relationship-repair')->post('/management/relationship-repair', $payload)->assertRedirect('/management/relationship-repair')->assertSessionHasErrors('operation');
$this->assertDatabaseHas('cluster_projects', ['id' => $f['id'], 'source_reference' => null]);
$this->assertSame(0, DB::table('audit_events')->where('source_system', 'territory-traceability-v2')->count());
}
public function test_expired_backup_and_modified_code_proof_require_updated_plan(): void
{
$f = $this->fixture();
$proofFile = $this->directory.'/territory-backup-proof.json';
$proof = json_decode(file_get_contents($proofFile), true);
$proof['verified_at'] = gmdate('c', time() - 86401);
file_put_contents($proofFile, json_encode($proof));
$this->actingAs($f['manager'])->postJson('/management/relationship-repair', ['operation' => 'traceability', 'hash' => $f['hash'], 'reverse' => false])->assertUnprocessable();
$proof['verified_at'] = gmdate('c');
$proof['code_hash'] = 'wrong';
file_put_contents($proofFile, json_encode($proof));
$this->assertFalse(app(InvestmentTerritorialTraceability::class)->preview()['backup_ready']);
$this->assertDatabaseHas('cluster_projects', ['id' => $f['id'], 'source_reference' => null]);
}
}