Entrega dashboard e correccoes transversais preservando Ofertas instalado
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-15 18:56:39 +02:00
parent 1349789226
commit fb076c174f
117 changed files with 10380 additions and 1905 deletions
@@ -71,12 +71,14 @@ export function AcquisitionClosure({
);
return (
<details className="rounded border p-3">
<summary>L3-A/B — crédito,fecho e pagamentos por período</summary>
<summary>
IVA — crédito, apuramento e valores documentados por período
</summary>
<p>
Reutiliza resultados congelados de L2. Crédito anterior,saldo
calculado,pagamento registado e transporte são distintos.
Identifique o âmbito fiscal da entidade,sem consolidar
oportunidades implicitamente.
Reutiliza os resultados guardados das aquisições. Crédito
anterior, saldo calculado,pagamento registado e transporte são
distintos. Identifique o âmbito fiscal da entidade,sem
consolidar oportunidades implicitamente.
</p>
<p>
Primeira declaração em prazo,2026/MZN e reporte integral ou
@@ -0,0 +1,70 @@
import { useId, useState } from 'react';
import TerritorySearchSelect from './territory-search-select';
import { matchesChoice } from '@/lib/catalogue-choice';
export type CatalogueChoice = {
value: string;
label: string;
keywords?: string[];
};
export default function CatalogueChoiceSelect({
options,
value,
onChange,
label,
id,
disabled = false,
required = false,
error,
className,
}: {
options: CatalogueChoice[];
value: string;
onChange: (value: string) => void;
label: string;
id?: string;
disabled?: boolean;
required?: boolean;
error?: string;
className?: string;
}) {
const generated = useId();
const [search, setSearch] = useState('');
const selected = options.find((o) => o.value === value);
return (
<TerritorySearchSelect
id={id ?? generated}
label={label}
search={search}
onSearch={setSearch}
selected={
value
? {
id: value,
name:
selected?.label ??
`${value} — valor anterior; confirme a selecção`,
}
: undefined
}
options={options
.filter((o) =>
matchesChoice(search, [
o.value,
o.label,
...(o.keywords ?? []),
]),
)
.map((o) => ({ id: o.value, name: o.label }))}
onChange={(o) => onChange(o?.id ?? '')}
disabled={disabled}
required={required}
error={error}
className={
className ??
'bg-background text-foreground w-full rounded border p-2'
}
placeholder={`Seleccionar ou pesquisar ${label.toLowerCase()}`}
/>
);
}
@@ -21,7 +21,8 @@ export default function CatalogueNavigation({
dimensionUrl
)
return dimensionUrl(u.searchParams.get('dimension')!);
if (context) u.searchParams.set('context', context);
if (context && ['/oportunidades', '/educacao'].includes(u.pathname))
u.searchParams.set('context', context);
return searchTerritoryHref(u.pathname + u.search, url);
};
const sections = {
@@ -1,5 +1,6 @@
import { forceLabels, forces } from '@/lib/cluster-competitiveness';
import type { CompetitivenessDraft } from '@/lib/cluster-competitiveness';
import EvidenceDetails from './evidence-details';
export type ApprovedCompetitiveness = {
draft: CompetitivenessDraft;
@@ -27,9 +28,13 @@ export default function ClusterCompetitivenessPublic({
Competitividade — cinco forças de Porter
</h2>
<p>
{analysis.draft.sector} · {analysis.draft.region} · Versão
aprovada {analysis.version} · {analysis.at}
{analysis.draft.sector} · {analysis.draft.region}
</p>
<EvidenceDetails title="Versão e data da análise">
<p>
Versão aprovada {analysis.version} · {analysis.at}
</p>
</EvidenceDetails>
<p>
Apreciação qualitativa fundamentada nas fontes e períodos
indicados. Não representa garantia de procura ou viabilidade.
@@ -55,14 +60,18 @@ export default function ClusterCompetitivenessPublic({
'Oportunidade e fundamento',
],
] as const
).map(([field, label]) => (
<div key={field}>
<dt className="font-semibold">{label}</dt>
<dd className="whitespace-pre-wrap">
{row[field]}
</dd>
</div>
))}
)
.filter(([field]) => row[field]?.trim())
.map(([field, label]) => (
<div key={field}>
<dt className="font-semibold">
{label}
</dt>
<dd className="whitespace-pre-wrap">
{row[field]}
</dd>
</div>
))}
</dl>
</details>
);
+15 -75
View File
@@ -1,7 +1,5 @@
import { useId, useState } from 'react';
import CatalogueChoiceSelect from './catalogue-choice-select';
export type Country = { code: string; name: string; name_en: string };
export default function CountrySelect({
countries,
value,
@@ -10,7 +8,6 @@ export default function CountrySelect({
disabled = false,
label = 'País',
required = false,
allowLegacyValue = false,
error,
}: {
countries: Country[];
@@ -23,77 +20,20 @@ export default function CountrySelect({
allowLegacyValue?: boolean;
error?: string;
}) {
const generatedId = useId();
const [search, setSearch] = useState('');
const matches = countries.filter(
(country) =>
country.code === value ||
`${country.name} ${country.name_en} ${country.code}`
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase()
.includes(
search
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase(),
),
);
return (
<div className="space-y-2">
<input
disabled={disabled}
className="w-full rounded border p-2"
aria-label={`Pesquisar ${label.toLowerCase()}`}
maxLength={100}
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Pesquisar nome ou código do país"
/>
{search.trim() && (
<p role="status" aria-live="polite">
Países:{' '}
{matches.length
? `${matches.length} opções disponíveis`
: 'Nenhuma opção encontrada'}
</p>
)}
<select
disabled={disabled}
id={id ?? generatedId}
aria-label={label}
aria-invalid={!!error}
aria-describedby={
error ? (id ?? generatedId) + '-error' : undefined
}
required={required}
className="w-full rounded border p-2"
value={value}
onChange={(event) => onChange(event.target.value)}
>
<option value="">Não informado</option>
{allowLegacyValue &&
value &&
!countries.some((country) => country.code === value) && (
<option value={value}>
{value} (valor anterior conservado)
</option>
)}
{matches.map((country) => (
<option key={country.code} value={country.code}>
{country.name} ({country.code})
</option>
))}
</select>
{error && (
<p
id={(id ?? generatedId) + '-error'}
role="alert"
className="text-red-700"
>
{error}
</p>
)}
</div>
<CatalogueChoiceSelect
options={countries.map((c) => ({
value: c.code,
label: `${c.name} — ${c.code}`,
keywords: [c.name_en, c.code],
}))}
value={value}
onChange={onChange}
id={id}
label={label}
disabled={disabled}
required={required}
error={error}
/>
);
}
@@ -0,0 +1,24 @@
import CatalogueChoiceSelect from './catalogue-choice-select';
import { currencyChoices } from '@/lib/catalogue-choice';
export default function CurrencySelect({
codes,
...props
}: {
codes?: readonly string[];
value: string;
onChange: (value: string) => void;
label?: string;
id?: string;
disabled?: boolean;
required?: boolean;
error?: string;
className?: string;
}) {
return (
<CatalogueChoiceSelect
{...props}
label={props.label ?? 'Moeda'}
options={currencyChoices(codes)}
/>
);
}
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import DemographicEvidence, {
type DemographicAnalysis,
} from './demographic-evidence';
@@ -8,10 +8,17 @@ export default function DemographicContext({
}: {
territoryId?: string | null;
}) {
if (!territoryId) return null;
// A change of territory resets this consultation, never the investor's dossier.
return <TerritoryDemography key={territoryId} territoryId={territoryId} />;
}
function TerritoryDemography({ territoryId }: { territoryId: string }) {
const [evidence, setEvidence] = useState<DemographicAnalysis | null>(null);
const [message, setMessage] = useState('');
const [busy, setBusy] = useState(false);
if (!territoryId) return null;
const pending = useRef<AbortController | null>(null);
useEffect(() => () => pending.current?.abort(), []);
return (
<details className="rounded border p-4">
<summary>Demografia na análise de viabilidade</summary>
@@ -26,20 +33,35 @@ export default function DemographicContext({
onClick={async () => {
setBusy(true);
setMessage('');
setEvidence(null);
pending.current?.abort();
const controller = new AbortController();
pending.current = controller;
try {
const response = await fetch(
`/api/v1/investment/demography?territories[]=${encodeURIComponent(territoryId)}`,
{ headers: { Accept: 'application/json' } },
`/api/v1/investment/demography?investment_context=1&territories[]=${encodeURIComponent(territoryId)}`,
{
headers: { Accept: 'application/json' },
signal: controller.signal,
},
);
if (!response.ok)
throw new Error('Consulta indisponível.');
setEvidence(await response.json());
const result = await response.json();
if (!controller.signal.aborted) {
setEvidence(result);
if (result.broader_context)
setMessage(
'Contexto administrativo mais amplo. Estes indicadores não representam a população da localidade escolhida.',
);
}
} catch {
if (controller.signal.aborted) return;
setMessage(
'Não foi possível consultar a evidência demográfica.',
);
} finally {
setBusy(false);
if (!controller.signal.aborted) setBusy(false);
}
}}
>
+194 -89
View File
@@ -1,4 +1,8 @@
import EvidenceDetails from './evidence-details';
import DemographicReadingSummary from './demographic-reading-summary';
export type DemographicAnalysis = {
sector?: string;
state: string;
start_year: number;
end_year: number;
@@ -59,6 +63,24 @@ const indicators: Record<string, string> = {
fertility_rate: 'Fecundidade',
population_growth_rate: 'Crescimento populacional',
};
type Value =
DemographicAnalysis['territories'][number]['series'][number]['values'][number];
export function demographicHighlights(values: Value[]): Value[] {
const totals = values.filter(
(v) => v.age_group === 'all' && v.residence === 'all',
);
// Never add age groups, choose between sources or mix observed/projected values.
return totals.filter(
(v) =>
!totals.some(
(other) =>
other.indicator === v.indicator &&
other.unit === v.unit &&
other.data_kind === v.data_kind &&
other.year > v.year,
),
);
}
export default function DemographicEvidence({
evidence,
}: {
@@ -66,8 +88,17 @@ export default function DemographicEvidence({
}) {
return (
<section className="space-y-4" aria-label="Evidência demográfica">
<p className="text-sm">
Os indicadores demográficos não demonstram procura ou
rentabilidade. Cruze-os com oferta existente, acessos, custos e
procura documentada.
</p>
{evidence.state !== 'available' && (
<p>Sem séries demográficas aprovadas para esta selecção.</p>
<p>
Sem indicadores disponíveis para esta selecção. Isto não
significa população inexistente nem ausência de potencial
económico.
</p>
)}
{evidence.territories.map((t) => (
<article
@@ -85,101 +116,175 @@ export default function DemographicEvidence({
<p>Sem dados no período escolhido.</p>
)}
{t.series.map((s) => (
<details key={s.import_id} open={t.series.length === 1}>
<summary>
{s.source} · {s.version} · {s.file_name}
</summary>
<p className="text-xs break-all">
SHA256: {s.sha256}
</p>
<section key={s.import_id} className="space-y-3">
<h3 className="font-semibold">{s.source}</h3>
<DemographicReadingSummary
series={s}
evidence={evidence}
/>
{demographicHighlights(s.values).some(
(v) => v.indicator !== 'population',
) && (
<>
<h4 className="font-semibold">
Outros indicadores mais recentes do
período
</h4>
<dl className="grid gap-3 sm:grid-cols-2">
{demographicHighlights(s.values)
.filter(
(v) =>
v.indicator !==
'population',
)
.map((v) => (
<div
className="rounded border p-3"
key={`${v.sheet}:${v.cell}`}
>
<dt>
{indicators[
v.indicator
] ?? v.indicator}{' '}
· {v.year}
</dt>
<dd className="text-lg font-semibold">
{v.original_value}{' '}
{v.unit ===
'unspecified'
? '(unidade não indicada)'
: v.unit}
</dd>
<dd className="text-sm">
{v.data_kind ===
'projected'
? 'Projecção'
: 'Tipo estatístico não especificado'}
</dd>
{v.validation_status !==
'valid' && (
<dd className="text-sm">
Valor com
advertência na
fonte; consulte o
detalhe antes de o
utilizar.
</dd>
)}
</div>
))}
</dl>
</>
)}
{s.missing_years.length > 0 && (
<p>
Anos sem dados: {s.missing_years.join(', ')}
. Não foram preenchidos por estimativa.
</p>
)}
{Object.keys(s.issue_counts).length > 0 && (
<details>
<summary>Advertências da série</summary>
<pre className="overflow-auto text-xs">
{JSON.stringify(
s.issue_counts,
null,
2,
)}
</pre>
</details>
{(Object.keys(s.issue_counts).length > 0 ||
s.values.some(
(v) => v.validation_status !== 'valid',
)) && (
<p>
Esta série contém advertências. Consulte-as
antes de comparar ou utilizar os valores.
</p>
)}
<div className="max-h-96 overflow-auto">
<table className="w-full text-left text-sm">
<caption className="text-left">
Valores originais por ano e dimensão —
versões apresentadas separadamente
</caption>
<thead>
<tr>
{[
'Ano',
'Indicador',
'Idade',
'Residência',
'Valor',
'Unidade',
'Tipo',
'Referência',
].map((h) => (
<th className="p-2" key={h}>
{h}
</th>
))}
</tr>
</thead>
<tbody>
{s.values.map((v) => (
<tr
key={`${v.sheet}:${v.cell}`}
className="border-t"
>
<td className="p-2">
{v.year}
</td>
<td>
{indicators[v.indicator] ??
v.indicator}
</td>
<td>
{v.age_group === 'all'
? 'Todas'
: v.age_group}
</td>
<td>
{
{
all: 'Total',
urban: 'Urbana',
rural: 'Rural',
}[v.residence]
}
</td>
<td>{v.original_value}</td>
<td>
{v.unit === 'unspecified'
? 'Não indicada na fonte'
: v.unit}
</td>
<td>
{v.data_kind === 'projected'
? 'Projecção'
: 'Não especificado'}
</td>
<td>
{v.sheet}!{v.cell}
</td>
<EvidenceDetails title="Valores por dimensão, fonte e advertências">
<p>
{s.version} · {s.file_name}
</p>
<p className="text-xs break-all">
SHA256: {s.sha256}
</p>
{Object.keys(s.issue_counts).length > 0 && (
<details>
<summary>Advertências da série</summary>
<pre className="overflow-auto text-xs">
{JSON.stringify(
s.issue_counts,
null,
2,
)}
</pre>
</details>
)}
<div className="max-h-96 overflow-auto">
<table className="w-full min-w-[44rem] text-left text-sm whitespace-nowrap">
<caption className="text-left">
Valores originais por ano e dimensão
— versões apresentadas separadamente
</caption>
<thead>
<tr>
{[
'Ano',
'Indicador',
'Idade',
'Residência',
'Valor',
'Unidade',
'Tipo',
'Referência',
].map((h) => (
<th className="p-2" key={h}>
{h}
</th>
))}
</tr>
))}
</tbody>
</table>
</div>
</details>
</thead>
<tbody>
{s.values.map((v) => (
<tr
key={`${v.sheet}:${v.cell}`}
className="border-t"
>
<td className="p-2">
{v.year}
</td>
<td>
{indicators[
v.indicator
] ?? v.indicator}
</td>
<td>
{v.age_group === 'all'
? 'Todas'
: v.age_group}
</td>
<td>
{
{
all: 'Total',
urban: 'Urbana',
rural: 'Rural',
}[v.residence]
}
</td>
<td>{v.original_value}</td>
<td>
{v.unit ===
'unspecified'
? 'Não indicada na fonte'
: v.unit}
</td>
<td>
{v.data_kind ===
'projected'
? 'Projecção'
: 'Não especificado'}
</td>
<td>
{v.sheet}!{v.cell}
</td>
</tr>
))}
</tbody>
</table>
</div>
</EvidenceDetails>
</section>
))}
</article>
))}
@@ -0,0 +1,159 @@
import type { DemographicAnalysis } from './demographic-evidence';
import {
demographicReading,
populationLabel,
percentageLabel,
} from '@/lib/demographic-reading';
export default function DemographicReadingSummary({
series,
evidence,
}: {
series: DemographicAnalysis['territories'][number]['series'][number];
evidence: DemographicAnalysis;
}) {
const reading = demographicReading(
series,
evidence.start_year,
evidence.end_year,
);
const current = reading.last;
const sector = evidence.sector ?? 'general';
return (
<section
className="space-y-4 rounded-lg bg-slate-50 p-4"
aria-label="Leitura para o investimento"
>
<h3 className="font-semibold">
Retrato da população · {evidence.end_year}
</h3>
<p className="text-sm">
{series.source} ·{' '}
{current.kind === 'projected'
? 'Projecção'
: 'Tipo de dado não especificado'}
. Valores de apresentação arredondados; os originais permanecem
disponíveis abaixo.
</p>
<dl className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{[
[
'População total',
populationLabel(current.total),
'pessoas',
],
[
'População rural',
populationLabel(current.rural),
percentageLabel(current.ruralShare) + ' do total',
],
[
'Menores de 15 anos',
populationLabel(current.under15),
percentageLabel(current.under15Share) + ' do total',
],
[
'População de 15 a 64 anos',
populationLabel(current.age15to64),
percentageLabel(current.age15to64Share) + ' do total',
],
].map(([label, value, note]) => (
<div key={label} className="rounded border bg-white p-3">
<dt className="text-sm">{label}</dt>
<dd className="text-2xl font-semibold">{value}</dd>
<dd className="text-sm text-slate-600">{note}</dd>
</div>
))}
</dl>
{evidence.start_year === evidence.end_year ? (
<p>
Está a consultar um único ano. Escolha um ano final
posterior para conhecer a evolução projectada.
</p>
) : (
<div>
<h4 className="font-semibold">
Evolução entre {evidence.start_year} e{' '}
{evidence.end_year}
</h4>
{reading.delta === null ? (
<p>
Faltam totais comparáveis nos anos extremos; não foi
calculado crescimento.
</p>
) : (
<p>
{populationLabel(reading.first.total)} →{' '}
{populationLabel(reading.last.total)} pessoas.
Variação no período:{' '}
{populationLabel(reading.delta)} pessoas (
{percentageLabel(reading.growth)}). Não é uma taxa
anual.
</p>
)}
<details>
<summary>Série anual de população</summary>
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead>
<tr>
<th>Ano</th>
<th>Total</th>
<th>Urbana</th>
<th>Rural</th>
</tr>
</thead>
<tbody>
{reading.years.map((y) => (
<tr key={y.year}>
<td>{y.year}</td>
<td>{populationLabel(y.total)}</td>
<td>{populationLabel(y.urban)}</td>
<td>{populationLabel(y.rural)}</td>
</tr>
))}
</tbody>
</table>
</div>
</details>
</div>
)}
<div className="space-y-2">
<h4 className="font-semibold">
Como usar estes dados na ideia de investimento
</h4>
{current.ruralShare !== null && (
<p>
{percentageLabel(current.ruralShare)} da população está
em áreas rurais. Para avaliar distribuição, comércio ou
serviços, confronte essa dispersão com acessos,
distâncias, custos de entrega e oferta existente.
</p>
)}
{current.under15Share !== null &&
['general', 'education', 'health'].includes(sector) && (
<p>
Os menores de 15 anos representam{' '}
{percentageLabel(current.under15Share)} do total. É
uma base para estudar serviços educativos e de
saúde, cruzando população-alvo, capacidade
instalada, acessibilidade e rendimento das famílias.
</p>
)}
{current.age15to64 !== null && (
<p>
As {populationLabel(current.age15to64)} pessoas entre 15
e 64 anos ajudam a dimensionar a população nessa faixa
etária. Para planear contratações, faltam qualificações,
participação no mercado de trabalho e disponibilidade.
</p>
)}
<p>
Próximo passo: comparar estes indicadores com empresas e
serviços existentes, infra-estruturas, preços e procura
documentada. Só essa comparação permite fundamentar uma
lacuna de mercado.
</p>
</div>
</section>
);
}
@@ -7,6 +7,10 @@ import {
type ReactNode,
} from 'react';
import { contextApi, type DossierContext } from '@/lib/investor-context';
import {
readNavigationFocus,
rememberNavigationFocus,
} from '@/lib/navigation-focus';
export type NavigationView = {
case: { id: string; title: string; version: number };
phases: Record<string, string>;
@@ -129,7 +133,15 @@ export function NavigationContextProvider({
new URL(url, 'https://context.invalid').searchParams.get(
'context',
);
let focus = pref.focus;
const localFocus = readNavigationFocus(
actor,
listing.contexts.map((c) => c.id),
);
// The server preference seeds a new tab, but another tab cannot
// replace this tab's deliberate dossier choice on navigation/reload.
let focus = localFocus
? { ...localFocus, version: pref.focus?.version ?? 0 }
: pref.focus;
const code = /^#S(0[1-9]|1[0-9])$/.test(window.location.hash)
? window.location.hash.slice(1)
: null;
@@ -157,6 +169,7 @@ export function NavigationContextProvider({
)
: null;
if (!stopped) {
rememberNavigationFocus(actor, focus);
setLoaded({ actor, cases: listing.contexts, focus, view });
if (pref.message) setError(pref.message);
}
@@ -182,16 +195,22 @@ export function NavigationContextProvider({
if (!actor || !current?.cases.some((c) => c.id === id)) return;
setBusy(true);
setError('');
void contextApi(
void contextApi<{ focus: Focus | null }>(
'/investimentos/contexto-atual',
{
case_id: id,
step_code: step,
version: current.focus?.version ?? 0,
},
'PUT',
)
.then(() => {
.then((pref) =>
contextApi<{ focus: Focus }>(
'/investimentos/contexto-atual',
{
case_id: id,
step_code: step,
version: pref.focus?.version ?? 0,
},
'PUT',
),
)
.then(({ focus }) => {
rememberNavigationFocus(actor, focus);
const target = `/investimentos/${id}${step ? '#' + step : ''}`;
if (url !== target) router.visit(target);
else setReload((x) => x + 1);
+1 -1
View File
@@ -32,7 +32,7 @@ const empty = (v: unknown) =>
v === '' ||
(Array.isArray(v) && v.length === 0);
const text = (v: unknown) =>
typeof v === 'string' ? v : JSON.stringify(v ?? '');
empty(v) ? '' : typeof v === 'string' ? v : JSON.stringify(v);
function savedOpportunity(values: Record<string, unknown>): string {
if (values.context_opportunity)
return inputText(values.context_opportunity);
@@ -0,0 +1,20 @@
import type { ReactNode } from 'react';
/** Keep provenance available without making it the investor's primary content. */
export default function EvidenceDetails({
children,
title = 'Fontes e detalhes da informação',
}: {
children: ReactNode;
title?: string;
}) {
if (!children) return null;
return (
<details className="min-w-0 rounded-lg border border-slate-200 p-3 text-sm [overflow-wrap:anywhere]">
<summary className="cursor-pointer font-semibold focus-visible:outline-2 focus-visible:outline-offset-2">
{title}
</summary>
<div className="mt-3 min-w-0 space-y-3">{children}</div>
</details>
);
}
@@ -14,7 +14,7 @@ export function FiscalL3Preparation({
if (!forms.length) return null;
return (
<details className="rounded border p-3">
<summary>Preparação dos quadros L3 e formalidades</summary>
<summary>Correspondência documental e formalidades</summary>
<p>
Reutiliza entradas e resultados congelados. Os campos com
correspondência identificada ficam preparados para
@@ -0,0 +1,86 @@
import type { ReactNode } from 'react';
import CatalogueChoiceSelect from '@/components/catalogue-choice-select';
export default function FiscalOperationPicker({
family,
selected,
operations,
onChange,
}: {
family: string;
selected: unknown;
operations: {
id: string;
label: string;
description: string;
render: () => ReactNode;
}[];
onChange: (selected: string[]) => void;
}) {
const saved = Array.isArray(selected)
? selected.filter((id): id is string => typeof id === 'string')
: [];
const chosen = operations.filter((operation) =>
saved.includes(`${family}:${operation.id}`),
);
return (
<section
className="space-y-4 rounded border p-4"
aria-label="Operações fiscais adicionais"
>
<h4 className="font-semibold">Operações que pretende analisar</h4>
<p>
Acrescente apenas as operações que prevê realizar. Se não sabe
se uma operação se aplica, consulte a orientação e conserve-a
por confirmar; o sector, por si só, não determina o
enquadramento.
</p>
<CatalogueChoiceSelect
label="Adicionar outra operação"
value=""
options={operations
.filter(
(operation) =>
!saved.includes(`${family}:${operation.id}`),
)
.map((operation) => ({
value: operation.id,
label: operation.label,
keywords: [operation.description],
}))}
onChange={(id) => {
if (operations.some((operation) => operation.id === id))
onChange([...saved, `${family}:${id}`]);
}}
/>
{!chosen.length && (
<p>
Nenhuma operação adicional escolhida. As preparações e os
resultados anteriormente guardados permanecem no rascunho e
no histórico.
</p>
)}
{chosen.map((operation) => (
<section key={operation.id} className="space-y-3 border-t pt-3">
<h5 className="font-semibold">{operation.label}</h5>
<p>{operation.description}</p>
<button
type="button"
className="underline"
onClick={() =>
onChange(
saved.filter(
(id) => id !== `${family}:${operation.id}`,
),
)
}
>
Retirar da análise actual, conservando os dados
guardados
</button>
{operation.render()}
</section>
))}
</section>
);
}
@@ -0,0 +1,63 @@
import CurrencySelect from './currency-select';
/** A planning interval is not the amount used in a financial calculation. */
export default function InvestmentBudgetRange({
values,
onChange,
}: {
values: Record<string, string>;
onChange?: (field: string, value: string) => void;
}) {
if (
!onChange &&
!values.investment_budget_min &&
!values.investment_budget_max
)
return null;
return (
<section className="grid gap-3 rounded border p-4">
<h3 className="font-semibold">Orçamento previsto</h3>
{onChange ? (
<>
<div className="grid gap-3 sm:grid-cols-2">
{(
[
'investment_budget_min',
'investment_budget_max',
] as const
).map((field, index) => (
<label key={field} className="grid gap-1">
{index === 0 ? 'Desde' : 'Até'}
<input
className="min-w-0 rounded border p-2"
type="number"
min="0"
step="any"
value={values[field] ?? ''}
onChange={(event) =>
onChange(field, event.target.value)
}
/>
</label>
))}
</div>
<CurrencySelect
label="Moeda do orçamento"
value={values.currency ?? ''}
onChange={(value) => onChange('currency', value)}
/>
</>
) : (
<p>
{values.investment_budget_min || 'Mínimo por indicar'} –{' '}
{values.investment_budget_max || 'Máximo por indicar'}{' '}
{values.currency}
</p>
)}
<p className="text-muted-foreground text-sm">
Este intervalo orienta a preparação. O valor de cada cenário de
investimento será indicado por si no simulador.
</p>
</section>
);
}
@@ -0,0 +1,159 @@
import { useState } from 'react';
import { sumFinancialAmounts } from '@/lib/financial-calculators';
type Row = { label: string; amount: string };
const initialRows = (): Row[] =>
[
'Instalações',
'Equipamentos',
'Preparação e arranque',
'Fundo de maneio inicial',
].map((label) => ({ label, amount: '' }));
export function restoreInitialBudget(snapshot: string): Row[] {
try {
const parsed = JSON.parse(snapshot);
if (
parsed.version === 1 &&
Array.isArray(parsed.rows) &&
parsed.rows.length <= 30 &&
parsed.rows.every(
(row: Row) =>
typeof row?.label === 'string' &&
row.label.length <= 120 &&
typeof row.amount === 'string' &&
row.amount.length <= 40,
)
)
return parsed.rows;
} catch {
/* Preserve the saved original; no invented amounts. */
}
return initialRows();
}
export default function InvestmentInitialBudget({
snapshot,
currency,
onChange,
}: {
snapshot: string;
currency: string;
onChange: (key: string, value: string) => void;
}) {
const [rows, setRows] = useState(() => restoreInitialBudget(snapshot));
const [message, setMessage] = useState('');
const save = (next: Row[]) => {
setRows(next);
setMessage('');
onChange(
'initial_budget_snapshot',
JSON.stringify({ version: 1, rows: next }),
);
};
return (
<section
className="space-y-3 rounded border p-4"
aria-label="Construir orçamento inicial"
>
<h3 className="font-semibold">
Ajuda para construir o investimento inicial
</h3>
<p>
Liste apenas os custos iniciais aplicáveis. O fundo de maneio
cobre o arranque; não repita aqui custos já incluídos noutra
parcela. Um valor desconhecido fica em branco, não é zero.
</p>
{rows.map((row, index) => (
<div key={index} className="grid gap-2 sm:grid-cols-2">
<label>
Parcela
<input
className="block w-full rounded border p-2"
maxLength={120}
value={row.label}
onChange={(e) =>
save(
rows.map((item, i) =>
i === index
? { ...item, label: e.target.value }
: item,
),
)
}
/>
</label>
<label>
Montante {currency}
<input
className="block w-full rounded border p-2"
type="number"
min="0"
step="0.01"
value={row.amount}
onChange={(e) =>
save(
rows.map((item, i) =>
i === index
? {
...item,
amount: e.target.value,
}
: item,
),
)
}
/>
</label>
<button
type="button"
className="text-left underline"
onClick={() => save(rows.filter((_, i) => i !== index))}
>
Retirar parcela não aplicável
</button>
</div>
))}
<button
type="button"
className="mr-3 rounded border px-3 py-2"
disabled={rows.length >= 30}
onClick={() => save([...rows, { label: '', amount: '' }])}
>
Acrescentar parcela
</button>
<button
type="button"
className="rounded border px-3 py-2"
onClick={() => {
try {
if (
!currency ||
!rows.length ||
rows.some(
(row) =>
!row.label.trim() || !row.amount.trim(),
)
)
throw new Error(
'Indique a moeda e as parcelas conhecidas; complete os montantes em falta antes de usar a soma.',
);
const total = sumFinancialAmounts(
rows.map((row) => row.amount),
);
onChange('total_investment', total);
setMessage(
`Soma adoptada por sua escolha: ${total} ${currency}. O intervalo orçamental original permanece separado.`,
);
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Confira as parcelas.',
);
}
}}
>
Usar a soma como investimento deste cenário
</button>
{message && <p role="status">{message}</p>}
</section>
);
}
@@ -0,0 +1,267 @@
import { useState } from 'react';
import {
estimateOperatingCosts,
estimateOperatingRevenue,
restoreOperatingAssumptions,
} from '@/lib/investment-operating-assistance';
export default function InvestmentOperatingAssistance({
snapshot,
currency,
onChange,
}: {
snapshot: string;
currency: string;
onChange: (key: string, value: string) => void;
}) {
const [data, setData] = useState(() =>
restoreOperatingAssumptions(snapshot),
);
const [message, setMessage] = useState('');
const save = (next: typeof data) => {
setData(next);
setMessage('');
onChange(
'planning_assumptions_snapshot',
JSON.stringify({ version: 1, data: next }),
);
};
const field = (
key: 'capacity' | 'price' | 'occupancy' | 'frequency',
label: string,
) => (
<label className="block">
{label}
<input
className="block w-full rounded border p-2"
type="number"
min="0"
step="0.01"
value={data[key]}
onChange={(e) => save({ ...data, [key]: e.target.value })}
/>
</label>
);
const adopt = (kind: 'revenue' | 'costs') => {
try {
if (!currency)
throw new Error(
'Seleccione a moeda do investimento antes de utilizar a estimativa.',
);
const value =
kind === 'revenue'
? estimateOperatingRevenue(data)
: estimateOperatingCosts(data);
onChange(
kind === 'revenue'
? 'annual_revenue'
: 'annual_operating_costs',
value,
);
setMessage(
`Estimativa anual de ${kind === 'revenue' ? 'receitas' : 'custos'} adoptada por sua escolha: ${value} ${currency}. Pode alterá-la nos campos acima.`,
);
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Confira os pressupostos.',
);
}
};
return (
<section
className="space-y-4 rounded border p-4"
aria-label="Ajuda para estimar receitas e custos"
>
<h3 className="font-semibold">
Não sei estimar receitas ou custos
</h3>
<p>
Escolha a actividade e introduza os pressupostos que conhece.
Não são previsões de procura nem valores recomendados. Nenhuma
estimativa substitui os seus valores até clicar em Usar.
</p>
<label className="block">
Modelo para esta estimativa
<select
className="block w-full rounded border p-2"
value={data.model}
onChange={(e) =>
save({
...data,
model: e.target.value as typeof data.model,
})
}
>
<option value="">Escolher</option>
<option value="hotel">Hotel — quartos e ocupação</option>
<option value="agriculture">
Agronegócio — produção e ciclos
</option>
<option value="other">
Outra actividade — unidades e frequência
</option>
</select>
</label>
{data.model && (
<>
<div className="grid gap-3 sm:grid-cols-2">
{field(
'capacity',
data.model === 'hotel'
? 'Quartos disponíveis'
: 'Unidades vendáveis por ciclo ou período',
)}
{field(
'price',
data.model === 'hotel'
? 'Preço por quarto/noite'
: 'Preço por unidade',
)}
{data.model === 'hotel' &&
field('occupancy', 'Ocupação prevista (%)')}
{field(
'frequency',
data.model === 'hotel'
? 'Dias de funcionamento previstos no ano'
: 'Ciclos ou períodos no ano',
)}
</div>
<p className="text-sm">
{data.model === 'hotel'
? 'Receita anual = quartos × dias de funcionamento × ocupação ÷ 100 × preço. Considere sazonalidade ao escolher a ocupação e os dias.'
: 'Receita anual = unidades vendáveis × preço × ciclos. Considere perdas e sazonalidade nas unidades e ciclos declarados.'}{' '}
A facturação não equivale a recebimentos; a próxima
etapa trata a tesouraria.
</p>
<label className="block">
Fundamento ou informação ainda a confirmar
<textarea
className="block w-full rounded border p-2"
maxLength={1000}
value={data.source}
onChange={(e) =>
save({ ...data, source: e.target.value })
}
/>
</label>
<button
type="button"
className="rounded border px-3 py-2"
onClick={() => adopt('revenue')}
>
Usar esta estimativa de receitas
</button>
<details className="rounded border p-3">
<summary>Categorias de custos anuais</summary>
<p>
{data.model === 'hotel'
? 'Considere pessoal, limpeza/lavandaria, energia, água, manutenção, consumíveis e distribuição.'
: data.model === 'agriculture'
? 'Considere insumos, pessoal, água/energia, armazenagem, transformação, transporte e perdas.'
: 'Considere pessoal, matérias-primas, serviços, instalações, energia, manutenção e distribuição.'}{' '}
Acrescente apenas categorias aplicáveis; a soma não
demonstra que todos os custos foram identificados.
</p>
{data.costs.map((row, index) => (
<div
className="my-3 grid gap-2 sm:grid-cols-2"
key={index}
>
<label>
Categoria
<input
className="block w-full rounded border p-2"
maxLength={120}
value={row.label}
onChange={(e) =>
save({
...data,
costs: data.costs.map(
(item, i) =>
i === index
? {
...item,
label: e
.target
.value,
}
: item,
),
})
}
/>
</label>
<label>
Estimativa anual
<input
className="block w-full rounded border p-2"
type="number"
min="0"
step="0.01"
value={row.annual}
onChange={(e) =>
save({
...data,
costs: data.costs.map(
(item, i) =>
i === index
? {
...item,
annual: e
.target
.value,
}
: item,
),
})
}
/>
</label>
<button
type="button"
className="text-left underline"
onClick={() =>
save({
...data,
costs: data.costs.filter(
(_, i) => i !== index,
),
})
}
>
Retirar esta categoria
</button>
</div>
))}
<button
type="button"
className="mr-3 rounded border px-3 py-2"
disabled={data.costs.length >= 30}
onClick={() =>
save({
...data,
costs: [
...data.costs,
{ label: '', annual: '' },
],
})
}
>
Acrescentar categoria
</button>
<button
type="button"
className="rounded border px-3 py-2"
onClick={() => adopt('costs')}
>
Usar esta estimativa de custos
</button>
</details>
</>
)}
{message && <p role="status">{message}</p>}
</section>
);
}
@@ -36,10 +36,16 @@ function ChoiceCard({
const [parkError, setParkError] = useState('');
const [parkLoading, setParkLoading] = useState(false);
const corridor =
corridors.find((r) => r.key === c.corridor_key) ||
corridors.find((r) => r.name === c.coverage);
c.corridor_key !== undefined
? corridors.find((r) => r.key === c.corridor_key)
: corridors.find((r) => r.name === c.coverage);
const path = c.territory_path ?? [];
function location(next: TerritoryOption[], key = corridor?.key) {
function location(
next: TerritoryOption[],
key: string | null | undefined = c.corridor_key !== undefined
? c.corridor_key
: corridor?.key,
) {
update({
corridor_key: key,
territory_path: next,
@@ -64,16 +70,8 @@ function ChoiceCard({
!corridor.provinces.some((p) => p.id === path[0].id)
) {
setNotice(
'A localização anterior foi retirada porque não pertence ao corredor escolhido. Escolha uma localização compatível.',
'Localizacao guardada conservada. A associacao ao corredor nao e compativel; altere-a ou retire-a antes de confirmar.',
);
location(corridor.provinces.length === 1 ? corridor.provinces : []);
} else if (!path.length && corridor.provinces.length === 1) {
setNotice(
'Província seleccionada automaticamente: ' +
corridor.provinces[0].name +
'.',
);
location(corridor.provinces);
}
}, [
corridor?.key,
@@ -140,33 +138,18 @@ function ChoiceCard({
const next = corridors.find(
(r) => r.key === e.target.value,
);
if (!next) return;
const compatible =
!path.length ||
next.provinces.some((p) => p.id === path[0].id);
const kept = compatible ? path : [];
location(
kept.length
? kept
: next.provinces.length === 1
? next.provinces
: [],
next.key,
);
update({
corridor_key: next?.key ?? null,
corridor_name: next?.name ?? null,
});
setNotice(
!path.length
? next.provinces.length === 1
? 'Província seleccionada automaticamente: ' +
next.provinces[0].name +
'.'
: 'Escolha uma das províncias deste corredor.'
: compatible
? 'A localização compatível foi conservada.'
: 'A província e os níveis territoriais incompatíveis foram retirados.',
'A localizacao foi conservada; a associacao e opcional e exige compatibilidade documentada.',
);
}}
>
<option value="">Seleccione um corredor</option>
<option value="">
Sem corredor associado (opcional)
</option>
{corridors.map((r) => (
<option key={r.key} value={r.key}>
{r.name}
@@ -381,7 +364,7 @@ export default function OpportunityChoices({
</h2>
<p>
{onChange
? 'Escolha o corredor e confirme onde pretende realizar o investimento.'
? 'Confirme a localização conhecida. Corredores e zonas são associações opcionais, quando documentadas.'
: 'Escolhas guardadas no dossier; cada oportunidade conserva a sua localização e associações.'}
</p>
{choices.map((c, i) => (
@@ -1,5 +1,6 @@
import { useEffect, useId } from 'react';
import CountrySelect, { type Country } from './country-select';
import CatalogueChoiceSelect from './catalogue-choice-select';
import OrganizationCountryReuse from './organization-country-reuse';
import { Field, input, button } from '@/pages/investment/shared';
import {
@@ -18,6 +19,7 @@ export default function InvestmentProfileEditor({
reportDirty,
labels,
organizations = [],
legalForms = [],
}: {
record: ProfileRecord;
fields: string[];
@@ -28,6 +30,7 @@ export default function InvestmentProfileEditor({
reportDirty: (id: string, dirty: boolean) => void;
labels: Record<string, string>;
organizations?: OrganizationRecord[];
legalForms?: { value: string; label: string }[];
}) {
const isCompany = company || !!record.id;
const editor = useInvestmentProfileEditor(
@@ -113,6 +116,18 @@ export default function InvestmentProfileEditor({
editor.change(key, value)
}
/>
) : key === 'legal_form' ? (
<CatalogueChoiceSelect
id={fieldId}
label={labels[key]}
options={legalForms}
value={editor.draft[key] ?? ''}
disabled={disabled}
error={error}
onChange={(value) =>
editor.change(key, value)
}
/>
) : long ? (
<textarea
id={fieldId}
@@ -0,0 +1,214 @@
import { useRef, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import CatalogueChoiceSelect from './catalogue-choice-select';
import { contextApi, type PromoterEntity } from '@/lib/investor-context';
import { createOperationKey } from '@/lib/operation-key';
type Options = {
version: number;
selected: PromoterEntity;
can_write: boolean;
companies: { id: string; name: string; version: number }[];
organizations: { id: string; name: string; version: number }[];
};
const valueOf = (entity?: PromoterEntity) =>
entity && ['company', 'organization'].includes(entity.kind)
? entity.kind + ':' + entity.id
: (entity?.kind ?? 'undetermined');
export default function InvestmentPromoter({
caseId,
selected,
canEdit,
}: {
caseId: string;
selected?: PromoterEntity;
canEdit: boolean;
}) {
const [options, setOptions] = useState<Options | null>(null);
const [choice, setChoice] = useState(valueOf(selected));
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [uncertain, setUncertain] = useState(false);
const command = useRef<Record<string, unknown> | null>(null);
const current = options?.selected ?? selected;
const url = `/investimentos/${caseId}/contexto/entidade`;
const recover = async () => {
setBusy(true);
setError('');
try {
setOptions(await contextApi<Options>(url));
command.current = null;
setUncertain(false);
} catch (error) {
setError(
error instanceof Error
? error.message
: 'Não foi possível consultar a associação.',
);
} finally {
setBusy(false);
}
};
return (
<section
id="entidade-promotora"
className="space-y-3 rounded border p-4"
>
<h2 className="font-semibold">Entidade promotora</h2>
<p>
{current?.snapshot?.name ||
(current?.kind === 'being_formed'
? 'Entidade por constituir'
: 'Entidade por definir')}
</p>
<p>
{current?.kind === 'company' || current?.kind === 'organization'
? 'Cadastro associado no portal. A associação não comprova constituição legal nem altera a propriedade ou o acesso ao dossier.'
: 'Pode continuar a ideia e a viabilidade. Os actos que dependam da entidade serão identificados na respectiva etapa.'}
</p>
<nav className="flex flex-wrap gap-3">
{canEdit && (
<Link
className="underline"
href={`/simulador-fiscal?context=${caseId}`}
>
Continuar a viabilidade
</Link>
)}
{current?.kind === 'being_formed' && (
<Link
className="underline"
href={`/investimentos/${caseId}/preparar-empresa`}
>
Continuar a preparação da empresa
</Link>
)}
{current?.kind !== 'company' &&
current?.kind !== 'organization' && (
<Link
className="underline"
href={`/investimentos/${caseId}/forma-juridica`}
>
Comparar formas jurídicas, se precisar
</Link>
)}
</nav>
{canEdit && (
<details
onToggle={(event) => {
if (event.currentTarget.open && !options && !busy)
void recover();
}}
>
<summary>Associar ou alterar a entidade promotora</summary>
{options && (
<div className="mt-3 grid gap-3">
<CatalogueChoiceSelect
label="Entidade para este investimento"
value={choice}
disabled={
busy || uncertain || !options.can_write
}
options={[
{
value: 'undetermined',
label: 'Continuar com entidade por definir',
},
{
value: 'being_formed',
label: 'Preparar uma entidade por constituir',
},
...options.companies.map((company) => ({
value: 'company:' + company.id,
label:
company.name +
' — empresa declarada',
})),
...options.organizations.map(
(organization) => ({
value:
'organization:' +
organization.id,
label:
organization.name +
' — organização com acesso autorizado',
}),
),
]}
onChange={(value) => {
setChoice(value || 'undetermined');
command.current = null;
}}
/>
<Link
className="underline"
href={`/investidor/profile?dossier=${caseId}`}
>
Registar uma empresa existente no cadastro
habitual e regressar
</Link>
<button
type="button"
className="min-h-11 rounded border p-2"
disabled={
busy || uncertain || !options.can_write
}
onClick={async () => {
setBusy(true);
setError('');
const [kind, id] = choice.split(':');
const source = (
kind === 'company'
? options.companies
: options.organizations
).find((source) => source.id === id);
command.current ??= {
version: options.version,
operation_key: createOperationKey(),
kind,
...(id
? {
id,
source_version:
source?.version,
}
: {}),
};
try {
const result = await contextApi<{
continue: string;
}>(url, command.current);
command.current = null;
router.visit(result.continue);
} catch (error) {
setUncertain(true);
setError(
error instanceof Error
? error.message
: 'Não foi possível confirmar a associação.',
);
} finally {
setBusy(false);
}
}}
>
Guardar associação e continuar
</button>
</div>
)}
{error && <p role="alert">{error}</p>}
{(error || uncertain) && (
<button
type="button"
className="underline"
disabled={busy}
onClick={() => void recover()}
>
Recuperar associação guardada sem perder a escolha
</button>
)}
</details>
)}
</section>
);
}
@@ -0,0 +1,172 @@
import { useRef, useState } from 'react';
import { router } from '@inertiajs/react';
import { contextApi, type SupplyAggregate } from '@/lib/investor-context';
import { createOperationKey } from '@/lib/operation-key';
export default function InvestmentSupplyAggregate({
caseId,
version,
revision,
history,
disabled = false,
}: {
caseId: string;
version: number;
revision: number;
history: SupplyAggregate[];
disabled?: boolean;
}) {
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState('');
const command = useRef<{ version: number; operation_key: string } | null>(
null,
);
const latest = history.at(-1);
return (
<section
className="space-y-3 rounded border p-4"
aria-label="Oferta empresarial agregada"
>
<h2 className="font-semibold">
Actividades existentes na localização
</h2>
<p>
Consulte uma análise agregada no seu dossier. As listas, nomes e
contactos internos permanecem reservados.
</p>
<button
type="button"
className="min-h-11 rounded border px-3 py-2 underline"
disabled={disabled || busy}
onClick={async () => {
if (busy) return;
setBusy(true);
setMessage('');
command.current ??= {
version,
operation_key: createOperationKey(),
};
try {
await contextApi(
`/investimentos/${caseId}/contexto/oferta-agregada`,
command.current,
);
command.current = null;
setMessage('Análise agregada guardada no dossier.');
router.reload({
only: [
'case',
'supply_aggregates',
'supply_aggregate_enabled',
],
});
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Não foi possível confirmar a consulta. A repetição conserva o mesmo comando.',
);
} finally {
setBusy(false);
}
}}
>
{busy
? 'A consultar…'
: command.current
? 'Repetir a mesma consulta'
: 'Consultar e guardar análise agregada'}
</button>
{message && <p role="status">{message}</p>}
{latest && (
<>
<h3 className="font-semibold">
{latest.scope.level === 'district'
? 'Contexto distrital'
: latest.scope.level === 'province'
? 'Contexto provincial'
: 'Contexto local'}{' '}
— {latest.scope.name}
</h3>
{latest.broader_context && (
<p>
Local escolhido: {latest.requested_territory.name}.
Os totais referem-se ao território mais amplo
indicado acima.
</p>
)}
<p>
{latest.entities} entidades identificadas nos registos
administrativos; {latest.repeated} observações repetidas
e {latest.uncertain} identificações incertas, separadas
dos totais.
</p>
{latest.context_revision !== revision && (
<p role="status">
O contexto mudou depois desta análise. Reveja-a; a
consulta anterior mantém-se no histórico.
</p>
)}
<div className="overflow-x-auto">
<table className="w-full">
<caption className="text-left">
Grupos para investigar actividades similares e
complementares
</caption>
<thead>
<tr>
<th className="p-2 text-left">
Actividade
</th>
<th className="p-2">Entidades</th>
<th className="p-2">Período conhecido</th>
</tr>
</thead>
<tbody>
{latest.groups.map((group) => (
<tr key={group.code}>
<td className="p-2">{group.label}</td>
<td className="p-2 text-center">
{group.total}
</td>
<td className="p-2">
{group.first_year ??
'Por confirmar'}
{group.last_year &&
group.last_year !== group.first_year
? '–' + group.last_year
: ''}
</td>
</tr>
))}
</tbody>
</table>
</div>
{!latest.groups.length && (
<p>
Não existem registos aplicáveis nesta consulta. A
oferta empresarial permanece por determinar; não
significa ausência de empresas.
</p>
)}
{latest.truncated && (
<p>
Apresentação limitada aos primeiros 100 grupos; não
representa cobertura completa.
</p>
)}
<p>{latest.interpretation}</p>
<p>{latest.limitations}</p>
<details>
<summary>Consulta e histórico</summary>
<p>
{history.length} análises preservadas. Última
consulta: {latest.recorded_at}. Cobertura
territorial e actividade actual por confirmar.
</p>
</details>
</>
)}
</section>
);
}
@@ -185,12 +185,16 @@ export function TerritoryFields({
endpoint = '/api/v1/investment/territory-options',
disabled = false,
corridor,
showMap = true,
levelCount = 4,
}: {
initial?: TerritoryOption[];
onChange?: (path: TerritoryOption[]) => void;
endpoint?: string;
disabled?: boolean;
corridor?: string | null;
showMap?: boolean;
levelCount?: 2 | 4;
}) {
const [path, setPath] = useState(initial);
useEffect(() => setPath(initial), [initial]);
@@ -203,41 +207,45 @@ export function TerritoryFields({
'admin_post_id',
'locality_id',
] as const
).map((field, index) => (
<div key={`${field}-${path[index - 1]?.id ?? ''}`}>
<input
type="hidden"
name={field}
value={path[index]?.id ?? ''}
/>
<TerritoryLevel
disabled={disabled}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint={endpoint}
corridor={corridor}
onChange={(value) => {
const next = replaceTerritoryPath(
path,
index,
value,
);
setPath(next);
onChange?.(next);
}}
/>
</div>
))}
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
management={endpoint.startsWith('/management/')}
endpoint={
endpoint.startsWith('/minhas-oportunidades/')
? '/minhas-oportunidades/territory-geometries'
: undefined
}
/>
)
.slice(0, levelCount)
.map((field, index) => (
<div key={`${field}-${path[index - 1]?.id ?? ''}`}>
<input
type="hidden"
name={field}
value={path[index]?.id ?? ''}
/>
<TerritoryLevel
disabled={disabled}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint={endpoint}
corridor={corridor}
onChange={(value) => {
const next = replaceTerritoryPath(
path,
index,
value,
);
setPath(next);
onChange?.(next);
}}
/>
</div>
))}
{showMap && (
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
management={endpoint.startsWith('/management/')}
endpoint={
endpoint.startsWith('/minhas-oportunidades/')
? '/minhas-oportunidades/territory-geometries'
: undefined
}
/>
)}
</div>
);
}
@@ -2,6 +2,8 @@ import { Field, input, button, groupLabels } from '@/pages/investment/shared';
import type { References } from '@/pages/investment/shared';
import { TerritoryLevel, type TerritoryOption } from './investment-territory';
import CatalogueFilterGroup from './catalogue-filter-group';
import { createInvestmentHref } from '@/lib/preparation-intent';
import CurrencySelect from './currency-select';
import { useEffect, useState } from 'react';
import { ChevronDown, Search, SlidersHorizontal } from 'lucide-react';
@@ -96,56 +98,69 @@ export default function OpportunitySearchFilters({
key: string,
choices: { value: string; label: string }[],
hint?: string,
) => (
<Field key={key} label={labels[key]}>
<select
className={input}
aria-label={labels[key]}
aria-describedby={
specialisedEmpty[key] ? `filter-help-${key}` : undefined
}
disabled={
Boolean(specialisedEmpty[key]) &&
choices.length === 0 &&
!data[key]
}
) =>
key === 'currency' ? (
<CurrencySelect
key={key}
label={labels[key]}
codes={choices.map((choice) => choice.value).filter(Boolean)}
value={String(data[key] ?? '')}
onChange={(e) =>
change({
[key]: e.target.value,
...(key === 'sector'
? { subsector_id: '', chain_id: '' }
: {}),
})
}
>
<option value="">Todos</option>
{data[key] &&
!choices.some((o) => o.value === String(data[key])) && (
<option value={String(data[key])}>
Selecção indisponível neste contexto — remova o
filtro
onChange={(value) => change({ [key]: value })}
error={errors[key]}
/>
) : (
<Field key={key} label={labels[key]}>
<select
className={input}
aria-label={labels[key]}
aria-describedby={
specialisedEmpty[key] ? `filter-help-${key}` : undefined
}
disabled={
Boolean(specialisedEmpty[key]) &&
choices.length === 0 &&
!data[key]
}
value={String(data[key] ?? '')}
onChange={(e) =>
change({
[key]: e.target.value,
...(key === 'sector'
? { subsector_id: '', chain_id: '' }
: {}),
})
}
>
<option value="">Todos</option>
{data[key] &&
!choices.some((o) => o.value === String(data[key])) && (
<option value={String(data[key])}>
Selecção indisponível neste contexto — remova o
filtro
</option>
)}
{choices.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
)}
{choices.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
{specialisedEmpty[key] && (
<p id={`filter-help-${key}`} className="text-sm text-slate-600">
{choices.length === 0
? specialisedEmpty[key]
: `${choices.length} opções públicas disponíveis, mesmo sem oportunidades associadas.`}
{key === 'subsector_id' &&
choices.length > 0 &&
' Classificação de actividades; não confirma a existência de investimentos nesta localização.'}
</p>
)}
{hint && <p className="text-sm text-slate-600">{hint}</p>}
</Field>
);
))}
</select>
{specialisedEmpty[key] && (
<p
id={`filter-help-${key}`}
className="text-sm text-slate-600"
>
{choices.length === 0
? specialisedEmpty[key]
: `${choices.length} opções públicas disponíveis, mesmo sem oportunidades associadas.`}
{key === 'subsector_id' &&
choices.length > 0 &&
' Classificação de actividades; não confirma a existência de investimentos nesta localização.'}
</p>
)}
{hint && <p className="text-sm text-slate-600">{hint}</p>}
</Field>
);
const zoneChoices = (category: string) =>
(references.zones ?? [])
.filter((z) => z.category === category)
@@ -727,6 +742,15 @@ export default function OpportunitySearchFilters({
</p>
))}
<div className="catalogue-filter-submit grid gap-3">
{mode === 'opportunities' && (
<a
className="rounded border p-3 underline"
href={createInvestmentHref(data, path)}
>
Criar investimento com estas escolhas, sem anúncio
associado
</a>
)}
{select('sort', [
{ value: 'recent', label: 'Mais recentes' },
{ value: 'title', label: 'Título' },
+2 -2
View File
@@ -290,13 +290,13 @@ export default function PortalHero({
href="/investimentos/iniciar"
className="inline-flex min-h-11 items-center rounded-lg border border-white/50 bg-black/15 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-white/15 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-white sm:min-h-9"
>
Partir de uma ideia
Criar investimento
</Link>
<Link
href="/oportunidades"
className="inline-flex min-h-11 items-center gap-1.5 rounded-lg bg-white px-3 py-1.5 text-sm font-semibold text-[#101820] transition-colors hover:bg-slate-100 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-white sm:min-h-9"
>
Consultar oportunidades
Procurar oportunidades
<ArrowRight size={16} aria-hidden="true" />
</Link>
<Link
@@ -1,4 +1,5 @@
import { Link } from '@inertiajs/react';
import EvidenceDetails from './evidence-details';
export type PublicDocument = {
id: number;
@@ -36,50 +37,51 @@ export function PublicDocumentContent({
{r.description && (
<p className="whitespace-pre-line">{r.description}</p>
)}
<dl className="grid gap-3 text-sm sm:grid-cols-2">
<div>
<dt className="font-semibold">Entidade emissora / autor</dt>
<dd>{r.issuer ?? 'Não indicada'}</dd>
</div>
{r.document_number && (
<div>
<dt className="font-semibold">Número</dt>
<dd>{r.document_number}</dd>
</div>
)}
{r.document_date && (
<div>
<dt className="font-semibold">Data do documento</dt>
<dd>{r.document_date}</dd>
</div>
)}
{r.applicable_from && (
<div>
<dt className="font-semibold">
Data de início indicada no registo
</dt>
<dd>{r.applicable_from}</dd>
</div>
)}
{r.applicable_until && (
<div>
<dt className="font-semibold">
Data final indicada no registo
</dt>
<dd>{r.applicable_until}</dd>
</div>
)}
<div>
<dt className="font-semibold">Fonte</dt>
<dd>
{r.source_confirmation === 'official_confirmed'
? 'Fonte oficial'
: r.source_url
? 'Fonte identificada'
: 'Não indicada'}
</dd>
</div>
</dl>
<EvidenceDetails title="Identificação e fonte do documento">
<dl className="grid gap-3 text-sm sm:grid-cols-2">
{r.issuer && (
<div>
<dt className="font-semibold">
Entidade emissora / autor
</dt>
<dd>{r.issuer}</dd>
</div>
)}
{r.document_number && (
<div>
<dt className="font-semibold">Número</dt>
<dd>{r.document_number}</dd>
</div>
)}
{r.document_date && (
<div>
<dt className="font-semibold">Data do documento</dt>
<dd>{r.document_date}</dd>
</div>
)}
{(r.source_url ||
r.source_confirmation === 'official_confirmed') && (
<div>
<dt className="font-semibold">Fonte</dt>
<dd>
{r.source_confirmation === 'official_confirmed'
? 'Fonte oficial'
: r.source_url
? 'Fonte identificada'
: 'Não indicada'}
</dd>
</div>
)}
</dl>
</EvidenceDetails>
{(r.applicable_from || r.applicable_until) && (
<p className="text-sm">
Período indicado:{' '}
{r.applicable_from ?? 'início não indicado'}
{' — '}
{r.applicable_until ?? 'fim não indicado'}.
</p>
)}
{r.usage_notice && (
<p
role="note"
@@ -94,7 +96,7 @@ export function PublicDocumentContent({
className="underline"
href={`/documentos/${r.id}?${new URLSearchParams({ back }).toString()}`}
>
Consultar ficha
Consultar documento
</Link>
)}
{r.view_url && (
@@ -0,0 +1,28 @@
import { Link } from '@inertiajs/react';
export default function PublishedOpportunitiesEmpty({
href = '/oportunidades',
label = 'Rever a pesquisa de oportunidades',
}: {
href?: string;
label?: string;
}) {
return (
<div
className="space-y-2 rounded-lg border border-slate-200 p-4"
role="status"
>
<p className="font-semibold">
Sem anúncios publicados nesta selecção.
</p>
<p className="text-sm">
Este resultado não indica ausência de empresas, recursos ou
potencial de investimento. Consulte também o contexto
territorial e sectorial; a viabilidade exige análise própria.
</p>
<Link className="inline-block py-2 underline" href={href}>
{label}
</Link>
</div>
);
}
+4 -1
View File
@@ -1,5 +1,6 @@
import { Link } from '@inertiajs/react';
import SectorEntry, { type SectorEntryData } from '@/components/sector-entry';
import PublishedOpportunitiesEmpty from './published-opportunities-empty';
export type SectorDetailData = {
sector: {
@@ -90,7 +91,9 @@ export default function SectorContent({
</article>
))}
{!opportunities?.length && (
<p>Sem oportunidades publicadas neste sector.</p>
<PublishedOpportunitiesEmpty
href={`/oportunidades?sector=${sector.slug}`}
/>
)}
<Link
className={button}
@@ -1,3 +1,4 @@
import CurrencySelect from '@/components/currency-select';
import { useEffect, useState } from 'react';
import {
compareBusinessScenarios,
@@ -23,48 +24,48 @@ const emptyPlan: BusinessFinancialPlanInput = {
fxRate: '',
fxDate: '',
fxSource: '',
openingCash: '0',
openingCash: '',
products: [
{
label: 'Produto ou serviço',
monthlyUnits: '100',
unitPrice: '1000',
unitVariableCost: '400',
monthlyUnits: '',
unitPrice: '',
unitVariableCost: '',
},
],
monthlyCollections: '100000',
monthlyCollections: '',
salesCollectionLagMonths: null,
salesCollectionPercent: '100',
salesCollectionPercent: '',
salesRecoverySchedule: [],
openingReceivablesCollectionMonth: null,
openingReceivablesCollectionPercent: '100',
openingReceivablesCollectionPercent: '',
openingReceivablesInstallments: [],
openingPayablesInstallments: [],
monthlyVariableCostPayments: '40000',
monthlyVariableCostPayments: '',
monthlyVariableCostPaymentsByPeriod: null,
monthlyInventoryPurchases: '40000',
monthlyInventoryPurchases: '',
inventoryPurchaseLeadMonths: 0,
inventoryPurchaseSchedule: null,
useInventoryPurchaseSchedule: false,
useProductInventorySchedule: false,
useSupplierPaymentTerms: false,
monthlyOperatingExpenses: '20000',
monthlyOperatingPayments: '20000',
monthlyPayrollExpense: '15000',
monthlyPayrollPayments: '15000',
assetInvestment: '100000',
inventory: '20000',
receivables: '10000',
payables: '5000',
equity: '80000',
shareholderLoans: '0',
bankLoanProceeds: '50000',
grants: '0',
assetDepreciation: '100000',
monthlyOperatingExpenses: '',
monthlyOperatingPayments: '',
monthlyPayrollExpense: '',
monthlyPayrollPayments: '',
assetInvestment: '',
inventory: '',
receivables: '',
payables: '',
equity: '',
shareholderLoans: '',
bankLoanProceeds: '',
grants: '',
assetDepreciation: '',
depreciationLifeMonths: 60,
monthlyInterestExpense: '0',
monthlyInterestPayment: '0',
monthlyPrincipalRepayment: '0',
monthlyInterestExpense: '',
monthlyInterestPayment: '',
monthlyPrincipalRepayment: '',
periods: 12,
};
@@ -913,30 +914,23 @@ export function SimulationBusinessPlan({
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<label className="block text-sm font-medium">
Moeda (código ISO)
<input
list="plan-currency-options"
maxLength={3}
pattern="[A-Z]{3}"
Moeda
<CurrencySelect
label="Moeda"
codes={simulationCurrencyOptions}
value={currency}
onChange={(event) => {
const value = event.target.value.toUpperCase();
onChange={(value) => {
onCurrencyChange(value);
savePlan({ ...plan, currency: value });
}}
className="mt-1 w-full rounded border p-2"
aria-invalid={Boolean(
currency && !isSimulationCurrency(currency),
)}
error={
currency && !isSimulationCurrency(currency)
? 'Confirme a moeda seleccionada.'
: undefined
}
/>
</label>
<datalist id="plan-currency-options">
{simulationCurrencyOptions.map((code) => (
<option key={code} value={code}>
{code}
</option>
))}
</datalist>
<p className="text-sm text-slate-700">
O plano financeiro aceita moedas ISO suportadas com duas
casas decimais. Se um investidor indicar uma moeda com
@@ -952,31 +946,22 @@ export function SimulationBusinessPlan({
</p>
<label className="block text-sm font-medium">
Moeda de apresentação (opcional)
<input
list="plan-presentation-currency-options"
maxLength={3}
pattern="[A-Z]{3}"
<CurrencySelect
label="Moeda de apresentação"
codes={simulationCurrencyOptions}
value={plan.presentationCurrency ?? ''}
onChange={(event) =>
update(
'presentationCurrency',
event.target.value.toUpperCase(),
)
onChange={(value) =>
update('presentationCurrency', value)
}
className="mt-1 w-full rounded border p-2"
aria-invalid={Boolean(
error={
plan.presentationCurrency &&
!isSimulationCurrency(plan.presentationCurrency),
)}
!isSimulationCurrency(plan.presentationCurrency)
? 'Confirme a moeda seleccionada.'
: undefined
}
/>
</label>
<datalist id="plan-presentation-currency-options">
{simulationCurrencyOptions.map((code) => (
<option key={code} value={code}>
{code}
</option>
))}
</datalist>
{plan.presentationCurrency &&
plan.presentationCurrency !== currency && (
<>
@@ -1,3 +1,4 @@
import CurrencySelect from '@/components/currency-select';
import { useEffect, useState } from 'react';
import {
exportMonthlyCashflowCsv,
@@ -90,30 +91,20 @@ export function SimulationCashflowPlanner({
aria-labelledby="cashflow-title"
>
<label className="block max-w-xs text-sm font-medium">
Moeda do projecto (código ISO)
<input
list="cashflow-currency-options"
inputMode="text"
maxLength={3}
pattern="[A-Z]{3}"
autoCapitalize="characters"
Moeda do projecto
<CurrencySelect
label="Moeda do projecto"
codes={simulationCurrencyOptions}
value={currency}
onChange={(event) =>
onCurrencyChange(event.target.value.toUpperCase())
}
className="mt-1 w-full rounded border p-2"
aria-invalid={
currency !== '' && !isSimulationCurrency(currency)
onChange={onCurrencyChange}
error={
currency && !isSimulationCurrency(currency)
? 'Confirme a moeda seleccionada.'
: undefined
}
/>
</label>
<datalist id="cashflow-currency-options">
{simulationCurrencyOptions.map((code) => (
<option key={code} value={code}>
{code}
</option>
))}
</datalist>
<h3 id="cashflow-title" className="text-lg font-semibold">
Projecção de tesouraria — 12 meses
</h3>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,5 @@
import type { AdvanceFiscalPeriod } from '@/lib/irpc-ppc-obligation';
import {SimulationIrpcPecObligation} from './simulation-irpc-pec-obligation';
import { SimulationIrpcPecObligation } from './simulation-irpc-pec-obligation';
import { SimulationIrpcPpcObligation } from './simulation-irpc-ppc-obligation';
import { SimulationIrpcInvestment } from './simulation-irpc-investment';
import { SimulationIrpcEconomic } from './simulation-irpc-economic';
@@ -38,6 +38,19 @@ type Props = {
export function SimulationIrpcAnnual({ draft, onChange }: Props) {
const [error, setError] = useState('');
if (draft.fiscal_component !== 'irpc') return null;
if (
typeof draft.fiscal_period === 'string' &&
draft.fiscal_period &&
draft.fiscal_period !== '2026'
)
return (
<p role="alert">
Esta estimativa anual tem cobertura documentada para 2026. O
período escolhido, {draft.fiscal_period}, permanece inalterado;
os dados e resultados anteriores ficam preservados, sem aplicar
este cálculo a outro ano.
</p>
);
try {
const b = annualBook(draft),
save = (next: AnnualBook) => {
@@ -51,10 +64,10 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
if (!b)
return (
<section
aria-label="IRPC — L8 fecho anual"
aria-label="IRPC — estimativa anual"
className="rounded border p-4"
>
<h4>L8 — da colecta ao saldo anual simulado</h4>
<h4>Do imposto estimado ao saldo anual simulado</h4>
<p>
Reutiliza a colecta válida, retenções efectivamente
sofridas por conta e PPC comprovados do próprio
@@ -77,14 +90,14 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
}
}}
>
Preparar saldo anual L8
Preparar estimativa anual
</button>
{error && <p role="alert">{error}</p>}
</section>
);
const patch = (p: Partial<AnnualBook>) => save({ ...b, ...p }),
a = annualAssessment(draft),
advancePeriod = annualAdvancePeriod(draft,b),
advancePeriod = annualAdvancePeriod(draft, b),
options = annualWithholdingOptions(draft);
const field = (
key: 'subjectNuit' | 'year' | 'reference' | 'assessmentReference',
@@ -143,10 +156,10 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
);
return (
<section
aria-label="IRPC — L8 fecho anual"
aria-label="IRPC — estimativa anual"
className="space-y-3 rounded border p-4"
>
<h4>L8 — colecta, abatimentos e saldo anual simulado</h4>
<h4>Imposto estimado, abatimentos e saldo anual simulado</h4>
<p>
A colecta acima é anterior aos abatimentos. Este saldo tem
cálculo e histórico próprios; retenção entregue pela empresa
@@ -350,11 +363,33 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
</fieldset>
<fieldset className="space-y-2 rounded border p-3">
<legend>Estimativas PPC e PEC para a viabilidade</legend>
<p>Simulação fiscal para avaliar a viabilidade do negócio e as necessidades de tesouraria. Os valores e meses previstos são estimativas; o portal não executa pagamentos nem submete declarações fiscais.</p>
<SimulationIrpcAdvancePeriodDeclaration draft={draft} book={b} onChange={declaration=>patch({advancePeriodDeclaration:declaration})}/>
<SimulationIrpcPecObligation book={b} period={advancePeriod} onChange={pecObligation=>patch({pecObligation})}/>
<SimulationIrpcPpcObligation book={b} period={advancePeriod} onChange={ppcObligation=>patch({ppcObligation})}/>
<SimulationIrpcAdvanceCashflow book={b} period={advancePeriod}/>
<p>
Simulação fiscal para avaliar a viabilidade do negócio e
as necessidades de tesouraria. Os valores e meses
previstos são estimativas; o portal não executa
pagamentos nem submete declarações fiscais.
</p>
<SimulationIrpcAdvancePeriodDeclaration
draft={draft}
book={b}
onChange={(declaration) =>
patch({ advancePeriodDeclaration: declaration })
}
/>
<SimulationIrpcPecObligation
book={b}
period={advancePeriod}
onChange={(pecObligation) => patch({ pecObligation })}
/>
<SimulationIrpcPpcObligation
book={b}
period={advancePeriod}
onChange={(ppcObligation) => patch({ ppcObligation })}
/>
<SimulationIrpcAdvanceCashflow
book={b}
period={advancePeriod}
/>
</fieldset>
<fieldset className="space-y-2 rounded border p-3">
<legend>PPC documentados como pagos</legend>
@@ -627,33 +662,255 @@ export function SimulationIrpcAnnual({ draft, onChange }: Props) {
}
}
export function SimulationIrpcAdvanceCashflow({book,period}: {book: AnnualBook;period?: AdvanceFiscalPeriod}) {
export function SimulationIrpcAdvanceCashflow({
book,
period,
}: {
book: AnnualBook;
period?: AdvanceFiscalPeriod;
}) {
if (!book.ppcObligation && !book.pecObligation) return null;
const m = annualAdvanceCashflow(book,period);
const m = annualAdvanceCashflow(book, period);
const show = advanceCashflowAmount;
return <section className="space-y-3 rounded border p-3" aria-label="Projecção conjunta PPC e PEC">
<h5 className="font-semibold">Saídas previstas PPC/PEC por mês</h5>
{period && <p>Período preparado em L6: {period.from || 'por confirmar'} — {period.to || 'por confirmar'}.</p>}
<p>Reúne as estimativas PPC e a hipótese de tesouraria PEC. Os comprovativos pagos e o fecho anual permanecem separados; esta vista não acrescenta outra saída ao fluxo financeiro do negócio.</p>
<p role="status">{m.total ? 'Total da projecção: '+show(m.total) : 'Projecção parcial — total por determinar.'}</p>
{!!m.pending.length && <ul className="list-disc pl-5">{m.pending.map(p=><li key={p}>{p}</li>)}</ul>}
{!!m.rows.length && <div className="overflow-x-auto"><table className="w-full text-left text-sm">
<caption className="sr-only">Projecção mensal das estimativas PPC e PEC</caption>
<thead><tr><th className="p-2">Mês</th><th className="p-2">PPC</th><th className="p-2">PEC</th><th className="p-2">{m.total ? 'Total previsto' : 'Subtotal conhecido'}</th></tr></thead>
<tbody>{m.rows.map(r=><tr key={r.month} className="border-t"><th scope="row" className="p-2">{r.month}</th><td className="p-2">{m.ppcKnown ? show(r.ppc) : 'Por determinar'}</td><td className="p-2">{m.pecKnown ? show(r.pec) : 'Por determinar'}</td><td className="p-2">{show(r.knownSubtotal)}</td></tr>)}</tbody>
</table></div>}
{!m.rows.length && m.total && <p>Sem saída PPC/PEC estimada neste recorte.</p>}
<p>Meses e montantes dependem das fontes e opções preparadas acima. A opção PEC concentrada conserva o mês escolhido; esta apresentação não certifica o prazo legal.</p>
</section>;
return (
<section
className="space-y-3 rounded border p-3"
aria-label="Projecção conjunta PPC e PEC"
>
<h5 className="font-semibold">Saídas previstas PPC/PEC por mês</h5>
{period && (
<p>
Período preparado em L6: {period.from || 'por confirmar'} —{' '}
{period.to || 'por confirmar'}.
</p>
)}
<p>
Reúne as estimativas PPC e a hipótese de tesouraria PEC. Os
comprovativos pagos e o fecho anual permanecem separados; esta
vista não acrescenta outra saída ao fluxo financeiro do negócio.
</p>
<p role="status">
{m.total
? 'Total da projecção: ' + show(m.total)
: 'Projecção parcial — total por determinar.'}
</p>
{!!m.pending.length && (
<ul className="list-disc pl-5">
{m.pending.map((p) => (
<li key={p}>{p}</li>
))}
</ul>
)}
{!!m.rows.length && (
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<caption className="sr-only">
Projecção mensal das estimativas PPC e PEC
</caption>
<thead>
<tr>
<th className="p-2">Mês</th>
<th className="p-2">PPC</th>
<th className="p-2">PEC</th>
<th className="p-2">
{m.total
? 'Total previsto'
: 'Subtotal conhecido'}
</th>
</tr>
</thead>
<tbody>
{m.rows.map((r) => (
<tr key={r.month} className="border-t">
<th scope="row" className="p-2">
{r.month}
</th>
<td className="p-2">
{m.ppcKnown
? show(r.ppc)
: 'Por determinar'}
</td>
<td className="p-2">
{m.pecKnown
? show(r.pec)
: 'Por determinar'}
</td>
<td className="p-2">
{show(r.knownSubtotal)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{!m.rows.length && m.total && (
<p>Sem saída PPC/PEC estimada neste recorte.</p>
)}
<p>
Meses e montantes dependem das fontes e opções preparadas acima.
A opção PEC concentrada conserva o mês escolhido; esta
apresentação não certifica o prazo legal.
</p>
</section>
);
}
export function SimulationIrpcAdvancePeriodDeclaration({draft,book,onChange}:{draft:Record<string,unknown>;book:AnnualBook;onChange:(value:NonNullable<AnnualBook['advancePeriodDeclaration']>)=>void}){
const period=annualAdvancePeriod(draft,book),calendar=advanceCalendar(period,book.year,book.subjectNuit),d=book.advancePeriodDeclaration;
if(!d&&!calendar.candidate)return null;
if(!d)return <section className="rounded border p-3"><h5>Período anual não civil</h5><p>Confronte o fundamento do período L6 e os doze meses do período anterior. As datas sugeridas não substituem o suporte documental.</p><button type="button" className="rounded border p-2" onClick={()=>onChange(newAdvancePeriodDeclaration(book.subjectNuit,book.year,period))}>Preparar correspondência dos períodos</button></section>;
const patch=(values:Partial<typeof d>)=>onChange({...d,...values,confirmed:''});
const labels={subjectNuit:'NUIT dos períodos',year:'Exercício de termo',currentFrom:'Início do período L6 declarado',currentTo:'Termo do período L6 declarado',currentReference:'Fundamento documentado do período anual não civil',previousFrom:'Início do período anterior',previousTo:'Termo do período anterior',previousReference:'Fonte e correspondência do período anterior'};
return <section className="space-y-2 rounded border p-3" aria-label="Correspondência dos períodos anuais"><h5>Correspondência dos períodos anuais</h5><p role="status">{calendar.mode==='annual_non_civil'?'Correspondência documental conferida;previsões nos meses do período L6.':calendar.mode==='civil'?'L6 usa o ano civil;referência anterior conservada sem aplicação.':calendar.pending.join(' ')}</p><p>PPC: imposto anterior {book.ppcObligation?.previousTax||'por confirmar'} MZN;retenções {book.ppcObligation?.previousWithholdings||'por confirmar'} MZN. PEC: volume anterior {book.pecObligation?.previousTurnover||'por confirmar'} MZN;PPC anteriores {book.pecObligation?.previousPpcPaid||'por confirmar'} MZN.</p>{d.confirmed==='yes'&&(d.ppcBasisKey!==advancePeriodBasis(book,'ppc')||d.pecBasisKey!==advancePeriodBasis(book,'pec'))&&<button type="button" className="rounded border p-2" onClick={()=>onChange({...d,ppcBasisKey:advancePeriodBasis(book,'ppc'),pecBasisKey:advancePeriodBasis(book,'pec')})}>Reconferi os montantes e as fontes neste período</button>}<details open={d.confirmed!=='yes'||calendar.pending.length>0}><summary>Conferir ou alterar períodos</summary><label className="block">Aplicação<select aria-label="Aplicação do período não civil" value={d.mode} onChange={e=>patch({mode:e.target.value as typeof d.mode})}><option value="annual_non_civil">Período anual não civil</option><option value="">Conservar sem aplicação</option></select></label>{(Object.keys(labels) as Array<keyof typeof labels>).map(key=><label className="block" key={key}>{labels[key]}<input className="mt-1 block w-full rounded border px-3 py-2" aria-label={labels[key]} value={d[key]} onChange={e=>patch({[key]:e.target.value})}/></label>)}<p>No PPC, indique que o período anterior não é um ano civil completo. Os doze meses e a continuidade são conferidos pelas datas e fontes aqui indicadas.</p><label className="block"><input type="checkbox" checked={d.confirmed==='yes'} onChange={e=>onChange({...d,confirmed:e.target.checked?'yes':'',ppcBasisKey:advancePeriodBasis(book,'ppc'),pecBasisKey:advancePeriodBasis(book,'pec')})}/>Conferi no suporte os dois períodos, o fundamento do enquadramento e a correspondência dos montantes e fontes PPC/PEC</label></details><p>Guardar conserva estas escolhas. Uma alteração nas datas L6 exige reconferência; o portal não autoriza uma mudança do período fiscal.</p></section>;
export function SimulationIrpcAdvancePeriodDeclaration({
draft,
book,
onChange,
}: {
draft: Record<string, unknown>;
book: AnnualBook;
onChange: (
value: NonNullable<AnnualBook['advancePeriodDeclaration']>,
) => void;
}) {
const period = annualAdvancePeriod(draft, book),
calendar = advanceCalendar(period, book.year, book.subjectNuit),
d = book.advancePeriodDeclaration;
if (!d && !calendar.candidate) return null;
if (!d)
return (
<section className="rounded border p-3">
<h5>Período anual não civil</h5>
<p>
Confronte o fundamento do período L6 e os doze meses do
período anterior. As datas sugeridas não substituem o
suporte documental.
</p>
<button
type="button"
className="rounded border p-2"
onClick={() =>
onChange(
newAdvancePeriodDeclaration(
book.subjectNuit,
book.year,
period,
),
)
}
>
Preparar correspondência dos períodos
</button>
</section>
);
const patch = (values: Partial<typeof d>) =>
onChange({ ...d, ...values, confirmed: '' });
const labels = {
subjectNuit: 'NUIT dos períodos',
year: 'Exercício de termo',
currentFrom: 'Início do período L6 declarado',
currentTo: 'Termo do período L6 declarado',
currentReference: 'Fundamento documentado do período anual não civil',
previousFrom: 'Início do período anterior',
previousTo: 'Termo do período anterior',
previousReference: 'Fonte e correspondência do período anterior',
};
return (
<section
className="space-y-2 rounded border p-3"
aria-label="Correspondência dos períodos anuais"
>
<h5>Correspondência dos períodos anuais</h5>
<p role="status">
{calendar.mode === 'annual_non_civil'
? 'Correspondência documental conferida;previsões nos meses do período L6.'
: calendar.mode === 'civil'
? 'L6 usa o ano civil;referência anterior conservada sem aplicação.'
: calendar.pending.join(' ')}
</p>
<p>
PPC: imposto anterior{' '}
{book.ppcObligation?.previousTax || 'por confirmar'}{' '}
MZN;retenções{' '}
{book.ppcObligation?.previousWithholdings || 'por confirmar'}{' '}
MZN. PEC: volume anterior{' '}
{book.pecObligation?.previousTurnover || 'por confirmar'}{' '}
MZN;PPC anteriores{' '}
{book.pecObligation?.previousPpcPaid || 'por confirmar'} MZN.
</p>
{d.confirmed === 'yes' &&
(d.ppcBasisKey !== advancePeriodBasis(book, 'ppc') ||
d.pecBasisKey !== advancePeriodBasis(book, 'pec')) && (
<button
type="button"
className="rounded border p-2"
onClick={() =>
onChange({
...d,
ppcBasisKey: advancePeriodBasis(book, 'ppc'),
pecBasisKey: advancePeriodBasis(book, 'pec'),
})
}
>
Reconferi os montantes e as fontes neste período
</button>
)}
<details
open={d.confirmed !== 'yes' || calendar.pending.length > 0}
>
<summary>Conferir ou alterar períodos</summary>
<label className="block">
Aplicação
<select
aria-label="Aplicação do período não civil"
value={d.mode}
onChange={(e) =>
patch({ mode: e.target.value as typeof d.mode })
}
>
<option value="annual_non_civil">
Período anual não civil
</option>
<option value="">Conservar sem aplicação</option>
</select>
</label>
{(Object.keys(labels) as Array<keyof typeof labels>).map(
(key) => (
<label className="block" key={key}>
{labels[key]}
<input
className="mt-1 block w-full rounded border px-3 py-2"
aria-label={labels[key]}
value={d[key]}
onChange={(e) =>
patch({ [key]: e.target.value })
}
/>
</label>
),
)}
<p>
No PPC, indique que o período anterior não é um ano civil
completo. Os doze meses e a continuidade são conferidos
pelas datas e fontes aqui indicadas.
</p>
<label className="block">
<input
type="checkbox"
checked={d.confirmed === 'yes'}
onChange={(e) =>
onChange({
...d,
confirmed: e.target.checked ? 'yes' : '',
ppcBasisKey: advancePeriodBasis(book, 'ppc'),
pecBasisKey: advancePeriodBasis(book, 'pec'),
})
}
/>
Conferi no suporte os dois períodos, o fundamento do
enquadramento e a correspondência dos montantes e fontes
PPC/PEC
</label>
</details>
<p>
Guardar conserva estas escolhas. Uma alteração nas datas L6
exige reconferência; o portal não autoriza uma mudança do
período fiscal.
</p>
</section>
);
}
@@ -1,4 +1,6 @@
import { SimulationIrpcSpecial } from '@/components/simulation-irpc-special';
import FiscalOperationPicker from '@/components/fiscal-operation-picker';
import { inputText } from '@/lib/input-text';
import { SimulationIrpcFormPreparation } from '@/components/simulation-irpc-form-preparation';
import { SimulationIrpcPeriodFx } from '@/components/simulation-irpc-period-fx';
import { SimulationIrpcDepreciation } from '@/components/simulation-irpc-depreciation';
@@ -31,7 +33,7 @@ export function SimulationIrpcNormal({
onChange,
}: {
draft: Record<string, unknown>;
onChange: (field: string, value: string) => void;
onChange: (field: string, value: string | string[]) => void;
}) {
const [error, setError] = useState('');
if (draft.fiscal_component !== 'irpc') return null;
@@ -46,6 +48,26 @@ export function SimulationIrpcNormal({
setError(String(e));
}
};
const selectedPeriod = inputText(draft.fiscal_period ?? '');
if (selectedPeriod && selectedPeriod !== b.year)
return (
<aside className="rounded border p-3" role="alert">
<p>
O enquadramento escolheu {selectedPeriod}, mas esta
preparação de IRPC está em {b.year}. Confira o período
antes de calcular; os dados anteriores ficam preservados
e nenhum ano foi alterado.
</p>
<button
type="button"
className="underline"
disabled={!/^\d{4}$/.test(selectedPeriod)}
onClick={() => save({ ...b, year: selectedPeriod })}
>
Preparar o ano escolhido, sujeito à cobertura disponível
</button>
</aside>
);
const patch = (id: string, p: Partial<NormalAdjustment>) =>
save({
...b,
@@ -74,16 +96,16 @@ export function SimulationIrpcNormal({
aria-label="IRPC normal — ajustamentos"
className="space-y-3 rounded border p-4"
>
<h4>L6 — IRPC normal: ajustamentos ao resultado financeiro</h4>
<h4>IRPC — ajustamentos ao resultado financeiro</h4>
<p>
Acréscimos de multas sem origem contratual e juros
compensatórios incluídos nos custos do plano, artigo 36(1)c.
A conferência anual pode determinar o lucro tributável
simulado no recorte ordinário documentado. A matéria
colectável exige conferência específica de deduções e
perdas; a colecta tem cálculo próprio e o saldo final a
pagar ou recuperar pertence aL8. Não reutiliza
automaticamente juros simulados de L5.
perdas; o imposto estimado e a estimativa anual têm cálculos
próprios. Os juros da simulação de empréstimo não são
adoptados automaticamente como custo fiscal.
</p>
{error && <p role="alert">{error}</p>}
{source ? (
@@ -437,31 +459,126 @@ export function SimulationIrpcNormal({
})}
</fieldset>
)}
<SimulationIrpcPeriodFx draft={draft} book={b} save={save} />
<SimulationIrpcSchedules book={b} save={save} />
<SimulationIrpcEconomicInclusion
key={JSON.stringify([
draft.context_opportunity,
b.base?.subjectNuit,
b.year,
])}
draft={draft}
book={b}
save={save}
/>
<SimulationIrpcDepreciation
draft={draft}
book={b}
save={save}
/>
<SimulationIrpcCosts draft={draft} book={b} save={save} />
<SimulationIrpcTaxableBase draft={draft} book={b} save={save} />
<SimulationIrpcAssessment book={b} save={save} />
<SimulationIrpcSpecial draft={draft} book={b} save={save} />
<SimulationIrpcFormPreparation
draft={draft}
book={b}
save={save}
<FiscalOperationPicker
family="irpc"
selected={draft.fiscal_tools_selection}
onChange={(selected) =>
onChange('fiscal_tools_selection', selected)
}
operations={[
{
id: 'period',
label: 'Período e moeda do plano',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcPeriodFx
draft={draft}
book={b}
save={save}
/>
),
},
{
id: 'schedules',
label: 'Mapas complementares',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcSchedules book={b} save={save} />
),
},
{
id: 'economic',
label: 'Inclusões e correcções económicas',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcEconomicInclusion
draft={draft}
book={b}
save={save}
/>
),
},
{
id: 'depreciation',
label: 'Amortizações e depreciações',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcDepreciation
draft={draft}
book={b}
save={save}
/>
),
},
{
id: 'costs',
label: 'Tratamento dos custos',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcCosts
draft={draft}
book={b}
save={save}
/>
),
},
{
id: 'taxable',
label: 'Matéria colectável',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcTaxableBase
draft={draft}
book={b}
save={save}
/>
),
},
{
id: 'assessment',
label: 'Estimativa do imposto',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcAssessment
book={b}
save={save}
/>
),
},
{
id: 'special',
label: 'Situações fiscais específicas',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcSpecial
draft={draft}
book={b}
save={save}
/>
),
},
{
id: 'forms',
label: 'Preparação documental fiscal',
description:
'Acrescente quando necessário ao seu cenário e confira os pressupostos e fontes da operação.',
render: () => (
<SimulationIrpcFormPreparation
draft={draft}
book={b}
save={save}
/>
),
},
]}
/>
<button
type="button"
@@ -49,6 +49,29 @@ export function SimulationIspcQuarter({
},
change = (patch: Partial<IspcQuarterInput>) =>
save({ ...book, input: { ...i, ...patch } });
if (
typeof draft.fiscal_period === 'string' &&
draft.fiscal_period &&
draft.fiscal_period !== i.year
)
return (
<aside className="rounded border p-3" role="alert">
<p>
O ano desta preparação difere do enquadramento fiscal
escolhido. Confira a correspondência antes de calcular;
nenhum período foi alterado automaticamente.
</p>
<button
type="button"
className="underline"
onClick={() =>
change({ year: draft.fiscal_period as string })
}
>
Preparar o ano escolhido, sujeito à cobertura disponível
</button>
</aside>
);
let service = false,
ready = false;
try {
@@ -47,7 +47,7 @@ export function SimulationMiners({
return (
<details className="rounded border p-3">
<summary>
Importações dos mineiros — regime da África do Sul (P059)
Importações dos mineiros — regime da África do Sul
</summary>
<p>
Lei n.º2/2011,artigos1–4:página1 doPDF;artigo5:página2/p110-(8).
@@ -3,6 +3,7 @@ import {
modeloAPurchaseReferences,
modeloAReference,
} from '@/lib/iva-modelo-a';
import EvidenceDetails from './evidence-details';
export function SimulationModeloA({
draft,
@@ -100,14 +101,15 @@ export function SimulationModeloA({
</div>
)}
</details>
<details>
<summary>
Ver campos, cálculos, fundamentos e cobertura do Modelo A
</summary>
<p>
{modeloAReference.file}. {modeloAReference.edition} SHA256:{' '}
{modeloAReference.sha256}.
</p>
<EvidenceDetails title="Campos e fundamentos da estimativa — Modelo A">
<EvidenceDetails title="Exemplar e integridade da fonte">
<p>
{modeloAReference.file}. {modeloAReference.edition}
</p>
<p className="break-all">
SHA256: {modeloAReference.sha256}
</p>
</EvidenceDetails>
<p>
O exemplar contém divergências de numeração/remissões,
registadas no confronto documental. Não foram corrigidas no
@@ -159,7 +161,7 @@ export function SimulationModeloA({
</tbody>
</table>
</div>
</details>
</EvidenceDetails>
</section>
);
}
@@ -1,3 +1,4 @@
import FiscalOperationPicker from './fiscal-operation-picker';
import { inputText } from '../lib/input-text.ts';
import { SimulationRemissionImports } from './simulation-remission-imports';
import { SimulationObjectiveImports } from './simulation-objective-imports';
@@ -58,7 +59,7 @@ export function SimulationMonthlyIva({
onCalculate: (
input: MonthlyIvaInput,
) => Promise<ApiSimulationExecutionV1 | null | undefined>;
onChange: (field: string, value: string) => void;
onChange: (field: string, value: string | string[]) => void;
}) {
const settings = readMonthlyIvaSettings(
inputText(draft.monthly_iva_settings ?? ''),
@@ -416,38 +417,394 @@ export function SimulationMonthlyIva({
</dl>
</details>
)}
<SimulationOperations draft={draft} onChange={onChange} />
<SimulationAcquisitions draft={draft} onChange={onChange} />
<SimulationImportExemptions draft={draft} onChange={onChange} />
<SimulationObjectiveImports draft={draft} onChange={onChange} />
<SimulationMiners draft={draft} onChange={onChange} />
<SimulationRemissionImports draft={draft} onChange={onChange} />
<SimulationReturnees draft={draft} onChange={onChange} />
<SimulationPublicAuthorityBase draft={draft} onChange={onChange} />
<SimulationCommissionBase draft={draft} onChange={onChange} />
<SimulationActSaleBase draft={draft} onChange={onChange} />
<SimulationFuelBase draft={draft} onChange={onChange} />
<SimulationNoncashBase draft={draft} onChange={onChange} />
<SimulationCompositionBase draft={draft} onChange={onChange} />
<SimulationExclusionBase draft={draft} onChange={onChange} />
<SimulationValueReview draft={draft} onChange={onChange} />
<SimulationServiceNormal draft={draft} onChange={onChange} />
<SimulationGoodsLocation draft={draft} onChange={onChange} />
<SimulationServiceLocation draft={draft} onChange={onChange} />
<SimulationListedServices draft={draft} onChange={onChange} />
<SimulationReducedBases draft={draft} onChange={onChange} />
<SimulationOwnName draft={draft} onChange={onChange} />
<SimulationGoodsAllocation draft={draft} onChange={onChange} />
<SimulationForeignOperations draft={draft} onChange={onChange} />
<SimulationDigital draft={draft} onChange={onChange} />
<SimulationTravel draft={draft} onChange={onChange} />
<SimulationTravelEvents draft={draft} onChange={onChange} />
<SimulationCurrencyEvents draft={draft} onChange={onChange} />
<SimulationPropertyTransfers draft={draft} onChange={onChange} />
<SimulationGoodsPresumptions draft={draft} onChange={onChange} />
<SimulationSecondhand draft={draft} onChange={onChange} />
<SimulationOfferPreparations draft={draft} onChange={onChange} />
<SimulationModeloA draft={draft} />
<FiscalOperationPicker
family="iva"
selected={draft.fiscal_tools_selection}
onChange={(selected) =>
onChange('fiscal_tools_selection', selected)
}
operations={[
{
id: 'operations',
label: 'Operações de venda e prestação de serviços',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationOperations
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'acquisitions',
label: 'Aquisições e dedutibilidade',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationAcquisitions
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'import_exemptions',
label: 'Importações com isenção',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationImportExemptions
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'objective_imports',
label: 'Condições específicas de importação',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationObjectiveImports
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'miners',
label: 'Importações no regime de trabalhadores mineiros',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationMiners
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'remission_imports',
label: 'Importações com isenção por remissão legal',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationRemissionImports
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'returnees',
label: 'Regresso definitivo e bagagem',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationReturnees
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'public_authority_base',
label: 'Operações de entidades públicas',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationPublicAuthorityBase
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'commission_base',
label: 'Comissões',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationCommissionBase
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'act_sale_base',
label: 'Venda por acto ou processo específico',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationActSaleBase
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'fuel_base',
label: 'Revenda de combustíveis',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationFuelBase
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'noncash_base',
label: 'Operações sem contrapartida em dinheiro',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationNoncashBase
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'composition_base',
label: 'Composição da base tributável',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationCompositionBase
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'exclusion_base',
label: 'Parcelas excluídas da base',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationExclusionBase
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'value_review',
label: 'Revisão do valor tributável',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationValueReview
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'service_normal',
label: 'Valor de serviços',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationServiceNormal
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'goods_location',
label: 'Localização das operações sobre bens',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationGoodsLocation
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'service_location',
label: 'Localização das prestações de serviços',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationServiceLocation
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'listed_services',
label: 'Serviços com enquadramento específico',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationListedServices
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'reduced_bases',
label: 'Bases reduzidas',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationReducedBases
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'own_name',
label: 'Operações em nome próprio',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationOwnName
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'goods_allocation',
label: 'Afectação de bens',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationGoodsAllocation
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'foreign_operations',
label: 'Operações com o exterior',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationForeignOperations
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'digital',
label: 'Serviços digitais',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationDigital
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'travel',
label: 'Viagens',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationTravel
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'travel_events',
label: 'Factos específicos de viagens',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationTravelEvents
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'currency_events',
label: 'Operações em moeda estrangeira',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationCurrencyEvents
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'property_transfers',
label: 'Transmissões de imóveis',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationPropertyTransfers
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'goods_presumptions',
label: 'Presunções relativas a bens',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationGoodsPresumptions
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'secondhand',
label: 'Bens em segunda mão',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationSecondhand
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'offer_preparations',
label: 'Preparação de ofertas',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => (
<SimulationOfferPreparations
draft={draft}
onChange={onChange}
/>
),
},
{
id: 'modelo_a',
label: 'Conferência do Modelo A',
description:
'Escolha quando esta operação fizer parte do cenário; confira as condições, fontes e período no cálculo correspondente.',
render: () => <SimulationModeloA draft={draft} />,
},
]}
/>
</section>
);
}
@@ -1,5 +1,6 @@
import { inputText } from '../lib/input-text.ts';
import { useState } from 'react';
import EvidenceDetails from '@/components/evidence-details';
import {
remissionBook,
saveRemissionBook,
@@ -52,9 +53,7 @@ export function SimulationRemissionImports({
}
return (
<details className="rounded border p-3">
<summary>
Importações — quatro famílias de isenção por remissão (P047)
</summary>
<summary>Importações — isenções por remissão legal</summary>
<p>
Confirme o fundamento e o âmbito da isenção de direitos. Taxa
pautal de 0%, redução e pedido apresentado são situações
@@ -500,7 +499,9 @@ export function SimulationRemissionImports({
)}
<details>
<summary>Fontes e limites de cobertura</summary>
<p>{remissionSource}</p>
<EvidenceDetails title="Fontes e âmbito deste cálculo">
<p>{remissionSource.replace(/^P\d+\s*[—-]\s*/, '')}</p>
</EvidenceDetails>
<p>
Avalia o IVA por remissão quando a isenção de direitos está
demonstrada. Não substitui a classificação pautal nem
@@ -45,8 +45,7 @@ export function SimulationReturnees({
return (
<details className="rounded border p-3">
<summary>
Regresso definitivo — veículos e bagagem (P058, cobertura
parcial)
Regresso definitivo — veículos e bagagem (cobertura parcial)
</summary>
<p>
Prepare os bens e escolha o percurso próprio:veículos no
@@ -54,7 +53,7 @@ export function SimulationReturnees({
artigos57.º/61.º do Decreto37/2023. Isenção, redução de80% e
redução excepcional de50% têm condições distintas. Estas
percentagens são benefícios sobre as imposições; não são taxas
deIVA. Não se aplicam aqui as condições dos mineirosP059.
de IVA. Não se aplicam aqui as condições próprias dos mineiros.
</p>
<p>
Bagagem de funcionários e estudantes tem percurso
@@ -1,3 +1,5 @@
import EvidenceDetails from './evidence-details';
export type TerritorialSourceEvidence = {
association: string;
role: string;
@@ -15,16 +17,7 @@ export default function TerritorialSources({
}) {
if (!sources?.length) return null;
return (
<section className="min-w-0 space-y-3 rounded border p-4 [overflow-wrap:anywhere]">
<h2 className="text-xl font-bold">
Fundamento documental das associações
</h2>
<p>
Fontes oficiais identificadas são aceites; recuperar uma
referência não retira a aceitação existente. O fundamento
aplica-se à informação indicada, sem deduzir implantação,
disponibilidade ou capacidade.
</p>
<EvidenceDetails title="Fontes das relações territoriais">
{sources.map((source, i) => (
<article className="border-t pt-3" key={i}>
<h3 className="font-semibold">
@@ -36,17 +29,19 @@ export default function TerritorialSources({
'ligação ao exemplar por recuperar'}
</p>
<p>{source.source_quote ?? source.supports}</p>
<p>
{source.official_source_accepted
? 'Fonte oficial identificada e aceite.'
: 'Aceitação existente preservada; ponte ao exemplar oficial por recuperar. Esta referência não recebe outra classificação de proveniência.'}{' '}
Rastreabilidade: {source.traceability}. Estado
registado:{' '}
{source.existing_validation ?? 'sem campo específico'};
preservado.
</p>
<EvidenceDetails title="Proveniência e versão da referência">
<p>
{source.official_source_accepted
? 'Fonte oficial identificada.'
: 'Ligação ao exemplar oficial por recuperar.'}
</p>
<p>{source.traceability}</p>
{source.existing_validation && (
<p>{source.existing_validation}</p>
)}
</EvidenceDetails>
</article>
))}
</section>
</EvidenceDetails>
);
}
+14 -4
View File
@@ -2,16 +2,26 @@ import { useEffect, useState } from 'react';
import { newSubmissionKey } from '@/lib/portal-api';
export function useInterestDraft<T>(name: string, initial: T) {
const storage = 'investemoz-interest:' + name;
const [draft, setDraft] = useState<{ form: T; key: string }>(() => {
const read = () => {
try {
const value = JSON.parse(sessionStorage.getItem(storage) ?? 'null');
if (value?.form && typeof value.key === 'string') return value;
if (value?.form && typeof value.key === 'string')
return { ...value, storage } as {
form: T;
key: string;
storage: string;
};
} catch {
/* unavailable storage leaves the current form usable */
}
return { form: initial, key: newSubmissionKey() };
});
return { form: initial, key: newSubmissionKey(), storage };
};
const [draft, setDraft] = useState(read);
// Inertia can reuse this component for a different opportunity. Never write
// the previous opportunity's answers into the new opportunity's storage key.
if (draft.storage !== storage) setDraft(read());
useEffect(() => {
if (draft.storage !== storage) return;
try {
sessionStorage.setItem(storage, JSON.stringify(draft));
} catch {}
+35
View File
@@ -0,0 +1,35 @@
export const normaliseChoice = (value: string) =>
value
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLocaleLowerCase('pt')
.trim();
export function matchesChoice(query: string, labels: string[]): boolean {
const needle = normaliseChoice(query);
return (
!needle ||
labels.some((label) => normaliseChoice(label).includes(needle))
);
}
/** The same ISO currency source already used by the simulator, with readable labels. */
export function currencyChoices(codes?: readonly string[]) {
const intl = Intl as unknown as {
supportedValuesOf?: (key: string) => string[];
};
const names = new Intl.DisplayNames(['pt-MZ'], { type: 'currency' });
return [
...new Set(
codes ??
intl.supportedValuesOf?.('currency') ?? [
'MZN',
'USD',
'EUR',
'ZAR',
],
),
].map((code) => ({
value: code,
label: `${names.of(code) ?? code} — ${code}`,
keywords: [code, names.of(code) ?? code],
}));
}
+110 -7
View File
@@ -1,10 +1,94 @@
import { searchTerritoryHref } from './search-territory.ts';
const geography = [
'province_id',
'district_id',
'admin_post_id',
'locality_id',
];
const catalogueKeys: Record<string, string[]> = {
'/carteira': ['q', 'kind', 'sector', 'geo_location_id'],
'/zonas': [
'q',
'category',
'physical_category',
'legal_regime',
'development_status',
'availability_status',
'province',
],
'/oportunidades': [
'q',
'query',
'sector',
'province',
'district',
'geo_location_id',
'include_national',
'cluster_id',
'zee_id',
'zfi_id',
'park_id',
'corridor_id',
'project_id',
'education',
'min_amount',
'max_amount',
'currency',
'maturity_level',
'preparation',
'before',
'sort',
'facets[]',
'view',
'dimension',
'association_type',
'association_target',
'association_state',
'association_purpose',
'chain_id',
'subsector_id',
],
};
function family(path: string): string {
if (path.startsWith('/management/portfolio')) return '/carteira';
if (path.startsWith('/management/investment/zones')) return '/zonas';
if (path === '/educacao' || path.startsWith('/educacao/'))
return '/oportunidades';
return (
Object.keys(catalogueKeys).find(
(route) => path === route || path.startsWith(route + '/'),
) ?? ''
);
}
/** Explicit URL criteria only. No ambient storage, dossier IDs or nested return URLs. */
export function catalogueQuery(path: string, query: string): URLSearchParams {
const group = family(path);
const allowed = new Set(
group
? [...geography, ...catalogueKeys[group], 'page', 'per_page']
: [],
);
const result = new URLSearchParams();
for (const [key, value] of new URLSearchParams(query)) {
if (!allowed.has(key) || !value || value.length > 2000) continue;
if (
['page', 'per_page'].includes(key) &&
(!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value)))
)
continue;
if (!key.endsWith('[]')) result.delete(key);
result.append(key, value);
}
return result;
}
/** Only a query string is carried; the return destination is always local. */
export function catalogueDetailHref(
path: string,
query: string,
pageUrl?: string,
): string {
const target = new URL(path, 'https://portal.invalid');
if (target.origin !== 'https://portal.invalid') return path;
if (pageUrl) {
const page = new URL(
pageUrl,
@@ -20,16 +104,35 @@ export function catalogueDetailHref(
query = params.toString();
}
}
return query
? `${path}?catalogue_query=${encodeURIComponent(query)}`
: path;
const selected = catalogueQuery(target.pathname, query).toString();
if (selected) target.searchParams.set('catalogue_query', selected);
return target.pathname + target.search + target.hash;
}
export function catalogueReturnHref(base: string, pageUrl: string): string {
const query = new URL(pageUrl, 'https://portal.invalid').searchParams.get(
'catalogue_query',
);
const source = new URL(pageUrl, 'https://portal.invalid');
const target = new URL(base, 'https://portal.invalid');
if (target.origin !== 'https://portal.invalid') return base;
const query = source.searchParams.get('catalogue_query');
const selected = catalogueQuery(target.pathname, query ?? '');
let changedAncestor = false;
for (const key of geography) {
if (target.searchParams.has(key))
changedAncestor ||=
target.searchParams.get(key) !== selected.get(key);
else if (changedAncestor) selected.delete(key);
}
const explicit = new Set(target.searchParams.keys());
for (const [key, value] of selected) {
// Text, kind, price and page belong to their original catalogue only.
if (
family(source.pathname) !== family(target.pathname) &&
!geography.includes(key)
)
continue;
if (!explicit.has(key)) target.searchParams.append(key, value);
}
return searchTerritoryHref(
base + (query ? `?${new URLSearchParams(query).toString()}` : ''),
target.pathname + target.search + target.hash,
pageUrl,
);
}
+8
View File
@@ -1,3 +1,11 @@
/** Historical definitions remain stored verbatim; internal delivery wording is not investor guidance. */
export function companyPreparationNotice(notice: string): string {
return notice.replace(
'Os sete exemplares referidos no complemento ainda não foram fornecidos.',
'Os modelos contratuais não estão disponíveis nesta preparação.',
);
}
export type Party = {
id: string;
name: string | null;
+124
View File
@@ -0,0 +1,124 @@
import type { DemographicAnalysis } from '../components/demographic-evidence';
type Series = DemographicAnalysis['territories'][number]['series'][number];
type Row = Series['values'][number];
const children = ['0-4', '5-9', '10-14'];
const adults = [
'15-19',
'20-24',
'25-29',
'30-34',
'35-39',
'40-44',
'45-49',
'50-54',
'55-59',
'60-64',
];
// Display-only derivation. Original decimals, persisted evidence and fiscal calculations are untouched.
function numeric(row: Row | undefined): number | null {
if (
!row ||
!['pessoas', 'persons'].includes(row.unit) ||
!/^\d+(\.\d+)?$/.test(row.value)
)
return null;
const n = Number(row.value);
return Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER ? n : null;
}
function one(rows: Row[], age: string, residence = 'all'): Row | undefined {
const found = rows.filter(
(r) =>
r.indicator === 'population' &&
r.age_group === age &&
r.residence === residence,
);
return found.length === 1 ? found[0] : undefined;
}
export const populationLabel = (n: number | null) =>
n === null
? 'Sem dados'
: new Intl.NumberFormat('pt-MZ', { maximumFractionDigits: 0 }).format(
n,
);
export const percentageLabel = (n: number | null) =>
n === null
? 'Sem dados'
: new Intl.NumberFormat('pt-MZ', {
maximumFractionDigits: 1,
minimumFractionDigits: 1,
}).format(n) + '%';
export function demographicReading(series: Series, start: number, end: number) {
function year(year: number) {
const rows = series.values.filter((r) => r.year === year);
const totalRow = one(rows, 'all');
const total = numeric(totalRow);
const compatible = (r: Row | undefined) =>
r &&
totalRow &&
r.unit === totalRow.unit &&
r.data_kind === totalRow.data_kind;
const part = (age: string, residence = 'all') => {
const r = one(rows, age, residence);
return compatible(r) ? numeric(r) : null;
};
const sum = (ages: string[]) => {
const values = ages.map((age) => part(age));
return values.every((v) => v !== null)
? values.reduce<number>((a, v) => a + (v ?? 0), 0)
: null;
};
const share = (n: number | null) =>
total !== null && total > 0 && n !== null && n <= total
? (n / total) * 100
: null;
const urban = part('all', 'urban'),
rural = part('all', 'rural');
const residenceReconciled =
total !== null &&
urban !== null &&
rural !== null &&
Math.abs(urban + rural - total) <=
Math.max(0.000001, total * 1e-10);
const under15 = sum(children),
age15to64 = sum(adults);
return {
year,
total,
kind: totalRow?.data_kind,
unit: totalRow?.unit,
urban,
rural,
urbanShare: residenceReconciled ? share(urban) : null,
ruralShare: residenceReconciled ? share(rural) : null,
under15,
under15Share: share(under15),
age15to64,
age15to64Share: share(age15to64),
};
}
const first = year(start),
last = year(end);
const comparable =
end > start &&
first.total !== null &&
last.total !== null &&
first.kind === last.kind &&
first.unit === last.unit;
const delta = comparable ? last.total! - first.total! : null;
const growth =
delta !== null && first.total! > 0
? (delta / first.total!) * 100
: null;
return {
first,
last,
delta,
growth,
years: Array.from({ length: end - start + 1 }, (_, i) =>
year(start + i),
),
};
}
+14 -9
View File
@@ -329,19 +329,24 @@ export function buildLoanSchedule(input: LoanScheduleInput) {
}
/** A simple one-period budget allows an operating deficit; it is not forced to zero. */
function sumMonetaryInputs(values: string[], label: string): bigint {
if (!values.length)
throw new Error('Indique pelo menos uma parcela conhecida.');
return values.reduce(
(sum, value) => sum + decimalToInteger(value, 2, label),
0n,
);
}
export function sumFinancialAmounts(values: string[]): string {
return money(sumMonetaryInputs(values, 'Parcela'));
}
export function calculateBudget(incomes: string[], expenses: string[]) {
if (incomes.length === 0 || expenses.length === 0)
throw new Error(
'Introduza pelo menos uma linha de receitas e uma linha de despesas; use zero apenas quando esse valor for conhecido.',
);
const incomeTotal = incomes.reduce(
(sum, value) => sum + decimalToInteger(value, 2, 'Receita'),
0n,
);
const expenseTotal = expenses.reduce(
(sum, value) => sum + decimalToInteger(value, 2, 'Despesa'),
0n,
);
const incomeTotal = sumMonetaryInputs(incomes, 'Receita');
const expenseTotal = sumMonetaryInputs(expenses, 'Despesa');
return {
incomeTotal: money(incomeTotal),
expenseTotal: money(expenseTotal),
@@ -444,7 +449,7 @@ export function exportFinancialToolsCsv(
['Estado', 'Estimativa com pressupostos introduzidos pelo utilizador'],
[
'Fonte dos pressupostos',
'Valores editaveis desta ferramenta; os valores iniciais sao exemplos demonstrativos',
'Pressupostos editáveis introduzidos ou recuperados pelo utilizador; conferir antes de utilizar os resultados.',
],
['Período do orçamento e dos custos fixos', input.budgetPeriod],
[
@@ -0,0 +1,94 @@
export type OperatingAssumptions = {
model: '' | 'hotel' | 'agriculture' | 'other';
capacity: string;
price: string;
occupancy: string;
frequency: string;
source: string;
costs: { label: string; annual: string }[];
};
export const emptyOperatingAssumptions = (): OperatingAssumptions => ({
model: '',
capacity: '',
price: '',
occupancy: '',
frequency: '',
source: '',
costs: [],
});
export function restoreOperatingAssumptions(
snapshot: string,
): OperatingAssumptions {
try {
const parsed = JSON.parse(snapshot);
const data = parsed?.data;
if (
parsed.version !== 1 ||
!data ||
!['', 'hotel', 'agriculture', 'other'].includes(data.model)
)
return emptyOperatingAssumptions();
if (
!['capacity', 'price', 'occupancy', 'frequency', 'source'].every(
(key) =>
typeof data[key] === 'string' && data[key].length <= 1000,
)
)
return emptyOperatingAssumptions();
if (
!Array.isArray(data.costs) ||
data.costs.length > 30 ||
!data.costs.every(
(row: { label: unknown; annual: unknown }) =>
typeof row?.label === 'string' &&
typeof row?.annual === 'string' &&
row.label.length <= 120 &&
row.annual.length <= 40,
)
)
return emptyOperatingAssumptions();
return data;
} catch {
return emptyOperatingAssumptions();
}
}
function hundredths(value: string): bigint {
const match = /^(\d{1,15})(?:\.(\d{1,2}))?$/.exec(value.trim());
if (!match)
throw new Error(
'Indique cada pressuposto em falta, com até duas casas decimais.',
);
return BigInt(match[1]) * 100n + BigInt((match[2] ?? '').padEnd(2, '0'));
}
const money = (cents: bigint) =>
`${cents / 100n}.${String(cents % 100n).padStart(2, '0')}`;
export function estimateOperatingRevenue(data: OperatingAssumptions): string {
if (!data.model)
throw new Error('Escolha o modelo de actividade que pretende estimar.');
const capacity = hundredths(data.capacity),
price = hundredths(data.price),
frequency = hundredths(data.frequency);
let numerator = capacity * price * frequency;
let divisor = 10000n;
if (data.model === 'hotel') {
const occupancy = hundredths(data.occupancy);
if (occupancy > 10000n)
throw new Error('A ocupação não pode exceder 100%.');
numerator *= occupancy;
divisor *= 10000n;
}
return money((numerator + divisor / 2n) / divisor);
}
export function estimateOperatingCosts(data: OperatingAssumptions): string {
if (!data.costs.length)
throw new Error(
'Acrescente as categorias de custos que conhece. Valores em falta não são zero.',
);
return money(
data.costs.reduce((total, row) => {
if (!row.label.trim())
throw new Error('Identifique a categoria de cada custo.');
return total + hundredths(row.annual);
}, 0n),
);
}
+31
View File
@@ -32,6 +32,27 @@ export type ContextDocument = {
opportunity_id: number;
download_url: string;
};
export type SupplyAggregate = {
context_revision: number;
recorded_at: string;
requested_territory: { id: string; name: string };
scope: { id: string; name: string; level: string };
broader_context: boolean;
entities: number;
repeated: number;
uncertain: number;
groups: {
code: string;
label: string;
total: number;
first_year: string | null;
last_year: string | null;
}[];
truncated: boolean;
coverage_unknown: boolean;
limitations: string;
interpretation: string;
};
export type ContextReference = {
key: string;
kind: string;
@@ -92,6 +113,7 @@ export type OpportunityChoice = {
source_sha256?: string | null;
};
export type DossierContext = {
promoter_entity?: PromoterEntity;
complements?: import('@/components/investment-complements').Complement[];
requirements_assessment?: RequirementsAssessment;
opportunity_choices?: OpportunityChoice[];
@@ -115,6 +137,12 @@ export type DossierContext = {
updated_at?: string;
dependency_hash?: string;
};
export type PromoterEntity = {
kind: 'company' | 'organization' | 'being_formed' | 'undetermined';
id?: string | null;
source_version?: number | null;
snapshot?: Record<string, string | null>;
};
export type ContextView = {
private_investment?: Preparation | null;
preparation_documents?: PreparationDocument[];
@@ -203,6 +231,9 @@ export async function contextApi<T>(
}
}
export const contextFieldNames: Record<string, string> = {
products_services: 'Actividade concreta e produto ou serviço',
investment_budget_min: 'Orçamento previsto — mínimo',
investment_budget_max: 'Orçamento previsto — máximo',
investment_form: 'Tipo do investimento',
investment_preparation: 'Preparação do pedido',
investment_activity_scope: 'Natureza da actividade',
+166 -4
View File
@@ -1,5 +1,7 @@
import { pathStates, type PathResult } from './investor-path.ts';
import type { SupplyAggregate } from './investor-context';
import { restoreFinancialToolsSnapshot } from './financial-calculators.ts';
import { restoreOperatingAssumptions } from './investment-operating-assistance.ts';
import { buildProjectDossierRows } from './project-dossier.ts';
import type { SwotDraft } from './investment-preparation.ts';
import type {
@@ -34,6 +36,7 @@ export type PreparationReport = {
swot_review_required: boolean;
};
export type InvestorDossierReportInput = {
supply_aggregates?: SupplyAggregate[];
case: { id: string; title: string; version: number };
context_opportunity: string | null;
opportunity_options: unknown[];
@@ -322,6 +325,7 @@ export function createInvestorDossierReport(
generatedAt = new Date().toISOString(),
): DossierReportModel {
const index = investorDossierReportIndex(input);
const supply = input.supply_aggregates?.at(-1);
const row = (
field: string,
value: string,
@@ -339,11 +343,101 @@ export function createInvestorDossierReport(
result.context_state !== 'review_required'
? 'Estimativa guardada'
: 'Histórico — rever antes de utilizar';
const preparation = result.preparation_snapshot ?? {};
for (const [key, label] of Object.entries({
total_investment: 'Investimento declarado do cenário',
secured_amount: 'Financiamento efectivamente mobilizado',
planned_funding: 'Financiamento previsto — não mobilizado',
requested_funding: 'Financiamento solicitado — não mobilizado',
approved_funding: 'Financiamento aprovado — não mobilizado',
annual_revenue: 'Receitas anuais estimadas',
annual_operating_costs: 'Custos anuais estimados',
investment_budget_min: 'Orçamento previsto — mínimo do intervalo',
investment_budget_max: 'Orçamento previsto — máximo do intervalo',
})) {
if (typeof preparation[key] === 'string' && preparation[key].trim())
finance.push(
row(
label,
`${preparation[key]} ${result.currency ?? ''}`.trim(),
reference,
state,
),
);
}
const assumptions = restoreOperatingAssumptions(
preparation.planning_assumptions_snapshot ?? '',
);
if (assumptions.model) {
const assumptionLabels = {
model: 'Modelo escolhido para estimar receitas',
capacity:
assumptions.model === 'hotel'
? 'Quartos disponíveis'
: 'Unidades vendáveis por ciclo',
price: 'Preço declarado',
occupancy: 'Ocupação prevista (%)',
frequency:
assumptions.model === 'hotel'
? 'Dias de funcionamento no ano'
: 'Ciclos ou períodos no ano',
source: 'Fundamento dos pressupostos',
};
for (const [key, label] of Object.entries(assumptionLabels)) {
const value =
key === 'model'
? {
hotel: 'Hotel',
agriculture: 'Agronegócio',
other: 'Outra actividade',
}[assumptions.model]
: assumptions[key as keyof typeof assumptionLabels];
finance.push(
row(
label,
value || 'Por confirmar',
reference,
'Pressuposto declarado, não comprova procura ou rentabilidade',
),
);
}
for (const cost of assumptions.costs)
finance.push(
row(
`Custo anual — ${cost.label}`,
cost.annual || 'Por confirmar',
reference,
state,
),
);
}
try {
if (
result.engine !== 'financial-calculators:v1' ||
!restoreFinancialToolsSnapshot(result.financial_snapshot)
)
const budget = JSON.parse(
preparation.initial_budget_snapshot ?? '{}',
);
if (budget.version === 1 && Array.isArray(budget.rows))
for (const part of budget.rows) {
if (
typeof part?.label === 'string' &&
typeof part?.amount === 'string'
)
finance.push(
row(
`Investimento inicial — ${part.label}`,
part.amount || 'Por confirmar',
reference,
state,
),
);
}
} catch {
/* The original remains stored; malformed optional details do not become invented amounts. */
}
try {
const tools = restoreFinancialToolsSnapshot(
result.financial_snapshot,
);
if (result.engine !== 'financial-calculators:v1' || !tools)
throw new Error('Versão não recuperável');
const currency = result.currency ?? '';
const baseline = new Set(
@@ -358,6 +452,25 @@ export function createInvestorDossierReport(
'Financiamento',
'Orçamento',
]);
if (
preparation.planning_loan === 'no' ||
[
tools.loan.principal,
tools.loan.rate,
tools.loan.months,
].every((value) => !value.trim())
)
sections.delete('Empréstimo educativo');
if (Object.values(tools.breakEven).every((value) => !value.trim()))
sections.delete('Ponto de equilíbrio');
if (
[...tools.incomes, ...tools.expenses].every(
(value) => !value.amount.trim(),
)
)
sections.delete('Orçamento');
if (Object.values(tools.funding).every((value) => !value.trim()))
sections.delete('Financiamento');
const rows = buildProjectDossierRows({
currency,
financial_tools_snapshot: result.financial_snapshot,
@@ -400,6 +513,50 @@ export function createInvestorDossierReport(
'O índice referencia os originais; não incorpora automaticamente os seus anexos nem envia dados a entidades externas.',
],
sections: [
{
id: 'supply',
title: 'Actividades existentes — análise agregada',
private: true,
paragraphs: supply
? [
`Consulta de ${supply.recorded_at}; contexto v${supply.context_revision}.`,
`Âmbito: ${supply.scope.name} (${supply.scope.level}). Local escolhido: ${supply.requested_territory.name}.`,
supply.broader_context
? 'Contexto administrativo mais amplo; não representa apenas a localidade escolhida.'
: 'Âmbito da localização escolhida.',
supply.context_revision !==
input.investment_context?.revision
? 'Contexto alterado; análise anterior preservada e por rever.'
: 'Análise guardada para esta revisão do contexto.',
supply.interpretation,
supply.limitations,
]
: ['Análise agregada ainda não guardada neste dossier.'],
rows: supply
? [
row(
'Entidades identificadas administrativamente',
String(supply.entities),
),
row(
'Observações repetidas, separadas do total',
String(supply.repeated),
),
row(
'Identificações incertas, separadas do total',
String(supply.uncertain),
),
...supply.groups.map((group) =>
row(
group.label,
String(group.total),
`${group.first_year ?? 'Período por confirmar'}–${group.last_year ?? ''}; ${supply.scope.name}`,
'Actividade actual e relação económica por confirmar',
),
),
]
: [],
},
{
id: 'project',
title: 'Investimento e localização em preparação',
@@ -410,11 +567,16 @@ export function createInvestorDossierReport(
rows: Object.entries({
project_title: 'Projecto',
project_summary: 'Descrição',
products_services: 'Actividade e produtos ou serviços',
sector: 'Sector',
province: 'Província',
district: 'Distrito',
location: 'Localização',
total_investment: 'Investimento previsto',
investment_budget_min:
'Orçamento previsto — mínimo do intervalo',
investment_budget_max:
'Orçamento previsto — máximo do intervalo',
currency: 'Moeda',
expected_start_date: 'Início previsto',
})
+1
View File
@@ -22,6 +22,7 @@ export type PathResult = {
context_opportunity?: string | null;
id: string;
financial_snapshot: string;
preparation_snapshot?: Record<string, string>;
currency: string | null;
draft_id: string;
draft_version: number;
+8 -8
View File
@@ -2,16 +2,16 @@ import { csvCell } from './csv.js';
export function defaultCashflowDraftInputs() {
return {
openingCash: '0',
monthlyRevenue: '200000',
monthlyOperatingCosts: '150000',
monthlyDebtService: '0',
openingCash: '',
monthlyRevenue: '',
monthlyOperatingCosts: '',
monthlyDebtService: '',
monthlyTaxAssessed: '',
monthlyTaxSchedule: Array.from({ length: 12 }, () => ''),
vatCreditEstimated: '0',
vatRefundRequested: '0',
vatRefundRecognized: '0',
vatRefundExpectedReceipt: '0',
vatCreditEstimated: '',
vatRefundRequested: '',
vatRefundRecognized: '',
vatRefundExpectedReceipt: '',
vatRefundExpectedMonth: '',
};
}
+8 -1
View File
@@ -91,10 +91,17 @@ export function monthlyIvaInput(
draft: Record<string, unknown>,
settings: MonthlyIvaSettings,
): MonthlyIvaInput {
if (
draft.fiscal_period &&
inputText(draft.fiscal_period) !== settings.start.slice(0, 4)
)
throw new Error(
'O ano escolhido no enquadramento fiscal difere do primeiro mês da projecção. Confira o período; nenhum ano foi alterado automaticamente.',
);
const sales = monthlySalesFromDraft(draft);
if (!/^2026-(0[1-9]|1[0-2])$/.test(settings.start))
throw new Error(
'Indique o primeiro mês real da projecção. Este lote abrange apenas 2026.',
'Indique o primeiro mês real da projecção. Este cálculo dispõe de cobertura apenas para 2026.',
);
const start = Number(settings.start.slice(5));
if (sales.amounts.length > 12 || start + sales.amounts.length > 13)
+45
View File
@@ -0,0 +1,45 @@
export type NavigationFocus = {
case_id: string;
step_code: string | null;
version: number;
};
const key = (actor: number) => `investmoz-navigation-focus:${actor}`;
/** A per-tab hint, never authority to access a dossier. Recheck the server listing. */
export function readNavigationFocus(
actor: number,
allowed: string[],
): NavigationFocus | null {
try {
const value = JSON.parse(sessionStorage.getItem(key(actor)) ?? 'null');
if (
!value ||
!allowed.includes(value.case_id) ||
!Number.isSafeInteger(value.version) ||
value.version < 0
)
return null;
if (
value.step_code !== null &&
!/^S(0[1-9]|1[0-9])$/.test(value.step_code)
)
return null;
return {
case_id: value.case_id,
step_code: value.step_code,
version: value.version,
};
} catch {
return null;
}
}
export function rememberNavigationFocus(
actor: number,
focus: NavigationFocus | null,
): void {
try {
if (focus) sessionStorage.setItem(key(actor), JSON.stringify(focus));
else sessionStorage.removeItem(key(actor));
} catch {
// The current consultation remains usable when browser storage is blocked.
}
}
@@ -0,0 +1,61 @@
import { restoreFinancialToolsSnapshot } from './financial-calculators.ts';
const amount = (value: unknown): string | null => {
if (typeof value !== 'string') return null;
const match = /^(\d+)(?:\.(\d+))?$/.exec(value.trim());
if (!match) return null;
return (
match[1].replace(/^0+(?=\d)/, '') +
'.' +
(match[2] ?? '').replace(/0+$/, '')
);
};
export const samePlanningAmount = (a: string, b: string) =>
(!a && !b) || (amount(a) !== null && amount(a) === amount(b));
/** Compare named origins without adopting either one or turning unknown into zero. */
export function fundingDifferences(
source: { total: string; secured: string },
calculator: { total: string; secured: string },
) {
return (['total', 'secured'] as const).filter(
(key) => !samePlanningAmount(source[key], calculator[key]),
);
}
/** Unknown calculator inputs may reuse the canonical source; a known divergent value requires a decision. */
export function canLinkFundingSource(
source: { total: string; secured: string } | undefined,
stored: { total: string; secured: string } | undefined,
): boolean {
return Boolean(
source &&
(!stored ||
(['total', 'secured'] as const).every(
(key) =>
!stored[key].trim() ||
samePlanningAmount(source[key], stored[key]),
)),
);
}
export function draftFundingDifferences(draft: Record<string, unknown>) {
const snapshot = restoreFinancialToolsSnapshot(
typeof draft.financial_tools_snapshot === 'string'
? draft.financial_tools_snapshot
: undefined,
);
if (!snapshot) return [];
return fundingDifferences(
{
total:
typeof draft.total_investment === 'string'
? draft.total_investment
: '',
secured:
typeof draft.secured_amount === 'string'
? draft.secured_amount
: '',
},
snapshot.funding,
);
}
+50
View File
@@ -0,0 +1,50 @@
/** Only confirmed context becomes a criterion; titles never assign a sector. */
export function preparationSearch(
query: string,
sector: string,
path: { id: string; location_type: string }[],
) {
const params = new URLSearchParams();
if (query.trim()) params.set('q', query.trim());
if (/^sector:[1-9]\d*$/.test(sector))
params.set('sector_id', sector.slice(7));
for (const place of path)
if (
['province', 'district', 'admin_post', 'locality'].includes(
place.location_type,
)
)
params.set(place.location_type + '_id', place.id);
return params.toString();
}
/** Carry only deliberate preparation criteria, never catalogue relationships. */
export function createInvestmentHref(
values: Record<string, unknown>,
path: { id: string; location_type: string }[] = [],
) {
const query = new URLSearchParams();
for (const key of ['sector_id', 'project_title', 'currency']) {
if (typeof values[key] === 'string' && values[key])
query.set(key, values[key]);
}
if (typeof values.sector === 'string' && values.sector)
query.set('sector', values.sector);
for (const [from, to] of [
['min_amount', 'investment_budget_min'],
['max_amount', 'investment_budget_max'],
] as const) {
if (typeof values[from] === 'string' && values[from] !== '')
query.set(to, values[from]);
}
for (const place of path)
if (
['province', 'district', 'admin_post', 'locality'].includes(
place.location_type,
)
)
query.set(place.location_type + '_id', place.id);
return (
'/investimentos/iniciar' + (query.size ? '?' + query.toString() : '')
);
}
+2 -1
View File
@@ -33,7 +33,8 @@ export const dossierReportSections = [
] as const;
export type DossierReportSectionId =
(typeof dossierReportSections)[number]['id'];
| (typeof dossierReportSections)[number]['id']
| 'supply';
export type DossierReference = {
version: number;
date: string;
+1
View File
@@ -38,6 +38,7 @@ export function simulationApiFieldErrors(
for (const [path, messages] of Object.entries(value.errors ?? {})) {
const key = path
.replace(/^(economic_snapshot|personal_snapshot)\./, '')
.replace(/^selection_labels\./, '')
.split('.')[0];
if (/^[a-z][a-z0-9_]*$/.test(key) && messages.length)
fields[key] = messages.join(' ');
+164 -2
View File
@@ -8,6 +8,114 @@ export type SimulationDraft = Record<string, string | string[]>;
export const projectQuestionnaireVersion =
'investmoz-project-dossier-2026-10-05.1';
export function isAssistedInvestmentJourney(draft: SimulationDraft): boolean {
return (
draft.journey_type === 'investor' &&
['simulate_only', 'own_investment'].includes(String(draft.purpose)) &&
draft.detail_level !== 'advanced'
);
}
export const assistedInvestmentSections = [
{ id: 'purpose', title: 'Intenção, entidade e localização' },
{ id: 'market', title: 'Mercado e dimensão do negócio' },
{ id: 'investment', title: 'Investimento inicial' },
{ id: 'financial', title: 'Financiamento' },
{ id: 'operating', title: 'Receitas e custos' },
{ id: 'cashflow', title: 'Tesouraria e cenários' },
{ id: 'tax', title: 'Enquadramento fiscal' },
{ id: 'review', title: 'Resultados e próximos passos' },
];
/** One field contract for rendering, validation and the final review. */
export function simulationFieldsForSection(
draft: SimulationDraft,
section: string,
) {
if (!isAssistedInvestmentJourney(draft))
return simulationFieldGroups[section] ?? [];
const unique = (fields: (typeof simulationFieldGroups)[string]) =>
fields.filter(
(field, index) =>
fields.findIndex((other) => other.key === field.key) === index,
);
if (section === 'purpose')
return unique([
...simulationFieldGroups.purpose.filter((field) =>
[
'journey_type',
'detail_level',
'purpose',
'preferred_language',
].includes(field.key),
),
...simulationFieldGroups.project.filter((field) =>
[
'project_title',
'project_summary',
'products_services',
'sector_id',
'activity_id',
].includes(field.key),
),
...simulationFieldGroups.location.filter((field) =>
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
].includes(field.key),
),
]);
if (section === 'market')
return unique([
...simulationFieldGroups.project.filter(
(field) =>
![
'project_title',
'project_summary',
'products_services',
'sector_id',
'activity_id',
].includes(field.key),
),
...simulationFieldGroups.market,
]);
if (section === 'investment')
return simulationFieldGroups.financial.filter((field) =>
['cost_estimate_status', 'currency', 'total_investment'].includes(
field.key,
),
);
if (section === 'financial')
return simulationFieldGroups.financial.filter(
(field) =>
![
'cost_estimate_status',
'currency',
'total_investment',
'annual_revenue',
'annual_operating_costs',
'expected_profit',
'receivables_timing_status',
'planning_loan',
].includes(field.key),
);
if (section === 'operating')
return simulationFieldGroups.financial.filter((field) =>
[
'annual_revenue',
'annual_operating_costs',
'expected_profit',
].includes(field.key),
);
if (section === 'cashflow')
return simulationFieldGroups.financial.filter((field) =>
['receivables_timing_status', 'planning_loan'].includes(field.key),
);
return simulationFieldGroups[section] ?? [];
}
function isProjectGuidedJourney(draft: SimulationDraft): boolean {
return (
draft.purpose === 'simulate_only' &&
@@ -80,6 +188,7 @@ export const simulationSections = [
/** Keep the anonymous arithmetic journey short; formal submissions retain the full questionnaire. */
export function getSimulationSections(draft: SimulationDraft) {
if (isAssistedInvestmentJourney(draft)) return assistedInvestmentSections;
if (isProjectGuidedJourney(draft)) {
if (draft.journey_type === 'small_business') {
return [
@@ -192,7 +301,28 @@ export const advancedSimulationFields = new Set([
'required_documents',
]);
export function simulationFieldAvailableAtDetailLevel(
draft: SimulationDraft,
section: string,
key: string,
): boolean {
return (
draft.detail_level === 'advanced' ||
(isAssistedInvestmentJourney(draft) &&
[
'secured_amount',
'sought_amount',
'annual_revenue',
'annual_operating_costs',
'expected_profit',
].includes(key)) ||
(section === 'procedures' && key === 'required_documents') ||
!advancedSimulationFields.has(key)
);
}
export const simulationOptions: Record<string, string[]> = {
planning_loan: ['yes', 'no', 'unknown'],
journey_type: ['personal', 'small_business', 'company', 'investor'],
detail_level: ['simple', 'advanced'],
purpose: [
@@ -784,6 +914,30 @@ export const simulationFieldGroups: Record<
},
],
financial: [
{
key: 'planning_loan',
label: 'Pretende estudar um empréstimo neste cenário?',
options: 'planning_loan',
showWhen: isAssistedInvestmentJourney,
},
{
key: 'planned_funding',
label: 'Financiamento previsto (ainda não mobilizado)',
type: 'number',
showWhen: isAssistedInvestmentJourney,
},
{
key: 'requested_funding',
label: 'Financiamento solicitado (ainda não mobilizado)',
type: 'number',
showWhen: isAssistedInvestmentJourney,
},
{
key: 'approved_funding',
label: 'Financiamento aprovado (ainda não mobilizado)',
type: 'number',
showWhen: isAssistedInvestmentJourney,
},
{
key: 'cost_estimate_status',
label: 'Já identificou os principais custos e respectiva periodicidade?',
@@ -1540,6 +1694,9 @@ export function restoreSimulationDraft(
export function simulationDraftFingerprint(draft: SimulationDraft): string {
const sort = (value: unknown): unknown => {
// Nullable empty form inputs are normalised to null by the HTTP
// middleware. They remain unknown, never numeric zero.
if (value === null) return '';
if (Array.isArray(value)) return value.map(sort);
if (value && typeof value === 'object')
return Object.fromEntries(
@@ -1561,7 +1718,7 @@ export function validateSimulationDraft(
if (sectionId === 'tax' && draft.fiscal_scenario_mode === 'custom_planning')
return {};
const errors: Record<string, string> = {};
for (const field of simulationFieldGroups[sectionId] ?? []) {
for (const field of simulationFieldsForSection(draft, sectionId)) {
if (field.showWhen && !field.showWhen(draft)) continue;
if (
sectionId === 'tax' &&
@@ -1581,7 +1738,12 @@ export function validateSimulationDraft(
if (
required &&
empty &&
!(sectionId === 'tax' && isInvestorProjectJourney(draft))
!(isAssistedInvestmentJourney(draft) && sectionId !== 'purpose') &&
!(
sectionId === 'tax' &&
(isInvestorProjectJourney(draft) ||
isAssistedInvestmentJourney(draft))
)
) {
errors[field.key] = 'Este campo é obrigatório.';
}
+259 -100
View File
@@ -9,14 +9,25 @@ import {
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 Index({
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[];
@@ -36,6 +47,10 @@ export default function Index({
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 }[];
@@ -44,7 +59,11 @@ export default function Index({
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 ?? '',
@@ -57,9 +76,21 @@ export default function Index({
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 && (
@@ -76,20 +107,96 @@ export default function Index({
investimento.
</p>
<form
className={`${card} flex flex-wrap gap-4`}
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
Categoria da instituição
<select
className="block rounded border p-2"
value={form.data.category}
onChange={(e) =>
form.setData('category', e.target.value)
}
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(
@@ -102,7 +209,7 @@ export default function Index({
</select>
</label>
<label>
Tipo
Tipo de instituição
<select
className="block rounded border p-2"
value={form.data.institution_type}
@@ -111,11 +218,19 @@ export default function Index({
}
>
<option value="">Todos</option>
{Object.entries(financialTypes).map(([id, label]) => (
<option key={id} value={id}>
{label}
</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>
@@ -174,7 +289,7 @@ export default function Index({
/>
</label>
<label>
Tipo
Tipo de registo a consultar
<select
className="block rounded border p-2"
value={form.data.kind}
@@ -206,23 +321,41 @@ export default function Index({
))}
</select>
</label>
<label>
Local de interesse
<select
className="block rounded border p-2"
value={form.data.territory}
onChange={(e) =>
form.setData('territory', e.target.value)
<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 ?? '',
})
}
>
<option value="">Todos</option>
{options.territories.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
/>
</fieldset>
<label>
Informação por confirmar
<select
@@ -256,82 +389,108 @@ export default function Index({
</select>
</label>
</form>
<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 && (
<p>
Não foram encontrados programas publicados para esta
pesquisa.
{criteriaChanged && (
<p role="status">
Alterou os critérios. Clique em Pesquisar para os aplicar.
Os resultados anteriores ficam separados abaixo.
</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 ? (
<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 existe uma janela de candidatura confirmada para
este programa.
Não foram encontradas instituições, fundos ou
programas publicados que correspondam a todos os
critérios desta pesquisa.
</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>
{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>
);
}
@@ -3,6 +3,7 @@ import {
persistOpportunitySelection,
} from '@/lib/opportunity-selection';
import CatalogueGuideLinks from '@/components/catalogue-guide-links';
import PublishedOpportunitiesEmpty from '@/components/published-opportunities-empty';
import DemographicContext from '@/components/demographic-context';
import OpportunityCorridorGroups, {
type CorridorGroup,
@@ -409,6 +410,10 @@ export default function Catalogue({
: 'Catálogo de investimento'
}
>
<section className="my-4 space-y-3 rounded border p-4" aria-label="Estudar a localização">
<h2 className="font-semibold">Estudar a localização e preparar uma ideia</h2>
<p>A análise territorial é independente dos anúncios publicados. Os filtros comerciais abaixo aplicam-se à pesquisa de oportunidades.</p>
<div className="flex flex-wrap items-center gap-4">
<Link
className="underline"
href={
@@ -435,6 +440,8 @@ export default function Catalogue({
Iniciar ou continuar ideia nesta localização
</Link>
)}
</div>
</section>
<p className="catalogue-intro">
Combine os filtros para encontrar oportunidades publicadas.
Nenhum critério é alargado automaticamente.
@@ -506,6 +513,15 @@ export default function Catalogue({
error={searchError}
total={results.total}
/>
{!searchLoading &&
!searchError &&
results.total === 0 &&
selectedStructures.length === 0 && (
<PublishedOpportunitiesEmpty
href="/localizacoes/demografia"
label="Consultar indicadores territoriais"
/>
)}
{!searchLoading &&
!searchError &&
results.total === 0 &&
@@ -36,6 +36,7 @@ type Result = {
}[];
};
type Props = {
entity_kind?: string;
definition: { version: string; questions: Record<string, Question> };
case: { id: string; title: string; version: number } | null;
canWrite: boolean;
@@ -98,7 +99,7 @@ function Comparator(props: Props) {
}),
);
};
async function save() {
async function save(next?: string) {
if (!dossier || busy) return;
setBusy(true);
setError('');
@@ -107,8 +108,9 @@ function Comparator(props: Props) {
version: dossier.version,
operation_key: operation.current,
answers: currentValues(),
...(next ? { continue_preparation: true } : {}),
});
router.visit(base, { preserveState: false });
router.visit(next ?? base, { preserveState: false });
} catch (e) {
setError(
e instanceof Error
@@ -222,7 +224,7 @@ function Comparator(props: Props) {
type="button"
className={button}
disabled={busy}
onClick={save}
onClick={() => void save()}
>
{busy ? 'A guardar…' : 'Guardar no dossier'}
</button>
@@ -321,9 +323,36 @@ function Comparator(props: Props) {
</article>
))}
</div>
<h3 className="mt-4 font-semibold">
Preparar a próxima conversa
</h3>
<h3 className="mt-4 font-semibold">Continuar a preparação</h3>
{dossier &&
!['company', 'organization'].includes(
props.entity_kind ?? '',
) &&
!readOnly &&
props.canWrite &&
answers.preferred &&
answers.preferred !== 'unknown' && (
<button
className={button}
type="button"
disabled={busy}
onClick={() =>
void save(
`/investimentos/${dossier.id}/preparar-empresa?form=${encodeURIComponent(answers.preferred)}`,
)
}
>
Usar esta opção e continuar a preparação da empresa
</button>
)}
{dossier && (
<Link
className="block underline"
href={`/simulador-fiscal?context=${dossier.id}`}
>
Continuar a viabilidade sem repetir esta comparação
</Link>
)}
<ul className="list-disc pl-5">
{result.preparation.map((item) => (
<li key={item}>{item}</li>
@@ -1,9 +1,11 @@
import CurrencySelect from '@/components/currency-select';
import { useRef, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { Frame, card, input, button } from './shared';
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
import { createOperationKey } from '@/lib/operation-key';
import {
companyPreparationNotice,
preparationValues,
type CompanyFacts,
type Party,
@@ -34,12 +36,17 @@ type Props = {
>;
history: { id: string; revision: number; at: string }[];
historyNext: number | null;
entity?: {
kind: string;
snapshot?: { name?: string; legal_form?: string };
} | null;
proposedForm?: string | null;
};
export default function CompanyPreparation(props: Props) {
return (
<Preparation
key={`${props.case.id}:${props.saved?.revision}:${props.historical}`}
key={`${props.case.id}:${props.saved?.revision}:${props.historical}:${props.proposedForm ?? ''}`}
{...props}
/>
);
@@ -86,19 +93,19 @@ function Preparation(props: Props) {
onChange={(e) => update(key, e.target.value)}
maxLength={2000}
/>
) : key === 'currency' ? (
<CurrencySelect
label="Moeda"
value={facts[key] ?? ''}
onChange={(value) => update(key, value)}
/>
) : (
<input
className={input}
name={key}
value={facts[key] ?? ''}
onChange={(e) => update(key, e.target.value)}
maxLength={
key === 'proposed_name'
? 250
: key === 'currency'
? 3
: 25
}
maxLength={key === 'proposed_name' ? 250 : 25}
/>
)}
</label>
@@ -138,7 +145,7 @@ function Preparation(props: Props) {
</label>
);
}
async function save() {
async function save(next?: string) {
if (busy || readOnly) return;
setBusy(true);
setError('');
@@ -151,7 +158,7 @@ function Preparation(props: Props) {
operation_key: operation.current,
facts: values,
});
router.visit(base, { preserveState: false });
router.visit(next ?? base, { preserveState: false });
} catch (e) {
setError(
e instanceof Error
@@ -178,7 +185,41 @@ function Preparation(props: Props) {
}
}
return (
<Frame title="Preparar a constituição da empresa">
<Frame
title={
['company', 'organization'].includes(props.entity?.kind ?? '')
? 'Preparação da empresa existente'
: 'Preparar a constituição da empresa'
}
>
{props.entity?.snapshot?.name && (
<p>
Entidade associada: {props.entity.snapshot.name}. Os dados
recuperados não alteram o cadastro nem comprovam um acto
legal.
</p>
)}
{props.proposedForm &&
facts.form !== props.proposedForm &&
!readOnly && (
<aside className={card}>
<p>
A alternativa escolhida não substituiu a forma já
preparada.
</p>
<button
type="button"
className="underline"
onClick={() => {
update('form', props.proposedForm!);
setDirty(true);
operation.current = createOperationKey();
}}
>
Usar a alternativa escolhida nesta preparação
</button>
</aside>
)}
<p>
<Link
className="underline"
@@ -194,7 +235,7 @@ function Preparation(props: Props) {
Comparar formas jurídicas
</Link>
</p>
<p>{props.definition.template_notice}</p>
<p>{companyPreparationNotice(props.definition.template_notice)}</p>
<p>
Guarde mesmo que faltem dados. Só se pedem informações desta
preparação; valores indicados como realizados são declarações,
@@ -619,6 +660,18 @@ function Preparation(props: Props) {
<button type="submit" className={button}>
Guardar ficha no dossier
</button>
<button
type="button"
className={button}
disabled={busy}
onClick={() =>
void save(
`/simulador-fiscal?context=${props.case.id}`,
)
}
>
Guardar e continuar para a viabilidade
</button>
</section>
</fieldset>
</form>
+126 -23
View File
@@ -1,11 +1,21 @@
import { router } from '@inertiajs/react';
import { useState } from 'react';
import CatalogueChoiceSelect from '@/components/catalogue-choice-select';
import DemographicEvidence, {
type DemographicAnalysis,
} from '@/components/demographic-evidence';
import { Frame, button } from './shared';
export default function Demography({
export default function Demography(
props: Parameters<typeof DemographySelection>[0],
) {
// Server filters identify this consultation, including browser back/forward.
return (
<DemographySelection key={JSON.stringify(props.filters)} {...props} />
);
}
function DemographySelection({
evidence,
filters,
territories,
@@ -27,6 +37,10 @@ export default function Demography({
sectors: Record<string, string>;
}) {
const [selected, setSelected] = useState(filters.territories ?? []);
const [province, setProvince] = useState('');
const [district, setDistrict] = useState('');
const [selectionNotice, setSelectionNotice] = useState('');
const candidate = district || province;
const [start, setStart] = useState(
filters.start_year ?? new Date().getFullYear(),
);
@@ -55,31 +69,96 @@ export default function Demography({
);
}}
>
<label>
Províncias ou distritos (até quatro)
<select
multiple
className="block h-48 w-full rounded border p-2"
value={selected}
onChange={(e) =>
setSelected(
Array.from(
e.target.selectedOptions,
(o) => o.value,
).slice(0, 4),
<fieldset className="min-w-0 space-y-3">
<legend>Localizações a comparar (até quatro)</legend>
<label htmlFor="demography-province" className="block">
Província
</label>
<CatalogueChoiceSelect
id="demography-province"
label="Província da comparação"
value={province}
options={territories
.filter((t) => t.location_type === 'province')
.map((t) => ({ value: t.id, label: t.name }))}
onChange={(value) => {
setProvince(value);
if (district)
setSelectionNotice(
'A escolha do distrito foi limpa. Os locais já acrescentados à comparação foram mantidos.',
);
setDistrict('');
}}
/>
<label htmlFor="demography-district" className="block">
Distrito (opcional)
</label>
<CatalogueChoiceSelect
id="demography-district"
label="Distrito da comparação (opcional)"
value={district}
disabled={!province}
options={territories
.filter(
(t) =>
t.location_type === 'district' &&
t.parent_id === province,
)
.map((t) => ({ value: t.id, label: t.name }))}
onChange={setDistrict}
/>
<p>
Pode comparar apenas a província ou escolher um dos seus
distritos.
</p>
{selectionNotice && <p role="status">{selectionNotice}</p>}
<button
type="button"
className={button}
disabled={
!candidate ||
selected.length >= 4 ||
selected.includes(candidate)
}
onClick={() =>
setSelected((current) => [...current, candidate])
}
>
{territories.map((t) => (
<option key={t.id} value={t.id}>
{t.name} —{' '}
{t.location_type === 'province'
? 'Província'
: `Distrito (${territories.find((p) => p.id === t.parent_id)?.name ?? ''})`}
</option>
))}
</select>
</label>
Acrescentar à comparação
</button>
<ul className="space-y-2">
{selected.map((id) => {
const t = territories.find(
(item) => item.id === id,
);
const label = t
? `${t.name} — ${t.location_type === 'province' ? 'Província' : 'Distrito'}`
: 'Localização guardada';
return (
<li
key={id}
className="flex flex-wrap items-center gap-2"
>
<span>{label}</span>
<button
type="button"
className="underline"
aria-label={`Retirar ${label} da comparação`}
onClick={() =>
setSelected((current) =>
current.filter(
(value) => value !== id,
),
)
}
>
Retirar
</button>
</li>
);
})}
</ul>
</fieldset>
<div className="space-y-3">
<label className="block">
Sector
@@ -123,6 +202,30 @@ export default function Demography({
</div>
</form>
<DemographicEvidence evidence={evidence} />
{evidence.territories.length > 0 && (
<section className="space-y-3 rounded border p-4">
<h2 className="text-xl font-semibold">
Transformar a análise numa ideia
</h2>
<p>
Prepare uma ideia nesta localização e confronte-a com a
oferta existente. Não é necessário haver uma
oportunidade publicada para iniciar a análise.
</p>
{evidence.territories.map((t) => (
<a
key={t.id}
className="block py-2 underline"
href={
'/investimentos/iniciar?source=' +
encodeURIComponent('territory:' + t.id)
}
>
Preparar ideia em {t.name}
</a>
))}
</section>
)}
</Frame>
);
}
+21
View File
@@ -34,6 +34,7 @@ const labels: Record<string, string> = {
investment_capacity: 'Capacidade de investimento declarada',
name: 'Nome da empresa',
registration: 'Referência de registo / NUIT',
legal_form: 'Forma jurídica declarada',
role: 'Função ou relação com a empresa',
description: 'Actividade e observações',
};
@@ -45,9 +46,13 @@ export default function Profile({
countries,
organizations = [],
organizationCountryAvailable = false,
continuation = null,
legalForms = [],
}: {
account: RecordData;
actorId: number;
continuation?: { id: string; title: string; href: string } | null;
legalForms?: { value: string; label: string }[];
companies: Company[];
countries: Country[];
organizations?: Organization[];
@@ -69,6 +74,17 @@ export default function Profile({
);
return (
<Frame title="Perfil de investimento e empresas">
{continuation && (
<aside className={card}>
<p>
Preparação de {continuation.title}. O cadastro no portal
não comprova a constituição legal.
</p>
<Link className="underline" href={continuation.href}>
Voltar ao dossier e associar esta empresa
</Link>
</aside>
)}
<Link className="underline" href="/formas-juridicas">
Comparar formas jurídicas antes de constituir uma entidade
</Link>
@@ -88,6 +104,7 @@ export default function Profile({
actorId={actorId}
editorId="account"
labels={labels}
legalForms={legalForms}
reportDirty={reportDirty}
record={account}
countries={countries}
@@ -132,6 +149,7 @@ export default function Profile({
actorId={actorId}
editorId={company.id}
labels={labels}
legalForms={legalForms}
reportDirty={reportDirty}
record={company}
organizations={organizations}
@@ -140,6 +158,7 @@ export default function Profile({
'name',
'incorporation_country_code',
'registration',
'legal_form',
'sector',
'role',
'description',
@@ -172,6 +191,7 @@ export default function Profile({
actorId={actorId}
editorId="new-company"
labels={labels}
legalForms={legalForms}
reportDirty={reportDirty}
record={{ version: 0, payload: {} }}
company
@@ -180,6 +200,7 @@ export default function Profile({
'name',
'incorporation_country_code',
'registration',
'legal_form',
'sector',
'role',
'description',
@@ -12,6 +12,7 @@ import {
type OpportunityChoice,
} from '@/lib/investor-context';
import { createOperationKey } from '@/lib/operation-key';
import InvestmentBudgetRange from '@/components/investment-budget-range';
export default function ContextStart({
contexts,
source,
@@ -36,7 +37,10 @@ export default function ContextStart({
0,
200,
)
: (source?.title ?? opportunityChoices[0]?.opportunity.title ?? ''),
: (entryQuery.project_title ??
source?.title ??
opportunityChoices[0]?.opportunity.title ??
''),
);
const [consent, setConsent] = useState(false);
const [busy, setBusy] = useState(false);
@@ -80,6 +84,14 @@ export default function ContextStart({
};
return (
<Frame title="Iniciar ou continuar um investimento">
{!source && !opportunityChoices.length && (
<p>
Prepare a sua ideia no mesmo dossier, mesmo sem anúncios
publicados. Corredores, parques e zonas são associações
opcionais.
</p>
)}
<InvestmentBudgetRange values={entryQuery} />
<SelectedComplements items={entryComplements} />
{!!opportunityChoices.length && (
<section className={card}>
+445 -281
View File
@@ -29,14 +29,30 @@ import OpportunityChoices from '@/components/investment-opportunity-choices';
import InvestmentRequirements from '@/components/investment-requirements';
import type { OpportunityChoice } from '@/lib/investor-context';
import type { CorridorOption } from '@/components/investment-opportunity-choices';
import CountrySelect, { type Country } from '@/components/country-select';
import CurrencySelect from '@/components/currency-select';
import InvestmentBudgetRange from '@/components/investment-budget-range';
import DemographicContext from '@/components/demographic-context';
import { preparationSearch } from '@/lib/preparation-intent';
type Options = {
opportunities: { key: string; title: string; kind: string }[];
opportunities: {
key: string;
title: string;
kind: string;
relevance?: string;
}[];
countries?: Country[];
sectors: { id: number; name: string }[];
parks: { id: string; name: string; version_no: number }[];
search_limited: boolean;
};
type Slot = 'portfolio' | 'opportunity' | 'sector' | 'territory' | 'park';
export default function ContextEditor({
export default function ContextEditor(
props: Parameters<typeof ScopedContextEditor>[0],
) {
return <ScopedContextEditor key={props.initial.case.id} {...props} />;
}
function ScopedContextEditor({
initial,
options: initialOptions,
source,
@@ -47,6 +63,7 @@ export default function ContextEditor({
entryLocationDifferences = [],
entryComplements = [],
entryTerritory = null,
entryIdea = {},
}: {
initial: ContextView;
options: Options;
@@ -56,6 +73,7 @@ export default function ContextEditor({
entrySources?: string[];
entryComplements?: Complement[];
entryTerritory?: ContextReference | null;
entryIdea?: Record<string, string>;
entryLocationDifferences?: {
title: string;
saved: string;
@@ -78,7 +96,21 @@ export default function ContextEditor({
>([]);
const [complementError, setComplementError] = useState('');
const [choices, setChoices] = useState<OpportunityChoice[]>(
requestedChoices ?? initial.context.opportunity_choices ?? [],
requestedChoices ??
(initial.context.opportunity_choices?.length
? initial.context.opportunity_choices
: initial.context.selection.opportunity?.kind === 'opportunity'
? [
{
opportunity: initial.context.selection.opportunity,
territory:
initial.context.selection.territory ?? null,
territory_path: territorySelection,
location_reason: '',
location_state: 'undetermined',
},
]
: []),
);
const [manageChoices, setManageChoices] = useState(
requestedChoices !== null ||
@@ -149,8 +181,17 @@ export default function ContextEditor({
const [preparation, setPreparation] = useState(initial.private_investment);
const [options, setOptions] = useState(initialOptions);
const [query, setQuery] = useState('');
const [relatedOpen, setRelatedOpen] = useState(false);
const [relatedSearch, setRelatedSearch] = useState<string | null>(null);
const [consultationPath, setConsultationPath] =
useState(territorySelection);
const [changes, setChanges] = useState<Partial<Record<Slot, string>>>(
() => ({
...(entryIdea.sector_id &&
!initial.context.selection.sector &&
!draft?.selection?.sector
? { sector: 'sector:' + entryIdea.sector_id }
: {}),
...draft?.selection,
...(entryTerritory &&
!draft?.selection?.territory &&
@@ -159,7 +200,7 @@ export default function ContextEditor({
: {}),
...(source?.kind === 'portfolio'
? { portfolio: source.key }
: draft?.selection
: draft?.selection || source?.kind === 'territory'
? {}
: source
? {
@@ -171,7 +212,20 @@ export default function ContextEditor({
}),
);
const [declarations, setDeclarations] = useState<Record<string, string>>(
draft?.declarations ?? {},
() => ({
...Object.fromEntries(
Object.entries(entryIdea).filter(
([key]) =>
[
'project_title',
'investment_budget_min',
'investment_budget_max',
'currency',
].includes(key) && !initial.context.fields[key],
),
),
...draft?.declarations,
}),
);
const [documentLinks, setDocumentLinks] = useState<
Record<string, string | null>
@@ -188,21 +242,32 @@ export default function ContextEditor({
const [message, setMessage] = useState('');
const [corridors, setCorridors] = useState<CorridorOption[]>([]);
const [parks, setParks] = useState<Options['parks']>([]);
const [corridorLoading, setCorridorLoading] = useState(true);
const [corridorLoading, setCorridorLoading] = useState(
choices.length > 0 || consultationPath.length > 0,
);
const [corridorError, setCorridorError] = useState('');
const [corridorRetry, setCorridorRetry] = useState(0);
const [draftStatus, setDraftStatus] = useState('');
const [draftRetry, setDraftRetry] = useState(0);
const queue = useRef<Promise<unknown>>(Promise.resolve());
const firstCorridor =
choices[0]?.corridor_key ??
corridors.find((c) => c.name === choices[0]?.coverage)?.key;
const firstTerritory = choices[0]?.territory?.id;
choices[0]?.corridor_key !== undefined
? choices[0].corridor_key
: corridors.find((c) => c.name === choices[0]?.coverage)?.key;
const firstTerritory =
choices[0]?.territory?.id ?? consultationPath.at(-1)?.id;
useEffect(() => {
let active = true;
if (!choices.length && !firstTerritory) {
setCorridorLoading(false);
setCorridorError('');
setParks([]);
return;
}
setCorridorLoading(true);
setCorridorError('');
const params = new URLSearchParams();
if (!choices.length) params.set('include_corridors', '0');
if (firstCorridor) params.set('corridor', firstCorridor);
if (firstTerritory) params.set('territory', firstTerritory);
void contextApi<{
@@ -222,10 +287,9 @@ export default function ContextEditor({
park &&
!data.parks.some((p) => 'park:' + p.id === park)
) {
setChanges((old) => ({ ...old, park: '' }));
setPlan(null);
// Keep the previous association until the investor reviews it.
setMessage(
'A zona ou parque anterior foi retirado porque não tem enquadramento compatível com a localização escolhida.',
'Reveja a zona ou parque anterior: a compatibilidade com esta escolha ainda nao foi confirmada.',
);
}
})
@@ -238,7 +302,7 @@ export default function ContextEditor({
return () => {
active = false;
};
}, [firstCorridor, firstTerritory, corridorRetry]);
}, [firstCorridor, firstTerritory, corridorRetry, choices.length]);
const draftBody = JSON.stringify({
complements: complements.map(complementInput),
entry_sources: entrySources,
@@ -512,8 +576,8 @@ export default function ContextEditor({
</Link>
<p>{view.case.title}</p>
<p>
Confirme as oportunidades e a localização, complete os dados
disponíveis e reveja antes de guardar.
Confirme a sua ideia, o sector e a localização. Complete
apenas o que falta; associar anúncios é opcional.
</p>
<SelectedComplements
items={complements}
@@ -616,7 +680,9 @@ export default function ContextEditor({
</p>
)}
{corridorLoading && (
<p role="status">A carregar opções do corredor…</p>
<p role="status">
A consultar associações documentadas…
</p>
)}
<p role="status">{draftStatus}</p>
{draft?.needs_review && (
@@ -635,16 +701,20 @@ export default function ContextEditor({
Tentar guardar novamente
</button>
)}
<OpportunityChoices
corridors={corridors}
choices={choices}
disabled={busy || corridorLoading || !!corridorError}
onChange={(next) => {
setChoices(next);
setManageChoices(true);
setPlan(null);
}}
/>
{!!choices.length && (
<OpportunityChoices
corridors={corridors}
choices={choices}
disabled={
busy || corridorLoading || !!corridorError
}
onChange={(next) => {
setChoices(next);
setManageChoices(true);
setPlan(null);
}}
/>
)}
{(changes.portfolio ||
view.context.selection.portfolio) && (
<p className="rounded border p-3">
@@ -694,145 +764,165 @@ export default function ContextEditor({
contextId={view.case.id}
/>
)}
<label className="block">
Acrescentar uma oportunidade à escolha
<select
className={input}
value=""
disabled={busy}
onChange={(e) => {
const o = options.opportunities.find(
(o) => o.key === e.target.value,
);
if (
o &&
!choices.some(
(c) => c.opportunity.key === o.key,
<details
open={relatedOpen}
onToggle={(e) => setRelatedOpen(e.currentTarget.open)}
className="rounded border p-3"
>
<summary className="cursor-pointer font-semibold">
Oportunidades relacionadas (opcional)
</summary>
<p>
Pode preparar a sua ideia sem associar um anuncio ou
corredor. Pesquise apenas se uma oportunidade puder
apoiar este investimento.
</p>
<div className="flex flex-wrap gap-2">
<label className="min-w-0 flex-1">
Pesquisar oportunidades
<input
className={input}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</label>
<button
type="button"
className={button}
disabled={busy}
onClick={() => {
setBusy(true);
void contextApi<Options>(
'/investimentos/fontes-contexto?' +
preparationSearch(
query,
selected('sector'),
consultationPath,
),
)
) {
setChoices([
...choices,
{
opportunity: {
...o,
id: o.key.split(':')[1],
href: '/oportunidades',
version: null,
sha256: '',
fields: {},
},
territory: null,
location_reason: '',
location_state: 'undetermined',
},
]);
setManageChoices(true);
setPlan(null);
}
}}
>
<option value="">Seleccionar ficha</option>
{options.opportunities
.filter(
(o) =>
o.kind === 'opportunity' &&
.then((data) => {
setOptions(data);
setRelatedSearch(
preparationSearch(
query,
selected('sector'),
consultationPath,
),
);
})
.catch((e) => setError(e.message))
.finally(() => setBusy(false));
}}
>
Pesquisar
</button>
</div>
<label className="block">
Acrescentar uma oportunidade à escolha
<select
className={input}
value=""
disabled={busy}
onChange={(e) => {
const o = options.opportunities.find(
(o) => o.key === e.target.value,
);
if (o?.kind === 'business') {
change('opportunity', o.key);
setManageChoices(false);
setPlan(null);
return;
}
if (
o &&
!selected('opportunity').startsWith(
'business:',
) &&
!choices.some(
(c) => c.opportunity.key === o.key,
),
)
) {
setChoices([
...choices,
{
opportunity: {
...o,
id: o.key.split(':')[1],
href: '/oportunidades',
version: null,
sha256: '',
fields: {},
},
territory: null,
location_reason: '',
location_state: 'undetermined',
},
]);
setManageChoices(true);
setPlan(null);
}
}}
>
<option value="">Seleccionar ficha</option>
{(relatedSearch ===
preparationSearch(
query,
selected('sector'),
consultationPath,
)
.map((o) => (
<option key={o.key} value={o.key}>
{o.title}
</option>
))}
</select>
</label>
<h2 className="text-xl font-bold">Dados do investimento</h2>
<div className="flex flex-wrap gap-2">
<label className="min-w-0 flex-1">
Pesquisar oportunidades
<input
className={input}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
? options.opportunities
: []
)
.filter(
(o) =>
!choices.some(
(c) =>
c.opportunity.key === o.key,
),
)
.map((o) => (
<option
key={o.key}
value={o.key}
disabled={
o.kind === 'business'
? choices.length > 0
: selected(
'opportunity',
).startsWith('business:')
}
>
{o.title} —{' '}
{o.relevance ??
'Correspondência pelo título; confirme o sector e a localização.'}
</option>
))}
</select>
</label>
<button
type="button"
className={button}
disabled={busy}
onClick={() => {
setBusy(true);
void contextApi<Options>(
'/investimentos/fontes-contexto?q=' +
encodeURIComponent(query),
)
.then(setOptions)
.catch((e) => setError(e.message))
.finally(() => setBusy(false));
}}
>
Pesquisar
</button>
</div>
<label className="grid min-w-0 gap-1">
Referência individual (sem selecção múltipla)
<select
className={input + ' max-w-full min-w-0'}
value={selected('opportunity')}
disabled={busy || manageChoices}
onChange={(e) =>
change('opportunity', e.target.value)
}
>
<option value="">Sem oportunidade associada</option>
{source &&
['opportunity', 'business'].includes(
source.kind,
) &&
!options.opportunities.some(
(x) => x.key === source.key,
) && (
<option value={source.key}>
{source.title}
</option>
)}
{view.context.selection.opportunity &&
!options.opportunities.some(
(x) =>
x.key ===
view.context.selection.opportunity!.key,
) && (
<option
value={
view.context.selection.opportunity
.key
}
>
{
view.context.selection.opportunity
.title
}{' '}
— referência guardada
</option>
)}
{options.opportunities.map((o) => (
<option key={o.key} value={o.key}>
{o.title} ·{' '}
{o.kind === 'business'
? 'Negócios'
: 'Catálogo'}
</option>
))}
</select>
</label>
{options.search_limited && (
<p>
Resultados limitados por página de pesquisa;
especifique o título para encontrar outras
oportunidades.
</p>
)}
{selected('opportunity').startsWith('business:') && (
<p>
{options.opportunities.find(
(o) => o.key === selected('opportunity'),
)?.title ??
view.context.selection.opportunity?.title}
<button
type="button"
className="ml-3 underline"
disabled={busy}
onClick={() => change('opportunity', '')}
>
Retirar esta referencia
</button>
</p>
)}
{options.search_limited && (
<p>
Resultados limitados por página de pesquisa;
especifique o título para encontrar outras
oportunidades.
</p>
)}
</details>
<label className="grid min-w-0 gap-1">
Sector
<select
@@ -866,7 +956,8 @@ export default function ContextEditor({
</select>
</label>
{!manageChoices && (
<>
<details className="rounded border p-3">
<summary>Zonas e parques (opcional)</summary>
<label className="grid min-w-0 gap-1">
{choices.length > 1
? 'Zona ou parque da primeira oportunidade'
@@ -877,7 +968,7 @@ export default function ContextEditor({
busy ||
corridorLoading ||
!!corridorError ||
(!!firstCorridor && !firstTerritory)
!firstTerritory
}
value={selected('park')}
onChange={(e) =>
@@ -887,10 +978,7 @@ export default function ContextEditor({
<option value="">
Sem ZEE, ZFI ou parque seleccionado
</option>
{(firstCorridor
? parks
: options.parks
).map((p) => (
{parks.map((p) => (
<option
key={p.id}
value={'park:' + p.id}
@@ -911,7 +999,7 @@ export default function ContextEditor({
: 'A consulta não confirma disponibilidade de lotes, admissão ou incentivos.'}
</p>
)}
</>
</details>
)}
{!manageChoices && (
<>
@@ -922,15 +1010,16 @@ export default function ContextEditor({
initial={territorySelection}
disabled={busy || manageChoices}
endpoint="/api/v1/investment/territory-options"
onChange={(path) =>
onChange={(path) => {
setConsultationPath(path);
change(
'territory',
path.length
? 'territory:' +
path[path.length - 1].id
: '',
)
}
);
}}
/>
{view.context.selection.territory && (
<p>
@@ -942,117 +1031,11 @@ export default function ContextEditor({
)}
</section>
<section className={card + ' space-y-3'}>
<h2 className="text-xl font-bold">
Declarações deste investimento
</h2>
<p>
Estes campos pertencem ao processo. Alterá-los não muda
o cadastro da oportunidade nem o perfil da organização.
</p>
<p>
Origem do investidor, residência fiscal e constituição
da entidade são declarações distintas. A localização não
confirma benefícios. A prévia identifica o impacto antes
de guardar.
</p>
{[
['currency', 'Moeda do projecto', null],
[
'expected_start_date',
'Data prevista de início',
null,
],
[
'investor_origin',
'Origem do investidor',
[
['national', 'Nacional'],
['foreign', 'Estrangeiro'],
['mixed', 'Misto'],
],
],
[
'person_type',
'Tipo de entidade',
[
['singular', 'Pessoa singular'],
['collective', 'Pessoa colectiva'],
['consortium', 'Consórcio'],
],
],
[
'entity_stage',
'Situação da entidade',
[
['existing', 'Existente'],
['being_formed', 'Em constituição'],
],
],
[
'tax_residency_country',
'País de residência fiscal declarado (ISO de duas letras)',
null,
],
].map(([key, label, choices]) => (
<label className="grid gap-1" key={String(key)}>
{String(label)}
{Array.isArray(choices) ? (
<select
className={input}
disabled={busy}
value={
declarations[String(key)] ??
view.context.fields[String(key)] ??
''
}
onChange={(e) => {
setDeclarations({
...declarations,
[String(key)]: e.target.value,
});
setPlan(null);
}}
>
<option value="">Por indicar</option>
{choices.map(([value, text]) => (
<option key={value} value={value}>
{text}
</option>
))}
</select>
) : (
<input
className={input}
disabled={busy}
type={
key === 'expected_start_date'
? 'date'
: 'text'
}
maxLength={
key === 'currency'
? 3
: key === 'tax_residency_country'
? 2
: 10
}
value={
declarations[String(key)] ??
view.context.fields[String(key)] ??
''
}
onChange={(e) => {
setDeclarations({
...declarations,
[String(key)]: e.target.value,
});
setPlan(null);
}}
/>
)}
</label>
))}
{['project_title', 'project_summary'].map((k) => (
'project_title',
'products_services',
'project_summary',
].map((k) => (
<label className="grid gap-1" key={k}>
{contextFieldNames[k]}
<textarea
@@ -1063,7 +1046,13 @@ export default function ContextEditor({
''
}
disabled={busy}
maxLength={k === 'project_title' ? 200 : 5000}
maxLength={
k === 'project_title'
? 200
: k === 'products_services'
? 2000
: 5000
}
onChange={(e) => {
setDeclarations({
...declarations,
@@ -1074,6 +1063,181 @@ export default function ContextEditor({
/>
</label>
))}
</section>
<InvestmentBudgetRange
values={{ ...view.context.fields, ...declarations }}
onChange={(field, value) => {
setDeclarations((old) => ({ ...old, [field]: value }));
setPlan(null);
}}
/>
<DemographicContext territoryId={consultationPath.at(-1)?.id} />
<section className={card + ' space-y-3'}>
<h2 className="text-xl font-bold">
Declarações deste investimento
</h2>
<details className="rounded border p-3">
<summary>
Enquadramento da entidade e fiscal, quando
necessário
</summary>
<p>
Estes campos pertencem ao processo. Alterá-los não
muda o cadastro da oportunidade nem o perfil da
organização.
</p>
<p>
Origem do investidor, residência fiscal e
constituição da entidade são declarações distintas.
A localização não confirma benefícios. A prévia
identifica o impacto antes de guardar.
</p>
{[
[
'expected_start_date',
'Data prevista de início',
null,
],
[
'investor_origin',
'Origem do investidor',
[
['national', 'Nacional'],
['foreign', 'Estrangeiro'],
['mixed', 'Misto'],
],
],
[
'person_type',
'Tipo de entidade',
[
['singular', 'Pessoa singular'],
['collective', 'Pessoa colectiva'],
['consortium', 'Consórcio'],
],
],
[
'entity_stage',
'Situação da entidade',
[
['existing', 'Existente'],
['being_formed', 'Em constituição'],
],
],
[
'tax_residency_country',
'País de residência fiscal',
null,
],
].map(([key, label, choices]) => (
<label className="grid gap-1" key={String(key)}>
{String(label)}
{key === 'currency' ? (
<CurrencySelect
label="Moeda do projecto"
disabled={busy}
value={
declarations.currency ??
view.context.fields.currency ??
''
}
error={
(declarations.currency ??
view.context.fields.currency) &&
!/^[A-Z]{3}$/.test(
declarations.currency ??
view.context.fields
.currency ??
'',
)
? 'Seleccione a moeda na lista para confirmar este valor anterior.'
: undefined
}
onChange={(value) => {
setDeclarations({
...declarations,
currency: value,
});
setPlan(null);
}}
/>
) : key === 'tax_residency_country' ? (
<CountrySelect
label="País de residência fiscal"
countries={options.countries ?? []}
disabled={busy}
value={
declarations.tax_residency_country ??
view.context.fields
.tax_residency_country ??
''
}
onChange={(value) => {
setDeclarations({
...declarations,
tax_residency_country: value,
});
setPlan(null);
}}
/>
) : Array.isArray(choices) ? (
<select
className={input}
disabled={busy}
value={
declarations[String(key)] ??
view.context.fields[String(key)] ??
''
}
onChange={(e) => {
setDeclarations({
...declarations,
[String(key)]: e.target.value,
});
setPlan(null);
}}
>
<option value="">Por indicar</option>
{choices.map(([value, text]) => (
<option key={value} value={value}>
{text}
</option>
))}
</select>
) : (
<input
className={input}
disabled={busy}
type={
key === 'expected_start_date'
? 'date'
: 'text'
}
maxLength={
key === 'currency'
? 3
: key ===
'tax_residency_country'
? 2
: 10
}
value={
declarations[String(key)] ??
view.context.fields[String(key)] ??
''
}
onChange={(e) => {
setDeclarations({
...declarations,
[String(key)]: e.target.value,
});
setPlan(null);
}}
/>
)}
</label>
))}
</details>
<details>
<summary>
Substituições explícitas de declarações
+42 -2
View File
@@ -15,6 +15,11 @@ import {
type Preparation,
} from '@/components/private-investment-preparation';
import ContextDocuments from '@/components/context-documents';
import InvestmentBudgetRange from '@/components/investment-budget-range';
import DemographicContext from '@/components/demographic-context';
import InvestmentSupplyAggregate from '@/components/investment-supply-aggregate';
import InvestmentPromoter from '@/components/investment-promoter';
import type { SupplyAggregate } from '@/lib/investor-context';
import { SelectedComplements } from '@/components/investment-complements';
import InvestmentRequirements from '@/components/investment-requirements';
import OpportunityChoices from '@/components/investment-opportunity-choices';
@@ -91,6 +96,9 @@ type Path = {
private_investment?: Preparation | null;
fintech: FintechView | null;
investment_context: DossierContext | null;
can_set_promoter?: boolean;
supply_aggregate_enabled?: boolean;
supply_aggregates?: SupplyAggregate[];
zone_contexts?: {
zone_id: string;
consulted_public_version: number;
@@ -652,11 +660,16 @@ export default function InvestmentPath(path: Path) {
)}
{!!path.sector_references?.length && (
<section className="space-y-3 rounded border p-4">
<h2 className="text-lg font-semibold">Sectores e cadeias de valor</h2>
<h2 className="text-lg font-semibold">
Sectores e cadeias de valor
</h2>
{path.sector_references.map((reference) => (
<article key={reference.key}>
<h3>{reference.title}</h3>
<p>{reference.location_label ?? reference.locations_text}</p>
<p>
{reference.location_label ??
reference.locations_text}
</p>
<p>{reference.value_chain}</p>
<Link className="underline" href={reference.href}>
Consultar a referência mineral
@@ -668,12 +681,39 @@ export default function InvestmentPath(path: Path) {
<ContextDocuments
source={path.investment_context?.selection.opportunity}
/>
{path.supply_aggregate_enabled && (
<InvestmentSupplyAggregate
key={path.case.id}
caseId={path.case.id}
version={path.case.version}
revision={path.investment_context?.revision ?? 0}
history={path.supply_aggregates ?? []}
disabled={!path.canWrite}
/>
)}
<InvestmentPromoter
key={path.case.id}
caseId={path.case.id}
selected={path.investment_context?.promoter_entity}
canEdit={path.can_set_promoter ?? false}
/>
<PreparationSummary
data={path.private_investment}
caseId={path.case.id}
/>
{path.investment_context && (
<section className="space-y-2 rounded border border-emerald-300 bg-emerald-50 p-4">
<InvestmentBudgetRange
values={path.investment_context.fields}
/>
<DemographicContext
territoryId={
path.investment_context.fields.locality_id ||
path.investment_context.fields.admin_post_id ||
path.investment_context.fields.district_id ||
path.investment_context.fields.province_id
}
/>
<h2 className="font-semibold">As suas escolhas</h2>
{Object.values(path.investment_context.selection).map(
(ref) => (
+6
View File
@@ -459,6 +459,12 @@ export default function Search({
Experimente outras palavras ou uma expressão
mais curta.
</p>
<p className="mt-2 text-sm text-slate-600">
A pesquisa consulta informação disponível no
portal. Não encontrar anúncios não comprova
ausência de empresas, recursos ou potencial
no território.
</p>
<div className="mt-5">
<QuickLinks />
</div>
+4 -1
View File
@@ -1,6 +1,7 @@
import { Link, useForm, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { catalogueReturnHref } from '@/lib/catalogue-context';
import PublishedOpportunitiesEmpty from '@/components/published-opportunities-empty';
import {
searchTerritoryHref,
portfolioPreparationHref,
@@ -366,7 +367,9 @@ function Editor({
</article>
))}
{!opportunities.length && (
<p>Sem oportunidades publicadas associadas a esta ficha.</p>
<PublishedOpportunitiesEmpty
href={searchTerritoryHref('/oportunidades', pageUrl)}
/>
)}
</section>
{management ? (
+7 -8
View File
@@ -1,3 +1,4 @@
import CurrencySelect from '@/components/currency-select';
import { Link, router, useForm } from '@inertiajs/react';
import InvestmentTerritory, {
TerritoryFields,
@@ -287,19 +288,17 @@ export default function Editor({
/>
</Field>
<Field
label="Moeda (código de três letras)"
label="Moeda do orçamento"
error={form.errors.budget_currency}
>
<input
maxLength={3}
<CurrencySelect
label="Moeda do orçamento"
className={control}
value={form.data.budget_currency}
onChange={(e) =>
form.setData(
'budget_currency',
e.target.value.toUpperCase(),
)
onChange={(value) =>
form.setData('budget_currency', value)
}
error={form.errors.budget_currency}
/>
</Field>
<Field