resolvemos o problema dos ZEE e ZFI
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-07 19:46:35 +02:00
parent 0a086c3fa5
commit bdd766c68a
74 changed files with 6401 additions and 32 deletions
+47 -12
View File
@@ -3,6 +3,7 @@
namespace App\Services;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\InvestmentDossier;
use App\Models\Opportunity;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
@@ -54,6 +55,7 @@ class InvestmentCatalogue
$territory->whereIn('opportunities.primary_territory_id', $ids)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('opportunity_locations as territory_link')
->whereColumn('territory_link.opportunity_id', 'opportunities.id')->whereIn('territory_link.geo_location_id', $ids));
app(InvestmentRelations::class)->opportunityTerritories($territory, $ids);
if ($includeNational) {
$territory->orWhere('opportunities.geography_scope', 'national');
}
@@ -83,7 +85,13 @@ class InvestmentCatalogue
if (! empty($filters['q'])) {
$term = '%'.$filters['q'].'%';
$query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term)
->orWhere('province', 'ilike', $term)->orWhereHas('sector', fn ($s) => $s->where('name', 'ilike', $term)));
->orWhere('province', 'ilike', $term)->orWhereHas('sector', fn ($s) => $s->where('name', 'ilike', $term))
->orWhereExists(fn ($d) => $d->selectRaw('1')->from('investment_dossiers as searchable_dossier')
->whereNull('searchable_dossier.deleted_at')->where('searchable_dossier.publication_status', 'published')
->where(fn ($text) => $text->where('searchable_dossier.title', 'ilike', $term)->orWhereRaw('searchable_dossier.content::text ILIKE ?', [$term]))
->where(fn ($relation) => $relation
->whereExists(fn ($p) => $p->selectRaw('1')->from('opportunity_projects as search_project')->whereColumn('search_project.opportunity_id', 'opportunities.id')->whereColumn('search_project.project_id', 'searchable_dossier.project_id'))
->orWhereExists(fn ($c) => $c->selectRaw('1')->from('opportunity_clusters as search_cluster')->whereColumn('search_cluster.opportunity_id', 'opportunities.id')->whereColumn('search_cluster.cluster_id', 'searchable_dossier.cluster_id')))));
}
if (! empty($filters['sector'])) {
$query->whereHas('sector', fn ($s) => $s->where('slug', $filters['sector']));
@@ -99,11 +107,14 @@ class InvestmentCatalogue
? app(InvestmentGeography::class)->descendants((string) $filters[$foreign])
: null;
if ($relation === 'locations') {
$query->where(fn ($matches) => $matches->whereIn('opportunities.primary_territory_id', $locationIds ?? [])
->orWhereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_locations as link')
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
->whereNull('target.deleted_at')->where('target.data_classification', 'public')));
$query->where(function ($matches) use ($locationIds) {
$matches->whereIn('opportunities.primary_territory_id', $locationIds ?? [])
->orWhereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_locations as link')
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
->whereNull('target.deleted_at')->where('target.data_classification', 'public'));
app(InvestmentRelations::class)->opportunityTerritories($matches, $locationIds ?? []);
});
continue;
}
@@ -113,9 +124,8 @@ class InvestmentCatalogue
->whereIn('link.'.$foreign, $this->publicStructureIds($relation, $foreign)));
} else {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign)
->whereColumn('link.opportunity_id', 'opportunities.id')->when($relation === 'locations', fn ($q) => $q->whereIn('link.'.$foreign, $locationIds ?? []), fn ($q) => $q->where('link.'.$foreign, $filters[$foreign]))->whereNull('target.deleted_at')
->when($relation === 'locations', fn ($q) => $q->where('target.data_classification', 'public'),
fn ($q) => $q->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign))));
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])->whereNull('target.deleted_at')
->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign)));
}
}
}
@@ -149,7 +159,8 @@ class InvestmentCatalogue
};
}
/** @return array<string,mixed> */
/** @param array<string,mixed> $territoryFilters
* @return array<string,mixed> */
public function references(bool $management = false, array $territoryFilters = []): array
{
$result = ['options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
@@ -203,6 +214,15 @@ class InvestmentCatalogue
}
}
$result[$relation] = $query->get(['t.id', 't.name']);
if (in_array($relation, ['projects', 'clusters'], true)) {
$result[$relation] = $result[$relation]->map(function ($entity) use ($foreign, $management) {
$dossiers = ($management ? InvestmentDossier::query() : InvestmentPortfolioController::visible())->where($foreign, $entity->id)->get();
$entity->dossiers = $dossiers->map(fn ($dossier) => ['id' => $dossier->id, 'title' => $dossier->title, 'source' => $dossier->source]);
$entity->geography = $dossiers->first() ? app(InvestmentRelations::class)->dossier($dossiers->first(), $management) : null;
return $entity;
});
}
}
$result['zones'] = app(InvestmentZones::class)->links()->join('investment_item_opportunities as m', 'm.item_id', '=', 'zl.item_id')
@@ -224,6 +244,13 @@ class InvestmentCatalogue
$ids = $records->pluck('id');
$points = DB::table('opportunities as o')->join('geo_locations as g', function ($join) {
$join->on('g.id', '=', 'o.primary_territory_id')->orWhereExists(fn ($q) => $q->selectRaw('1')->from('opportunity_locations as l')->whereColumn('l.opportunity_id', 'o.id')->whereColumn('l.geo_location_id', 'g.id'));
$join->orWhereExists(fn ($q) => $q->selectRaw('1')->from('opportunity_projects as map_project')
->join('projects as p', 'p.id', '=', 'map_project.project_id')->whereColumn('map_project.opportunity_id', 'o.id')->whereNull('p.deleted_at')
->whereNotIn('p.data_classification', ['confidential', 'restricted'])->whereIn('p.id', app(InvestmentRelations::class)->projectIds())
->where(fn ($site) => $site->whereColumn('p.primary_territory_id', 'g.id')
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as map_location')
->whereColumn('map_location.project_id', 'p.id')->whereColumn('map_location.geo_location_id', 'g.id')
->whereNull('map_location.deleted_at')->where('map_location.data_classification', 'public')->where('map_location.role', '!=', 'impact'))));
})->join('geo_geometries as shape', 'shape.geo_location_id', '=', 'g.id')
->whereIn('o.id', $ids)->where('g.data_classification', 'public')->where('shape.data_classification', 'public')
->where('g.location_type', 'site')->whereNull('g.deleted_at')->whereNull('shape.deleted_at')->where('shape.geometry_type', 'point')
@@ -234,7 +261,14 @@ class InvestmentCatalogue
) SELECT 1 FROM parents WHERE deleted_at IS NOT NULL OR data_classification<>'public' OR cycle)")
->whereRaw('ST_IsValid(shape.geom) AND NOT ST_IsEmpty(shape.geom) AND ST_SRID(shape.geom)=4326')
->orderBy('o.id')->orderByRaw("CASE WHEN g.source_system='investment-site-editor' THEN 0 ELSE 1 END")->orderBy('g.id')->orderBy('shape.id')
->get(['o.id', 'g.name', DB::raw('ST_AsGeoJSON(shape.geom) as geometry')])->unique('id')->keyBy('id');
->get(['o.id', 'g.name', 'g.id as location_id', DB::raw('ST_AsGeoJSON(shape.geom) as geometry'),
DB::raw("CASE WHEN o.primary_territory_id=g.id OR EXISTS (SELECT 1 FROM opportunity_locations direct WHERE direct.opportunity_id=o.id AND direct.geo_location_id=g.id) THEN 'opportunity_site' ELSE 'linked_project_site' END as location_basis")])
->groupBy('id')->map(function ($candidates) {
$direct = $candidates->where('location_basis', 'opportunity_site');
$selected = $direct->isNotEmpty() ? $direct : $candidates;
return $selected->unique('location_id')->count() === 1 && $selected->unique('geometry')->count() === 1 ? $selected->first() : null;
})->filter();
$relations = [];
foreach (['clusters', 'corridors', 'projects'] as $relation) {
[$foreign, $table] = self::RELATIONS[$relation];
@@ -251,7 +285,8 @@ class InvestmentCatalogue
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
}
if ($point = $points->get($record->id)) {
$features[] = ['type' => 'Feature', 'geometry' => json_decode($point->geometry, true), 'properties' => [...$properties, 'location' => trim($properties['location'].' — '.$point->name)]];
$features[] = ['type' => 'Feature', 'geometry' => json_decode($point->geometry, true), 'properties' => [...$properties,
'location_basis' => $point->location_basis, 'location' => trim($properties['location'].' — '.$point->name).($point->location_basis === 'linked_project_site' ? ' (local documentado do projecto associado; implantação da oportunidade por confirmar)' : '')]];
} else {
$missing[] = [...$properties, 'reason' => 'missing_public_site_coordinates'];
}
+29 -6
View File
@@ -2,8 +2,9 @@
namespace App\Services;
use Illuminate\Database\Query\Builder;
use App\Models\InvestmentDossier;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
@@ -13,14 +14,25 @@ final class InvestmentGeography
/**
* Restrict published dossier searches using direct territories and public, validated structure links.
* @param EloquentBuilder<\App\Models\InvestmentDossier> $query
* @param list<string> $territoryIds
* @return EloquentBuilder<\App\Models\InvestmentDossier>
*
* @param EloquentBuilder<InvestmentDossier> $query
* @param list<string> $territoryIds
* @return EloquentBuilder<InvestmentDossier>
*/
public function constrainDossiersToTerritories(EloquentBuilder $query, array $territoryIds): EloquentBuilder
{
return $query->where(function ($matches) use ($territoryIds): void {
$matches->whereIn('project_id', DB::table('projects')->whereNull('deleted_at')->whereIn('primary_territory_id', $territoryIds)->select('id'))
$matches->orWhereExists(fn ($coverage) => $coverage->selectRaw('1')->from('economic_clusters as coverage_cluster')
->whereColumn('coverage_cluster.id', 'investment_dossiers.cluster_id')->whereNull('coverage_cluster.deleted_at')
->whereRaw(app(InvestmentRelations::class)->coverageSql('coverage_cluster.metadata', $territoryIds), $territoryIds));
$matches->orWhereExists(fn ($member) => $member->selectRaw('1')->fromSub(app(InvestmentRelations::class)->memberships()->select(['cp.cluster_id', 'cp.project_id']), 'documented_member')
->join('projects as member_project', 'member_project.id', '=', 'documented_member.project_id')
->whereColumn('documented_member.cluster_id', 'investment_dossiers.cluster_id')
->where(fn ($area) => $area->whereIn('member_project.primary_territory_id', $territoryIds)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as member_location')
->whereColumn('member_location.project_id', 'member_project.id')->whereNull('member_location.deleted_at')
->where('member_location.data_classification', 'public')->whereIn('member_location.geo_location_id', $territoryIds))));
$matches->orWhereIn('project_id', DB::table('projects')->whereNull('deleted_at')->whereIn('primary_territory_id', $territoryIds)->select('id'))
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as pl')
->whereColumn('pl.project_id', 'investment_dossiers.project_id')->whereNull('pl.deleted_at')
->where('pl.data_classification', 'public')->whereIn('pl.geo_location_id', $territoryIds))
@@ -177,7 +189,18 @@ final class InvestmentGeography
? DB::table('geo_locations')->whereNull('deleted_at')
: $this->publicReferences();
return array_values($query->whereIn('id', array_map(fn ($row) => $row->id, $rows))->pluck('id')->map(fn ($id) => (string) $id)->all());
$treeIds = array_map(fn ($row) => $row->id, $rows);
$ids = $query->whereIn('id', $treeIds)->pluck('id')->map(fn ($id) => (string) $id)->all();
if (! $includeNonPublic) {
// Documented sites need not be administrative registry entries themselves.
// Their parent must belong to the same public, trusted administrative hierarchy.
$sites = DB::table('geo_locations')->whereIn('id', $treeIds)->where('location_type', 'site')
->whereNull('deleted_at')->where('data_classification', 'public')
->whereIn('parent_id', $this->publicReferences()->select('id'))->pluck('id')->all();
$ids = array_merge($ids, $sites);
}
return array_values(array_unique($ids));
}
/** @return list<\stdClass> */
+178
View File
@@ -0,0 +1,178 @@
<?php
namespace App\Services;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\InvestmentDossier;
use App\Models\Opportunity;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
/** Resolve documented relationships without generating geography or spreading opportunity memberships. */
class InvestmentRelations
{
public function projectIds(): Builder
{
return InvestmentPortfolioController::visible()->whereNotNull('project_id')->select('project_id')->toBase();
}
public function memberships(): Builder
{
// Legacy proposal links are consultable when both dossiers disclose the exact project code.
// Their pending/legal status remains independent from permission to consult the source.
return DB::table('cluster_projects as cp')->join('projects as member', 'member.id', '=', 'cp.project_id')
->whereNull('cp.deleted_at')->whereNull('member.deleted_at')->whereNotIn('member.data_classification', ['confidential', 'restricted'])
->where('cp.validation_status', '!=', 'revoked')
->where(fn ($q) => $q->whereNull('cp.valid_from')->orWhereDate('cp.valid_from', '<=', today()))
->where(fn ($q) => $q->whereNull('cp.valid_until')->orWhereDate('cp.valid_until', '>=', today()))
->whereIn('cp.project_id', $this->projectIds())
->whereExists(fn ($q) => $q->selectRaw('1')->from('investment_dossiers as disclosed_cluster')
->whereColumn('disclosed_cluster.cluster_id', 'cp.cluster_id')->where('disclosed_cluster.publication_status', 'published')->whereNull('disclosed_cluster.deleted_at')
->where(fn ($authorized) => $authorized->where('cp.data_classification', 'public')
->orWhere(fn ($legacy) => $legacy->where('cp.source_system', 'upgrade-v4')
->whereRaw("(disclosed_cluster.content->>'anchors') ~ ('\\m' || member.code || '\\M')"))));
}
/** @return list<array<string,mixed>> */
public function projectLocations(string $id, bool $management = false): array
{
$project = DB::table('projects')->where('id', $id)->whereNull('deleted_at')->first();
if (! $project || (! $management && (in_array($project->data_classification, ['confidential', 'restricted'], true)
|| ! InvestmentPortfolioController::visible()->where('project_id', $id)->exists()))) {
return [];
}
$links = DB::table('project_locations')->where('project_id', $id)->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))->orderBy('role')->get();
$items = [];
$metadata = json_decode($project->metadata, true);
foreach ($links as $link) {
$items[] = ['id' => $link->geo_location_id, 'role' => $link->role, 'relation_id' => $link->id,
'source_reference' => $metadata['documented_location_sources'][$link->geo_location_id.':'.$link->role]['source_reference'] ?? $link->source_system,
'source_quote' => $metadata['documented_location_sources'][$link->geo_location_id.':'.$link->role]['source_quote'] ?? null,
'external_id' => $link->external_id];
}
if ($project->primary_territory_id && ! collect($items)->contains(fn ($item) => $item['id'] === $project->primary_territory_id && $item['role'] === 'primary')) {
$items[] = ['id' => $project->primary_territory_id, 'role' => 'primary', 'source_reference' => $project->source_system, 'relation_id' => null];
}
return $this->locations($items, $management);
}
/** @param list<array<string,mixed>> $items
* @return list<array<string,mixed>> */
public function locations(array $items, bool $management = false): array
{
$result = [];
foreach ($items as $item) {
$path = app(InvestmentGeography::class)->path($item['id'], $management);
// Site nodes are not administrative references; use their documented parent path.
$site = DB::table('geo_locations')->where('id', $item['id'])->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))->first();
if (! $site) {
continue;
}
if ($site->location_type === 'site') {
$path = app(InvestmentGeography::class)->path($site->parent_id, $management);
if ($site->parent_id && ! $path) {
continue;
}
} elseif (! $path) {
continue;
}
$shapes = DB::table('geo_geometries')->where('geo_location_id', $item['id'])->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))
->where('geometry_type', 'point')->whereRaw('ST_IsValid(geom) AND NOT ST_IsEmpty(geom) AND ST_SRID(geom)=4326')
->orderBy('id')->get(['id', 'source_system', DB::raw('ST_AsGeoJSON(geom) as geometry')]);
$coordinates = $shapes->map(fn ($shape) => ['geometry_id' => $shape->id, 'source_reference' => $shape->source_system,
'geometry' => json_decode($shape->geometry, true)])->all();
$result[] = [...$item, 'name' => $site->name, 'location_type' => $site->location_type, 'path' => $path, 'coordinates' => $coordinates];
}
return $result;
}
/** @return array<string,mixed> */
public function dossier(InvestmentDossier $dossier, bool $management = false): array
{
$result = ['locations' => [], 'members' => [], 'clusters' => [], 'chainLinks' => [], 'chains' => []];
if ($dossier->project_id) {
$result['locations'] = $this->projectLocations($dossier->project_id, $management);
$memberships = $this->memberships()->where('cp.project_id', $dossier->project_id)->get(['cp.cluster_id', 'cp.role', 'cp.validation_status', 'cp.source_reference']);
foreach ($memberships as $membership) {
foreach (InvestmentPortfolioController::visible()->where('cluster_id', $membership->cluster_id)->get() as $cluster) {
$result['clusters'][] = ['id' => $cluster->cluster_id, 'dossier_id' => $cluster->id, 'title' => $cluster->title,
'role' => $membership->role, 'validation_status' => $membership->validation_status, 'source_reference' => $membership->source_reference ?? $cluster->source];
}
}
}
if ($dossier->cluster_id) {
$result['chains'] = DB::table('value_chains')->where('cluster_id', $dossier->cluster_id)->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))->orderBy('code')->get(['id', 'code', 'name', 'stage'])->all();
$cluster = DB::table('economic_clusters')->where('id', $dossier->cluster_id)->first();
$metadata = json_decode($cluster->metadata ?? '{}', true);
$coverage = array_values(array_filter($metadata['documented_coverage'] ?? [], fn ($item) => isset($item['id'], $item['source_reference']) && ($management || ($item['data_classification'] ?? '') === 'public')));
if ($cluster?->primary_territory_id) {
$coverage[] = ['id' => $cluster->primary_territory_id, 'role' => 'coverage', 'source_reference' => $cluster->source_system];
}
$result['locations'] = $this->locations($coverage, $management);
foreach ($this->memberships()->where('cp.cluster_id', $dossier->cluster_id)->get(['cp.project_id', 'member.code', 'member.name', 'cp.role', 'cp.validation_status', 'cp.source_reference']) as $member) {
$projectDossier = InvestmentPortfolioController::visible()->where('project_id', $member->project_id)->first();
if ($projectDossier) {
$result['members'][] = ['id' => $member->project_id, 'dossier_id' => $projectDossier->id, 'title' => $projectDossier->title,
'code' => $member->code, 'role' => $member->role, 'validation_status' => $member->validation_status,
'source_reference' => $member->source_reference ?? $dossier->source, 'locations' => $this->projectLocations($member->project_id, $management)];
}
}
$result['chainLinks'] = DB::table('value_chain_links as link')->join('value_chains as origin', 'origin.id', '=', 'link.from_value_chain_id')
->join('value_chains as destination', 'destination.id', '=', 'link.to_value_chain_id')
->where('origin.cluster_id', $dossier->cluster_id)->where('destination.cluster_id', $dossier->cluster_id)
->whereNull('link.deleted_at')->whereNull('origin.deleted_at')->whereNull('destination.deleted_at')
->when(! $management, fn ($q) => $q->where('link.data_classification', 'public')->where('origin.data_classification', 'public')->where('destination.data_classification', 'public'))
->get(['link.id', 'origin.name as origin', 'destination.name as destination', 'link.link_type'])->all();
}
return $result;
}
/** Add explicitly linked project and cluster member territories without creating opportunity-project links.
* @param Builder|\Illuminate\Database\Eloquent\Builder<Opportunity> $query
* @param list<string> $ids */
public function opportunityTerritories(Builder|\Illuminate\Database\Eloquent\Builder $query, array $ids): void
{
$query->orWhereExists(fn ($links) => $links->selectRaw('1')->from('opportunity_projects as geographic_project')
->join('projects as documented_project', 'documented_project.id', '=', 'geographic_project.project_id')
->whereColumn('geographic_project.opportunity_id', 'opportunities.id')->whereNull('documented_project.deleted_at')
->whereIn('documented_project.id', $this->projectIds())
->where(fn ($area) => $area->whereIn('documented_project.primary_territory_id', $ids)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as documented_location')
->whereColumn('documented_location.project_id', 'documented_project.id')->whereNull('documented_location.deleted_at')
->where('documented_location.data_classification', 'public')->whereIn('documented_location.geo_location_id', $ids))));
$query->orWhereExists(fn ($links) => $links->selectRaw('1')->from('opportunity_clusters as geographic_cluster')
->join('economic_clusters as documented_cluster', 'documented_cluster.id', '=', 'geographic_cluster.cluster_id')
->whereColumn('geographic_cluster.opportunity_id', 'opportunities.id')->whereNull('documented_cluster.deleted_at')
->whereIn('documented_cluster.id', InvestmentPortfolioController::visible()->whereNotNull('cluster_id')->select('cluster_id'))
->where(fn ($area) => $area->whereIn('documented_cluster.primary_territory_id', $ids)
->orWhereRaw($this->coverageSql('documented_cluster.metadata', $ids), $ids)
->orWhereExists(fn ($members) => $members->selectRaw('1')->fromSub($this->memberships()->select(['cp.cluster_id', 'cp.project_id']), 'territorial_member')
->join('projects as member_project', 'member_project.id', '=', 'territorial_member.project_id')->whereColumn('territorial_member.cluster_id', 'documented_cluster.id')
->where(fn ($territory) => $territory->whereIn('member_project.primary_territory_id', $ids)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as member_location')
->whereColumn('member_location.project_id', 'member_project.id')->whereNull('member_location.deleted_at')
->where('member_location.data_classification', 'public')->whereIn('member_location.geo_location_id', $ids))))));
}
/** @param list<string> $ids */
public function coverageSql(string $column, array $ids): string
{
if (! in_array($column, ['documented_cluster.metadata', 'coverage_cluster.metadata'], true)) {
throw new \InvalidArgumentException('Unsupported coverage column');
}
if (! $ids) {
return 'false';
}
return "EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof({$column}->'documented_coverage')='array' THEN {$column}->'documented_coverage' ELSE '[]'::jsonb END) AS coverage_entry
WHERE coverage_entry->>'data_classification'='public' AND NULLIF(coverage_entry->>'source_reference','') IS NOT NULL
AND coverage_entry->>'id' IN (".implode(',', array_fill(0, count($ids), '?')).'))';
}
}
@@ -0,0 +1,213 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/** @phpstan-type RepairPlan array{target:array<string,mixed>,locations:list<array<string,mixed>>,memberships:list<array<string,mixed>>,pending:list<array<string,mixed>>,prepared_opportunities:list<array<string,mixed>>} */
class InvestmentRelationshipRepair
{
public function directory(): string
{
return config('investment.repair_directory', storage_path('app/private/anchor-project-reconciliation'));
}
/** @return array{hash:string,plan:RepairPlan,territorial:list<array<string,mixed>>,history:list<array<string,mixed>>,unproposed:list<array<string,mixed>>} */
public function preview(): array
{
$file = $this->directory().'/preview.json';
abort_unless(is_file($file), 404, 'Pré-visualização não preparada.');
$contents = file_get_contents($file);
abort_if($contents === false, 503, 'Pré-visualização não pode ser lida.');
$hash = hash('sha256', $contents);
$plan = $this->decodePlan($contents);
$history = $this->history($hash);
$validation = app(InvestmentTerritorialValidation::class);
$territorial = [];
foreach ($plan['locations'] as $row) {
$result = $validation->validate($row);
$result['applied'] = $this->wasApplied($history, $result['row_id']);
$result['validation_hash'] = hash('sha256', json_encode($result, JSON_THROW_ON_ERROR));
$territorial[] = $result;
}
$unproposed = [];
foreach (array_unique(array_column($plan['pending'], 'code')) as $code) {
if (! preg_match('/^A\d{2}$/', $code) || collect($plan['locations'])->contains('code', $code)) {
continue;
}
$project = DB::table('projects')->where('code', $code)->whereNull('deleted_at')->first();
if (! $project) {
continue;
}
$dossier = DB::table('investment_dossiers')->where('project_id', $project->id)->whereNull('deleted_at')->first();
$unproposed[] = ['code' => $code, 'current' => app(InvestmentRelations::class)->projectLocations($project->id, true),
'source' => $dossier?->source, 'location_text' => $dossier ? (json_decode($dossier->content, true)['location'] ?? null) : null,
'reasons' => collect($plan['pending'])->where('code', $code)->pluck('reason')->all()];
}
return ['hash' => $hash, 'plan' => $plan, 'territorial' => $territorial, 'history' => $history, 'unproposed' => $unproposed];
}
/** @return RepairPlan */
private function decodePlan(string $contents): array
{
$plan = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
abort_unless(is_array($plan) && is_array($plan['target'] ?? null) && is_array($plan['locations'] ?? null) && is_array($plan['memberships'] ?? null), 422, 'Plano de associações inválido.');
$target = [];
foreach ($plan['target'] as $key => $value) {
abort_unless(is_string($key), 422, 'Destino inválido.');
$target[$key] = $value;
}
return ['target' => $target, 'locations' => $this->decodeRows($plan['locations']), 'memberships' => $this->decodeRows($plan['memberships']),
'pending' => $this->decodeRows($plan['pending'] ?? []), 'prepared_opportunities' => $this->decodeRows($plan['prepared_opportunities'] ?? [])];
}
/** @return list<array<string,mixed>> */
private function decodeRows(mixed $rows): array
{
abort_unless(is_array($rows), 422, 'Linhas do plano inválidas.');
$result = [];
foreach ($rows as $row) {
abort_unless(is_array($row), 422, 'Linha do plano inválida.');
$item = [];
foreach ($row as $key => $value) {
abort_unless(is_string($key), 422, 'Campo do plano inválido.');
$item[$key] = $value;
}
$result[] = $item;
}
return $result;
}
/** @return list<array<string,mixed>> */
private function history(string $hash): array
{
return array_values(DB::table('audit_events as event')->leftJoin('users as actor', 'actor.id', '=', 'event.actor_user_id')
->where('event.source_system', 'documented-relations-repair')->whereRaw("event.after_data->>'plan_hash' = ?", [$hash])
->orderBy('event.created_at')->orderBy('event.id')->get(['event.id', 'event.created_at', 'event.actor_user_id', 'actor.name as actor_name', 'event.after_data'])
->map(fn ($event) => ['id' => $event->id, 'date' => $event->created_at, 'actor_id' => $event->actor_user_id, 'actor' => $event->actor_name,
'data' => json_decode($event->after_data, true)])->all());
}
/** @param list<array<string,mixed>> $history */
private function wasApplied(array $history, string $rowId): bool
{
foreach ($history as $event) {
if (! isset($event['data']['location_row_ids']) || in_array($rowId, $event['data']['location_row_ids'], true)) {
return true;
}
}
return false;
}
/** @return array<string,mixed> */
public function apply(string $hash, int $actor, ?string $rowId = null, ?string $validationHash = null): array
{
$preview = $this->preview();
abort_unless(hash_equals($preview['hash'], $hash), 409, 'Pré-visualização alterada. Reveja as associações.');
$proofFile = $this->directory().'/backup-proof.json';
abort_unless(is_file($proofFile), 422, 'Backup e restauro isolado ainda não verificados.');
$contents = file_get_contents($proofFile);
abort_if($contents === false, 503, 'Evidência de restauro não pode ser lida.');
$proof = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
$dumpHash = is_file($proof['dump_path'] ?? '') ? hash_file('sha256', $proof['dump_path']) : false;
abort_unless(($proof['restore_verified'] ?? false) && is_file($proof['dump_path'] ?? '')
&& $dumpHash !== false && hash_equals($proof['sha256'], $dumpHash), 422, 'Evidência de backup/restauro inválida.');
$plan = $preview['plan'];
$validation = app(InvestmentTerritorialValidation::class);
if ($rowId !== null) {
abort_unless(collect($plan['locations'])->contains(fn ($row) => $validation->rowId($row) === $rowId), 422, 'Associação não pertence ao plano.');
}
$identity = DB::selectOne('select current_database() as database, inet_server_port() as port');
abort_unless($identity->database === $plan['target']['database'] && (int) $identity->port === (int) $plan['target']['port']
&& ($proof['target'] ?? null) === $plan['target'], 409, 'Base de destino diferente da pré-visualização e do backup.');
if (app()->environment('testing')) {
abort_unless(str_ends_with($identity->database, '_test') && (int) $identity->port === 55441, 409, 'QA exige base *_test isolada na porta 55441.');
}
return DB::transaction(function () use ($plan, $hash, $actor, $rowId, $validation, $validationHash): array {
DB::select('select pg_advisory_xact_lock(71026, 150000)');
$history = $this->history($hash);
if (($rowId !== null && $this->wasApplied($history, $rowId)) || ($rowId === null && collect($history)->contains(fn ($event) => ! isset($event['data']['location_row_ids']) || ($event['data']['batch_complete'] ?? false)))) {
return ['replayed' => true, 'locations_created' => 0, 'memberships_created' => 0];
}
DB::statement('LOCK TABLE geo_locations, geo_geometries IN SHARE MODE');
$created = $memberships = 0;
$projects = $appliedRows = $sources = $before = [];
foreach ($plan['locations'] as $row) {
$id = $validation->rowId($row);
if (($rowId !== null && $rowId !== $id) || $this->wasApplied($history, $id)) {
continue;
}
$territory = $validation->validate($row);
if ($rowId !== null) {
$territory['applied'] = false;
abort_unless($validationHash !== null && hash_equals(hash('sha256', json_encode($territory, JSON_THROW_ON_ERROR)), $validationHash), 409, 'Validação territorial alterada. Reveja a proposta.');
}
if ($territory['status'] !== 'grounded') {
abort_if($rowId !== null, 409, 'Associação pendente ou contraditória; não pode ser aplicada.');
continue;
}
$project = $projects[$row['project_id']] ?? DB::table('projects')->where('id', $row['project_id'])->whereNull('deleted_at')->lockForUpdate()->first();
$increments = collect($history)->filter(fn ($event) => in_array($row['project_id'], $event['data']['project_ids'] ?? [], true))->count();
abort_unless($project && (int) $project->version_no === (int) $row['expected_project_version'] + $increments, 409, 'Projecto alterado desde a pré-visualização.');
$dossier = DB::table('investment_dossiers')->where('id', $row['dossier_id'])->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($dossier && $dossier->project_id === $project->id && (int) $dossier->version_no === (int) $row['dossier_version'], 409, 'Dossier alterado.');
$content = json_decode($dossier->content, true);
abort_unless(($content['location'] ?? null) === $row['source_quote'] && $dossier->source === $row['source_reference'], 409, 'Citação documental alterada.');
abort_unless($row['data_classification'] !== 'public' || $dossier->publication_status === 'published', 409, 'Autorização de divulgação alterada.');
abort_unless(app(InvestmentGeography::class)->references(true)->where('id', $row['geo_location_id'])->exists(), 409, 'Referência territorial indisponível.');
$appliedRows[] = $id;
$before[] = ['row_id' => $id, 'project_id' => $project->id, 'current' => $territory['current']];
$sources[] = ['row_id' => $id, 'project_id' => $project->id, 'geo_location_id' => $row['geo_location_id'], 'role' => $row['role'],
'source_reference' => $row['source_reference'], 'source_quote' => $row['source_quote'], 'dossier_id' => $dossier->id, 'reason' => $row['reason']];
$key = ['project_id' => $project->id, 'geo_location_id' => $row['geo_location_id'], 'role' => $row['role']];
if (! DB::table('project_locations')->where($key)->whereNull('deleted_at')->exists()) {
DB::table('project_locations')->insert([...$key, 'id' => (string) Str::uuid(), 'source_system' => 'documented-relations-repair',
'external_id' => $row['dossier_id'].':'.$row['geo_location_id'].':'.$row['role'], 'data_classification' => $row['data_classification']]);
$metadata = json_decode($project->metadata, true);
$metadata['documented_location_sources'][$row['geo_location_id'].':'.$row['role']] = ['source_reference' => $row['source_reference'], 'source_quote' => $row['source_quote'], 'dossier_id' => $dossier->id, 'plan_hash' => $hash, 'reason' => $row['reason'], 'actor_user_id' => $actor, 'applied_at' => now()->toIso8601String()];
$project->metadata = json_encode($metadata, JSON_THROW_ON_ERROR);
$projects[$project->id] = $project;
$created++;
}
}
foreach ($projects as $project) {
DB::table('projects')->where('id', $project->id)->update(['metadata' => $project->metadata, 'version_no' => $project->version_no + 1]);
}
foreach ($rowId === null ? $plan['memberships'] : [] as $row) {
if ($row['existing_id']) {
continue;
}
$key = ['cluster_id' => $row['cluster_id'], 'project_id' => $row['project_id']];
$dossier = DB::table('investment_dossiers')->where('id', $row['dossier_id'])->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($dossier && $dossier->cluster_id === $row['cluster_id'] && (int) $dossier->version_no === (int) $row['dossier_version']
&& (json_decode($dossier->content, true)['anchors'] ?? null) === $row['source_quote'], 409, 'Fonte da relação do cluster alterada.');
abort_unless(DB::table('projects')->where('id', $row['project_id'])->where('code', $row['project_code'])->whereNull('deleted_at')->exists(), 409, 'Identidade do projecto alterada.');
if (! DB::table('cluster_projects')->where($key)->whereNull('deleted_at')->exists()) {
DB::table('cluster_projects')->insert([...$key, 'id' => (string) Str::uuid(), 'role' => $row['role'], 'source_system' => 'documented-relations-repair',
'source_reference' => $row['source_reference'], 'evidence_reference' => $row['dossier_id'], 'editor_id' => $actor,
'data_classification' => $dossier->publication_status === 'published' ? 'public' : 'internal', 'validation_status' => 'pending', 'association_type' => 'potential']);
$memberships++;
}
}
if (! $appliedRows && ! $memberships) {
return ['replayed' => true, 'locations_created' => 0, 'memberships_created' => 0];
}
DB::table('audit_events')->insert(['source_system' => 'documented-relations-repair', 'entity_type' => 'project_locations',
'actor_user_id' => $actor, 'action' => 'documented_relations_applied', 'before_data' => json_encode($before, JSON_THROW_ON_ERROR), 'after_data' => json_encode(['plan_hash' => $hash,
'locations_created' => $created, 'memberships_created' => $memberships, 'project_ids' => array_keys($projects),
'location_row_ids' => $appliedRows, 'sources' => $sources,
'batch_complete' => $rowId === null && count(array_filter($plan['locations'], fn ($row) => ! in_array($validation->rowId($row), $appliedRows, true) && ! $this->wasApplied($history, $validation->rowId($row)))) === 0], JSON_THROW_ON_ERROR)]);
return ['replayed' => false, 'locations_created' => $created, 'memberships_created' => $memberships];
});
}
}
@@ -0,0 +1,132 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
/** Validate only the territory explicitly proposed in the documentary plan. */
class InvestmentTerritorialValidation
{
/** @param array<string,mixed> $row */
public function rowId(array $row): string
{
return hash('sha256', json_encode($row, JSON_THROW_ON_ERROR));
}
/** @param array<string,mixed> $row
* @return array<string,mixed>
*/
public function validate(array $row): array
{
$issues = $warnings = $path = $visited = [];
$pending = false;
$project = DB::table('projects')->where('id', $row['project_id'])->whereNull('deleted_at')->first();
$dossier = DB::table('investment_dossiers')->where('id', $row['dossier_id'])->whereNull('deleted_at')->first();
if (! $project || ! $dossier || $dossier->project_id !== $row['project_id']) {
$issues[] = 'Projeto ou documento de origem indisponível ou de outra identidade.';
} elseif (($row['source_reference'] ?? '') === '' || ($row['source_quote'] ?? '') === '') {
$pending = true;
$warnings[] = 'Falta referência ou citação documental da localização.';
} elseif ($dossier->source !== $row['source_reference'] || (json_decode($dossier->content, true)['location'] ?? null) !== $row['source_quote']
|| (int) $dossier->version_no !== (int) $row['dossier_version']) {
$issues[] = 'Fonte, citação ou versão do dossier diverge da proposta.';
}
if (($row['data_classification'] ?? null) === 'public' && $dossier && $dossier->publication_status !== 'published') {
$issues[] = 'A autorização de divulgação do dossier já não corresponde à proposta pública.';
}
if (! in_array($row['role'] ?? null, ['primary', 'secondary', 'impact'], true)) {
$issues[] = 'Papel territorial inválido.';
}
$id = $row['geo_location_id'];
while ($id) {
if (isset($visited[$id])) {
$issues[] = 'Ciclo na hierarquia territorial.';
break;
}
$visited[$id] = true;
$node = DB::table('geo_locations')->where('id', $id)->first();
if (! $node || $node->deleted_at || ! in_array($node->data_classification, ['public', 'internal'], true)) {
$issues[] = 'Território ou antepassado indisponível para esta associação.';
break;
}
array_unshift($path, ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type]);
$id = $node->parent_id;
}
$levels = ['country' => 0, 'province' => 1, 'district' => 2, 'admin_post' => 3, 'locality' => 4, 'site' => 5];
$previous = null;
foreach ($path as $node) {
$level = $levels[$node['type']] ?? null;
if ($level === null || ($previous !== null && $level !== $previous + 1 && $node['type'] !== 'site')) {
$issues[] = 'Hierarquia incompatível: província → distrito → posto administrativo → localidade.';
}
$previous = $level;
}
if (! collect($path)->contains('type', 'province')) {
$pending = true;
$warnings[] = 'A hierarquia não identifica uma província.';
}
foreach (InvestmentGeography::FIELDS as $field => $type) {
if (isset($row[$field]) && ! collect($path)->contains(fn ($node) => $node['type'] === $type && $node['id'] === $row[$field])) {
$issues[] = 'O nível indicado em '.$field.' não pertence à hierarquia proposta.';
}
}
$points = DB::table('geo_geometries')->where('geo_location_id', $row['geo_location_id'])->whereNull('deleted_at')
->whereIn('data_classification', ['public', 'internal'])->where('geometry_type', 'point')
->get(['id', 'source_system', DB::raw('ST_AsGeoJSON(geom) as geometry'), DB::raw('ST_SRID(geom) as srid')]);
$coordinates = [];
foreach ($points as $point) {
$geometry = json_decode($point->geometry, true);
$coordinates[] = ['geometry_id' => $point->id, 'source' => $point->source_system, 'coordinates' => $geometry['coordinates'] ?? [], 'srid' => $point->srid];
}
if (isset($row['coordinates'])) {
$coordinates[] = ['geometry_id' => null, 'source' => $row['source_reference'], 'coordinates' => $row['coordinates'], 'srid' => 4326];
}
$checks = [];
foreach ($coordinates as $point) {
$xy = $point['coordinates'];
if (count($xy) < 2 || ! is_numeric($xy[0]) || ! is_numeric($xy[1]) || ! is_finite((float) $xy[0]) || ! is_finite((float) $xy[1])
|| abs((float) $xy[0]) > 180 || abs((float) $xy[1]) > 90 || (int) $point['srid'] !== 4326) {
$issues[] = 'Coordenadas inválidas ou sistema de referência incompatível com WGS84.';
continue;
}
$boundaries = DB::table('geo_geometries')->whereIn('geo_location_id', array_column($path, 'id'))->whereNull('deleted_at')
->whereIn('data_classification', ['public', 'internal'])->whereIn('geometry_type', ['polygon', 'multipolygon'])
->whereRaw('ST_IsValid(geom) AND NOT ST_IsEmpty(geom) AND ST_SRID(geom)=4326')
->select(['id', 'geo_location_id', 'source_system'])
->selectRaw('ST_Covers(geom, ST_SetSRID(ST_MakePoint(?, ?),4326)) as compatible', [(float) $xy[0], (float) $xy[1]])->get();
if ($boundaries->isEmpty()) {
$warnings[] = 'Coordenadas com formato válido; sem limites cartográficos documentados para confirmar inclusão territorial.';
}
foreach ($boundaries as $boundary) {
$checks[] = ['geometry_id' => $point['geometry_id'], 'territory_id' => $boundary->geo_location_id, 'source' => $boundary->source_system, 'compatible' => (bool) $boundary->compatible];
if (! $boundary->compatible) {
$issues[] = 'Coordenadas fora do território '.(collect($path)->firstWhere('id', $boundary->geo_location_id)['name'] ?? $boundary->geo_location_id).'.';
}
}
}
if (! $coordinates) {
$warnings[] = 'Sem coordenadas; a ausência não impede validar a localização documental.';
}
$current = [];
if ($project) {
$links = DB::table('project_locations')->where('project_id', $project->id)->whereNull('deleted_at')->get();
foreach ($links as $link) {
$location = DB::table('geo_locations')->where('id', $link->geo_location_id)->first();
$current[] = ['id' => $link->geo_location_id, 'name' => $location->name ?? 'Território indisponível', 'role' => $link->role,
'path' => array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($link->geo_location_id, true))];
}
if ($project->primary_territory_id && ! collect($current)->contains(fn ($item) => $item['id'] === $project->primary_territory_id && $item['role'] === 'primary')) {
$location = DB::table('geo_locations')->where('id', $project->primary_territory_id)->first();
$current[] = ['id' => $project->primary_territory_id, 'name' => $location->name ?? 'Território indisponível', 'role' => 'primary',
'path' => array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($project->primary_territory_id, true))];
}
}
return ['row_id' => $this->rowId($row), 'status' => $issues ? 'contradictory' : ($pending ? 'pending' : 'grounded'),
'issues' => array_values(array_unique($issues)), 'warnings' => array_values(array_unique($warnings)), 'current' => $current,
'proposed' => ['id' => $row['geo_location_id'], 'name' => collect($path)->last()['name'] ?? ($row['name'] ?? 'Território indisponível'), 'role' => $row['role'], 'path' => $path],
'coordinates' => $coordinates, 'coordinate_checks' => $checks];
}
}
+241
View File
@@ -0,0 +1,241 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use stdClass;
class PartnershipExchange
{
public function represents(User $actor, ?string $organization, bool $write = true): bool
{
return $organization !== null && DB::table('memberships')->where('user_id', $actor->id)->where('organization_id', $organization)->whereNull('deleted_at')
->when($write, fn ($q) => $q->whereIn('role', ['admin', 'manager', 'officer']))->exists()
&& DB::table('organizations')->where('id', $organization)->whereNull('deleted_at')->exists();
}
public function owns(User $actor, stdClass $record, bool $write = true): bool
{
// An organization record follows its current representatives, including the original author.
return $record->organization_id ? $this->represents($actor, $record->organization_id, $write) : (int) $record->user_id === $actor->id;
}
public function find(int $id, bool $lock = false): stdClass
{
$record = DB::table('portal_partnerships')->where('id', $id)->when($lock, fn ($q) => $q->lockForUpdate())->first();
abort_unless($record !== null, 404);
return $record;
}
/** @param array<string,mixed> $data */
public function save(User $actor, array $data, ?int $id = null): stdClass
{
$data = Validator::make($data, [
'client_key' => [$id ? 'nullable' : 'required', 'uuid'], 'version' => [$id ? 'required' : 'nullable', 'integer', 'min:1'],
'title' => ['nullable', 'string', 'max:200'], 'offer' => ['nullable', 'string', 'max:15000'], 'seeking' => ['nullable', 'string', 'max:15000'],
'kind' => ['required', 'in:offering,seeking'], 'partnership_type' => ['nullable', Rule::in(array_keys(config('partnerships.types')))],
'organization_id' => ['nullable', 'uuid'], 'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->where('is_active', true)->whereNull('deleted_at')],
'deadline' => ['nullable', 'date_format:Y-m-d'], 'payload' => ['array:summary,requirements,mandatory,confidentiality,consent,availability'],
'payload.summary' => ['nullable', 'string', 'max:15000'], 'payload.requirements' => ['nullable', 'string', 'max:10000'],
'payload.mandatory' => ['array', 'max:7'], 'payload.mandatory.*' => [Rule::in(array_keys(config('partnerships.criteria')))],
'payload.confidentiality' => ['in:public,private'], 'payload.consent' => ['boolean'], 'payload.availability' => ['nullable', 'string', 'max:1000'],
'locations' => ['array', 'max:30'], 'locations.*.geo_location_id' => ['required', 'uuid'], 'locations.*.role' => ['required', 'in:primary,operating,coverage'],
'locations.*.source_reference' => ['required', 'string', 'max:2000'],
'origins' => ['array', 'max:20'], 'origins.*.type' => ['required', 'string'], 'origins.*.target_id' => ['required', 'string', 'max:100'],
])->validate();
abort_if(($data['organization_id'] ?? null) && ! $this->represents($actor, $data['organization_id']), 403, 'Representação da organização não autorizada.');
$creationHash = hash('sha256', json_encode(Arr::sortRecursive($data), JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $data, $id, $creationHash) {
DB::select('select pg_advisory_xact_lock(71026, ?)', [$actor->id]);
if ($id) {
$record = $this->find($id, true);
abort_unless($this->owns($actor, $record), 403);
abort_unless((int) $record->version === (int) $data['version'], 409, 'Rascunho alterado; recarregue.');
abort_unless(in_array($record->status, ['draft', 'returned', 'rejected', 'published'], true), 409, 'Estado não permite edição.');
} else {
$existing = DB::table('portal_partnerships')->where('user_id', $actor->id)->where('client_key', $data['client_key'])->first();
if ($existing) {
abort_unless((json_decode($existing->payload, true)['_creation_hash'] ?? null) === $creationHash, 409, 'Chave de rascunho já utilizada com outro conteúdo.');
return $existing;
}
$id = DB::table('portal_partnerships')->insertGetId(['user_id' => $actor->id, 'client_key' => $data['client_key'], 'title' => '', 'sector' => '', 'province' => '', 'offer' => '', 'seeking' => '', 'status' => 'draft', 'created_at' => now(), 'updated_at' => now()]);
$record = $this->find($id, true);
}
$origins = $data['origins'] ?? [];
foreach ($origins as $origin) {
app(PartnershipSources::class)->resolve($origin['type'], $origin['target_id'], $actor);
}
$locations = $data['locations'] ?? [];
foreach ($locations as $location) {
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $location['geo_location_id'])->exists(), 422, 'Localização não pertence ao cadastro territorial público.');
}
DB::table('portal_partnerships')->where('id', $id)->update(['title' => $data['title'] ?? '', 'offer' => $data['offer'] ?? '', 'seeking' => $data['seeking'] ?? '',
'organization_id' => $data['organization_id'] ?? null, 'sector_id' => $data['sector_id'] ?? null, 'kind' => $data['kind'], 'partnership_type' => $data['partnership_type'] ?? null,
'deadline' => $data['deadline'] ?? null, 'payload' => json_encode([...($data['payload'] ?? []), '_creation_hash' => json_decode($record->payload, true)['_creation_hash'] ?? $creationHash], JSON_THROW_ON_ERROR),
'status' => 'draft', 'version' => $record->version + 1, 'updated_at' => now()]);
DB::table('partnership_origins')->where('partnership_id', $id)->delete();
foreach ($origins as $origin) {
DB::table('partnership_origins')->insertOrIgnore(['partnership_id' => $id, 'type' => $origin['type'], 'target_id' => $origin['target_id']]);
}
DB::table('partnership_locations')->where('partnership_id', $id)->delete();
foreach ($locations as $location) {
DB::table('partnership_locations')->insertOrIgnore(['partnership_id' => $id, 'geo_location_id' => $location['geo_location_id'], 'role' => $location['role'], 'source_reference' => $location['source_reference']]);
}
$saved = $this->find($id);
$this->event($saved, $actor, 'partnership_opportunity.changed.v1', ['previous_status' => $record->status, 'origins' => $origins, 'locations' => $locations], 'Rascunho guardado', [$record->user_id]);
return $saved;
});
}
public function transition(User $actor, int $id, int $version, string $action, string $reason): stdClass
{
return DB::transaction(function () use ($actor, $id, $version, $action, $reason) {
$record = $this->find($id, true);
abort_unless((int) $record->version === $version, 409, 'Proposta alterada; recarregue.');
$moderation = in_array($action, ['publish', 'return', 'reject', 'suspend'], true);
if ($moderation) {
Gate::forUser($actor)->authorize('manage-portal');
abort_if($this->owns($actor, $record), 403, 'Não pode moderar a própria proposta.');
} else {
abort_unless($this->owns($actor, $record), 403);
}
$from = $record->status;
$allowed = ['submit' => ['draft', 'returned', 'rejected'], 'publish' => ['submitted', 'pending'], 'return' => ['submitted', 'pending'],
'reject' => ['submitted', 'pending'], 'suspend' => ['published'], 'archive' => ['draft', 'published', 'suspended', 'rejected'], 'renew' => ['published', 'suspended', 'archived']];
abort_unless(isset($allowed[$action]) && in_array($from, $allowed[$action], true), 409, 'Transição inválida.');
if ($action === 'submit') {
$payload = json_decode($record->payload, true);
Validator::make(['title' => $record->title, 'type' => $record->partnership_type, 'offer' => $record->offer, 'seeking' => $record->seeking, 'consent' => $payload['consent'] ?? false],
['title' => 'required', 'type' => 'required', 'offer' => 'required_without:seeking', 'seeking' => 'required_without:offer', 'consent' => 'accepted'])->validate();
}
$status = ['submit' => 'submitted', 'publish' => 'published', 'return' => 'returned', 'reject' => 'rejected', 'suspend' => 'suspended', 'archive' => 'archived', 'renew' => 'draft'][$action];
DB::table('portal_partnerships')->where('id', $id)->update(['status' => $status, 'version' => $version + 1, 'reviewed_by' => $moderation ? $actor->id : $record->reviewed_by,
'published_at' => $action === 'publish' ? now() : $record->published_at, 'updated_at' => now()]);
$saved = $this->find($id);
$this->event($saved, $actor, 'partnership_opportunity.'.$status.'.v1', ['from' => $from, 'to' => $status, 'reason' => $reason], 'Proposta: '.$status, [$record->user_id]);
return $saved;
});
}
/** @param array<string,mixed> $data */
public function interest(User $actor, int $id, array $data): stdClass
{
$data = Validator::make($data, ['version' => ['nullable', 'integer', 'min:1'], 'organization_id' => ['nullable', 'uuid'], 'proposal' => ['required', 'string', 'max:15000'],
'payload' => ['array:capacity,availability,contribution,conflicts,consent,sector_id,territory_id'], 'payload.consent' => ['accepted'],
'payload.capacity' => ['nullable', 'string', 'max:5000'], 'payload.availability' => ['nullable', 'string', 'max:1000'], 'payload.contribution' => ['nullable', 'string', 'max:5000'], 'payload.conflicts' => ['nullable', 'string', 'max:5000'],
'payload.sector_id' => ['nullable', 'integer', 'exists:sectors,id'], 'payload.territory_id' => ['nullable', 'uuid', 'exists:geo_locations,id']])->validate();
abort_if(($data['organization_id'] ?? null) && ! $this->represents($actor, $data['organization_id']), 403);
return DB::transaction(function () use ($actor, $id, $data) {
$record = $this->find($id, true);
abort_unless($record->status === 'published' && (! $record->deadline || $record->deadline >= today()->toDateString()), 409, 'Receção de interesses encerrada.');
abort_if((int) $record->user_id === $actor->id || $this->owns($actor, $record, false) || ($data['organization_id'] ?? null) && $data['organization_id'] === $record->organization_id, 403, 'Auto-candidatura não permitida.');
$existing = DB::table('partnership_interests')->where('partnership_id', $id)->where(fn ($q) => $q->where('user_id', $actor->id)
->when($data['organization_id'] ?? null, fn ($org) => $org->orWhere('organization_id', $data['organization_id'])))->orderBy('id')->lockForUpdate()->first();
if ($data['organization_id'] ?? null) {
abort_if(DB::table('partnership_interests')->where('partnership_id', $id)->where('organization_id', $data['organization_id'])->where('status', '!=', 'withdrawn')
->when($existing, fn ($q) => $q->where('id', '!=', $existing->id))->exists(), 409, 'A organização já tem uma candidatura ativa.');
}
if ($existing) {
abort_unless($this->owns($actor, $existing), 403);
abort_unless(isset($data['version']) && (int) $existing->version === (int) $data['version'], 409, 'Candidatura existente ou alterada; abra-a para atualizar.');
abort_unless(in_array($existing->status, ['submitted', 'clarification', 'withdrawn'], true), 409);
$interestId = $existing->id;
DB::table('partnership_interests')->where('id', $interestId)->update(['proposal' => $data['proposal'], 'payload' => json_encode($data['payload']), 'organization_id' => $data['organization_id'] ?? null,
'status' => 'submitted', 'assessment' => '{}', 'version' => $existing->version + 1, 'updated_at' => now()]);
} else {
$interestId = DB::table('partnership_interests')->insertGetId(['partnership_id' => $id, 'user_id' => $actor->id, 'organization_id' => $data['organization_id'] ?? null,
'proposal' => $data['proposal'], 'payload' => json_encode($data['payload']), 'created_at' => now(), 'updated_at' => now()]);
}
$this->event($record, $actor, 'partnership_interest.submitted.v1', ['interest_id' => $interestId, 'interest_version' => $existing ? $existing->version + 1 : 1], 'Manifestação de interesse recebida', [$record->user_id, $actor->id]);
return DB::table('partnership_interests')->where('id', $interestId)->first();
});
}
/** @param array<string,mixed> $assessment */
public function decideInterest(User $actor, int $id, int $version, string $action, string $reason, array $assessment = []): stdClass
{
return DB::transaction(function () use ($actor, $id, $version, $action, $reason, $assessment) {
$interest = DB::table('partnership_interests')->where('id', $id)->lockForUpdate()->first();
abort_unless($interest !== null, 404);
$record = $this->find($interest->partnership_id, true);
abort_unless((int) $interest->version === $version, 409, 'Candidatura alterada.');
if ($action === 'withdraw') {
abort_if($assessment !== [], 403, 'A avaliação fundamentada pertence ao responsável pela proposta.');
abort_unless($this->owns($actor, $interest), 403);
abort_unless(in_array($interest->status, ['submitted', 'clarification', 'shortlisted'], true), 409);
} else {
abort_unless($this->owns($actor, $record), 403);
abort_unless(in_array($interest->status, ['submitted', 'clarification', 'shortlisted'], true), 409);
}
$states = ['withdraw' => 'withdrawn', 'clarify' => 'clarification', 'shortlist' => 'shortlisted', 'reject' => 'rejected', 'connect' => 'negotiation', 'assess' => $interest->status];
abort_unless(isset($states[$action]), 422);
foreach ($assessment as $code => $criterion) {
abort_unless(array_key_exists($code, config('partnerships.criteria')) && is_array($criterion), 422);
Validator::make($criterion, ['state' => 'required|in:met,unmet,unknown', 'evidence' => 'required_unless:state,unknown|nullable|string|max:2000'])->validate();
$assessment[$code]['assessed_by'] = $actor->id;
$assessment[$code]['assessed_at'] = now()->toIso8601String();
}
$assessed = array_replace(json_decode($interest->assessment, true), $assessment);
if (in_array($action, ['shortlist', 'connect'], true)) {
$match = app(PartnershipMatching::class)->explain($record, $interest, $assessed);
abort_if($match['eligibility'] === 'unmet', 422, 'Existe requisito obrigatório comprovadamente incumprido.');
}
if ($action === 'connect') {
abort_unless($interest->status === 'shortlisted', 409, 'Selecione primeiro a candidatura para lista curta.');
DB::table('partnership_rooms')->insertOrIgnore(['interest_id' => $id, 'created_at' => now(), 'updated_at' => now()]);
}
DB::table('partnership_interests')->where('id', $id)->update(['status' => $states[$action], 'assessment' => json_encode($assessed), 'decision_reason' => $reason, 'version' => $version + 1, 'updated_at' => now()]);
$this->event($record, $actor, 'partnership_interest.changed.v1', ['interest_id' => $id, 'interest_version' => $version + 1, 'from' => $interest->status, 'to' => $states[$action], 'reason' => $reason, 'assessment' => $assessed], 'Candidatura: '.$states[$action], [$record->user_id, $interest->user_id]);
return DB::table('partnership_interests')->where('id', $id)->first();
});
}
/** @return array{room:stdClass,interest:stdClass,partnership:stdClass} */
public function room(User $actor, int $id, bool $write = false): array
{
$room = DB::table('partnership_rooms')->where('id', $id)->first();
abort_unless($room !== null, 404);
$interest = DB::table('partnership_interests')->where('id', $room->interest_id)->first();
$record = $this->find($interest->partnership_id);
abort_unless($this->owns($actor, $record, $write) || $this->owns($actor, $interest, $write), 403, 'Sala privada reservada aos participantes.');
abort_if($write && in_array($room->status, ['closed', 'cancelled'], true), 409, 'Sala encerrada.');
return ['room' => $room, 'interest' => $interest, 'partnership' => $record];
}
/** @param array<string,mixed> $payload
* @param list<int> $recipients
*/
public function event(stdClass $record, User $actor, string $type, array $payload, string $title, array $recipients = []): void
{
DB::transaction(function () use ($record, $actor, $type, $payload, $title, $recipients): void {
DB::select('select pg_advisory_xact_lock(hashtextextended(?,0))', ['partnership-events:'.$record->id]);
$sequence = (DB::table('partnership_events')->where('partnership_id', $record->id)->max('aggregate_version') ?? 0) + 1;
$eventId = (string) Str::uuid();
$envelope = ['event_id' => $eventId, 'event_type' => $type, 'event_version' => 1, 'source' => 'investmoz.partnerships', 'subject_id' => $record->id,
'occurred_at' => now()->toIso8601String(), 'producer_version' => '1.0', 'correlation_id' => $eventId, 'causation_id' => null, 'data_classification' => 'internal',
'aggregate_id' => $record->id, 'aggregate_version' => $sequence, 'publication_version' => $record->version, 'payload' => $payload, 'external_delivery' => 'not_configured'];
DB::table('partnership_events')->insert(['id' => $eventId, 'partnership_id' => $record->id, 'actor_id' => $actor->id, 'event_type' => $type, 'aggregate_version' => $sequence, 'payload' => json_encode($envelope)]);
DB::table('audit_events')->insert(['source_system' => 'partnership-exchange', 'entity_type' => 'portal_partnerships', 'actor_user_id' => $actor->id,
'action' => $type, 'after_data' => json_encode($envelope)]);
foreach (array_unique($recipients) as $recipient) {
DB::table('partnership_notifications')->insert(['event_id' => $eventId, 'user_id' => $recipient, 'title' => $title, 'href' => '/parcerias/'.$record->id]);
}
});
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class PartnershipInstallation
{
private const MIGRATION = '2026_10_07_160000_extend_internal_partnership_exchange';
public function fingerprint(): string
{
$files = [...(glob(app_path('Services/Partnership*.php')) ?: []), app_path('Http/Controllers/PartnershipExchangeController.php'), app_path('Http/Controllers/PartnershipInstallationController.php'),
app_path('Http/Middleware/PartnershipInstalled.php'), database_path('migrations/'.self::MIGRATION.'.php'), config_path('partnerships.php'), base_path('routes/partnerships.php'),
...(glob(resource_path('js/pages/partnerships/*.tsx')) ?: []), resource_path('js/components/partnership-source-links.tsx'), resource_path('js/components/partnership-search-results.tsx'), resource_path('js/components/simulation-form.tsx'),
app_path('Http/Controllers/PortalServicesController.php'), base_path('routes/web.php'), resource_path('js/pages/portfolio/show.tsx'), resource_path('js/pages/portfolio/shared.tsx'),
...array_map(fn ($name) => resource_path('js/pages/investment/'.$name.'.tsx'), ['business-opportunity', 'catalogue', 'detail', 'profile', 'zone'])];
sort($files);
$hashes = [];
foreach ($files as $file) {
$hashes[str_replace(base_path().DIRECTORY_SEPARATOR, '', $file)] = hash_file('sha256', $file);
}
return hash('sha256', json_encode($hashes, JSON_THROW_ON_ERROR));
}
/** @return array<string,mixed> */
public function preview(): array
{
$identity = DB::selectOne('select current_database() as database, inet_server_port() as port');
$rows = DB::table('portal_partnerships')->orderBy('id')->get(['id', 'user_id', 'title', 'sector', 'province', 'offer', 'seeking', 'status', 'reviewed_by', 'created_at', 'updated_at'])->all();
$hash = hash('sha256', json_encode(['target' => $identity, 'code' => $this->fingerprint(), 'records' => $rows], JSON_THROW_ON_ERROR));
$proof = $this->read('backup-proof.json');
$qa = $this->read('qa-evidence.json');
$verified = ($proof['restore_verified'] ?? false) && ($proof['target']['database'] ?? null) === $identity->database && (int) ($proof['target']['port'] ?? 0) === (int) $identity->port
&& is_file($proof['dump_path'] ?? '') && hash_file('sha256', $proof['dump_path']) === ($proof['sha256'] ?? null);
$qaVerified = ($qa['passed'] ?? false) && ($qa['code_hash'] ?? null) === $this->fingerprint() && str_ends_with($qa['database'] ?? '', '_test') && (int) ($qa['port'] ?? 0) === 55441;
return ['hash' => $hash, 'installed' => Schema::hasTable('partnership_interests'), 'target' => $identity, 'records' => $rows, 'records_hash' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR)), 'backupVerified' => $verified, 'qaVerified' => $qaVerified,
'backupDate' => $proof['verified_at'] ?? null, 'changes' => ['Extensão de portal_partnerships com campos opcionais e versão, sem substituir os registos.',
'Entidades próprias de candidaturas, salas, mensagens, referências documentais, marcos, eventos e notificações locais.',
'Nenhuma cópia de contas, organizações, documentos, setores, territórios ou oportunidades de investimento.', 'Estados e autores antigos preservados; publicação nova continua moderada.']];
}
/** @return array<string,mixed> */
private function read(string $file): array
{
$path = config('partnerships.proof_directory', storage_path('app/private/partnership-exchange')).'/'.$file;
if (! is_file($path)) {
return [];
}
$contents = file_get_contents($path);
abort_unless(is_string($contents), 503, 'Evidência privada indisponível.');
return json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
}
public function apply(string $hash, User $actor): void
{
DB::transaction(function () use ($hash, $actor) {
DB::statement('LOCK TABLE portal_partnerships IN ACCESS EXCLUSIVE MODE');
$preview = $this->preview();
abort_unless(hash_equals($preview['hash'], $hash), 409, 'Pré-visualização alterada; reveja a instalação.');
if ($preview['installed']) {
return;
}
abort_unless($preview['backupVerified'] && $preview['qaVerified'], 422, 'Backup/restauro e QA desta versão ainda não estão comprovados.');
config(['partnerships.installation_authorized' => true]);
try {
$migration = require database_path('migrations/'.self::MIGRATION.'.php');
$migration->up();
} finally {
config(['partnerships.installation_authorized' => false]);
}
$rows = DB::table('portal_partnerships')->orderBy('id')->get(['id', 'user_id', 'title', 'sector', 'province', 'offer', 'seeking', 'status', 'reviewed_by', 'created_at', 'updated_at'])->all();
abort_unless(hash_equals($preview['records_hash'], hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))), 409, 'Os registos antigos não foram preservados.');
DB::table('migrations')->insert(['migration' => self::MIGRATION, 'batch' => (DB::table('migrations')->max('batch') ?? 0) + 1]);
DB::table('audit_events')->insert(['source_system' => 'partnership-exchange', 'entity_type' => 'portal_partnerships', 'actor_user_id' => $actor->id,
'action' => 'partnership_module_installed', 'after_data' => json_encode(['preview_hash' => $hash, 'code_hash' => $this->fingerprint(), 'preserved_records' => count($rows), 'migration' => self::MIGRATION])]);
});
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Services;
use stdClass;
class PartnershipMatching
{
/** @param array<string,mixed>|null $assessment
* @return array<string,mixed>
*/
public function explain(stdClass $partnership, stdClass $interest, ?array $assessment = null): array
{
$assessment ??= json_decode($interest->assessment, true);
$payload = json_decode($partnership->payload, true);
$weights = config('partnerships.type_weights.'.$partnership->partnership_type, config('partnerships.weights'));
$criteria = [];
$known = $unknown = 0;
$mandatoryUnmet = $mandatoryUnknown = false;
foreach ($weights as $code => $weight) {
$entry = $assessment[$code] ?? [];
$state = $entry['state'] ?? 'unknown';
if (in_array($state, ['met', 'unmet'], true) && empty($entry['evidence'])) {
$state = 'unknown';
}
$mandatory = in_array($code, $payload['mandatory'] ?? [], true);
$known += $state === 'met' ? $weight : 0;
$unknown += $state === 'unknown' ? $weight : 0;
$mandatoryUnmet = $mandatoryUnmet || ($mandatory && $state === 'unmet');
$mandatoryUnknown = $mandatoryUnknown || ($mandatory && $state === 'unknown');
$criteria[] = ['code' => $code, 'label' => config('partnerships.criteria.'.$code), 'weight' => $weight, 'state' => $state,
'mandatory' => $mandatory, 'evidence' => $entry['evidence'] ?? null,
'explanation' => $state === 'unknown' ? 'Informação insuficiente; declarações sem avaliação documental não provam cumprimento ou incumprimento.' : 'Avaliação fundamentada do responsável; não equivale a certificação ou aprovação.'];
}
$total = array_sum($weights);
return ['algorithm_version' => 'transparent-rules.v1', 'weights_hash' => hash('sha256', json_encode($weights, JSON_THROW_ON_ERROR)), 'score_min' => $total ? round(100 * $known / $total, 1) : null,
'score_max' => $total ? round(100 * ($known + $unknown) / $total, 1) : null,
'eligibility' => $mandatoryUnmet ? 'unmet' : ($mandatoryUnknown ? 'unknown' : 'met'), 'criteria' => $criteria,
'unknown_weight' => $unknown, 'recommendation_is_approval' => false];
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Services;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\ExistingBusiness;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
class PartnershipSources
{
/** @return array<string,mixed> */
public function resolve(string $type, string $id, ?User $actor = null): array
{
$result = ['type' => $type, 'target_id' => $id, 'geography' => null, 'public' => true];
if (in_array($type, ['project', 'cluster', 'dossier', 'zone', 'business', 'company', 'simulation'], true)) {
abort_unless(Str::isUuid($id), 422, 'Identificador da origem inválido.');
}
if (in_array($type, ['project', 'cluster', 'dossier'], true)) {
$dossier = InvestmentPortfolioController::visible()->where($type === 'dossier' ? 'id' : $type.'_id', $id)->first();
abort_unless($dossier !== null, 404, 'Dossier público de origem não disponível.');
return [...$result, 'title' => $dossier->title, 'href' => '/carteira/'.$dossier->id, 'geography' => app(InvestmentRelations::class)->dossier($dossier)];
}
if ($type === 'investment') {
abort_unless(ctype_digit($id), 422);
$record = Opportunity::query()->published()->whereKey((int) $id)->first();
abort_unless($record !== null, 404);
return [...$result, 'title' => $record->title, 'href' => '/oportunidades/'.$record->slug];
}
if ($type === 'zone') {
$record = DB::table('investment_zones')->where('id', $id)->where('publication_status', 'published')->whereNull('deleted_at')->first();
abort_unless($record !== null, 404);
return [...$result, 'title' => $record->name, 'href' => '/zonas/'.$id];
}
if ($type === 'business') {
$record = ExistingBusiness::query()->published()->whereKey($id)->first();
abort_unless($record !== null, 404);
return [...$result, 'title' => $record->public_title, 'href' => '/negocios/'.$record->public_slug];
}
if ($type === 'company') {
abort_unless($actor !== null, 403);
$record = DB::table('investment_company_declarations')->where('id', $id)->where('user_id', $actor->id)->first();
abort_unless($record !== null, 404);
return [...$result, 'title' => 'Declaração empresarial existente', 'href' => '/investidor/profile', 'public' => false];
}
if ($type === 'simulation') {
abort_unless($actor !== null, 403);
$record = DB::table('simulation_form_drafts')->where('id', $id)->where('owner_user_id', $actor->id)->whereNull('deleted_at')->first();
abort_unless($record !== null, 404);
return [...$result, 'title' => 'Ficha de projeto do simulador', 'href' => '/simulador-fiscal?draft='.$id, 'public' => false];
}
abort(422, 'Tipo de origem não suportado.');
}
/** @return list<array<string,mixed>> */
public function forPartnership(int $id, ?User $actor = null): array
{
$result = [];
foreach (DB::table('partnership_origins')->where('partnership_id', $id)->get() as $origin) {
try {
$result[] = $this->resolve($origin->type, $origin->target_id, $actor);
} catch (HttpException $e) {
if (! in_array($e->getStatusCode(), [403, 404], true)) {
throw $e;
}
// Private or withdrawn source identifiers are not disclosed by a public proposal.
}
}
return $result;
}
}
+254
View File
@@ -0,0 +1,254 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class VirtualDesk
{
public function installed(): bool
{
return \Illuminate\Support\Facades\Schema::hasTable('desk_cases');
}
public function encode(array $data): string
{
return Crypt::encryptString(json_encode($data, JSON_THROW_ON_ERROR));
}
public function decode(?string $data): array
{
return $data ? json_decode(Crypt::decryptString($data), true, 512, JSON_THROW_ON_ERROR) : [];
}
public function represents(User $actor, string $organization, bool $write = true): bool
{
return DB::table('memberships')->where('user_id', $actor->id)->where('organization_id', $organization)->whereNull('deleted_at')
->when($write, fn ($q) => $q->whereIn('role', ['admin', 'manager', 'officer']))->exists();
}
public function owns(User $actor, object $case, bool $write = true): bool
{
return $case->organization_id ? $this->represents($actor, $case->organization_id, $write) : (int) $case->user_id === $actor->id;
}
public function case(User $actor, string $id, bool $write = false, bool $lock = false): object
{
$case = DB::table('desk_cases')->where('id', $id)->when($lock, fn ($q) => $q->lockForUpdate())->first();
abort_unless($case, 404);
abort_unless($this->owns($actor, $case, $write) || (! $write && ($actor->can('manage-portal') || DB::table('desk_requests')->where('case_id', $id)->where('analyst_id', $actor->id)->exists())), 403);
return $case;
}
public function request(User $actor, string $id, bool $ownerOnly = false, bool $lock = false): object
{
$request = DB::table('desk_requests')->where('id', $id)->when($lock, fn ($q) => $q->lockForUpdate())->first();
abort_unless($request, 404);
$case = $this->case($actor, $request->case_id, $ownerOnly);
abort_unless($this->owns($actor, $case, $ownerOnly) || (! $ownerOnly && ($actor->can('manage-portal') || (int) $request->analyst_id === $actor->id)), 403);
return $request;
}
public function createCase(User $actor, array $input): object
{
$data = Validator::make($input, ['title' => 'required|string|max:200', 'client_key' => 'required|uuid', 'reuse_consent' => 'accepted',
'organization_id' => 'nullable|uuid', 'company_id' => 'nullable|uuid', 'submission_id' => 'nullable|uuid', 'simulation_id' => 'nullable|uuid'])->validate();
return DB::transaction(function () use ($actor, $data) {
DB::table('users')->where('id', $actor->id)->lockForUpdate()->first();
$existing = DB::table('desk_cases')->where('user_id', $actor->id)->where('client_key', $data['client_key'])->first();
$inputHash = hash('sha256', json_encode(Arr::sortRecursive($data), JSON_THROW_ON_ERROR));
if ($existing) {
abort_unless(($this->decode($existing->payload)['_creation_hash'] ?? '') === $inputHash, 409, 'Chave de criação usada com outro conteúdo.');
abort_unless($this->owns($actor, $existing), 403);
return $existing;
}
abort_if(($data['organization_id'] ?? null) && ! $this->represents($actor, $data['organization_id']), 403);
$payload = ['profile' => app(InvestmentWorkspace::class)->account($actor->id)['payload'], 'name' => $actor->name, 'email' => $actor->email, '_creation_hash' => $inputHash, 'reuse_consent' => ['actor_id' => $actor->id, 'date' => now()->toIso8601String()]];
if ($data['company_id'] ?? null) {
$company = DB::table('investment_company_declarations')->where('id', $data['company_id'])->where('user_id', $actor->id)->first();
abort_unless($company, 404);
$payload['company'] = $this->decode($company->payload); $payload['company_version'] = $company->version;
}
if ($data['submission_id'] ?? null) {
$submission = \App\Models\InvestmentSubmission::where('id', $data['submission_id'])->where('user_id', $actor->id)->firstOrFail();
$payload['investment'] = $submission->payload; $payload['investment_version'] = $submission->version;
}
if ($data['simulation_id'] ?? null) app(PartnershipSources::class)->resolve('simulation', $data['simulation_id'], $actor);
// One case per explicitly reused investment; retries never create parallel dossiers.
if ($data['submission_id'] ?? null) {
$linked = DB::table('desk_cases')->where('submission_id', $data['submission_id'])->where('user_id', $actor->id)->first();
if ($linked) { abort_unless($this->owns($actor, $linked), 403); return $linked; }
}
$id = (string) Str::uuid();
DB::table('desk_cases')->insert(['id' => $id, 'user_id' => $actor->id, 'organization_id' => $data['organization_id'] ?? null, 'company_id' => $data['company_id'] ?? null,
'submission_id' => $data['submission_id'] ?? null, 'simulation_id' => $data['simulation_id'] ?? null, 'title' => $data['title'], 'client_key' => $data['client_key'],
'payload' => $this->encode($payload), 'workflow' => json_encode(array_map(fn ($s) => [...$s, 'status' => 'not_started', 'evidence' => null], config('virtual-desk.steps'))), 'created_at' => now(), 'updated_at' => now()]);
$case = DB::table('desk_cases')->where('id', $id)->first();
$this->event($case, $actor, 'case_created', ['reuse_consent' => true]);
return $case;
});
}
public function createRequest(User $actor, string $caseId, string $serviceId, string $clientKey): object
{
abort_unless(Str::isUuid($serviceId) && Str::isUuid($clientKey), 422);
return DB::transaction(function () use ($actor, $caseId, $serviceId, $clientKey) {
$case = $this->case($actor, $caseId, true, true);
abort_if($case->closed_at, 409, 'Dossier encerrado.');
$service = DB::table('desk_service_versions')->where('id', $serviceId)->where('status', 'published')->first();
abort_unless($service, 422, 'Versão do serviço indisponível para novos pedidos.');
$existing = DB::table('desk_requests')->where('case_id', $caseId)->where('client_key', $clientKey)->first();
if ($existing) { abort_unless($existing->service_version_id === $serviceId, 409); return $existing; }
$id = (string) Str::uuid(); $base = $this->decode($case->payload);
$payload = ['title' => $case->title, 'description' => $base['investment']['objective'] ?? '', 'regime' => 'unknown'];
DB::table('desk_requests')->insert(['id' => $id, 'case_id' => $caseId, 'service_version_id' => $serviceId, 'client_key' => $clientKey, 'payload' => $this->encode($payload), 'created_at' => now(), 'updated_at' => now()]);
$request = DB::table('desk_requests')->where('id', $id)->first(); $this->event($case, $actor, 'draft_created', [], $request);
return $request;
});
}
public function definition(object $request): array
{
return json_decode(DB::table('desk_service_versions')->where('id', $request->service_version_id)->value('definition'), true, 512, JSON_THROW_ON_ERROR);
}
public function validateFields(array $payload, array $definition, bool $submitting): array
{
$rules = ['payload' => ['required', 'array:'.implode(',', array_keys($definition['fields']))]];
foreach ($definition['fields'] as $key => $field) {
$active = ! isset($field['when']) || ($payload[$field['when']['field']] ?? null) === $field['when']['equals'];
$required = $submitting && ($field['required'] ?? false) && $active;
$rule = [$required ? 'required' : 'nullable'];
$rule = [...$rule, ...match ($field['type']) {
'number' => ['numeric', 'min:'.($field['min'] ?? 0), 'max:999999999999'], 'date' => ['date_format:Y-m-d'],
'select' => [\Illuminate\Validation\Rule::in(array_keys($field['options']))], 'territory' => ['uuid'],
default => ['string', 'max:'.($field['type'] === 'textarea' ? 15000 : 1000)],
}];
$rules['payload.'.$key] = $rule;
}
$validated = Validator::make(['payload' => $payload], $rules)->validate()['payload'];
if ($validated['territory_id'] ?? null) {
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $validated['territory_id'])->exists(), 422, 'Localização indisponível.');
if ($submitting && trim($validated['location_source'] ?? '') === '') throw ValidationException::withMessages(['payload.location_source' => 'Indique a fonte da localização.']);
}
return $validated;
}
public function findings(array $payload): array
{
$findings = [];
if (isset($payload['investment_amount'], $payload['own_finance'], $payload['other_finance']) && abs((float) $payload['investment_amount'] - (float) $payload['own_finance'] - (float) $payload['other_finance']) > 0.01) {
$findings[] = ['code' => 'finance_difference', 'severity' => 'error', 'field' => 'investment_amount', 'explanation' => 'A soma do financiamento difere do valor do investimento.', 'recommendation' => 'Confirme valores e moeda.', 'method' => 'deterministic', 'confidence' => null];
}
if (! ($payload['territory_id'] ?? null)) $findings[] = ['code' => 'location_unknown', 'severity' => 'warning', 'field' => 'territory_id', 'explanation' => 'Localização ainda não documentada.', 'recommendation' => 'Complete quando houver fonte.', 'method' => 'deterministic', 'confidence' => null];
$findings[] = ['code' => 'official_form_pending', 'severity' => 'warning', 'field' => null, 'explanation' => 'Adaptação digital do plano; não foi identificada uma versão oficial homologada do formulário APIEX no acervo.', 'recommendation' => 'A preparação e análise interna continuam disponíveis; confirme a versão exigida pela entidade para o ato oficial.', 'method' => 'documentary', 'confidence' => null];
return $findings;
}
public function save(User $actor, string $id, array $input, bool $submit = false): object
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'payload' => 'required|array', 'consent' => $submit ? 'accepted' : 'nullable|boolean', 'reason' => 'nullable|string|max:3000'])->validate();
return DB::transaction(function () use ($actor, $id, $data, $submit) {
$request = $this->request($actor, $id, true, true);
if ($submit && $request->status === 'submitted' && $request->version === (int) $data['version'] + 1 && hash_equals(hash('sha256', json_encode(Arr::sortRecursive($this->decode($request->payload)))), hash('sha256', json_encode(Arr::sortRecursive($data['payload']))))) return $request;
abort_unless(in_array($request->status, ['draft', 'returned'], true) && $request->version === (int) $data['version'], 409, 'Pedido alterado ou já submetido.');
$payload = $this->validateFields($data['payload'], $this->definition($request), $submit);
if ($request->status === 'returned') {
$editable = json_decode($request->editable_fields ?? '[]', true); $previous = $this->decode($request->payload);
foreach (array_unique([...array_keys($previous), ...array_keys($payload)]) as $key) {
if (! in_array($key, $editable, true) && ($previous[$key] ?? null) !== ($payload[$key] ?? null)) throw ValidationException::withMessages(['payload.'.$key => 'Campo não autorizado para esta correção.']);
}
abort_if($submit && trim($data['reason'] ?? '') === '', 422, 'Justifique a correção.');
}
$findings = $this->findings($payload);
if ($submit && array_filter($findings, fn ($f) => $f['severity'] === 'error')) throw ValidationException::withMessages(['payload.investment_amount' => $findings[0]['explanation']]);
$case = $this->case($actor, $request->case_id, true);
$snapshot = ['payload' => $payload, 'service_version_id' => $request->service_version_id, 'documents' => DB::table('desk_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('link.case_id', $case->id)->where(fn ($q) => $q->whereNull('link.request_id')->orWhere('link.request_id', $id))->get(['link.document_id', 'd.sha256', 'd.version_no', 'link.source_reference'])->all(), 'findings' => $findings, 'consent' => $submit, 'source' => config('virtual-desk.source')];
DB::table('desk_revisions')->insert(['request_id' => $id, 'version' => $request->version, 'snapshot' => $this->encode(['payload' => $this->decode($request->payload), 'status' => $request->status, 'submitted_snapshot' => $request->submitted_snapshot ? $this->decode($request->submitted_snapshot) : null])]);
$updates = ['payload' => $this->encode($payload), 'version' => $request->version + 1, 'updated_at' => now()];
if ($submit) $updates = [...$updates, 'status' => 'submitted', 'protocol' => $request->protocol ?? 'BV-'.date('Y').'-'.strtoupper(str_replace('-', '', $id)), 'submitted_at' => now(), 'submitted_snapshot' => $this->encode($snapshot)];
DB::table('desk_requests')->where('id', $id)->update($updates); $request = DB::table('desk_requests')->where('id', $id)->first();
$this->event($case, $actor, $submit ? 'submitted' : 'draft_saved', ['reason' => $data['reason'] ?? '', 'findings' => $findings], $request);
return $request;
});
}
public function transition(User $actor, string $id, array $data): object
{
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'status' => ['required', \Illuminate\Validation\Rule::in(array_keys(config('virtual-desk.request_states')))], 'reason' => 'required|string|min:3|max:5000', 'editable_fields' => 'nullable|array', 'editable_fields.*' => 'string|max:100'])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$request = $this->request($actor, $id, false, true); $case = $this->case($actor, $request->case_id);
abort_unless($request->version === (int) $data['version'], 409);
$cancel = $data['status'] === 'cancelled';
if ($cancel) { abort_unless($this->owns($actor, $case) && in_array($request->status, ['draft', 'returned'], true), 403); }
else {
abort_if($this->owns($actor, $case, false), 403, 'O proponente não pode analisar ou decidir o seu próprio pedido.');
abort_unless($actor->can('manage-portal') || (int) $request->analyst_id === $actor->id, 403);
if (in_array($data['status'], ['accepted', 'rejected', 'closed'], true)) abort_unless($actor->can('manage-portal'), 403);
abort_unless(in_array($data['status'], config('virtual-desk.transitions.'.$request->status, []), true), 409, 'Transição inválida.');
}
$editable = $data['editable_fields'] ?? [];
abort_if($data['status'] === 'returned' && ! $editable, 422, 'Indique os campos autorizados para correção.');
abort_if(array_diff($editable, array_keys($this->definition($request)['fields'])), 422);
DB::table('desk_requests')->where('id', $id)->update(['status' => $data['status'], 'version' => $request->version + 1, 'editable_fields' => json_encode($editable), 'closed_at' => in_array($data['status'], ['closed', 'cancelled'], true) ? now() : null, 'updated_at' => now()]);
$request = DB::table('desk_requests')->where('id', $id)->first(); $this->event($case, $actor, 'request_'.$data['status'], ['reason' => $data['reason'], 'editable_fields' => $editable], $request);
return $request;
});
}
public function stage(User $actor, string $id, array $data): object
{
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'stage' => ['required', \Illuminate\Validation\Rule::in(array_keys(config('virtual-desk.steps')))],
'status' => ['required', \Illuminate\Validation\Rule::in(array_keys(config('virtual-desk.step_states')))], 'reason' => 'required|string|min:3|max:3000',
'evidence' => 'nullable|string|max:5000', 'document_id' => 'nullable|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'exception' => 'nullable|boolean'])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$case = $this->case($actor, $id, false, true);
abort_unless($this->owns($actor, $case) || $actor->can('manage-portal'), 403);
abort_unless((int) $case->version === (int) $data['version'], 409);
$workflow = json_decode($case->workflow, true, 512, JSON_THROW_ON_ERROR); $current = $workflow[$data['stage']];
$decision = in_array($data['status'], ['completed', 'not_applicable'], true);
if ($decision) {
abort_unless($actor->can('manage-portal') && ! $this->owns($actor, $case, false), 403, 'Conclusão documental exige revisão interna por outra pessoa autorizada.');
abort_unless(trim($data['evidence'] ?? '') !== '', 422, 'Identifique a evidência documental.');
foreach ($current['dependencies'] as $dependency) {
abort_unless(in_array($workflow[$dependency]['status'], ['completed', 'not_applicable'], true) || (($data['exception'] ?? false) && ($data['document_id'] ?? null)), 422, 'Dependência '.$dependency.' pendente; uma exceção exige evidência própria.');
}
if ($data['stage'] !== 'E0') abort_unless($data['document_id'] ?? null, 422, 'Ligue o documento de suporte ou de não aplicabilidade.');
}
if ($data['document_id'] ?? null) {
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('d.id', $data['document_id'])->whereNull('d.deleted_at')->first(['d.status', 'd.malware_scan_status', 'd.sha256', 'd.malware_scanned_sha256', 'l.valid_until']);
abort_unless($document, 422);
if ($decision) abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean' && trim($document->sha256) === $document->malware_scanned_sha256 && (! $document->valid_until || $document->valid_until >= now()->toDateString()), 422, 'Documento ainda não consultável ou expirado.');
}
if (in_array($data['status'], ['referred', 'waiting'], true)) abort_unless(trim($data['evidence'] ?? '') !== '', 422, 'Registe referência e canal do encaminhamento.');
// Reopening an upstream step must never leave dependent conclusions falsely valid.
if (! in_array($data['status'], ['completed', 'not_applicable'], true)) {
$affected = [$data['stage']];
do { $changed = false; foreach ($workflow as $code => &$step) { if (! in_array($code, $affected, true) && array_intersect($step['dependencies'], $affected)) { $affected[] = $code; $changed = true; if ($step['status'] === 'completed') $step['status'] = 'pending'; } } unset($step); } while ($changed);
}
$workflow[$data['stage']] = [...$current, 'status' => $data['status'], 'evidence' => $data['evidence'] ?? null, 'document_id' => $data['document_id'] ?? null,
'valid_until' => $data['valid_until'] ?? null, 'reason' => $data['reason'], 'reviewed_by' => $actor->id, 'updated_at' => now()->toIso8601String()];
DB::table('desk_cases')->where('id', $id)->update(['workflow' => json_encode($workflow), 'version' => $case->version + 1, 'updated_at' => now()]);
$case = DB::table('desk_cases')->where('id', $id)->first(); $this->event($case, $actor, 'stage_updated', $data);
return $case;
});
}
public function event(object $case, User $actor, string $action, array $payload, ?object $request = null): void
{
$id = (string) Str::uuid(); $version = $request->version ?? $case->version;
DB::table('desk_events')->insert(['id' => $id, 'case_id' => $case->id, 'request_id' => $request->id ?? null, 'actor_id' => $actor->id, 'action' => $action, 'version' => $version, 'payload' => $this->encode($payload)]);
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => $request ? 'desk_requests' : 'desk_cases', 'entity_id' => $request->id ?? $case->id, 'actor_user_id' => $actor->id, 'action' => $action,
'after_data' => json_encode(['event_id' => $id, 'event_version' => 1, 'version' => $version, 'case_id' => $case->id, 'source_hash' => config('virtual-desk.source.sha256')])]);
$recipients = [(int) $case->user_id];
if ($case->organization_id) $recipients = [...$recipients, ...DB::table('memberships')->where('organization_id', $case->organization_id)->whereNull('deleted_at')->pluck('user_id')->all()];
if ($request?->analyst_id) $recipients[] = (int) $request->analyst_id;
foreach (array_unique($recipients) as $user) DB::table('desk_notifications')->insert(['event_id' => $id, 'user_id' => $user, 'title' => config('virtual-desk.request_states.'.$request?->status, 'Dossier atualizado'), 'href' => $request ? '/balcao-virtual/pedidos/'.$request->id : '/balcao-virtual/dossiers/'.$case->id]);
}
}