Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-23 15:33:56 +02:00
110 changed files with 4105 additions and 266 deletions
@@ -0,0 +1,118 @@
import { Head, Link, usePage } from '@inertiajs/react';
import ProfileNavigation from '@/components/profile-navigation';
import {
canShowLegacyManagement,
portalNavigation,
type PortalNavAccess,
} from '@/lib/portal-navigation';
export default function DashboardManagement({
summaryAvailable,
}: {
summaryAvailable: boolean;
}) {
const { props } = usePage<{
auth?: {
user?: unknown;
canManagePortal?: boolean;
legacyManagementAccess?: boolean;
};
profileAccess?: PortalNavAccess['profileAccess'];
opportunityManagement?: PortalNavAccess['opportunityManagement'];
contentManagementHref?: PortalNavAccess['contentManagementHref'];
contentManagementAccess?: PortalNavAccess['contentManagementAccess'];
scopedAdministration?: PortalNavAccess['scopedAdministration'];
administrationNavigation?: PortalNavAccess['administrationNavigation'];
dashboardNavigation?: PortalNavAccess['dashboardNavigation'];
existingBusinessEnabled?: boolean;
businessReviewUrl?: string | null;
educationEnabled?: boolean;
aiEnabled?: boolean;
legacyContentEnabled?: boolean;
procurementEnabled?: boolean;
}>();
const administration = portalNavigation({
authenticated: !!props.auth?.user,
manager: canShowLegacyManagement(props.auth),
profileAccess: props.profileAccess,
opportunityManagement: props.opportunityManagement,
contentManagementHref: props.contentManagementHref,
contentManagementAccess: props.contentManagementAccess,
scopedAdministration: props.scopedAdministration,
administrationNavigation: props.administrationNavigation,
dashboardNavigation: props.dashboardNavigation,
businesses: props.existingBusinessEnabled,
businessReviewUrl: props.businessReviewUrl,
education: props.educationEnabled,
ai: props.aiEnabled,
legacyContent: props.legacyContentEnabled,
procurement: props.procurementEnabled,
}).find((group) => group.id === 'administration');
const groups =
administration?.children?.filter(
(group) => group.id !== 'collaborative-dashboard',
) ?? [];
const managing = summaryAvailable || !!administration;
const title = managing
? 'Dashboard de gestão do portal'
: 'A minha área de trabalho';
return (
<>
<Head title={title} />
<header className="space-y-2">
<h1 className="text-2xl font-semibold">{title}</h1>
<p className="text-muted-foreground max-w-3xl">
{managing
? 'Gira as oportunidades, os conteúdos e os acessos do portal nas áreas que lhe estão atribuídas.'
: 'Consulte os seus investimentos, as tarefas e os acessos disponíveis para a sua conta.'}
</p>
</header>
{groups.length > 0 && (
<section
aria-label="Gestão do portal"
className="grid gap-4 md:grid-cols-2"
>
{groups.map((group) => (
<section
key={group.id}
className="min-w-0 space-y-3 rounded-xl border p-5"
>
<h2 className="text-lg font-semibold">
{group.label}
</h2>
<nav
aria-label={group.label}
className="grid gap-2"
>
{group.children?.map(
(item) =>
item.href && (
<Link
key={item.id}
href={item.href}
className="hover:bg-muted focus-visible:outline-primary rounded-lg px-3 py-2 underline underline-offset-4 focus-visible:outline-2"
>
{item.label}
</Link>
),
)}
</nav>
</section>
))}
</section>
)}
{managing ? (
<details className="rounded-xl border p-4">
<summary className="cursor-pointer font-medium">
A minha conta e oportunidades próprias
</summary>
<div className="mt-3">
<ProfileNavigation />
</div>
</details>
) : (
<ProfileNavigation />
)}
</>
);
}
@@ -1,9 +1,4 @@
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import {
newAnnualReferencePlan,
serializeAnnualExampleSnapshot,
} from '@/lib/business-plan-guidance';
/** Optional declarations share the existing plan snapshot; no independent storage. */
export function FinancialPlanDetails({
plan,
@@ -50,42 +45,23 @@ export function FinancialPlanDetails({
introduzida; não se presume que um mês tenha 30 dias. Confira a
compatibilidade entre contrato e cobranças previstas.
</p>
<label className="grid gap-1">
Fonte do relatório financeiro consolidado
<select
className="rounded border p-2"
value={plan.reportSource ?? 'investor'}
onChange={(e) =>
onChange({
...plan,
reportSource: e.target.value as
| 'investor'
| 'annual_example',
...(e.target.value === 'annual_example' &&
!plan.annualExampleSnapshot
? {
annualExampleSnapshot:
serializeAnnualExampleSnapshot(
newAnnualReferencePlan(),
),
}
: {}),
})
}
>
<option value="investor">Plano do investidor</option>
<option value="annual_example">
Exemplo sintético anual editável
</option>
</select>
</label>
<p className="text-sm">
A escolha do exemplo muda apenas a fonte do relatório, sem
substituir as entradas do investidor. As edições do exemplo são
feitas em «Carregar cenário anual de exemplo» e acompanham a
mesma versão guardada. Escolha novamente «Plano do investidor»
para regressar.
</p>
{plan.reportSource === 'annual_example' && (
<div role="alert" className="rounded border p-3">
<p>
Seleccione o plano do investidor para apresentar os seus
dados financeiros. Os dados guardados foram preservados.
</p>
<button
type="button"
className="underline"
onClick={() =>
onChange({ ...plan, reportSource: 'investor' })
}
>
Usar plano do investidor
</button>
</div>
)}
<label className="flex gap-2">
<input
type="checkbox"
@@ -7,7 +7,6 @@ import {
import { InvestmentReportTables } from './investment-report-tables';
import { BusinessPlanWarnings } from './business-plan-warnings';
import { financialPlanWarnings } from '@/lib/financial-plan-warnings';
import { buildAnnualExampleTables } from '@/lib/annual-example-report';
import { StartupAssetRequirements } from './startup-asset-requirements';
export function IntegralFinancialPlan({
@@ -18,28 +17,12 @@ export function IntegralFinancialPlan({
onChange: (plan: BusinessFinancialPlanInput) => void;
}) {
if (plan.reportSource === 'annual_example') {
try {
return (
<section aria-label="Relatório do exemplo sintético">
<h4>Relatório do exemplo sintético anual</h4>
<p>
As onze tabelas abaixo usam o exemplo editável. Os dados
reais do investimento ficam conservados separadamente.
</p>
<InvestmentReportTables
tables={buildAnnualExampleTables(plan)}
/>
</section>
);
} catch (error) {
return (
<p role="alert">
{error instanceof Error
? error.message
: 'Confira o cenário de exemplo.'}
</p>
);
}
return (
<p role="status">
Seleccione o plano do investidor para consultar o relatório
financeiro.
</p>
);
}
if (plan.reportAssumptions && !isReportAssumptions(plan.reportAssumptions))
return (
@@ -76,11 +59,10 @@ export function IntegralFinancialPlan({
Relatório financeiro integral — dados do investimento
</summary>
<p className="my-2">
Utiliza as vendas, custos e agendas do plano financeiro. Não
utiliza o cenário sintético. Todos os montantes são projecções
declaradas em {plan.currency || 'moeda por seleccionar'}. Campos
em falta permanecem por determinar; indique zero apenas quando
aplicável.
Utiliza as vendas, custos e agendas do plano financeiro. Todos
os montantes são projecções declaradas em{' '}
{plan.currency || 'moeda por seleccionar'}. Campos em falta
permanecem por determinar; indique zero apenas quando aplicável.
</p>
<StartupAssetRequirements
plan={plan}
@@ -0,0 +1,78 @@
import { calculateNormal, normalBook, normalCurrent } from '@/lib/irpc-normal';
import {
fractionPresentation,
type FiscalFraction,
} from '@/lib/fiscal-rational';
export default function IrpcCurrentBase({
draft,
}: {
draft: Record<string, unknown>;
}) {
try {
const book = normalBook(draft);
const model = calculateNormal(draft, book);
const display = (value: FiscalFraction | null | undefined) => {
if (!value) return 'Por determinar';
const shown = fractionPresentation(value);
return `${shown.decimal} ${model.currency}${shown.approximate ? ' (apresentação aproximada; cálculo exacto preservado)' : ''}`;
};
return (
<section
aria-label="Base actual do IRPC"
className="space-y-2 rounded border p-3"
>
<h5 className="font-semibold">
Matéria colectável gerada pelos dados actuais
</h5>
<p className="text-sm">
Calculada a partir do resultado contabilístico, dos
ajustamentos e das deduções declaradas para este exercício.
Não é necessário copiar ou introduzir novamente a base. Não
corresponde ao imposto a pagar.
</p>
<dl className="grid gap-2 text-sm sm:grid-cols-2">
<div>
<dt>Resultado contabilístico antes de imposto</dt>
<dd>{display(model.accountingProfit)}</dd>
</div>
<div>
<dt>Lucro tributável</dt>
<dd>{display(model.taxableProfit)}</dd>
</div>
<div>
<dt>Perdas fiscais deduzidas</dt>
<dd>{display(model.base?.deductedLosses)}</dd>
</div>
<div>
<dt>Benefícios deduzidos à base</dt>
<dd>{display(model.base?.benefitDeduction)}</dd>
</div>
<div>
<dt>Matéria colectável actual</dt>
<dd>
<output aria-label="Matéria colectável actual">
{display(model.taxableBase)}
</output>
</dd>
</div>
</dl>
{book.result && !normalCurrent(draft, book) && (
<p role="status">
Os dados mudaram desde o último cálculo guardado. A base
acima usa os dados actuais; calcule e guarde para
actualizar o resultado. O histórico anterior foi
preservado.
</p>
)}
</section>
);
} catch {
return (
<p role="status">
Base do IRPC por determinar: reveja os dados e o enquadramento
nas secções de IRPC. Nenhum valor alternativo foi utilizado.
</p>
);
}
}
@@ -23,7 +23,6 @@ import {
} from '@/lib/simulation-contract';
import { buildFinancialFiscalBridge } from '@/lib/financial-fiscal-bridge';
import { BusinessPlanWarnings } from '@/components/business-plan-warnings';
import { SimulationAnnualExample } from '@/components/simulation-annual-example';
import { IntegralFinancialPlan } from '@/components/integral-financial-plan';
import { MarketAnalysisPlan } from '@/components/market-analysis-plan';
import { FinancialRatiosPlan } from '@/components/financial-ratios-plan';
@@ -159,7 +158,6 @@ export function SimulationBusinessPlan({
);
const [workingPlan, setWorkingPlan] =
useState<BusinessFinancialPlanInput | null>(null);
const [showExample, setShowExample] = useState(false);
useEffect(() => setWorkingPlan(null), [snapshot]);
if (hasOversizedStoredSnapshot) {
return (
@@ -926,30 +924,12 @@ export function SimulationBusinessPlan({
</p>
)}
<p className="my-3 text-sm text-slate-700">
Projecção indicativa com valores de exemplo editáveis ou
pressupostos introduzidos pela pessoa. Facturação, cobranças,
despesas, pagamentos, juros e capital reembolsado ficam
separados. Não calcula impostos, não converte moedas e não
substitui um plano contabilístico validado.
Projecção indicativa com pressupostos introduzidos pelo
investidor. Facturação, cobranças, despesas, pagamentos, juros e
capital reembolsado ficam separados. Não calcula impostos, não
converte moedas e não substitui um plano contabilístico
validado.
</p>
<button
type="button"
className="rounded border px-3 py-2 text-sm"
onClick={() => setShowExample((previous) => !previous)}
>
{showExample
? 'Fechar cenário de exemplo'
: 'Carregar cenário anual de exemplo'}
</button>
{showExample && (
<SimulationAnnualExample
currency={currency}
snapshot={plan.annualExampleSnapshot}
onSnapshotChange={(annualExampleSnapshot) =>
savePlan({ ...plan, annualExampleSnapshot })
}
/>
)}
<PlanEconomicClassification plan={plan} onChange={savePlan} />
<FinancialPlanDetails plan={plan} onChange={savePlan} />
<FinancialDayTerms plan={plan} onChange={savePlan} />
@@ -184,8 +184,8 @@ export function SimulationCashflowPlanner({
{restored
? 'Pressupostos recuperados do rascunho deste investimento; reveja-os antes de interpretar os resultados ou exportar.'
: snapshot
? 'O rascunho guardado não pôde ser interpretado. Os campos mostram exemplos, que não substituem os dados guardados até os editar.'
: 'Os valores preenchidos ao abrir são exemplos demonstrativos. Confirme ou altere os pressupostos antes de interpretar os resultados ou exportar o CSV.'}
? 'O rascunho guardado não pôde ser interpretado. Os campos permanecem vazios; os dados guardados não foram substituídos.'
: 'Introduza os seus pressupostos antes de interpretar os resultados ou exportar o CSV.'}
</p>
{projection?.status === 'incomplete' && (
<p
@@ -4105,6 +4105,14 @@ export function SimulationForm() {
String(draft.fiscal_period ?? '') ===
'2026' ? (
<SimulationPublishedIva
planAlreadyVisible={
Array.isArray(
draft.fiscal_tools_selection,
) &&
draft.fiscal_tools_selection.includes(
'tax:sales',
)
}
draft={draft}
onChange={change}
busy={isCalculating}
@@ -4351,6 +4359,7 @@ export function SimulationForm() {
draft.fiscal_component === 'iva' &&
!assistedInvestment && (
<SimulationPublishedIva
planAlreadyVisible
draft={draft}
onChange={change}
busy={isCalculating}
@@ -1,3 +1,4 @@
import IrpcCurrentBase from '@/components/irpc-current-base';
import { SimulationIrpcSpecial } from '@/components/simulation-irpc-special';
import FiscalOperationPicker from '@/components/fiscal-operation-picker';
import { inputText } from '@/lib/input-text';
@@ -107,6 +108,7 @@ export function SimulationIrpcNormal({
próprios. Os juros da simulação de empréstimo não são
adoptados automaticamente como custo fiscal.
</p>
<IrpcCurrentBase draft={draft} />
{error && <p role="alert">{error}</p>}
{source ? (
<p>
@@ -195,7 +195,9 @@ export function SimulationMonthlyIva({
| undefined;
return (
<section
className="space-y-3 rounded border border-emerald-700 p-4"
id="monthly-projected-iva"
tabIndex={-1}
className="scroll-mt-24 space-y-3 rounded border border-emerald-700 p-4"
aria-label="IVA mensal das vendas projectadas"
>
<InvestmentContextAssessment
@@ -1,5 +1,7 @@
import { inputText } from '../lib/input-text.ts';
import { useEffect, useState } from 'react';
import { SimulationMonthlyIva } from './simulation-monthly-iva';
import type { ApiSimulationExecutionV1 } from '@/lib/simulation-contract';
import type { MonthlyIvaInput } from '@/lib/monthly-iva';
export type PublishedIvaInput =
@@ -13,17 +15,96 @@ export type PublishedIvaInput =
scope_declared: boolean;
};
export function SimulationPublishedIva({
type PublishedIvaProps = {
planAlreadyVisible?: boolean;
draft: Record<string, unknown>;
onChange: (field: string, value: string | string[]) => void;
busy: boolean;
onCalculate: (
input: PublishedIvaInput,
) => Promise<ApiSimulationExecutionV1 | null | undefined>;
};
export function SimulationPublishedIva(props: PublishedIvaProps) {
const hasPlan = !!(
props.draft.business_plan_snapshot || props.draft.cashflow_snapshot
);
const source =
props.draft.published_iva_base_source === 'plan'
? 'plan'
: props.draft.published_iva_base_source === 'operation'
? 'operation'
: hasPlan
? 'plan'
: 'operation';
return (
<section
aria-label="Origem da base do IVA"
className="min-w-0 space-y-3"
>
<label className="grid min-w-0 gap-1">
Origem dos valores para IVA
<select
aria-label="Origem dos valores para IVA"
className="w-full max-w-full min-w-0 rounded border p-2"
value={source}
onChange={(event) =>
props.onChange(
'published_iva_base_source',
event.target.value,
)
}
>
<option value="plan">
Vendas introduzidas no plano — base gerada por período
</option>
<option value="operation">
Operação avulsa — valores próprios, fora das vendas do
plano
</option>
</select>
</label>
{source === 'plan' ? (
<>
<p className="text-sm">
A base líquida é gerada pelas vendas do plano e pelo
enquadramento declarado em cada período. Não copie o
orçamento nem introduza novamente o valor calculado.
Alterações nas vendas tornam o resultado anterior
desactualizado.
</p>
{hasPlan ? (
props.planAlreadyVisible ? (
<a
className="underline"
href="#monthly-projected-iva"
>
Consultar a base e calcular o IVA das vendas do
plano
</a>
) : (
<SimulationMonthlyIva {...props} />
)
) : (
<p role="status">
Prepare as vendas no plano para gerar a base do IVA.
Não foi utilizada uma base alternativa.
</p>
)}
</>
) : (
<StandalonePublishedIva {...props} />
)}
</section>
);
}
function StandalonePublishedIva({
busy,
onCalculate,
draft,
onChange,
}: {
draft: Record<string, unknown>;
onChange: (field: string, value: string) => void;
busy: boolean;
onCalculate: (input: PublishedIvaInput) => Promise<unknown>;
}) {
}: PublishedIvaProps) {
const [available, setAvailable] = useState(false);
const [message, setMessage] = useState(
'A consultar disponibilidade do cálculo de IVA…',
@@ -115,10 +196,10 @@ export function SimulationPublishedIva({
<p role="status">{message}</p>
<p className="text-sm">
Cobertura: exigibilidade em 2026, operação interna à taxa geral.
A base tributável é indicada por si; não é copiada do orçamento.
Sem isenções, taxas reduzidas, bases especiais, importações,
deduções, declaração ou pagamento. O cálculo não valida o
enquadramento jurídico.
Esta operação avulsa usa os seus valores próprios; não é somada
nem confundida com as vendas do plano. Sem isenções, taxas
reduzidas, bases especiais, importações, deduções, declaração ou
pagamento. O cálculo não valida o enquadramento jurídico.
</p>
<fieldset disabled={busy} className="space-y-3">
<label className="block">
+1 -1
View File
@@ -3387,7 +3387,7 @@ export function exportBusinessPlanCsv(
['Moeda de apresentação', result.presentationCurrency],
[
'Fonte dos pressupostos',
'Valores do formulário; os valores iniciais podem ser exemplos demonstrativos',
'Pressupostos introduzidos pelo investidor no formulário',
],
['Facturação', 'unidades mensais × preço unitário'],
['Custo variável', 'unidades mensais × custo variável unitário'],
+10 -42
View File
@@ -11,7 +11,6 @@ import {
import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { financialPlanWarnings } from './financial-plan-warnings.ts';
import { buildAnnualExampleTables } from './annual-example-report.ts';
import { pathStates } from './investor-path.ts';
import {
buildProjectDossierRows,
@@ -664,47 +663,11 @@ function makeSections(
}
}
if (finance && financialPlan?.reportSource === 'annual_example') {
finance.rows = finance.rows
.filter((row) => row.field === 'Classificação CAE do plano')
.map((row) => ({
...row,
classification:
'Contexto do investimento preservado; não é a classificação do exemplo sintético',
}));
finance.rows = [];
finance.tables = [];
finance.paragraphs = [
'Exemplo sintético anual editável, da mesma versão guardada do plano. Não representa dados reais do investidor nem financiamento confirmado. As entradas do investidor permanecem preservadas.',
'Aviso não bloqueante — O detalhe original por serviço e departamento contém diferenças documentais ainda não reconciliadas. Os totais calculados usam os anuais aprovados; as linhas originais são identificadas separadamente e não são somadas como ajustamentos. A reprodução integral dos dados originais não está validada.',
'Seleccione o plano do investidor no editor para incluir os seus dados financeiros no relatório.',
];
try {
const example = buildAnnualExampleTables(financialPlan);
finance.tables = example.filter(
(t) =>
!['market-analysis', 'milestones', 'personnel'].includes(
t.id,
),
);
for (const [sectionId, tableId] of [
['market', 'market-analysis'],
['execution', 'milestones'],
['team', 'personnel'],
] as const) {
const section = sections.get(sectionId);
if (section) {
section.tables = example.filter((t) => t.id === tableId);
section.rows = [];
section.paragraphs = [
'Dados sintéticos de referência do exemplo anual; não são dados reais do investidor.',
];
}
}
} catch (error) {
finance.tables = [];
finance.paragraphs.push(
error instanceof Error
? error.message
: 'Não foi possível recuperar o exemplo.',
);
}
}
if (
finance &&
@@ -960,7 +923,12 @@ export function createIntegralFinancialReport(
...options,
selectedSections: new Set(['market', 'finance', 'team', 'execution']),
});
const tables = report.sections.flatMap((s) => s.tables ?? []);
const legacyExample =
restoreBusinessPlanSnapshot(text(draft, 'business_plan_snapshot'))
?.reportSource === 'annual_example';
const tables = legacyExample
? []
: report.sections.flatMap((s) => s.tables ?? []);
const finance = report.sections.find((s) => s.id === 'finance');
const planCurrency = restoreBusinessPlanSnapshot(
text(draft, 'business_plan_snapshot'),
@@ -1003,7 +971,7 @@ export function createIntegralFinancialReport(
...(finance?.paragraphs.filter(
(p) =>
p.startsWith('Aviso não bloqueante') ||
p.startsWith('Exemplo sintético anual'),
p.startsWith('Seleccione o plano do investidor'),
) ?? []),
],
rows:
+13
View File
@@ -976,6 +976,19 @@ export function buildProjectDossierRows(
'Sem inferência de dispensa legal',
]);
}
for (const [key, section, label] of [
['web_plan', 'Mercado', 'Plano web e presença digital'],
['management_summary', 'Equipa', 'Organização e gestão do negócio'],
]) {
const value = String(draft[key] ?? '');
if (value.trim())
rows.push([
section,
label,
value,
'Texto opcional declarado pelo investidor; não verificado',
]);
}
rows.push(...proactiveInvestmentRows(draft));
const lineageFields: Record<string, string> = {
Título: 'project_title',
+12
View File
@@ -810,6 +810,18 @@ export const simulationFieldGroups: Record<
d.purpose === 'simulate_only' &&
['small_business', 'investor'].includes(String(d.journey_type)),
},
{
key: 'web_plan',
label: 'Plano web e presença digital (texto opcional)',
type: 'textarea',
showWhen: (d) => isProjectGuidedJourney(d),
},
{
key: 'management_summary',
label: 'Organização e gestão do negócio (texto opcional)',
type: 'textarea',
showWhen: (d) => isProjectGuidedJourney(d),
},
],
location: [
{
+3 -8
View File
@@ -1,9 +1,8 @@
import ProfileNavigation from '@/components/profile-navigation';
import ContentManagementEntry from '@/components/content-management-entry';
import DashboardManagement from '@/components/dashboard-management';
import DashboardWorkQueue, {
type DashboardQueue,
} from '@/components/dashboard-work-queue';
import { Head, Link } from '@inertiajs/react';
import { Link } from '@inertiajs/react';
import { dashboard } from '@/routes';
import type { InvestmentContext } from '@/pages/investor-path/index';
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
@@ -56,10 +55,7 @@ export default function Dashboard({
}) {
return (
<div className="space-y-8 p-4 md:p-8">
<Head title="Painel" />
<h1 className="text-2xl font-semibold">Painel do portal</h1>
<ProfileNavigation />
<ContentManagementEntry />
<DashboardManagement summaryAvailable={!!summary} />
<section id="meu-trabalho" className="scroll-mt-24">
{workQueue ? (
<DashboardWorkQueue queue={workQueue} />
@@ -308,7 +304,6 @@ export default function Dashboard({
href={`/investimentos/${investorPath.current.id}#${investorPath.current.next.code}`}
>
Próxima acção:{' '}
{investorPath.current.next.code} ·{' '}
{investorPath.current.next.title}
</Link>
)}
+59 -11
View File
@@ -64,6 +64,7 @@ function Index({
criteriaErrors?: Record<string, string[]>;
}) {
const [notice, setNotice] = useState('');
const [searchAttempted, setSearchAttempted] = useState(false);
const [searchTerritory, setSearchTerritory] = useState(territorySelection);
const form = useForm({
category: filters.category ?? '',
@@ -93,6 +94,12 @@ function Index({
const searchReady = Boolean(
form.data.need && (form.data.territory || form.data.province_id),
);
const missingSearchCriteria = [
...(!form.data.need ? ['Seleccione a necessidade do processo.'] : []),
...(!(form.data.territory || form.data.province_id)
? ['Seleccione a província ou outra localização de interesse.']
: []),
];
const typeAllowed = (category: string, type: string) =>
!category ||
category === 'other' ||
@@ -118,7 +125,18 @@ function Index({
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();
if (!searchReady) return;
if (!searchReady) {
setSearchAttempted(true);
const target = !form.data.need
? e.currentTarget?.querySelector<HTMLElement>(
'[name="need"]',
)
: e.currentTarget?.querySelector<HTMLElement>(
'[data-funding-location] input[role="combobox"]',
);
target?.focus();
return;
}
form.get('/fundos');
}}
>
@@ -257,13 +275,21 @@ function Index({
tal
</label>
<label>
Necessidade do processo
Necessidade do processo (obrigatória)
<select
name="need"
aria-label="Necessidade do processo"
aria-invalid={
(searchAttempted && !form.data.need) || undefined
}
aria-describedby={
!searchReady ? 'funding-search-minimum' : undefined
}
className="block rounded border p-2"
value={form.data.need}
onChange={(e) => form.setData('need', e.target.value)}
>
<option value="">Todas / por identificar</option>
<option value="">Seleccione a necessidade</option>
{Object.entries(needs).map(([id, label]) => (
<option key={id} value={id}>
{label}
@@ -314,9 +340,16 @@ function Index({
))}
</select>
</label>
<fieldset className="min-w-0 basis-full">
<fieldset
data-funding-location
className="min-w-0 basis-full"
aria-describedby={
!searchReady ? 'funding-search-minimum' : undefined
}
>
<legend>
Local de interesse — seleccione até ao nível conhecido
Local de interesse (obrigatório) — seleccione até ao
nível conhecido
</legend>
<label>
Localização a pesquisar
@@ -411,19 +444,34 @@ function Index({
</select>
</label>
{!searchReady && (
<p id="funding-search-minimum" role="status">
Escolha a localização a pesquisar e a necessidade do
processo antes de pesquisar.
</p>
<div
id="funding-search-minimum"
role={searchAttempted ? 'alert' : 'status'}
className={
searchAttempted
? 'basis-full rounded border border-amber-600 p-3'
: 'basis-full text-sm'
}
>
{searchAttempted && (
<p className="font-semibold">
A pesquisa não foi executada. Complete os campos
indicados.
</p>
)}
{missingSearchCriteria.map((message) => (
<p key={message}>{message}</p>
))}
</div>
)}
<button
className={button}
disabled={form.processing || !searchReady}
disabled={form.processing}
aria-describedby={
!searchReady ? 'funding-search-minimum' : undefined
}
>
Pesquisar
{form.processing ? 'A pesquisar…' : 'Pesquisar'}
</button>
</form>
{criteriaChanged && (
+2 -3
View File
@@ -348,11 +348,10 @@ function Stage({ step, path }: { step: Step; path: Path }) {
licensing ? 'font-semibold' : 'cursor-pointer underline'
}
>
Fonte e referência desta etapa
Enquadramento desta etapa
</ReferenceHeading>
<p>
Referência interna {step.code}. Documento original,
parágrafo {step.source_paragraph}.{' '}
Etapa: {step.title}.{' '}
{step.detail.scope === 'internal_validation'
? 'Conferência interna; não equivale a decisão externa.'
: step.detail.scope === 'external_document_recorded'