*/ public function context(string $id, bool $management = false): array { $geography = app(InvestmentGeography::class); abort_unless($geography->references($management)->where('id', $id)->exists(), 404); $path = $geography->path($id, $management); $ids = array_map(fn ($node) => $node->id, $path); $approved = app(ApprovedAdministrativeBoundaries::class); $rows = DB::table('geo_geometries as g')->join('geo_locations as l', 'l.id', '=', 'g.geo_location_id') ->whereIn('g.geo_location_id', $ids)->whereNull('g.deleted_at')->whereNull('l.deleted_at') ->where(function ($query) use ($management, $approved) { $query->where('g.data_classification', 'public'); $query->orWhere(function ($internal) use ($management, $approved) { $internal->where('g.data_classification', 'internal'); if (! $management) { $internal->whereIn('g.id', array_keys($approved->snapshots())); } }); }) ->whereRaw("g.properties->>'purpose' = 'administrative_boundary'") ->whereIn('g.geometry_type', ['polygon', 'multipolygon']) ->whereRaw('ST_IsValid(g.geom) AND NOT ST_IsEmpty(g.geom) AND ST_SRID(g.geom)=4326') ->orderBy('g.geo_location_id')->orderBy('g.id')->limit(101) ->get(['g.id', 'g.geo_location_id', 'l.name', 'l.location_type', 'g.properties', 'g.data_classification', DB::raw('ST_AsGeoJSON(ST_SimplifyPreserveTopology(g.geom,0.0001),6) as geometry'), DB::raw("encode(sha256(ST_AsEWKB(g.geom)),'hex') as geometry_sha256"), DB::raw("encode(sha256(convert_to(g.properties::text,'UTF8')),'hex') as properties_sha256")]); if (! $management) { $rows = $rows->filter(fn ($row) => $row->data_classification === 'public' || $approved->allows($row->id, $row->geo_location_id, $row->geometry_sha256, $row->properties_sha256))->values(); } $areas = $rows->take(100)->map(function ($row) use ($id, $management) { $source = json_decode($row->properties, true, 512, JSON_THROW_ON_ERROR); return ['id' => $row->id, 'territory_id' => $row->geo_location_id, 'location_type' => $row->location_type, 'selected_territory' => $row->geo_location_id === $id, 'geometry' => json_decode($row->geometry, true, 512, JSON_THROW_ON_ERROR), 'title' => 'Limite administrativo: '.$row->name, 'purpose' => 'administrative_boundary', 'source_reference' => $source['authority'] ?? null, 'source_date' => $source['source_version'] ?? null, 'source_url' => $source['source_url'] ?? null, 'source_sha256' => $source['source_sha256'] ?? null, 'data_classification' => $management ? $row->data_classification : 'public', 'legal_currentness' => $source['legal_currentness'] ?? 'not_determined', 'url' => '']; })->all(); return ['territory_id' => $id, 'territory_registered' => true, 'selected_geometry_available' => $rows->contains('geo_location_id', $id), 'context_geometry_count' => count($areas), 'areas' => $areas, 'truncated' => $rows->count() > 100, 'investment_site' => false]; } }