Files
Investidor-V2/resources/js/pages/funding/index.tsx
T
2026-11-15 18:56:39 +02:00

497 lines
21 KiB
TypeScript

import {
InstitutionView,
type InstitutionDetails,
} from '@/components/funding-institution';
import {
financialCategories,
financialTypes,
} from '@/components/funding-classification';
import { Link, useForm } from '@inertiajs/react';
import { Frame, card, button } from '@/pages/investment/shared';
import { type Programme, windowLabels } from './shared';
import { useRef, useState } from 'react';
import {
TerritoryFields,
type TerritoryOption,
} from '@/components/investment-territory';
export default function FundingIndex(props: Parameters<typeof Index>[0]) {
return <Index key={JSON.stringify(props.filters)} {...props} />;
}
function Index({
items,
filters,
kinds,
management,
options,
needs = {},
categoryTypes = {},
territorySelection = [],
criteriaErrors = {},
}: {
items: {
data: Programme[];
links: { url: string | null; label: string; active: boolean }[];
};
filters: {
q?: string;
kind?: string;
sector?: string;
territory?: string;
certainty?: string;
state?: string;
need?: string;
context?: string;
opportunity?: string;
category?: string;
institution_type?: string;
location_mode?: string;
include_historical?: string;
province_id?: string;
district_id?: string;
admin_post_id?: string;
locality_id?: string;
};
options: {
sectors: { id: number; name: string }[];
territories: { id: string; name: string }[];
};
kinds: Record<string, string>;
needs?: Record<string, string>;
management: boolean;
categoryTypes?: Record<string, string[]>;
territorySelection?: TerritoryOption[];
criteriaErrors?: Record<string, string[]>;
}) {
const [notice, setNotice] = useState('');
const form = useForm({
category: filters.category ?? '',
institution_type: filters.institution_type ?? '',
location_mode: filters.location_mode ?? 'coverage',
include_historical: filters.include_historical ?? '0',
context: filters.context ?? '',
opportunity: filters.opportunity ?? '',
need: filters.need ?? '',
q: filters.q ?? '',
kind: filters.kind ?? '',
sector: filters.sector ?? '',
territory: filters.territory ?? '',
province_id: filters.province_id ?? '',
district_id: filters.district_id ?? '',
admin_post_id: filters.admin_post_id ?? '',
locality_id: filters.locality_id ?? '',
certainty: filters.certainty ?? 'include_unknown',
state: filters.state ?? '',
});
const applied = useRef(JSON.stringify(form.data));
const criteriaChanged = JSON.stringify(form.data) !== applied.current;
const typeAllowed = (category: string, type: string) =>
!category ||
category === 'other' ||
!type ||
type === 'other' ||
(categoryTypes[category] ?? []).includes(type);
return (
<Frame title="Instituições financeiras, fundos e programas de apoio">
{management && (
<Link className={button} href="/management/fundos">
Gerir fundos e programas
</Link>
)}
<Link className="underline" href="/fundos/guardados">
A minha selecção
</Link>
<p>
Encontre bancos, seguradoras, fundos e outros parceiros
financeiros. Explore as soluções e os contactos adequados ao seu
investimento.
</p>
<form
className={`${card} flex flex-wrap gap-4 [&_select]:w-full [&_select]:max-w-full [&_select]:min-w-0 [&>label]:w-full [&>label]:max-w-full [&>label]:min-w-0 sm:[&>label]:w-auto`}
onSubmit={(e) => {
e.preventDefault();
form.get('/fundos');
}}
>
{Object.keys(criteriaErrors).length > 0 && (
<aside
className="basis-full rounded border border-amber-600 p-3"
role="alert"
>
<h2 className="font-semibold">
Reveja esta combinação de critérios
</h2>
{Object.entries(criteriaErrors).map(
([key, messages]) => (
<p key={key}>{messages.join(' ')}</p>
),
)}
<p>
A pesquisa não foi executada. Corrija os critérios
indicados e volte a pesquisar.
</p>
</aside>
)}
{notice && (
<p className="basis-full" role="status">
{notice}
</p>
)}
{Object.entries(form.errors).map(([key, error]) => (
<p className="basis-full" role="alert" key={key}>
{error}
</p>
))}
{form.data.kind &&
form.data.kind !== 'institution' &&
(form.data.category ||
form.data.institution_type ||
form.data.location_mode === 'physical') && (
<aside className="basis-full rounded border p-3">
<p>
Categoria, tipo de instituição e presença física
não identificam um fundo ou programa. Reveja o
tipo de registo ou retire apenas estes critérios
incompatíveis.
</p>
<button
type="button"
className="underline"
onClick={() => {
form.setData({
...form.data,
category: '',
institution_type: '',
location_mode: 'coverage',
});
setNotice(
'Critérios de instituição retirados por sua escolha. Local, sector, necessidade e janela foram preservados.',
);
}}
>
Manter o fundo/programa e rever os critérios de
instituição
</button>
</aside>
)}
<label>
Categoria da instituição
<select
className="block rounded border p-2"
value={form.data.category}
onChange={(e) => {
const category = e.target.value;
const valid = typeAllowed(
category,
form.data.institution_type,
);
if (!valid)
setNotice(
'O tipo anterior não pertence à nova categoria e foi retirado. Escolha um dos tipos aplicáveis.',
);
form.setData({
...form.data,
category,
institution_type: valid
? form.data.institution_type
: '',
});
}}
>
<option value="">Todas</option>
{Object.entries(financialCategories).map(
([id, label]) => (
<option key={id} value={id}>
{label}
</option>
),
)}
</select>
</label>
<label>
Tipo de instituição
<select
className="block rounded border p-2"
value={form.data.institution_type}
onChange={(e) =>
form.setData('institution_type', e.target.value)
}
>
<option value="">Todos</option>
{Object.entries(financialTypes)
.filter(
([id]) =>
typeAllowed(form.data.category, id) ||
id === form.data.institution_type,
)
.map(([id, label]) => (
<option key={id} value={id}>
{typeAllowed(form.data.category, id)
? label
: 'Incompatível: ' + label}
</option>
))}
</select>
</label>
<label>
Localização a pesquisar
<select
className="block rounded border p-2"
value={form.data.location_mode}
onChange={(e) =>
form.setData('location_mode', e.target.value)
}
>
<option value="physical">
Sede, balcão ou presença física
</option>
<option value="coverage">
Cobertura do financiamento/produto
</option>
</select>
</label>
<label>
<input
type="checkbox"
checked={form.data.include_historical === '1'}
onChange={(e) =>
form.setData(
'include_historical',
e.target.checked ? '1' : '0',
)
}
/>
Incluir instituições históricas/fundidas, identificadas como
tal
</label>
<label>
Necessidade do processo
<select
className="block rounded border p-2"
value={form.data.need}
onChange={(e) => form.setData('need', e.target.value)}
>
<option value="">Todas / por identificar</option>
{Object.entries(needs).map(([id, label]) => (
<option key={id} value={id}>
{label}
</option>
))}
</select>
</label>
<label>
Palavras-chave
<input
className="block rounded border p-2"
value={form.data.q}
maxLength={150}
onChange={(e) => form.setData('q', e.target.value)}
/>
</label>
<label>
Tipo de registo a consultar
<select
className="block rounded border p-2"
value={form.data.kind}
onChange={(e) => form.setData('kind', e.target.value)}
>
<option value="">Todos</option>
{Object.entries(kinds).map(([key, name]) => (
<option key={key} value={key}>
{name}
</option>
))}
</select>
</label>
<button className={button} disabled={form.processing}>
Pesquisar
</button>
<label>
Sector
<select
className="block rounded border p-2"
value={form.data.sector}
onChange={(e) => form.setData('sector', e.target.value)}
>
<option value="">Todos</option>
{options.sectors.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
<fieldset className="min-w-0 basis-full">
<legend>
Local de interesse — seleccione até ao nível conhecido
</legend>
<TerritoryFields
initial={territorySelection}
showMap={false}
onChange={(path) =>
form.setData({
...form.data,
territory: path.at(-1)?.id ?? '',
province_id:
path.find(
(node) =>
node.location_type === 'province',
)?.id ?? '',
district_id:
path.find(
(node) =>
node.location_type === 'district',
)?.id ?? '',
admin_post_id:
path.find(
(node) =>
node.location_type === 'admin_post',
)?.id ?? '',
locality_id:
path.find(
(node) =>
node.location_type === 'locality',
)?.id ?? '',
})
}
/>
</fieldset>
<label>
Informação por confirmar
<select
className="block rounded border p-2"
value={form.data.certainty}
onChange={(e) =>
form.setData('certainty', e.target.value)
}
>
<option value="include_unknown">
Incluir e assinalar
</option>
<option value="documented">
Apenas âmbito documentado para os filtros escolhidos
</option>
</select>
</label>
<label>
Estado de uma janela
<select
className="block rounded border p-2"
value={form.data.state}
onChange={(e) => form.setData('state', e.target.value)}
>
<option value="">Qualquer estado</option>
{Object.entries(windowLabels).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</label>
</form>
{criteriaChanged && (
<p role="status">
Alterou os critérios. Clique em Pesquisar para os aplicar.
Os resultados anteriores ficam separados abaixo.
</p>
)}
<details
open={
!criteriaChanged && Object.keys(criteriaErrors).length === 0
}
className="space-y-3"
>
<summary>
{Object.keys(criteriaErrors).length
? 'Pesquisa não executada — critérios inválidos'
: criteriaChanged
? 'Resultados da pesquisa anterior — não correspondem aos critérios por aplicar'
: 'Resultados correspondentes à pesquisa'}
</summary>
<p className="text-sm">
Explore as instituições e soluções adequadas ao seu
investimento. Use os filtros para encontrar a informação de
que precisa.
</p>
{items.data.length === 0 &&
Object.keys(criteriaErrors).length === 0 && (
<p>
Não foram encontradas instituições, fundos ou
programas publicados que correspondam a todos os
critérios desta pesquisa.
</p>
)}
{items.data.map((item) => (
<article className={card} key={item.id}>
<h2 className="text-xl font-semibold">
<Link
className="underline"
href={`/fundos/${item.id}?${new URLSearchParams(Object.entries(filters).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))}`}
>
{item.payload.title}
</Link>
</h2>
{item.payload.kind === 'institution' ? (
<InstitutionView
compact
value={
item.payload as InstitutionDetails & {
title: string;
summary: string;
}
}
/>
) : (
<>
<p>{item.payload.summary}</p>
<p>
Entidade gestora:{' '}
{item.payload.manager_name}
</p>
{Object.entries(
item.filter_explanation ?? {},
).map(([key, message]) => (
<p key={key}>{message}</p>
))}
</>
)}
{item.payload.kind === 'institution' &&
item.payload.windows.length === 0 ? null : item.payload
.windows.length === 0 ? (
<p>
Não existe uma janela de candidatura confirmada
para este programa.
</p>
) : (
<ul>
{item.payload.windows.map((window) => (
<li key={window.code}>
{window.title}:{' '}
{windowLabels[window.state]}
</li>
))}
</ul>
)}
</article>
))}
<nav aria-label="Páginas do catálogo" className="flex gap-3">
{items.links.map((link, index) =>
link.url ? (
<Link
key={index}
href={link.url}
aria-current={link.active ? 'page' : undefined}
className="underline"
>
{link.label
.replace(/&laquo;/g, '«')
.replace(/&raquo;/g, '»')}
</Link>
) : null,
)}
</nav>
</details>
</Frame>
);
}