diff --git a/app/Http/Controllers/FundingProgrammeController.php b/app/Http/Controllers/FundingProgrammeController.php index 292ec2ce..fdfc5614 100644 --- a/app/Http/Controllers/FundingProgrammeController.php +++ b/app/Http/Controllers/FundingProgrammeController.php @@ -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')); diff --git a/app/Services/FundingProgrammes.php b/app/Services/FundingProgrammes.php index 3ce6a51d..86dd4904 100644 --- a/app/Services/FundingProgrammes.php +++ b/app/Services/FundingProgrammes.php @@ -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> + */ + 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 $filters + * @param array $filters * @return array{literal-string,list} */ 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]; } diff --git a/resources/js/pages/funding/index.tsx b/resources/js/pages/funding/index.tsx index c45239c6..65581019 100644 --- a/resources/js/pages/funding/index.tsx +++ b/resources/js/pages/funding/index.tsx @@ -26,6 +26,7 @@ function Index({ options, needs = {}, categoryTypes = {}, + needCategories = {}, territorySelection = [], criteriaErrors = {}, }: { @@ -60,6 +61,8 @@ function Index({ needs?: Record; management: boolean; categoryTypes?: Record; + /** Categories with at least one published product for each need. */ + needCategories?: Record; territorySelection?: TerritoryOption[]; criteriaErrors?: Record; }) { @@ -100,6 +103,13 @@ function Index({ ? ['Seleccione a província ou outra localização de interesse.'] : []), ]; + // Institution criteria only describe institutions, never a fund, programme or incentive. + const institutionCriteria = + !form.data.kind || form.data.kind === 'institution'; + const categoryAnswersNeed = (category: string) => + !form.data.need || + category === 'other' || + (needCategories[form.data.need] ?? []).includes(category); const typeAllowed = (category: string, type: string) => !category || category === 'other' || @@ -206,6 +216,7 @@ function Index({ + {!institutionCriteria && ( + + Aplica-se só a instituições. + + )}