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];
}
+48 -3
View File
@@ -26,6 +26,7 @@ function Index({
options,
needs = {},
categoryTypes = {},
needCategories = {},
territorySelection = [],
criteriaErrors = {},
}: {
@@ -60,6 +61,8 @@ function Index({
needs?: Record<string, string>;
management: boolean;
categoryTypes?: Record<string, string[]>;
/** Categories with at least one published product for each need. */
needCategories?: Record<string, string[]>;
territorySelection?: TerritoryOption[];
criteriaErrors?: Record<string, string[]>;
}) {
@@ -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({
<select
className="block rounded border p-2"
value={form.data.category}
disabled={!institutionCriteria && !form.data.category}
onChange={(e) => {
const category = e.target.value;
const valid = typeAllowed(
@@ -228,18 +239,35 @@ function Index({
<option value="">Todas</option>
{Object.entries(financialCategories).map(
([id, label]) => (
<option key={id} value={id}>
{label}
<option
key={id}
value={id}
disabled={
!categoryAnswersNeed(id) &&
id !== form.data.category
}
>
{categoryAnswersNeed(id)
? label
: `${label} — sem registos para esta necessidade`}
</option>
),
)}
</select>
{!institutionCriteria && (
<span className="block text-sm">
Aplica-se só a instituições.
</span>
)}
</label>
<label>
Tipo de instituição
<select
className="block rounded border p-2"
value={form.data.institution_type}
disabled={
!institutionCriteria && !form.data.institution_type
}
onChange={(e) =>
form.setData('institution_type', e.target.value)
}
@@ -296,6 +324,14 @@ function Index({
</option>
))}
</select>
<span className="block max-w-md text-sm">
A necessidade orienta toda a pesquisa: só aparecem os
registos com produtos ou serviços documentados para ela
(por exemplo, «Seguros» mostra seguradoras e «Fundo de
maneio» crédito para a actividade corrente). As
categorias de instituição sem registos para a
necessidade escolhida ficam indisponíveis.
</span>
</label>
<label>
Palavras-chave (opcional)
@@ -367,8 +403,17 @@ function Index({
})
}
>
<option value="physical">
<option
value="physical"
disabled={
!institutionCriteria &&
form.data.location_mode !== 'physical'
}
>
Sede, balcão ou presença física
{institutionCriteria
? ''
: ' (só instituições)'}
</option>
<option value="coverage">
Cobertura do financiamento/produto
@@ -83,6 +83,19 @@ final class FundingCriteriaCoherenceTest extends TestCase
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$this->geo['province'])->assertOk()->assertJsonCount(1, 'data');
}
public function test_the_process_need_tells_which_institution_categories_answer_it_from_the_published_products(): void
{
// Mapa de erros 4.2: the need is tied to the rest of the search; banks are not insurers.
$this->publish('qa-bank-need');
$this->publish('qa-insurer-need', overrides: ['institution_categories' => ['insurance'], 'institution_types' => ['insurer'],
'products' => [['code' => 'cover', 'title' => 'Synthetic insurance product', 'needs' => ['insurance'], 'coverage' => 'national', 'availability' => 'documented',
'source_url' => 'https://example.invalid/synthetic-qa', 'source_reference' => 'SYNTHETIC QA ONLY', 'checked_on' => today()->toDateString()]]]);
$map = app(FundingProgrammes::class)->needCategories();
$this->assertSame(['banking'], $map['investment']);
$this->assertSame(['insurance'], $map['insurance']);
$this->get('/fundos')->assertOk()->assertInertia(fn ($page) => $page->where('needCategories.insurance', ['insurance'])->where('needCategories.investment', ['banking']));
}
public function test_physical_search_defaults_to_documented_presence_but_preserves_explicit_unknown_choice(): void
{
$local = $this->publish('qa-local');