Fundos: a necessidade do processo orienta as categorias e os critérios incompatíveis ficam indisponíveis

Mapa de erros 4.2. A «Necessidade do processo» passa a ter ajuda própria e
a ligar-se ao resto da pesquisa: as categorias de instituição sem produtos
publicados para a necessidade escolhida ficam indisponíveis, com a razão
indicada (por exemplo, com «Seguros» só as seguradoras; os bancos não
aparecem como seguradoras). A correspondência vem dos próprios registos
publicados, não de uma lista fixa.

Com «Fundo», «Programa» ou «Incentivo» como tipo de registo, a categoria,
o tipo de instituição e a presença física deixam de poder ser escolhidos
(aplicam-se só a instituições); critérios já escolhidos continuam a ter a
opção existente de os retirar. O botão «Pesquisar» continua a exigir
localização e necessidade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
Claude
2026-12-05 06:34:11 +02:00
committed by nala
parent 9570d6232f
commit b29f500a09
4 changed files with 121 additions and 16 deletions
@@ -18,9 +18,11 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
@@ -172,10 +174,12 @@ final class FundingProgrammeController extends Controller
$territorySelection = ! empty($filters['territory']) ? $geography->path($filters['territory']) : [];
$query = $service->catalogueQuery($filters);
$items = $query->orderByDesc('v.published_at')->orderBy('p.id')->paginate(20, ['p.id', 'p.code', 'v.id as version_id', 'v.version', 'v.payload', 'v.published_at'])->withQueryString();
} catch (\Illuminate\Validation\ValidationException $error) {
if ($request->expectsJson()) throw $error;
} catch (ValidationException $error) {
if ($request->expectsJson()) {
throw $error;
}
$criteriaErrors = $error->errors();
$items = new \Illuminate\Pagination\LengthAwarePaginator([], 0, 20, 1, ['path' => '/fundos', 'query' => $request->query()]);
$items = new LengthAwarePaginator([], 0, 20, 1, ['path' => '/fundos', 'query' => $request->query()]);
}
$items->through(function ($row) use ($service, $filters) {
$record = $service->present($row);
@@ -183,7 +187,7 @@ final class FundingProgrammeController extends Controller
return [...$record, 'filter_explanation' => $service->filterExplanation($record, $filters)];
});
return tap(Inertia::render('funding/index', ['criteriaErrors' => $criteriaErrors, 'territorySelection' => $territorySelection, 'categoryTypes' => FundingInstitutionClassification::CATEGORY_TYPES, 'items' => $items, 'filters' => $filters, 'categories' => FundingInstitutionClassification::CATEGORIES, 'institutionTypes' => FundingInstitutionClassification::TYPES, 'kinds' => FundingProgrammes::KINDS, 'needs' => FundingInstitutionDetails::NEEDS, 'dossier' => $dossier,
return tap(Inertia::render('funding/index', ['needCategories' => $service->needCategories(), 'criteriaErrors' => $criteriaErrors, 'territorySelection' => $territorySelection, 'categoryTypes' => FundingInstitutionClassification::CATEGORY_TYPES, 'items' => $items, 'filters' => $filters, 'categories' => FundingInstitutionClassification::CATEGORIES, 'institutionTypes' => FundingInstitutionClassification::TYPES, 'kinds' => FundingProgrammes::KINDS, 'needs' => FundingInstitutionDetails::NEEDS, 'dossier' => $dossier,
'options' => ['territories' => $territorySelection,
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name'])], 'management' => $service->access($request->user())])
->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
+52 -9
View File
@@ -59,6 +59,30 @@ final class FundingProgrammes
->where('v.published_at', '<=', now());
}
/**
* Institution categories that have at least one published product for each process need, from the records
* themselves: the search can then offer only categories that answer the chosen need (mapa de erros, 4.2).
*
* @return array<string, list<string>>
*/
public function needCategories(): array
{
$map = [];
foreach ($this->publicQuery()->get(['v.payload']) as $row) {
$payload = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
$categories = $payload['institution_categories'] ?? [];
foreach ($payload['products'] ?? [] as $product) {
foreach ($product['needs'] ?? [] as $need) {
foreach ($categories as $category) {
$map[$need][$category] = true;
}
}
}
}
return array_map(fn (array $categories) => array_keys($categories), $map);
}
public function readableVersions(): Builder
{
return DB::table('funding_programme_versions')->where('published_at', '<=', now())
@@ -112,7 +136,7 @@ final class FundingProgrammes
}
/** Window dates and geographical scope concern the same documented window.
* @param array<string,mixed> $filters
* @param array<string,mixed> $filters
* @return array{literal-string,list<mixed>}
*/
private function windowFilter(array $filters): array
@@ -120,24 +144,43 @@ final class FundingProgrammes
$today = today()->toDateString();
$state = $filters['state'];
$bindings = [];
if ($state === 'unknown') $sql = "w->>'mode' = 'unknown'";
elseif ($state === 'closed') { $sql = "(w->>'mode' = 'closed' OR (w->>'mode' = 'dated' AND w->>'end_on' < ?))"; $bindings = [$today]; }
elseif ($state === 'upcoming') { $sql = "w->>'mode' = 'dated' AND w->>'start_on' > ?"; $bindings = [$today]; }
else { $sql = "w->>'mode' IN ('dated','rolling') AND COALESCE(NULLIF(w->>'start_on',''),?) <= ? AND COALESCE(NULLIF(w->>'end_on',''),?) >= ?"; $bindings = [$today, $today, $today, $today]; }
if ($state === 'unknown') {
$sql = "w->>'mode' = 'unknown'";
} elseif ($state === 'closed') {
$sql = "(w->>'mode' = 'closed' OR (w->>'mode' = 'dated' AND w->>'end_on' < ?))";
$bindings = [$today];
} elseif ($state === 'upcoming') {
$sql = "w->>'mode' = 'dated' AND w->>'start_on' > ?";
$bindings = [$today];
} else {
$sql = "w->>'mode' IN ('dated','rolling') AND COALESCE(NULLIF(w->>'start_on',''),?) <= ? AND COALESCE(NULLIF(w->>'end_on',''),?) >= ?";
$bindings = [$today, $today, $today, $today];
}
if (! empty($filters['territory']) && ($filters['location_mode'] ?? '') !== 'physical') {
$path = array_column(app(InvestmentGeography::class)->path($filters['territory']), 'id');
$window = ["EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(w->'territory_paths','[]'::jsonb)) t WHERE t @> ?::jsonb)"];
$scopeBindings = [json_encode([['id' => $filters['territory']]], JSON_THROW_ON_ERROR)];
foreach ($path as $id) { $window[] = "w->'territory_ids' @> ?::jsonb"; $scopeBindings[] = json_encode([$id], JSON_THROW_ON_ERROR); }
foreach ($path as $id) {
$window[] = "w->'territory_ids' @> ?::jsonb";
$scopeBindings[] = json_encode([$id], JSON_THROW_ON_ERROR);
}
$parent = ["v.payload->>'coverage'='national'", "v.payload->'territory_ancestor_ids' @> ?::jsonb"];
$scopeBindings[] = json_encode([$filters['territory']], JSON_THROW_ON_ERROR);
foreach ($path as $id) { $parent[] = "v.payload->'territory_ids' @> ?::jsonb"; $scopeBindings[] = json_encode([$id], JSON_THROW_ON_ERROR); }
if (($filters['certainty'] ?? 'include_unknown') === 'include_unknown') $parent[] = "v.payload->>'coverage'='unknown'";
foreach ($path as $id) {
$parent[] = "v.payload->'territory_ids' @> ?::jsonb";
$scopeBindings[] = json_encode([$id], JSON_THROW_ON_ERROR);
}
if (($filters['certainty'] ?? 'include_unknown') === 'include_unknown') {
$parent[] = "v.payload->>'coverage'='unknown'";
}
$scope = "(w->>'coverage'='national' OR (w->>'coverage'='territorial' AND (".implode(' OR ', $window).")) OR (w->>'coverage'='programme' AND (".implode(' OR ', $parent).')))';
if (($filters['certainty'] ?? 'include_unknown') === 'include_unknown') $scope = '('.$scope." OR w->>'coverage'='unknown')";
if (($filters['certainty'] ?? 'include_unknown') === 'include_unknown') {
$scope = '('.$scope." OR w->>'coverage'='unknown')";
}
$sql = '('.$sql.') AND '.$scope;
$bindings = [...$bindings, ...$scopeBindings];
}
return [$sql, $bindings];
}