fix: retain editable investment plans and record partial QA continuity evidence

This commit is contained in:
2026-11-20 09:25:49 +02:00
parent bae996e10d
commit 04d8db6c1b
17 changed files with 1011 additions and 290 deletions
@@ -1,7 +1,8 @@
import CurrencySelect from '@/components/currency-select';
import { useEffect, useState } from 'react';
import { useEffect, useId, useState } from 'react';
import {
compareBusinessScenarios,
businessPlanNumberError,
exportBusinessPlanCsv,
forecastBusinessPlan,
MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH,
@@ -74,23 +75,45 @@ function MoneyInput({
value,
onChange,
allowNegative = false,
step = '0.01',
}: {
label: string;
value: string;
onChange: (value: string) => void;
allowNegative?: boolean;
step?: string;
}) {
const errorId = useId();
const [touched, setTouched] = useState(false);
const error = touched
? businessPlanNumberError(value, { allowNegative })
: '';
return (
<label className="block text-sm font-medium">
{label}
<input
type="number"
min={allowNegative ? undefined : '0'}
step="0.01"
step={step}
value={value}
onChange={(event) => onChange(event.target.value)}
onChange={(event) => {
setTouched(true);
onChange(event.target.value);
}}
onBlur={() => setTouched(true)}
aria-invalid={!!error}
aria-describedby={error ? errorId : undefined}
className="mt-1 w-full rounded border p-2"
/>
{error && (
<span
id={errorId}
role="alert"
className="mt-1 block text-sm text-red-800"
>
{error}
</span>
)}
</label>
);
}
@@ -252,7 +275,7 @@ export function SimulationBusinessPlan({
unitVariableCostByPeriod: 'unitVariableCost',
};
const plan = workingPlan ??
restoreBusinessPlanSnapshot(snapshot) ?? {
restoreBusinessPlanSnapshot(snapshot, { editable: true }) ?? {
...emptyPlan,
currency: projectCurrency,
};
@@ -857,7 +880,11 @@ export function SimulationBusinessPlan({
const fiscalBridge = result ? buildFinancialFiscalBridge(result) : null;
return (
<details className="rounded-lg border border-slate-300 p-4" open>
<details
id="business-financial-plan"
className="rounded-lg border border-slate-300 p-4"
open
>
<summary className="cursor-pointer text-lg font-semibold">
Plano financeiro empresarial (pressupostos editáveis)
</summary>
@@ -1092,25 +1119,18 @@ export function SimulationBusinessPlan({
className="mt-1 w-full rounded border p-2"
/>
</label>
<label className="block text-sm">
{product.monthlyUnitsByPeriod
? 'Unidades mensais base'
: 'Unidades por mes'}
<input
type="number"
min="0"
step="0.001"
value={product.monthlyUnits}
onChange={(event) =>
updateProduct(
index,
'monthlyUnits',
event.target.value,
)
}
className="mt-1 w-full rounded border p-2"
/>
</label>
<MoneyInput
label={
product.monthlyUnitsByPeriod
? 'Unidades mensais base'
: 'Unidades por mes'
}
step="0.001"
value={product.monthlyUnits}
onChange={(value) =>
updateProduct(index, 'monthlyUnits', value)
}
/>
<MoneyInput
label="Preço por unidade"
value={product.unitPrice}
@@ -3298,6 +3298,21 @@ export function SimulationForm() {
>
{current.title}
</h3>
{errors.business_plan_snapshot && (
<p
role="alert"
className="rounded border border-red-400 bg-red-50 p-3 text-red-900"
>
<a
className="underline"
href="#business-financial-plan"
>
{errors.business_plan_snapshot}
</a>{' '}
Os dados permanecem no rascunho; corrija o plano
financeiro para continuar.
</p>
)}
<button
type="button"
data-form-help-open
+43 -10
View File
@@ -13,6 +13,29 @@ type ProductLine = {
productInventoryPurchasesByPeriod?: InventoryPurchasePeriod[] | null;
};
export const MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH = 60_000;
export function businessPlanNumberError(
value: string,
options: {
allowNegative?: boolean;
integer?: boolean;
percent?: boolean;
} = {},
): string {
if (value.trim() === '') return 'Preencha este campo para continuar.';
if (
!/^-?\d+(?:\.\d+)?$/.test(value.trim()) ||
!Number.isFinite(Number(value))
)
return 'Introduza apenas números (ex.: 25.000).';
if (!options.allowNegative && Number(value) < 0)
return 'Este valor não pode ser negativo.';
if (options.integer && !Number.isSafeInteger(Number(value)))
return 'Introduza um número inteiro de pessoas.';
if (options.percent && (Number(value) < 0 || Number(value) > 100))
return 'Introduza uma percentagem entre 0% e 100%.';
return '';
}
export type ScenarioAdjustment = {
unitVolumePercent: string;
unitPricePercent: string;
@@ -179,6 +202,7 @@ export function serializeBusinessPlanSnapshot(
export function restoreBusinessPlanSnapshot(
snapshot: string | undefined,
options: { editable?: boolean } = {},
): BusinessFinancialPlanInput | null {
if (!snapshot || snapshot.length > MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH)
return null;
@@ -210,6 +234,15 @@ export function restoreBusinessPlanSnapshot(
)
return null;
const plan = decoded.plan as Record<string, unknown>;
// A blank percentage is an unfinished draft, not a zero assumption.
// Editable recovery also retains invalid percentages for correction.
// The zero below is only an upper-bound validation accumulator, never
// a replacement in the returned plan. Calculation remains strict.
const snapshotPercentage = (value: string, label: string): bigint =>
options.editable || value.trim() === ''
? 0n
: percentMicro(value, label);
const textFields = [
'currency',
'openingCash',
@@ -336,7 +369,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
const collectionPercent = String(plan.salesCollectionPercent ?? '100');
const collectionRate = percentMicro(
const collectionRate = snapshotPercentage(
collectionPercent,
'Percentagem de cobrança',
);
@@ -360,7 +393,7 @@ export function restoreBusinessPlanSnapshot(
!Object.hasOwn(plan, 'openingReceivablesCollectionPercent'))
)
return null;
const openingCollectionRate = percentMicro(
const openingCollectionRate = snapshotPercentage(
String(plan.openingReceivablesCollectionPercent ?? '100'),
'Percentagem de cobrança dos valores a receber de abertura',
);
@@ -391,7 +424,7 @@ export function restoreBusinessPlanSnapshot(
typeof entry.percent !== 'string'
)
return null;
const rate = percentMicro(
const rate = snapshotPercentage(
entry.percent,
'Percentagem da parcela de recebíveis',
);
@@ -419,11 +452,11 @@ export function restoreBusinessPlanSnapshot(
entry.month < 1 ||
entry.month > 60 ||
typeof entry.percent !== 'string' ||
percentMicro(
snapshotPercentage(
entry.percent,
'Percentagem da liquidação de valores a pagar',
) < 0n ||
percentMicro(
snapshotPercentage(
entry.percent,
'Percentagem da liquidação de valores a pagar',
) > 100_000_000n,
@@ -431,7 +464,7 @@ export function restoreBusinessPlanSnapshot(
plan.openingPayablesInstallments.reduce(
(sum, entry) =>
sum +
percentMicro(
snapshotPercentage(
entry.percent,
'Percentagem da liquidação de valores a pagar',
),
@@ -462,7 +495,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
months.add(entry.month);
const rate = percentMicro(
const rate = snapshotPercentage(
entry.percent,
'Percentagem de recuperação de vendas',
);
@@ -634,11 +667,11 @@ export function restoreBusinessPlanSnapshot(
part.lagMonths > 12 ||
typeof part.percent !==
'string' ||
percentMicro(
snapshotPercentage(
part.percent,
'Percentagem da parcela',
) < 0n ||
percentMicro(
snapshotPercentage(
part.percent,
'Percentagem da parcela',
) > 100_000_000n,
@@ -646,7 +679,7 @@ export function restoreBusinessPlanSnapshot(
entry.paymentInstallments.reduce(
(sum: bigint, part: any) =>
sum +
percentMicro(
snapshotPercentage(
part.percent,
'Percentagem da parcela',
),
+20 -6
View File
@@ -26,6 +26,20 @@ function value(draft: ReadinessDraft, key: string): string {
return typeof current === 'string' ? current.trim() : '';
}
function statusLabel(status: string): string {
const labels: Record<string, string> = {
yes: 'Sim',
no: 'Não',
partial: 'Parcialmente',
unknown: 'Por confirmar',
not_applicable: 'Não aplicável',
in_process: 'Em curso',
not_started: 'Por iniciar',
confirmed: 'Confirmado',
};
return labels[status] ?? 'Não indicado';
}
function rows(
draft: ReadinessDraft,
key: string,
@@ -80,7 +94,7 @@ export function getProjectReadiness(
kind: 'missing',
title: 'Clientes ainda pouco definidos',
origin: customerStatus
? `Estado declarado: ${customerStatus}. Não foi indicada uma descrição de clientes ou beneficiários.`
? `Estado declarado: ${statusLabel(customerStatus)}. Não foi indicada uma descrição de clientes ou beneficiários.`
: 'Não foi indicada uma descrição de clientes ou beneficiários.',
affected: 'Procura e receitas previstas.',
consequence:
@@ -98,7 +112,7 @@ export function getProjectReadiness(
id: 'market-source',
kind: 'unverified',
title: 'Hipótese de mercado sem fonte ou data',
origin: `Foi registada informação de mercado sem origem/data confirmada${customerStatus ? `; estado declarado da conversa com clientes: ${customerStatus}` : ''}.`,
origin: `Foi registada informação de mercado sem origem/data confirmada${customerStatus ? `; estado declarado da conversa com clientes: ${statusLabel(customerStatus)}` : ''}.`,
affected: 'Procura, preço e projecções de vendas.',
consequence:
'A hipótese pode não representar informação actual ou verificável.',
@@ -117,7 +131,7 @@ export function getProjectReadiness(
kind: 'missing',
title: 'Custos do projecto por detalhar',
origin: costStatus
? `Estado declarado: ${costStatus}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}`
? `Estado declarado: ${statusLabel(costStatus)}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}`
: 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.',
affected: 'Investimento necessário, margem e tesouraria.',
consequence: 'O capital necessário pode estar subestimado.',
@@ -141,7 +155,7 @@ export function getProjectReadiness(
: 'missing',
title: 'Prazo de recebimentos por esclarecer',
origin: collectionStatus
? `Estado declarado sobre o prazo de recebimento: ${collectionStatus}.`
? `Estado declarado sobre o prazo de recebimento: ${statusLabel(collectionStatus)}.`
: 'Existe um plano/valor de vendas, mas não foi indicado se o prazo de recebimento é conhecido.',
affected: 'Fluxo de caixa e capital de giro.',
consequence:
@@ -162,7 +176,7 @@ export function getProjectReadiness(
id: 'location',
kind: territory && locationReason ? 'unverified' : 'missing',
title: 'Adequação da localização por esclarecer',
origin: `Estado declarado: ${locationStatus || 'não indicado'}. ${territory ? 'Há uma localização seleccionada.' : 'Não foi seleccionada uma localização territorial.'} ${locationReason ? '' : 'Falta explicar os critérios considerados.'}`,
origin: `Estado declarado: ${statusLabel(locationStatus)}. ${territory ? 'Há uma localização seleccionada.' : 'Não foi seleccionada uma localização territorial.'} ${locationReason ? '' : 'Falta explicar os critérios considerados.'}`,
affected:
'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
consequence:
@@ -205,7 +219,7 @@ export function getProjectReadiness(
origin:
sought > secured
? 'O montante indicado como necessário excede os recursos declarados como mobilizados.'
: `Estado do financiamento declarado: ${fundingStatus || 'não indicado'}; os montantes e condições não permitem confirmar recursos disponíveis.`,
: `Estado do financiamento declarado: ${statusLabel(fundingStatus)}; os montantes e condições não permitem confirmar recursos disponíveis.`,
affected: 'Calendário de investimento e implementação.',
consequence:
'Os recursos podem não estar disponíveis quando forem necessários.',
+24
View File
@@ -3,6 +3,10 @@ import { landStatusVisible } from './investment-land-preparation.ts';
import { csvCell } from './csv.js';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
import {
forecastBusinessPlan,
restoreBusinessPlanSnapshot,
} from './business-financial-plan.ts';
export type SimulationDraft = Record<string, string | string[]>;
export const projectQuestionnaireVersion =
@@ -1801,6 +1805,26 @@ export function validateSimulationDraft(
errors.total_investment =
'A soma do capital, dívida e subvenções deve corresponder ao investimento total.';
}
if (
sectionId === 'financial' &&
typeof draft.business_plan_snapshot === 'string' &&
draft.business_plan_snapshot
) {
const plan = restoreBusinessPlanSnapshot(draft.business_plan_snapshot);
if (!plan)
errors.business_plan_snapshot =
'Não foi possível recuperar o plano financeiro. Reveja os dados guardados.';
else {
try {
forecastBusinessPlan(plan);
} catch (cause) {
errors.business_plan_snapshot =
cause instanceof Error
? cause.message
: 'Reveja os dados do plano financeiro antes de continuar.';
}
}
}
return errors;
}
+211 -116
View File
@@ -1,10 +1,19 @@
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";
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} />;
@@ -54,35 +63,38 @@ function Index({
territorySelection?: TerritoryOption[];
criteriaErrors?: Record<string, string[]>;
}) {
const [notice, setNotice] = useState("");
const [notice, setNotice] = useState('');
const [searchTerritory, setSearchTerritory] = useState(territorySelection);
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 ?? "",
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 ??
(filters.location_mode === "physical" ? "documented" : "include_unknown"),
state: filters.state ?? "",
(filters.location_mode === 'physical'
? 'documented'
: '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" ||
category === 'other' ||
!type ||
type === "other" ||
type === 'other' ||
(categoryTypes[category] ?? []).includes(type);
return (
<Frame title="Instituições financeiras, fundos e programas de apoio">
@@ -95,25 +107,33 @@ function Index({
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.
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");
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>
))}
<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.
A pesquisa não foi executada. Corrija os critérios
indicados e volte a pesquisar.
</p>
</aside>
)}
@@ -128,15 +148,16 @@ function Index({
</p>
))}
{form.data.kind &&
form.data.kind !== "institution" &&
form.data.kind !== 'institution' &&
(form.data.category ||
form.data.institution_type ||
form.data.location_mode === "physical") && (
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.
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"
@@ -144,16 +165,17 @@ function Index({
onClick={() => {
form.setData({
...form.data,
category: "",
institution_type: "",
location_mode: "coverage",
category: '',
institution_type: '',
location_mode: 'coverage',
});
setNotice(
"Critérios de instituição retirados por sua escolha. Local, sector, necessidade e janela foram preservados.",
'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
Manter o fundo/programa e rever os critérios de
instituição
</button>
</aside>
)}
@@ -164,24 +186,31 @@ function Index({
value={form.data.category}
onChange={(e) => {
const category = e.target.value;
const valid = typeAllowed(category, form.data.institution_type);
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.",
'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 : "",
institution_type: valid
? form.data.institution_type
: '',
});
}}
>
<option value="">Todas</option>
{Object.entries(financialCategories).map(([id, label]) => (
<option key={id} value={id}>
{label}
</option>
))}
{Object.entries(financialCategories).map(
([id, label]) => (
<option key={id} value={id}>
{label}
</option>
),
)}
</select>
</label>
<label>
@@ -189,7 +218,9 @@ function Index({
<select
className="block rounded border p-2"
value={form.data.institution_type}
onChange={(e) => form.setData("institution_type", e.target.value)}
onChange={(e) =>
form.setData('institution_type', e.target.value)
}
>
<option value="">Todos</option>
{Object.entries(financialTypes)
@@ -202,7 +233,7 @@ function Index({
<option key={id} value={id}>
{typeAllowed(form.data.category, id)
? label
: "Incompatível: " + label}
: 'Incompatível: ' + label}
</option>
))}
</select>
@@ -210,19 +241,23 @@ function Index({
<label>
<input
type="checkbox"
checked={form.data.include_historical === "1"}
checked={form.data.include_historical === '1'}
onChange={(e) =>
form.setData("include_historical", e.target.checked ? "1" : "0")
form.setData(
'include_historical',
e.target.checked ? '1' : '0',
)
}
/>
Incluir instituições históricas/fundidas, identificadas como tal
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)}
onChange={(e) => form.setData('need', e.target.value)}
>
<option value="">Todas / por identificar</option>
{Object.entries(needs).map(([id, label]) => (
@@ -233,20 +268,24 @@ function Index({
</select>
</label>
<label>
Palavras-chave
Palavras-chave (opcional)
<input
className="block rounded border p-2"
value={form.data.q}
maxLength={150}
onChange={(e) => form.setData("q", e.target.value)}
onChange={(e) => form.setData('q', e.target.value)}
/>
<span className="block text-sm">
Refine pelo nome ou descrição; este campo não substitui
a localização, categoria ou finalidade.
</span>
</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)}
onChange={(e) => form.setData('kind', e.target.value)}
>
<option value="">Todos</option>
{Object.entries(kinds).map(([key, name]) => (
@@ -261,7 +300,7 @@ function Index({
<select
className="block rounded border p-2"
value={form.data.sector}
onChange={(e) => form.setData("sector", e.target.value)}
onChange={(e) => form.setData('sector', e.target.value)}
>
<option value="">Todos</option>
{options.sectors.map((item) => (
@@ -272,7 +311,9 @@ function Index({
</select>
</label>
<fieldset className="min-w-0 basis-full">
<legend>Local de interesse — seleccione até ao nível conhecido</legend>
<legend>
Local de interesse — seleccione até ao nível conhecido
</legend>
<label>
Localização a pesquisar
<select
@@ -283,40 +324,52 @@ function Index({
...form.data,
location_mode: e.target.value,
certainty:
e.target.value === "physical"
? "documented"
e.target.value === 'physical'
? 'documented'
: form.data.certainty,
})
}
>
<option value="physical">Sede, balcão ou presença física</option>
<option value="coverage">Cobertura do financiamento/produto</option>
<option value="physical">
Sede, balcão ou presença física
</option>
<option value="coverage">
Cobertura do financiamento/produto
</option>
</select>
</label>
<p className="mb-3 text-sm">
Escolha a província e, se necessário, o distrito. Sede e balcões identificam
onde pode contactar a instituição; a cobertura indica onde o financiamento
se aplica.
Escolha a província e, se necessário, o distrito. Sede e
balcões identificam onde pode contactar a instituição; a
cobertura indica onde o financiamento se aplica.
</p>
<TerritoryFields
initial={territorySelection}
initial={searchTerritory}
showMap={false}
onChange={(path) =>
form.setData({
...form.data,
territory: path.at(-1)?.id ?? "",
territory: path.at(-1)?.id ?? '',
province_id:
path.find((node) => node.location_type === "province")?.id ??
"",
path.find(
(node) =>
node.location_type === 'province',
)?.id ?? '',
district_id:
path.find((node) => node.location_type === "district")?.id ??
"",
path.find(
(node) =>
node.location_type === 'district',
)?.id ?? '',
admin_post_id:
path.find((node) => node.location_type === "admin_post")?.id ??
"",
path.find(
(node) =>
node.location_type === 'admin_post',
)?.id ?? '',
locality_id:
path.find((node) => node.location_type === "locality")?.id ??
"",
path.find(
(node) =>
node.location_type === 'locality',
)?.id ?? '',
})
}
/>
@@ -326,9 +379,13 @@ function Index({
<select
className="block rounded border p-2"
value={form.data.certainty}
onChange={(e) => form.setData("certainty", e.target.value)}
onChange={(e) =>
form.setData('certainty', e.target.value)
}
>
<option value="include_unknown">Incluir e assinalar</option>
<option value="include_unknown">
Incluir e assinalar
</option>
<option value="documented">
Apenas âmbito documentado para os filtros escolhidos
</option>
@@ -339,7 +396,7 @@ function Index({
<select
className="block rounded border p-2"
value={form.data.state}
onChange={(e) => form.setData("state", e.target.value)}
onChange={(e) => form.setData('state', e.target.value)}
>
<option value="">Qualquer estado</option>
{Object.entries(windowLabels).map(([key, label]) => (
@@ -355,46 +412,77 @@ function Index({
</form>
{criteriaChanged && (
<p role="status">
Alterou os critérios. Clique em Pesquisar para os aplicar. Os resultados
anteriores ficam separados abaixo.
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}
open={
!criteriaChanged && Object.keys(criteriaErrors).length === 0
}
className="space-y-3"
>
<summary>
{Object.keys(criteriaErrors).length
? "Pesquisa não executada — critérios inválidos"
? 'Pesquisa não executada — critérios inválidos'
: criteriaChanged
? "Resultados da pesquisa anterior — não correspondem aos critérios por aplicar"
: "Resultados correspondentes à pesquisa"}
? '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.
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.length === 0 &&
Object.keys(criteriaErrors).length === 0 && (
<div className="grid gap-3">
<p>
Não foram encontradas instituições, fundos ou
programas publicados que correspondam a todos os
critérios desta pesquisa.
</p>
{!criteriaChanged &&
filters.location_mode === 'physical' &&
filters.province_id && (
<button
type="button"
className={button}
onClick={() => {
form.setData({
...form.data,
territory: '',
province_id: '',
district_id: '',
admin_post_id: '',
locality_id: '',
});
setSearchTerritory([]);
setNotice(
'Escolha outra província no local a pesquisar. Categoria, tipo e finalidade foram conservados; a localização do investimento no dossier mantém-se.',
);
}}
>
Procurar instituição noutra província
</button>
)}
</div>
)}
{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"))}`}
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" ? (
{item.payload.kind === 'institution' ? (
<InstitutionView
compact
physicalTerritory={
filters.location_mode === "physical"
filters.location_mode === 'physical'
? filters.territory
: undefined
}
@@ -408,25 +496,30 @@ function Index({
) : (
<>
<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>
),
)}
<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 ? (
{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.
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]}
{window.title}:{' '}
{windowLabels[window.state]}
</li>
))}
</ul>
@@ -439,10 +532,12 @@ function Index({
<Link
key={index}
href={link.url}
aria-current={link.active ? "page" : undefined}
aria-current={link.active ? 'page' : undefined}
className="underline"
>
{link.label.replace(/&laquo;/g, "«").replace(/&raquo;/g, "»")}
{link.label
.replace(/&laquo;/g, '«')
.replace(/&raquo;/g, '»')}
</Link>
) : null,
)}
@@ -9,6 +9,17 @@ import {
} from '@/lib/company-comparison';
type Question = { label: string; options: Record<string, string> };
const questionThemes: Record<string, string> = {
purpose: 'Organização do pedido',
participants: 'Titulares, sócios e accionistas',
participation: 'Participações',
capital: 'Capital e contribuições',
management: 'Gestão',
responsibility: 'Responsabilidade limitada',
listing: 'Negociação em Bolsa',
regulated: 'Regras profissionais ou sectoriais',
preferred: 'Alternativa a aprofundar',
};
type Result = {
engine_version: string;
source: {
@@ -135,8 +146,8 @@ function Comparator(props: Props) {
</p>
)}
<p>
Compare a estrutura pretendida e os pontos a esclarecer antes de
preparar o acto constitutivo.
Compare alternativas para discutir a constituição; não existe
uma forma universalmente preferível.
</p>
{saved && (
<p>
@@ -178,32 +189,46 @@ function Comparator(props: Props) {
{Object.entries(definition.questions).map(
([key, question]) =>
active.includes(key) ? (
<label key={key} className="grid gap-1">
{question.label}
<select
className={input}
name={`answers[${key}]`}
value={answers[key] ?? 'unknown'}
disabled={busy}
onChange={(e) => {
setAnswers({
...answers,
[key]: e.target.value,
});
setDirty(true);
operation.current =
createOperationKey();
}}
>
{Object.entries(
question.options,
).map(([code, label]) => (
<option key={code} value={code}>
{label}
</option>
))}
</select>
</label>
<fieldset
key={key}
className="min-w-0 rounded border p-3"
>
<legend className="px-1 font-semibold">
{questionThemes[key] ??
question.label}
</legend>
<label className="grid gap-1">
{question.label}
<select
className={input}
name={`answers[${key}]`}
value={
answers[key] ?? 'unknown'
}
disabled={busy}
onChange={(e) => {
setAnswers({
...answers,
[key]: e.target.value,
});
setDirty(true);
operation.current =
createOperationKey();
}}
>
{Object.entries(
question.options,
).map(([code, label]) => (
<option
key={code}
value={code}
>
{label}
</option>
))}
</select>
</label>
</fieldset>
) : (
<input
key={key}