Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2 into front
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
businessPlanWarnings,
|
||||
type PlanWarningMetrics,
|
||||
type PlanWarningLimits,
|
||||
type PlanWarning,
|
||||
} from '@/lib/business-plan-guidance';
|
||||
|
||||
export function BusinessPlanWarnings({
|
||||
metrics = {},
|
||||
limits,
|
||||
warnings: suppliedWarnings,
|
||||
}: {
|
||||
metrics?: PlanWarningMetrics;
|
||||
limits?: PlanWarningLimits;
|
||||
warnings?: PlanWarning[];
|
||||
}) {
|
||||
const [dismissed, setDismissed] = useState<string[]>([]);
|
||||
const scope = JSON.stringify([metrics, suppliedWarnings, limits]);
|
||||
const warnings = (
|
||||
suppliedWarnings ?? businessPlanWarnings(metrics, limits)
|
||||
).filter((warning) => !dismissed.includes(`${scope}:${warning.id}`));
|
||||
if (!warnings.length) return null;
|
||||
return (
|
||||
<aside
|
||||
aria-label="Avisos de planeamento"
|
||||
className="my-3 space-y-2 rounded border border-amber-400 bg-amber-50 p-3 text-sm text-amber-950"
|
||||
>
|
||||
<h4 className="font-semibold">Avisos — pode continuar</h4>
|
||||
{warnings.map((warning) => (
|
||||
<div
|
||||
key={warning.id}
|
||||
className="flex items-start justify-between gap-3"
|
||||
>
|
||||
<p role="status">
|
||||
<span aria-hidden="true">⚠ </span>
|
||||
{warning.message}
|
||||
{warning.id === 'optional-texts' && (
|
||||
<span className="mt-1 block text-xs">
|
||||
Secções opcionais em falta:{' '}
|
||||
{metrics.optionalTexts
|
||||
?.filter((field) => !field.value.trim())
|
||||
.map((field) => field.label)
|
||||
.join(', ')}
|
||||
.
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 underline"
|
||||
aria-label={`Dispensar aviso: ${warning.message}`}
|
||||
onClick={() =>
|
||||
setDismissed((previous) => [
|
||||
...previous,
|
||||
`${scope}:${warning.id}`,
|
||||
])
|
||||
}
|
||||
>
|
||||
Dispensar
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -43,7 +43,7 @@ export default function CatalogueChoiceSelect({
|
||||
id: value,
|
||||
name:
|
||||
selected?.label ??
|
||||
`${value} — valor anterior; confirme a selecção`,
|
||||
'Escolha guardada — designação por recuperar',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { catalogueFilterHref } from '@/lib/catalogue-context';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
@@ -71,8 +72,17 @@ const values: Record<string, string> = {
|
||||
/** Name each active criterion without exposing IDs or taxonomy codes. */
|
||||
export default function CatalogueFilterContext() {
|
||||
const page = usePage();
|
||||
const filters = page.props.filters as Record<string, unknown> | undefined;
|
||||
if (!filters) return null;
|
||||
const supplied = page.props.filters as Record<string, unknown> | undefined;
|
||||
const path = page.props.territorySelection as
|
||||
| { id: string; name: string; location_type?: string }[]
|
||||
| undefined;
|
||||
const filters: Record<string, unknown> = { ...supplied };
|
||||
path?.forEach((place, index) => {
|
||||
const key = place.location_type
|
||||
? territoryKeys.find((name) => name === `${place.location_type}_id`)
|
||||
: territoryKeys[index];
|
||||
if (key && !filters[key]) filters[key] = place.id;
|
||||
});
|
||||
const active = Object.entries(filters).filter(
|
||||
([key, value]) =>
|
||||
!['page', 'per_page', 'sort', 'view', 'publication_state'].includes(
|
||||
@@ -93,28 +103,15 @@ export default function CatalogueFilterContext() {
|
||||
if (typeof value !== 'string') return 'seleccionado';
|
||||
return (
|
||||
values[value] ??
|
||||
(['q', 'query', 'province', 'topic', 'issuer'].includes(key)
|
||||
(['q', 'query', 'province', 'topic', 'issuer', 'activity'].includes(
|
||||
key,
|
||||
)
|
||||
? value
|
||||
: 'seleccionado')
|
||||
);
|
||||
};
|
||||
const href = (remove?: string) => {
|
||||
const url = new URL(page.url, 'https://portal.invalid');
|
||||
const keys = remove
|
||||
? [
|
||||
remove,
|
||||
...territoryKeys
|
||||
.slice(territoryKeys.indexOf(remove) + 1)
|
||||
.filter(() => territoryKeys.includes(remove)),
|
||||
]
|
||||
: Object.keys(filters);
|
||||
for (const key of keys) {
|
||||
url.searchParams.delete(key);
|
||||
url.searchParams.delete(`${key}[]`);
|
||||
}
|
||||
url.searchParams.delete('page');
|
||||
return url.pathname + url.search;
|
||||
};
|
||||
const href = (remove?: string) =>
|
||||
catalogueFilterHref(page.url, Object.keys(filters), remove);
|
||||
return (
|
||||
<nav
|
||||
aria-label="Filtros activos"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { populationValueLabel } from '@/lib/demographic-reading';
|
||||
import EvidenceDetails from './evidence-details';
|
||||
import DemographicReadingSummary from './demographic-reading-summary';
|
||||
|
||||
@@ -191,30 +192,13 @@ export default function DemographicEvidence({
|
||||
antes de comparar ou utilizar os valores.
|
||||
</p>
|
||||
)}
|
||||
<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>
|
||||
)}
|
||||
<EvidenceDetails title="Valores por ano e dimensão">
|
||||
<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
|
||||
Valores de apresentação por ano e
|
||||
dimensão — versões apresentadas
|
||||
separadamente
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -226,7 +210,6 @@ export default function DemographicEvidence({
|
||||
'Valor',
|
||||
'Unidade',
|
||||
'Tipo',
|
||||
'Referência',
|
||||
].map((h) => (
|
||||
<th className="p-2" key={h}>
|
||||
{h}
|
||||
@@ -262,7 +245,14 @@ export default function DemographicEvidence({
|
||||
}[v.residence]
|
||||
}
|
||||
</td>
|
||||
<td>{v.original_value}</td>
|
||||
<td>
|
||||
{v.indicator ===
|
||||
'population'
|
||||
? populationValueLabel(
|
||||
v.value,
|
||||
)
|
||||
: v.original_value}
|
||||
</td>
|
||||
<td>
|
||||
{v.unit ===
|
||||
'unspecified'
|
||||
@@ -275,9 +265,6 @@ export default function DemographicEvidence({
|
||||
? 'Projecção'
|
||||
: 'Não especificado'}
|
||||
</td>
|
||||
<td>
|
||||
{v.sheet}!{v.cell}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@@ -293,38 +280,55 @@ export default function DemographicEvidence({
|
||||
<h2 className="text-xl font-semibold">
|
||||
Diferenças entre localizações
|
||||
</h2>
|
||||
{evidence.comparisons.map((c) => (
|
||||
<p
|
||||
key={`${c.year}:${c.left_import}:${c.right_import}:${c.left}:${c.right}`}
|
||||
>
|
||||
{c.year}: {c.left} ({c.left_value}) / {c.right} (
|
||||
{c.right_value}). Diferença:{' '}
|
||||
{c.difference ?? 'não comparável'}. {c.explanation}
|
||||
</p>
|
||||
))}
|
||||
{Array.from(
|
||||
new Set(evidence.comparisons.map((c) => c.year)),
|
||||
)
|
||||
.sort((a, b) => a - b)
|
||||
.map((year) => (
|
||||
<section key={year} className="space-y-2">
|
||||
<h3 className="font-semibold">{year}</h3>
|
||||
{evidence.comparisons
|
||||
.filter((c) => c.year === year)
|
||||
.map((c) => (
|
||||
<p
|
||||
key={[
|
||||
c.year,
|
||||
c.left_import,
|
||||
c.right_import,
|
||||
c.left,
|
||||
c.right,
|
||||
].join(':')}
|
||||
>
|
||||
{c.left} (
|
||||
{populationValueLabel(c.left_value)}
|
||||
) / {c.right} (
|
||||
{populationValueLabel(
|
||||
c.right_value,
|
||||
)}
|
||||
). Diferença:{' '}
|
||||
{c.difference === null
|
||||
? 'não comparável: âmbitos ou metadados distintos'
|
||||
: populationValueLabel(
|
||||
c.difference,
|
||||
)}
|
||||
{c.difference !== null &&
|
||||
' pessoas'}
|
||||
.
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{evidence.differences.length > 0 && (
|
||||
<details>
|
||||
<summary>
|
||||
Reconciliação entre exemplares:{' '}
|
||||
{evidence.differences.length} dimensões comuns
|
||||
</summary>
|
||||
<ul>
|
||||
{evidence.differences.map((d) => (
|
||||
<li key={`${d.territory_id}:${d.dimension}`}>
|
||||
{d.dimension}:{' '}
|
||||
{d.state === 'matching_values'
|
||||
? 'valores coincidentes; conservar ambas as fontes'
|
||||
: 'valores divergentes'}{' '}
|
||||
—{' '}
|
||||
{d.values
|
||||
.map((v) => `${v.value} (${v.data_kind})`)
|
||||
.join(' / ')}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
{evidence.differences.some(
|
||||
(d) => d.state === 'divergent_values',
|
||||
) && (
|
||||
<p role="status">
|
||||
Há valores divergentes entre séries para a mesma localização
|
||||
e período. As séries são apresentadas separadamente; não
|
||||
foram somadas nem escolhidas como substitutas umas das
|
||||
outras.
|
||||
</p>
|
||||
)}
|
||||
<ul className="list-disc pl-5 text-sm">
|
||||
{evidence.limitations.map((l) => (
|
||||
|
||||
@@ -31,8 +31,8 @@ export default function DemographicReadingSummary({
|
||||
{current.kind === 'projected'
|
||||
? 'Projecção'
|
||||
: 'Tipo de dado não especificado'}
|
||||
. Valores de apresentação arredondados; os originais permanecem
|
||||
disponíveis abaixo.
|
||||
. Valores de apresentação arredondados; os originais são
|
||||
preservados na administração.
|
||||
</p>
|
||||
<dl className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{[
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
rememberNavigationFocus,
|
||||
} from '@/lib/navigation-focus';
|
||||
export type NavigationView = {
|
||||
context_opportunity?: string | null;
|
||||
case: { id: string; title: string; version: number };
|
||||
phases: Record<string, string>;
|
||||
steps: {
|
||||
@@ -105,7 +106,19 @@ export function NavigationContextProvider({
|
||||
useEffect(() => {
|
||||
setHash(window.location.hash);
|
||||
}, [url]);
|
||||
const current = loaded?.actor === actor ? loaded : null;
|
||||
const pageLocation = new URL(url, 'https://context.invalid');
|
||||
const requestedCase =
|
||||
url.match(/^\/investimentos\/([a-f0-9-]{36})(?:[/?#]|$)/i)?.[1] ??
|
||||
pageLocation.searchParams.get('context');
|
||||
const requestedOpportunity = pageLocation.searchParams.get('opportunity');
|
||||
// Never label the new page with the previous dossier while its request is pending.
|
||||
const current =
|
||||
loaded?.actor === actor &&
|
||||
(!requestedCase || loaded?.focus?.case_id === requestedCase) &&
|
||||
(!requestedOpportunity ||
|
||||
loaded?.view?.context_opportunity === requestedOpportunity)
|
||||
? loaded
|
||||
: null;
|
||||
const active = current?.focus?.case_id ?? '';
|
||||
useEffect(() => {
|
||||
if (!actor || !props.investorPathEnabled) return;
|
||||
@@ -163,13 +176,31 @@ export function NavigationContextProvider({
|
||||
)
|
||||
).focus;
|
||||
}
|
||||
// An explicit URL without an opportunity opens the whole dossier.
|
||||
// A general menu preserves this tab's last server-confirmed scope.
|
||||
const opportunity = direct
|
||||
? new URL(url, 'https://context.invalid').searchParams.get(
|
||||
'opportunity',
|
||||
)
|
||||
: localFocus?.opportunity;
|
||||
if (direct && !listing.contexts.some((c) => c.id === direct)) {
|
||||
focus = null;
|
||||
}
|
||||
const view = focus
|
||||
? await contextApi<NavigationView>(
|
||||
`/investimentos/${focus.case_id}${direct === focus.case_id && new URL(url, 'https://context.invalid').searchParams.get('opportunity') ? '?opportunity=' + encodeURIComponent(new URL(url, 'https://context.invalid').searchParams.get('opportunity')!) : ''}`,
|
||||
`/investimentos/${focus.case_id}${opportunity && (!direct || direct === focus.case_id) ? '?opportunity=' + encodeURIComponent(opportunity) : ''}`,
|
||||
)
|
||||
: null;
|
||||
if (!stopped) {
|
||||
rememberNavigationFocus(actor, focus);
|
||||
rememberNavigationFocus(
|
||||
actor,
|
||||
focus
|
||||
? {
|
||||
...focus,
|
||||
opportunity: view?.context_opportunity ?? null,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
setLoaded({ actor, cases: listing.contexts, focus, view });
|
||||
if (pref.message) setError(pref.message);
|
||||
}
|
||||
@@ -210,8 +241,13 @@ export function NavigationContextProvider({
|
||||
),
|
||||
)
|
||||
.then(({ focus }) => {
|
||||
rememberNavigationFocus(actor, focus);
|
||||
const target = `/investimentos/${id}${step ? '#' + step : ''}`;
|
||||
const opportunity =
|
||||
id === active ? current.view?.context_opportunity : null;
|
||||
rememberNavigationFocus(actor, {
|
||||
...focus,
|
||||
opportunity: opportunity ?? null,
|
||||
});
|
||||
const target = `/investimentos/${id}${opportunity ? '?opportunity=' + encodeURIComponent(opportunity) : ''}${step ? '#' + step : ''}`;
|
||||
if (url !== target) router.visit(target);
|
||||
else setReload((x) => x + 1);
|
||||
})
|
||||
@@ -255,7 +291,9 @@ export function NavigationContextSummary() {
|
||||
const ref = saved?.selection;
|
||||
const params = new URLSearchParams(url.split('?')[1] ?? '');
|
||||
const scopedChoice = saved?.opportunity_choices?.find(
|
||||
(c) => c.opportunity.key === params.get('opportunity'),
|
||||
(c) =>
|
||||
c.opportunity.key ===
|
||||
(params.get('opportunity') ?? view?.context_opportunity),
|
||||
);
|
||||
const multiple = (saved?.opportunity_choices?.length ?? 0) > 1;
|
||||
const currentStep = view?.steps.find((s) => s.code === step);
|
||||
@@ -449,7 +487,7 @@ export function NavigationContextSummary() {
|
||||
{view.investment_context && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`/investimentos/${active}/contexto/editar`}
|
||||
href={`/investimentos/${active}/contexto/editar${scopedChoice ? '?opportunity=' + encodeURIComponent(scopedChoice.opportunity.key) : ''}`}
|
||||
>
|
||||
Comparar e guardar oportunidade,
|
||||
sector ou localização
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { DossierReportModel } from '@/lib/project-dossier-report';
|
||||
import { InvestmentReportTables } from './investment-report-tables';
|
||||
export function DossierReportPreview({
|
||||
report,
|
||||
}: {
|
||||
report: DossierReportModel;
|
||||
}) {
|
||||
return (
|
||||
<article
|
||||
aria-label="Pré-visualização do relatório"
|
||||
className="min-w-0 space-y-3 rounded border p-3"
|
||||
>
|
||||
<h3 className="font-semibold">{report.title}</h3>
|
||||
<p className="text-sm">{report.version}</p>
|
||||
{report.sections.map((section, i) => (
|
||||
<section
|
||||
key={`${section.id}-${i}`}
|
||||
className="min-w-0 space-y-2"
|
||||
>
|
||||
<h4 className="font-medium">{section.title}</h4>
|
||||
{section.paragraphs.map((p, j) => (
|
||||
<p key={j}>{p}</p>
|
||||
))}
|
||||
{section.id !== 'finance' &&
|
||||
section.id !== 'financial-report' ? (
|
||||
section.rows.map((row, j) => (
|
||||
<p key={j} className="break-words">
|
||||
<strong>{row.field}: </strong>
|
||||
{row.value}
|
||||
<small className="block">
|
||||
{row.classification}. {row.origin}
|
||||
</small>
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<dl className="space-y-2">
|
||||
{section.rows.map((r, j) => (
|
||||
<div className="break-words" key={j}>
|
||||
<dt className="font-medium">{r.field}</dt>
|
||||
<dd>{r.value}</dd>
|
||||
<dd className="text-sm">
|
||||
{r.classification} · {r.origin}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
{section.tables && (
|
||||
<InvestmentReportTables tables={section.tables} />
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
{report.limitations.map((p, i) => (
|
||||
<p className="text-sm" key={i}>
|
||||
{p}
|
||||
</p>
|
||||
))}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
type BusinessFinancialPlanInput,
|
||||
} from '@/lib/business-financial-plan';
|
||||
import {
|
||||
dayTermLabels,
|
||||
type DayTermKind,
|
||||
type DayTermOperation,
|
||||
type DayTerms,
|
||||
} from '@/lib/financial-day-terms';
|
||||
|
||||
const kinds = Object.keys(dayTermLabels) as DayTermKind[];
|
||||
const empty = (): DayTerms => ({
|
||||
sales: false,
|
||||
purchases: false,
|
||||
services: false,
|
||||
operations: [],
|
||||
});
|
||||
|
||||
export function FinancialDayTerms({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (plan: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const config = plan.dayTerms ?? empty();
|
||||
const save = (next: DayTerms) => onChange({ ...plan, dayTerms: next });
|
||||
const update = (index: number, patch: Partial<DayTermOperation>) =>
|
||||
save({
|
||||
...config,
|
||||
operations: config.operations.map((o, i) =>
|
||||
i === index ? { ...o, ...patch } : o,
|
||||
),
|
||||
});
|
||||
let economic: ReturnType<typeof forecastBusinessPlan> | undefined;
|
||||
let calculated: ReturnType<typeof forecastBusinessPlan> | undefined;
|
||||
try {
|
||||
economic = forecastBusinessPlan({ ...plan, dayTerms: undefined });
|
||||
} catch {
|
||||
/* Existing diagnostics remain in the report. */
|
||||
}
|
||||
try {
|
||||
calculated = forecastBusinessPlan(plan);
|
||||
} catch {
|
||||
/* One existing report diagnostic, no duplicate here. */
|
||||
}
|
||||
const prepare = (kind: DayTermKind) => {
|
||||
if (
|
||||
!economic ||
|
||||
config[kind] ||
|
||||
config.operations.some((o) => o.kind === kind)
|
||||
)
|
||||
return;
|
||||
const operations: DayTermOperation[] = [];
|
||||
for (const row of economic.rows) {
|
||||
const amount =
|
||||
kind === 'sales'
|
||||
? row.revenue
|
||||
: kind === 'purchases'
|
||||
? row.inventoryReceipts
|
||||
: row.operatingExpenses;
|
||||
if (amount === null || Number(amount) === 0) continue;
|
||||
operations.push({
|
||||
kind,
|
||||
month: row.month,
|
||||
amount,
|
||||
originId: `${kind}-${row.month}`,
|
||||
parcelId: '1',
|
||||
recognitionBasis: 'monthly',
|
||||
recognitionDate: '',
|
||||
originBasis: 'recognition',
|
||||
originDate: '',
|
||||
termDays: '',
|
||||
});
|
||||
}
|
||||
save({ ...config, operations: [...config.operations, ...operations] });
|
||||
};
|
||||
return (
|
||||
<details className="my-3 min-w-0 space-y-3 rounded border p-3">
|
||||
<summary className="font-semibold">
|
||||
Prazos em dias — operações sem adiantamentos
|
||||
</summary>
|
||||
<p>
|
||||
Adesão opcional por agenda. A agenda em dias substitui
|
||||
integralmente a agenda de caixa correspondente, incluindo
|
||||
cobranças mensais e recuperações de vendas do período. Os
|
||||
valores manuais correspondentes ficam guardados, inactivos;
|
||||
outras receitas explicitamente classificadas mantêm-se activas.
|
||||
Os saldos de abertura mantêm as agendas próprias. Para misturar
|
||||
operações datadas e coortes, distribua o total reconhecido entre
|
||||
parcelas sem repetir montantes.
|
||||
</p>
|
||||
<p>
|
||||
Mercadorias: só após recepção reconhecida. Serviços adquiridos:
|
||||
este modo abrange a totalidade das despesas operacionais
|
||||
declaradas; use-o apenas se todas corresponderem a serviços
|
||||
elegíveis. Não inclui salários, impostos, juros, empréstimos ou
|
||||
novos activos. Antecipações e datas insuficientes bloqueiam o
|
||||
cálculo automático, sem conversão para pagamentos normais.
|
||||
</p>
|
||||
<p>
|
||||
Sem data individual, escolha explicitamente «Último dia do mês
|
||||
(aproximação)». O vencimento também será aproximado. A origem
|
||||
dos pagamentos é o evento contratual indicado; não se presume
|
||||
que factura e recepção coincidam. O prazo em dias deste editor é
|
||||
independente do campo histórico usado nos avisos de crédito.
|
||||
</p>
|
||||
<p>
|
||||
Ano inicial:{' '}
|
||||
{plan.reportAssumptions?.startYear ||
|
||||
'preencha o ano no relatório financeiro integral'}
|
||||
. Horizonte: {plan.periods} meses. Os vencimentos posteriores
|
||||
ficam identificados fora do horizonte.
|
||||
</p>
|
||||
{kinds.map((kind) => (
|
||||
<fieldset
|
||||
key={kind}
|
||||
className="min-w-0 space-y-2 rounded border p-3"
|
||||
>
|
||||
<legend className="font-medium">
|
||||
{dayTermLabels[kind]}
|
||||
</legend>
|
||||
<label className="grid gap-1">
|
||||
Modo de {dayTermLabels[kind]}
|
||||
<select
|
||||
className="w-full rounded border p-2"
|
||||
value={config[kind] ? 'days' : 'manual'}
|
||||
onChange={(e) => {
|
||||
if (
|
||||
e.target.value === 'days' &&
|
||||
!window.confirm(
|
||||
`Activar prazos em dias para ${dayTermLabels[kind]}? A agenda em dias substitui toda a agenda de caixa desta categoria. Os valores anteriores ficam guardados e não serão somados. Confira primeiro as parcelas e as datas.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
save({
|
||||
...config,
|
||||
[kind]: e.target.value === 'days',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="manual">
|
||||
Agenda anterior/manual preservada
|
||||
</option>
|
||||
<option value="days">
|
||||
Prazos em dias (adesão explícita)
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={
|
||||
!economic ||
|
||||
config[kind] ||
|
||||
config.operations.some((o) => o.kind === kind)
|
||||
}
|
||||
onClick={() => prepare(kind)}
|
||||
>
|
||||
Preparar coortes mensais de {dayTermLabels[kind]}
|
||||
</button>
|
||||
<p className="text-sm">
|
||||
Preparar coortes não activa o modo. Revise os valores,
|
||||
indique o prazo de cada parcela e só depois escolha o
|
||||
modo em dias.
|
||||
</p>
|
||||
{config.operations.map((o, index) =>
|
||||
o.kind !== kind ? null : (
|
||||
<div
|
||||
key={index}
|
||||
className="grid min-w-0 gap-2 rounded border p-3 sm:grid-cols-2 lg:grid-cols-3"
|
||||
aria-label={`Parcela ${index + 1} de ${dayTermLabels[kind]}`}
|
||||
>
|
||||
{(
|
||||
[
|
||||
['Origem', 'originId'],
|
||||
['Parcela', 'parcelId'],
|
||||
['Montante', 'amount'],
|
||||
['Prazo (dias)', 'termDays'],
|
||||
] as const
|
||||
).map(([label, key]) => (
|
||||
<label
|
||||
key={key}
|
||||
className="grid min-w-0 gap-1"
|
||||
>
|
||||
{label}
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={o[key]}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<label className="grid gap-1">
|
||||
Mês económico
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type="number"
|
||||
min="1"
|
||||
max={plan.periods}
|
||||
value={o.month}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
month: Number(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Reconhecimento
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={o.recognitionBasis}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
recognitionBasis: e.target
|
||||
.value as DayTermOperation['recognitionBasis'],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Data por confirmar (excluída)
|
||||
</option>
|
||||
<option value="monthly">
|
||||
Último dia do mês (aproximação)
|
||||
</option>
|
||||
<option value="date">
|
||||
Data individual
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{o.recognitionBasis === 'date' && (
|
||||
<label className="grid gap-1">
|
||||
Data de reconhecimento
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type="date"
|
||||
value={o.recognitionDate}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
recognitionDate:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<label className="grid gap-1">
|
||||
Origem do prazo
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={o.originBasis}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
originBasis: e.target
|
||||
.value as DayTermOperation['originBasis'],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Evento por confirmar (excluído)
|
||||
</option>
|
||||
<option value="recognition">
|
||||
Na data do reconhecimento
|
||||
</option>
|
||||
<option value="date">
|
||||
Data do evento contratual
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{o.originBasis === 'date' && (
|
||||
<label className="grid gap-1">
|
||||
Data de origem do prazo
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type="date"
|
||||
value={o.originDate}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
originDate: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() =>
|
||||
save({
|
||||
...config,
|
||||
operations:
|
||||
config.operations.filter(
|
||||
(_, i) => i !== index,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover parcela {index + 1}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={config.operations.length >= 240}
|
||||
onClick={() =>
|
||||
save({
|
||||
...config,
|
||||
operations: [
|
||||
...config.operations,
|
||||
{
|
||||
kind,
|
||||
originId: '',
|
||||
parcelId: '',
|
||||
month: 1,
|
||||
amount: '',
|
||||
termDays: '',
|
||||
recognitionBasis: 'unknown',
|
||||
recognitionDate: '',
|
||||
originBasis: 'unknown',
|
||||
originDate: '',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar parcela de {dayTermLabels[kind]}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
{calculated?.dayTermEvents && (
|
||||
<section aria-label="Vencimentos em dias" className="space-y-2">
|
||||
<h4 className="font-semibold">Vencimentos previstos</h4>
|
||||
{calculated.dayTermEvents.map((e) => (
|
||||
<p
|
||||
key={JSON.stringify([
|
||||
e.kind,
|
||||
e.originId,
|
||||
e.parcelId,
|
||||
])}
|
||||
>
|
||||
{dayTermLabels[e.kind]} — {e.originId}/{e.parcelId}:
|
||||
reconhecimento {e.recognition}; origem {e.origin};
|
||||
vencimento {e.due}; {e.amount} {plan.currency}.{' '}
|
||||
{e.approximate
|
||||
? 'Aproximação mensal explícita.'
|
||||
: 'Datas individuais.'}{' '}
|
||||
{e.outsideHorizon
|
||||
? 'Fora do horizonte; não incluído na caixa do plano.'
|
||||
: `Caixa no mês ${e.dueMonth}.`}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
|
||||
import {
|
||||
newAnnualReferencePlan,
|
||||
serializeAnnualExampleSnapshot,
|
||||
} from '@/lib/business-plan-guidance';
|
||||
|
||||
/** Optional declarations share the existing plan snapshot; no independent storage. */
|
||||
export function FinancialPlanDetails({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (plan: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const input = (label: string, value: string, save: (s: string) => void) => (
|
||||
<label className="grid gap-1 text-sm">
|
||||
{label}
|
||||
<input
|
||||
className="min-w-0 rounded border p-2"
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={value}
|
||||
onChange={(e) => save(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
return (
|
||||
<details className="my-3 space-y-3 rounded border p-3">
|
||||
<summary className="font-semibold">
|
||||
Crescimento, despesas discriminadas, capital e dividendos
|
||||
</summary>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Prazo de recebimento a crédito (dias, quando conhecido)
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="365"
|
||||
step="1"
|
||||
className="min-w-0 rounded border p-2"
|
||||
value={plan.creditTermDays ?? ''}
|
||||
onChange={(e) =>
|
||||
onChange({ ...plan, creditTermDays: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
O prazo contratual declarado permite avaliar o aviso acima de 90
|
||||
dias. As cobranças de caixa conservam a agenda mensal
|
||||
introduzida; não se presume que um mês tenha 30 dias. Confira a
|
||||
compatibilidade entre contrato e cobranças previstas.
|
||||
</p>
|
||||
<label className="grid gap-1">
|
||||
Fonte do relatório financeiro consolidado
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={plan.reportSource ?? 'investor'}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
...plan,
|
||||
reportSource: e.target.value as
|
||||
| 'investor'
|
||||
| 'annual_example',
|
||||
...(e.target.value === 'annual_example' &&
|
||||
!plan.annualExampleSnapshot
|
||||
? {
|
||||
annualExampleSnapshot:
|
||||
serializeAnnualExampleSnapshot(
|
||||
newAnnualReferencePlan(),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="investor">Plano do investidor</option>
|
||||
<option value="annual_example">
|
||||
Exemplo sintético anual editável
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
A escolha do exemplo muda apenas a fonte do relatório, sem
|
||||
substituir as entradas do investidor. As edições do exemplo são
|
||||
feitas em «Carregar cenário anual de exemplo» e acompanham a
|
||||
mesma versão guardada. Escolha novamente «Plano do investidor»
|
||||
para regressar.
|
||||
</p>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={plan.applyAnnualGrowth ?? false}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
...plan,
|
||||
applyAnnualGrowth: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Projectar os anos seguintes com o crescimento anual declarado
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
Aplica o crescimento às quantidades a partir do segundo ano,
|
||||
conservando preços e custos unitários. Agendas mensais
|
||||
explícitas prevalecem. A taxa é uma hipótese, não uma previsão
|
||||
de procura.
|
||||
</p>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!plan.operatingExpenseLines}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
...plan,
|
||||
operatingExpenseLines: e.target.checked
|
||||
? [
|
||||
'Rendas',
|
||||
'Seguros',
|
||||
'Utilidades',
|
||||
'Marketing',
|
||||
'Outras despesas',
|
||||
].map((label, i) => ({
|
||||
label,
|
||||
monthlyAmount:
|
||||
i === 4
|
||||
? plan.monthlyOperatingExpenses
|
||||
: '0',
|
||||
...(i === 4 &&
|
||||
plan.monthlyOperatingExpensesByPeriod
|
||||
? {
|
||||
amountsByPeriod: [
|
||||
...plan.monthlyOperatingExpensesByPeriod,
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
}))
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Discriminar despesas operacionais
|
||||
</label>
|
||||
{plan.operatingExpenseLines && (
|
||||
<p className="text-sm">
|
||||
O total anterior começa em Outras despesas; redistribua
|
||||
apenas montantes conhecidos. As linhas substituem o total
|
||||
reconhecido, sem alterar pagamentos. Depreciação e juros
|
||||
mantêm os campos próprios. Agendas existentes permanecem nas
|
||||
linhas respectivas.
|
||||
</p>
|
||||
)}
|
||||
{plan.operatingExpenseLines?.map((line, index) => (
|
||||
<div key={index}>
|
||||
{input(line.label, line.monthlyAmount, (value) =>
|
||||
onChange({
|
||||
...plan,
|
||||
operatingExpenseLines:
|
||||
plan.operatingExpenseLines!.map((r, i) =>
|
||||
i === index
|
||||
? { ...r, monthlyAmount: value }
|
||||
: r,
|
||||
),
|
||||
}),
|
||||
)}
|
||||
{line.amountsByPeriod && (
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
{line.amountsByPeriod.map((value, month) => (
|
||||
<div key={month}>
|
||||
{input(
|
||||
`${line.label}, mês ${month + 1}`,
|
||||
value,
|
||||
(next) =>
|
||||
onChange({
|
||||
...plan,
|
||||
operatingExpenseLines:
|
||||
plan.operatingExpenseLines!.map(
|
||||
(r, i) =>
|
||||
i === index
|
||||
? {
|
||||
...r,
|
||||
amountsByPeriod:
|
||||
r.amountsByPeriod!.map(
|
||||
(
|
||||
v,
|
||||
m,
|
||||
) =>
|
||||
m ===
|
||||
month
|
||||
? next
|
||||
: v,
|
||||
),
|
||||
}
|
||||
: r,
|
||||
),
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!plan.fundingBreakdown}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
...plan,
|
||||
fundingBreakdown: e.target.checked
|
||||
? {
|
||||
ownerCapital: '',
|
||||
investorCapital: '',
|
||||
additionalCapital: '',
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Discriminar o capital introduzido
|
||||
</label>
|
||||
{plan.fundingBreakdown && (
|
||||
<>
|
||||
<p className="text-sm">
|
||||
Capital adicional angariado é apenas capital próprio.
|
||||
Empréstimos, suprimentos e subvenções conservam os
|
||||
campos próprios. A soma deve corresponder ao capital
|
||||
introduzido.
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{(
|
||||
[
|
||||
['ownerCapital', 'Capital do proprietário'],
|
||||
['investorCapital', 'Capital do investidor'],
|
||||
[
|
||||
'additionalCapital',
|
||||
'Capital adicional angariado',
|
||||
],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<div key={key}>
|
||||
{input(
|
||||
label,
|
||||
plan.fundingBreakdown![key],
|
||||
(value) => {
|
||||
const f = {
|
||||
...plan.fundingBreakdown!,
|
||||
[key]: value,
|
||||
};
|
||||
const values = Object.values(f);
|
||||
const valid = values.every((v) =>
|
||||
/^\d+(?:\.\d{1,2})?$/.test(v),
|
||||
);
|
||||
const total = values.reduce(
|
||||
(sum, v) => {
|
||||
if (
|
||||
!/^\d+(?:\.\d{1,2})?$/.test(
|
||||
v,
|
||||
)
|
||||
)
|
||||
return sum;
|
||||
const [a, b = ''] =
|
||||
v.split('.');
|
||||
return (
|
||||
sum +
|
||||
BigInt(a) * 100n +
|
||||
BigInt(b.padEnd(2, '0'))
|
||||
);
|
||||
},
|
||||
0n,
|
||||
);
|
||||
onChange({
|
||||
...plan,
|
||||
fundingBreakdown: f,
|
||||
...(valid
|
||||
? {
|
||||
equity: `${total / 100n}.${String(total % 100n).padStart(2, '0')}`,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
},
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!plan.dividendsByPeriod}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
...plan,
|
||||
dividendsByPeriod: e.target.checked
|
||||
? Array(plan.periods ?? 12).fill('0')
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Planear dividendos distribuídos por mês
|
||||
</label>
|
||||
{plan.dividendsByPeriod && (
|
||||
<>
|
||||
<p className="text-sm">
|
||||
Começa sem distribuições (zero). Cada dividendo reduz
|
||||
caixa e capital; não é despesa nem reduz o lucro. São
|
||||
hipóteses de distribuição, não pagamentos executados ou
|
||||
autorização jurídica.
|
||||
</p>
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
{Array.from(
|
||||
{ length: plan.periods ?? 12 },
|
||||
(_, month) => (
|
||||
<div key={month}>
|
||||
{input(
|
||||
`Dividendos, mês ${month + 1}`,
|
||||
plan.dividendsByPeriod?.[month] ?? '',
|
||||
(value) =>
|
||||
onChange({
|
||||
...plan,
|
||||
dividendsByPeriod: Array.from(
|
||||
{
|
||||
length:
|
||||
plan.periods ?? 12,
|
||||
},
|
||||
(_, i) =>
|
||||
i === month
|
||||
? value
|
||||
: (plan
|
||||
.dividendsByPeriod?.[
|
||||
i
|
||||
] ?? ''),
|
||||
),
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
|
||||
import { buildFinancialRatiosTable } from '@/lib/financial-ratios-report';
|
||||
import { InvestmentReportTables } from './investment-report-tables';
|
||||
export function FinancialRatiosPlan({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (p: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const periods = plan.periods ?? 12,
|
||||
s = plan.ratioCurrentBalances;
|
||||
if (
|
||||
s &&
|
||||
(!Array.isArray(s.assetsByMonth) ||
|
||||
!Array.isArray(s.liabilitiesByMonth) ||
|
||||
s.assetsByMonth.some((x) => typeof x !== 'string') ||
|
||||
s.liabilitiesByMonth.some((x) => typeof x !== 'string'))
|
||||
)
|
||||
return (
|
||||
<p role="alert">
|
||||
A classificação corrente guardada tem uma estrutura
|
||||
desconhecida. O original foi preservado.
|
||||
</p>
|
||||
);
|
||||
const save = (
|
||||
key: 'assetsByMonth' | 'liabilitiesByMonth',
|
||||
index: number,
|
||||
value: string,
|
||||
) =>
|
||||
onChange({
|
||||
...plan,
|
||||
ratioCurrentBalances: {
|
||||
assetsByMonth: s?.assetsByMonth ?? Array(periods).fill(''),
|
||||
liabilitiesByMonth:
|
||||
s?.liabilitiesByMonth ?? Array(periods).fill(''),
|
||||
[key]: Array.from(
|
||||
{ length: Math.max(periods, s?.[key].length ?? 0) },
|
||||
(_, i) => (i === index ? value : (s?.[key][i] ?? '')),
|
||||
),
|
||||
},
|
||||
});
|
||||
return (
|
||||
<details className="my-4 rounded border p-3">
|
||||
<summary>Rácios financeiros e classificação corrente</summary>
|
||||
<p className="my-2 text-sm">
|
||||
Para a liquidez, declare os totais classificados como activo e
|
||||
passivo correntes no fecho de cada mês, segundo os vencimentos
|
||||
aplicáveis. Não alteram o balanço. Vazio permanece por
|
||||
determinar; zero só quando aplicável. Os restantes rácios
|
||||
utilizam as demonstrações já guardadas.
|
||||
</p>
|
||||
<details>
|
||||
<summary>Classificar saldos correntes para liquidez</summary>
|
||||
{Array.from({ length: periods }, (_, i) => (
|
||||
<fieldset
|
||||
key={i}
|
||||
className="my-2 grid gap-2 rounded border p-2 sm:grid-cols-2"
|
||||
>
|
||||
<legend>Mês {i + 1}</legend>
|
||||
{(['assetsByMonth', 'liabilitiesByMonth'] as const).map(
|
||||
(key) => (
|
||||
<label
|
||||
key={key}
|
||||
className="grid min-w-0 gap-1 text-sm"
|
||||
>
|
||||
{key === 'assetsByMonth'
|
||||
? 'Activo corrente'
|
||||
: 'Passivo corrente'}{' '}
|
||||
— mês {i + 1}
|
||||
<input
|
||||
className="min-w-0 rounded border p-2"
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={s?.[key][i] ?? ''}
|
||||
onChange={(e) =>
|
||||
save(key, i, e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
</fieldset>
|
||||
))}
|
||||
</details>
|
||||
<InvestmentReportTables
|
||||
tables={[buildFinancialRatiosTable(plan)]}
|
||||
/>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -85,7 +85,7 @@ export default function FintechInvestment({
|
||||
{
|
||||
version: 'Versão do dossier',
|
||||
'profile.model': 'Natureza do modelo',
|
||||
'profile.activity_basis': 'Fundamento das atividades',
|
||||
'profile.activity_basis': 'Fundamento das actividades',
|
||||
} as Record<string, string>
|
||||
)[field] ?? 'Caracterização'
|
||||
);
|
||||
@@ -179,7 +179,7 @@ export default function FintechInvestment({
|
||||
</option>
|
||||
<option value="technology_provider">
|
||||
Fornecedor de tecnologia, sem presumir
|
||||
atividade financeira reservada
|
||||
actividade financeira reservada
|
||||
</option>
|
||||
<option value="financial_operator">
|
||||
Operador de serviços financeiros declarado,
|
||||
@@ -248,7 +248,7 @@ export default function FintechInvestment({
|
||||
</p>
|
||||
<fieldset className="grid gap-3 md:grid-cols-2">
|
||||
<legend className="font-semibold">
|
||||
Atividades pretendidas, ainda sujeitas a
|
||||
Actividades pretendidas, ainda sujeitas a
|
||||
enquadramento
|
||||
</legend>
|
||||
{Object.entries(data.activities).map(
|
||||
@@ -285,7 +285,7 @@ export default function FintechInvestment({
|
||||
)}
|
||||
</fieldset>
|
||||
<label className="grid gap-1">
|
||||
Fundamento e limites da declaração de atividades
|
||||
Fundamento e limites da declaração de actividades
|
||||
<textarea
|
||||
rows={3}
|
||||
maxLength={3000}
|
||||
@@ -375,7 +375,7 @@ export default function FintechInvestment({
|
||||
className="mt-5 space-y-3"
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
Aplicabilidade por atividade e ação
|
||||
Aplicabilidade por actividade e acção
|
||||
</h3>
|
||||
<p>
|
||||
Quem prepara: promotor. Quem confere: responsável
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
|
||||
import {
|
||||
buildIntegralFinancialTables,
|
||||
newReportAssumptions,
|
||||
isReportAssumptions,
|
||||
} from '@/lib/integral-financial-report';
|
||||
import { InvestmentReportTables } from './investment-report-tables';
|
||||
import { BusinessPlanWarnings } from './business-plan-warnings';
|
||||
import { financialPlanWarnings } from '@/lib/financial-plan-warnings';
|
||||
import { buildAnnualExampleTables } from '@/lib/annual-example-report';
|
||||
import { StartupAssetRequirements } from './startup-asset-requirements';
|
||||
|
||||
export function IntegralFinancialPlan({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (plan: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
if (plan.reportSource === 'annual_example') {
|
||||
try {
|
||||
return (
|
||||
<section aria-label="Relatório do exemplo sintético">
|
||||
<h4>Relatório do exemplo sintético anual</h4>
|
||||
<p>
|
||||
As onze tabelas abaixo usam o exemplo editável. Os dados
|
||||
reais do investimento ficam conservados separadamente.
|
||||
</p>
|
||||
<InvestmentReportTables
|
||||
tables={buildAnnualExampleTables(plan)}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
} catch (error) {
|
||||
return (
|
||||
<p role="alert">
|
||||
{error instanceof Error
|
||||
? error.message
|
||||
: 'Confira o cenário de exemplo.'}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
}
|
||||
if (plan.reportAssumptions && !isReportAssumptions(plan.reportAssumptions))
|
||||
return (
|
||||
<p role="alert">
|
||||
Os dados complementares guardados não têm uma estrutura
|
||||
reconhecida. Foram preservados e não serão substituídos
|
||||
automaticamente.
|
||||
</p>
|
||||
);
|
||||
const a =
|
||||
plan.reportAssumptions ?? newReportAssumptions(plan.periods ?? 12);
|
||||
const update = (patch: Partial<typeof a>) =>
|
||||
onChange({ ...plan, reportAssumptions: { ...a, ...patch } });
|
||||
const numeric = (
|
||||
label: string,
|
||||
value: string,
|
||||
save: (value: string) => void,
|
||||
) => (
|
||||
<label className="grid gap-1 text-sm">
|
||||
{label}
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
className="min-w-0 rounded border p-2"
|
||||
value={value}
|
||||
onChange={(event) => save(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
return (
|
||||
<details className="my-4 rounded border border-teal-500 p-3">
|
||||
<summary className="font-semibold">
|
||||
Relatório financeiro integral — dados do investimento
|
||||
</summary>
|
||||
<p className="my-2">
|
||||
Utiliza as vendas, custos e agendas do plano financeiro. Não
|
||||
utiliza o cenário sintético. Todos os montantes são projecções
|
||||
declaradas em {plan.currency || 'moeda por seleccionar'}. Campos
|
||||
em falta permanecem por determinar; indique zero apenas quando
|
||||
aplicável.
|
||||
</p>
|
||||
<StartupAssetRequirements
|
||||
plan={plan}
|
||||
onChange={onChange}
|
||||
showError={false}
|
||||
/>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="grid gap-1 text-sm">
|
||||
Ano inicial
|
||||
<input
|
||||
type="number"
|
||||
min="1900"
|
||||
max="9999"
|
||||
step="1"
|
||||
className="rounded border p-2"
|
||||
value={a.startYear}
|
||||
onChange={(event) =>
|
||||
update({ startYear: event.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{!plan.startupAssetRequirements &&
|
||||
numeric(
|
||||
'Activos fixos anteriores (valor líquido)',
|
||||
a.openingFixedAssets,
|
||||
(openingFixedAssets) => update({ openingFixedAssets }),
|
||||
)}
|
||||
{!plan.startupAssetRequirements &&
|
||||
numeric(
|
||||
'Outros activos anteriores',
|
||||
a.openingOtherAssets,
|
||||
(openingOtherAssets) => update({ openingOtherAssets }),
|
||||
)}
|
||||
{numeric(
|
||||
'Capital e resultados anteriores',
|
||||
a.openingEquity,
|
||||
(openingEquity) => update({ openingEquity }),
|
||||
)}
|
||||
<label className="grid gap-1 text-sm">
|
||||
Tratamento das subvenções
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={a.grantsTreatment}
|
||||
onChange={(event) =>
|
||||
update({
|
||||
grantsTreatment: event.target
|
||||
.value as typeof a.grantsTreatment,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar / sem subvenção</option>
|
||||
<option value="capital">Capital</option>
|
||||
<option value="deferred">Passivo diferido</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm">
|
||||
Natureza dos recebimentos manuais
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={a.manualCollectionsKind}
|
||||
onChange={(event) =>
|
||||
update({
|
||||
manualCollectionsKind: event.target
|
||||
.value as typeof a.manualCollectionsKind,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar / sem montante</option>
|
||||
<option value="sales">Cobranças de vendas</option>
|
||||
<option value="other_income">
|
||||
Outras receitas reconhecidas e recebidas
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<fieldset className="my-3 space-y-2">
|
||||
<legend>
|
||||
Despesas de arranque — reconhecidas e pagas na abertura
|
||||
</legend>
|
||||
{a.startupExpenses.map((row, index) => (
|
||||
<div className="grid gap-2 sm:grid-cols-3" key={index}>
|
||||
<label className="grid text-sm">
|
||||
Despesa {index + 1}
|
||||
<input
|
||||
className="rounded border p-2"
|
||||
value={row.label}
|
||||
maxLength={160}
|
||||
onChange={(event) =>
|
||||
update({
|
||||
startupExpenses: a.startupExpenses.map(
|
||||
(entry, i) =>
|
||||
i === index
|
||||
? {
|
||||
...entry,
|
||||
label: event.target
|
||||
.value,
|
||||
}
|
||||
: entry,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{numeric(
|
||||
`Montante de arranque ${index + 1}`,
|
||||
row.amount,
|
||||
(amount) =>
|
||||
update({
|
||||
startupExpenses: a.startupExpenses.map(
|
||||
(entry, i) =>
|
||||
i === index
|
||||
? { ...entry, amount }
|
||||
: entry,
|
||||
),
|
||||
}),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
update({
|
||||
startupExpenses: a.startupExpenses.filter(
|
||||
(_, i) => i !== index,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover despesa
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
disabled={a.startupExpenses.length >= 40}
|
||||
onClick={() =>
|
||||
update({
|
||||
startupExpenses: [
|
||||
...a.startupExpenses,
|
||||
{ label: '', amount: '' },
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar despesa de arranque
|
||||
</button>
|
||||
</fieldset>
|
||||
<p className="my-2 text-sm">
|
||||
Os saldos anteriores têm de reconciliar entre si. Não inclua os
|
||||
novos activos no saldo anterior, nem os novos capitais nos
|
||||
resultados anteriores.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Sem linhas significa que não declarou despesas de arranque; para
|
||||
confirmar a inexistência, registe uma linha «Sem despesas de
|
||||
arranque» com zero.
|
||||
</p>
|
||||
<label className="my-2 grid gap-1 text-sm">
|
||||
Fonte ou pressuposto dos impostos estimados
|
||||
<input
|
||||
className="rounded border p-2"
|
||||
maxLength={1000}
|
||||
value={a.taxSource}
|
||||
onChange={(event) =>
|
||||
update({ taxSource: event.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<details>
|
||||
<summary>Impostos por mês — estimativa e tesouraria</summary>
|
||||
<p className="text-sm">
|
||||
Não activa taxas fiscais nem certifica pagamentos. Preencha
|
||||
cada mês, incluindo zero declarado.
|
||||
</p>
|
||||
{Array.from({ length: plan.periods ?? 12 }, (_, index) => (
|
||||
<div className="my-2 grid gap-2 sm:grid-cols-2" key={index}>
|
||||
{numeric(
|
||||
`Imposto reconhecido — mês ${index + 1}`,
|
||||
a.taxExpenseByMonth[index] ?? '',
|
||||
(value) =>
|
||||
update({
|
||||
taxExpenseByMonth: Array.from(
|
||||
{ length: plan.periods ?? 12 },
|
||||
(_, i) =>
|
||||
i === index
|
||||
? value
|
||||
: (a.taxExpenseByMonth[i] ??
|
||||
''),
|
||||
),
|
||||
}),
|
||||
)}
|
||||
{numeric(
|
||||
`Pagamento fiscal previsto — mês ${index + 1}`,
|
||||
a.taxPaymentByMonth[index] ?? '',
|
||||
(value) =>
|
||||
update({
|
||||
taxPaymentByMonth: Array.from(
|
||||
{ length: plan.periods ?? 12 },
|
||||
(_, i) =>
|
||||
i === index
|
||||
? value
|
||||
: (a.taxPaymentByMonth[i] ??
|
||||
''),
|
||||
),
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</details>
|
||||
<InvestmentReportTables
|
||||
tables={buildIntegralFinancialTables(plan)}
|
||||
/>
|
||||
<BusinessPlanWarnings
|
||||
warnings={financialPlanWarnings(
|
||||
plan,
|
||||
buildIntegralFinancialTables(plan),
|
||||
)}
|
||||
/>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { publicReference } from '@/lib/public-presentation';
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import type {
|
||||
Map as LeafletMap,
|
||||
@@ -231,7 +232,7 @@ export default function InteractiveInvestmentMap({
|
||||
: 0;
|
||||
for (const area of allAreas) {
|
||||
const label = document.createElement('p');
|
||||
label.textContent = `${area.title} · ${areaDescription(area)} · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
|
||||
label.textContent = `${area.title} · ${areaDescription(area)} · Fonte: ${publicReference(area.source_reference) ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
|
||||
const layer = L.geoJSON(
|
||||
area.geometry,
|
||||
area.purpose === 'administrative_boundary'
|
||||
@@ -299,7 +300,7 @@ export default function InteractiveInvestmentMap({
|
||||
for (const text of [
|
||||
p.category,
|
||||
p.location,
|
||||
`Fonte: ${p.source_reference ?? 'Não indicada'} · Data: ${p.source_date ?? 'Não documentada'}`,
|
||||
`Fonte: ${publicReference(p.source_reference) ?? 'Não indicada'} · Data: ${p.source_date ?? 'Não documentada'}`,
|
||||
`Corredor: ${p.corridors?.join(', ') || 'Não associado'}`,
|
||||
`Cluster: ${p.clusters?.join(', ') || 'Não associado'}`,
|
||||
`Projecto âncora: ${p.projects?.join(', ') || 'Não associado'}`,
|
||||
@@ -468,8 +469,9 @@ export default function InteractiveInvestmentMap({
|
||||
</p>
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{p.properties.source_reference ?? 'Não indicada'} ·
|
||||
Data:{' '}
|
||||
{publicReference(p.properties.source_reference) ??
|
||||
'Não indicada'}{' '}
|
||||
· Data:{' '}
|
||||
{p.properties.source_date ?? 'Não documentada'}
|
||||
</p>
|
||||
<a className="underline" href={p.properties.url}>
|
||||
@@ -496,8 +498,9 @@ export default function InteractiveInvestmentMap({
|
||||
area.title
|
||||
)}{' '}
|
||||
· {areaDescription(area)} · Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} ·
|
||||
Edição: {area.source_date ?? 'Não indicada'}
|
||||
{publicReference(area.source_reference) ??
|
||||
'Não indicada'}{' '}
|
||||
· Edição: {area.source_date ?? 'Não indicada'}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
@@ -510,8 +513,9 @@ export default function InteractiveInvestmentMap({
|
||||
{area.title}
|
||||
</a>{' '}
|
||||
· {areaDescription(area)} · Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} · Data:{' '}
|
||||
{area.source_date ?? 'Não documentada'}
|
||||
{publicReference(area.source_reference) ??
|
||||
'Não indicada'}{' '}
|
||||
· Data: {area.source_date ?? 'Não documentada'}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import {
|
||||
displayReportMoney,
|
||||
type InvestmentReportTable,
|
||||
} from '@/lib/integral-financial-report';
|
||||
import { financialIssuesForDisplay } from '@/lib/financial-issue-presentation';
|
||||
|
||||
export function InvestmentReportTables({
|
||||
tables,
|
||||
}: {
|
||||
tables: InvestmentReportTable[];
|
||||
}) {
|
||||
const issues = financialIssuesForDisplay(tables);
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{issues.length > 0 && (
|
||||
<aside
|
||||
aria-label="Dados financeiros a corrigir"
|
||||
className="space-y-2 rounded border border-amber-400 bg-amber-50 p-3 text-sm"
|
||||
>
|
||||
<h4 className="font-semibold">
|
||||
Confira os dados de origem
|
||||
</h4>
|
||||
<ul className="list-disc space-y-2 pl-5">
|
||||
{issues.map((issue) => (
|
||||
<li
|
||||
key={issue.message}
|
||||
data-correction-message={issue.message}
|
||||
>
|
||||
<p>{issue.message}</p>
|
||||
<p className="text-xs">
|
||||
Tabelas afectadas: {issue.tables.join('; ')}
|
||||
.
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</aside>
|
||||
)}
|
||||
{tables.map((table) => (
|
||||
<section key={table.id} aria-label={table.title}>
|
||||
<h4 className="font-semibold">{table.title}</h4>
|
||||
{table.rows.length > 0 && (
|
||||
<div
|
||||
className="overflow-x-auto"
|
||||
tabIndex={0}
|
||||
role="region"
|
||||
aria-label={`Tabela ${table.title}`}
|
||||
>
|
||||
<table className="w-full border-collapse text-left text-sm">
|
||||
<caption className="sr-only">
|
||||
{table.title}
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
{table.headers.map((header, index) => (
|
||||
<th
|
||||
className="min-w-28 border p-2"
|
||||
key={index}
|
||||
>
|
||||
{header}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{table.rows.map((row, i) => (
|
||||
<tr key={i}>
|
||||
{row.map((cell, j) =>
|
||||
j === 0 ? (
|
||||
<th
|
||||
className="min-w-40 border p-2 font-medium"
|
||||
key={j}
|
||||
>
|
||||
{cell}
|
||||
</th>
|
||||
) : (
|
||||
<td
|
||||
className="border p-2 whitespace-nowrap"
|
||||
key={j}
|
||||
>
|
||||
{displayReportMoney(
|
||||
cell,
|
||||
)}
|
||||
</td>
|
||||
),
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{table.notes.map((note, i) => (
|
||||
<p className="mt-1 text-sm" key={i}>
|
||||
{note}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -41,6 +41,7 @@ export function InvestmentHelpGuide({
|
||||
const [active, setActive] = useState<string | null>(null);
|
||||
const [automatic, setAutomatic] = useState(true);
|
||||
const paused = useRef(false);
|
||||
const pointerFocus = useRef(false);
|
||||
const key = helpPreferenceKey(user, flow);
|
||||
const firstCode = steps.some((step) => step.code === initialCode)
|
||||
? initialCode
|
||||
@@ -151,8 +152,24 @@ export function InvestmentHelpGuide({
|
||||
<div
|
||||
ref={root}
|
||||
className="space-y-5"
|
||||
onFocusCapture={(event) => orient(event.target)}
|
||||
onClickCapture={(event) => orient(event.target)}
|
||||
onPointerDownCapture={() => {
|
||||
pointerFocus.current = true;
|
||||
}}
|
||||
onPointerUpCapture={() => {
|
||||
pointerFocus.current = false;
|
||||
}}
|
||||
onPointerCancelCapture={() => {
|
||||
pointerFocus.current = false;
|
||||
}}
|
||||
onFocusCapture={(event) => {
|
||||
// Opening inline help during pointer focus can move the
|
||||
// target between pointerdown and click, losing the action.
|
||||
if (!pointerFocus.current) orient(event.target);
|
||||
}}
|
||||
onClickCapture={(event) => {
|
||||
pointerFocus.current = false;
|
||||
orient(event.target);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key === 'Escape' &&
|
||||
|
||||
@@ -75,7 +75,7 @@ export function ProvinceSelect({
|
||||
setGeometrySelection({ value, id: matches[0].id });
|
||||
else
|
||||
setGeometryFeedback(
|
||||
'Seleção guardada preservada; sem correspondência cartográfica inequívoca neste cadastro.',
|
||||
'Selecção guardada preservada; sem correspondência cartográfica inequívoca neste cadastro.',
|
||||
);
|
||||
})
|
||||
.catch((cause: unknown) => {
|
||||
|
||||
@@ -577,7 +577,9 @@ export function ParkIntegralPublic({ value }: { value?: ParkIntegral }) {
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{String(
|
||||
item.source_reference || 'Não informada',
|
||||
publicReference(
|
||||
String(item.source_reference ?? ''),
|
||||
) || 'Referência pública não disponível',
|
||||
)}{' '}
|
||||
· data:{' '}
|
||||
{String(item.source_date || 'Não informada')} ·
|
||||
@@ -590,3 +592,4 @@ export function ParkIntegralPublic({ value }: { value?: ParkIntegral }) {
|
||||
</section>
|
||||
);
|
||||
}
|
||||
import { publicReference } from '@/lib/public-presentation';
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import PublicReference from './public-reference';
|
||||
import { publicReference } from '@/lib/public-presentation';
|
||||
import ParkIntegralEditor, {
|
||||
ParkIntegralPublic,
|
||||
type ParkIntegral,
|
||||
@@ -175,8 +177,14 @@ export function ParkDetailsPublic({ value }: { value?: Partial<ParkDetails> }) {
|
||||
)}
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{item.source_reference || 'Não informada'} ·
|
||||
data: {item.source_date || 'Não informada'} ·
|
||||
{publicReference(item.source_reference) ? (
|
||||
<PublicReference
|
||||
value={item.source_reference}
|
||||
/>
|
||||
) : (
|
||||
'Referência pública não disponível'
|
||||
)}{' '}
|
||||
· data: {item.source_date || 'Não informada'} ·
|
||||
âmbito: {item.scope || 'Não informado'}
|
||||
</p>
|
||||
</article>
|
||||
@@ -192,15 +200,25 @@ export function ParkDetailsPublic({ value }: { value?: Partial<ParkDetails> }) {
|
||||
<div key={k}>
|
||||
<dt>{reviewLabels[k]}</dt>
|
||||
<dd>
|
||||
{k === 'confidence'
|
||||
? ({
|
||||
unknown: 'Não informada',
|
||||
reported: 'Declarada',
|
||||
documented: 'Documentada',
|
||||
disputed: 'Divergente',
|
||||
}[value.review?.[k] ?? ''] ??
|
||||
'Não informada')
|
||||
: value.review?.[k] || 'Não informado'}
|
||||
{k === 'confidence' ? (
|
||||
({
|
||||
unknown: 'Não informada',
|
||||
reported: 'Declarada',
|
||||
documented: 'Documentada',
|
||||
disputed: 'Divergente',
|
||||
}[value.review?.[k] ?? ''] ??
|
||||
'Não informada')
|
||||
) : k === 'source_reference' ? (
|
||||
publicReference(value.review?.[k]) ? (
|
||||
<PublicReference
|
||||
value={value.review?.[k]}
|
||||
/>
|
||||
) : (
|
||||
'Referência pública não disponível'
|
||||
)
|
||||
) : (
|
||||
value.review?.[k] || 'Não informado'
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
@@ -276,7 +294,7 @@ export default function ParkDetailsEditor({
|
||||
<h2 className="font-semibold">Complemento operacional</h2>
|
||||
<p>
|
||||
Uma entidade pode exercer várias funções. Guardar prepara em
|
||||
privado; divulgar exige seleção por detalhe e publicação
|
||||
privado; divulgar exige selecção por detalhe e publicação
|
||||
expressa. Contactos pessoais, notas e suporte permanecem
|
||||
privados.
|
||||
</p>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { BusinessPlanWarnings } from './business-plan-warnings';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { DossierReportPreview } from './dossier-report-preview';
|
||||
import {
|
||||
createInvestorDossierReport,
|
||||
createInvestorStageReport,
|
||||
investorDossierReportIndex,
|
||||
investorFinancialReportChoices,
|
||||
type InvestorDossierReportInput,
|
||||
} from '@/lib/investor-dossier-report';
|
||||
import {
|
||||
@@ -31,6 +34,7 @@ function InvestorDossierReportsContent({
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [stage, setStage] = useState('');
|
||||
const [financialResultId, setFinancialResultId] = useState('');
|
||||
const [download, setDownload] = useState<{
|
||||
url: string;
|
||||
name: string;
|
||||
@@ -44,13 +48,44 @@ function InvestorDossierReportsContent({
|
||||
const requiresChoice =
|
||||
dossier.opportunity_options.length > 1 && !dossier.context_opportunity;
|
||||
const entries = requiresChoice ? [] : investorDossierReportIndex(dossier);
|
||||
const financialChoices = requiresChoice
|
||||
? []
|
||||
: investorFinancialReportChoices(dossier);
|
||||
const financialChoiceRequired =
|
||||
(!stage || stage === 'S03') &&
|
||||
financialChoices.length > 1 &&
|
||||
!financialResultId;
|
||||
const report = useMemo(
|
||||
() =>
|
||||
requiresChoice || financialChoiceRequired
|
||||
? null
|
||||
: stage
|
||||
? createInvestorStageReport(
|
||||
dossier,
|
||||
stage,
|
||||
undefined,
|
||||
financialResultId || undefined,
|
||||
)
|
||||
: createInvestorDossierReport(dossier, undefined, {
|
||||
financialResultId: financialResultId || undefined,
|
||||
}),
|
||||
[
|
||||
dossier,
|
||||
stage,
|
||||
financialResultId,
|
||||
requiresChoice,
|
||||
financialChoiceRequired,
|
||||
],
|
||||
);
|
||||
async function exportReport(format: 'word' | 'html') {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const model = stage
|
||||
? createInvestorStageReport(dossier, stage)
|
||||
: createInvestorDossierReport(dossier);
|
||||
if (!report)
|
||||
throw Error(
|
||||
'Escolha o contexto e a versão financeira antes de exportar.',
|
||||
);
|
||||
const model = report;
|
||||
const blob =
|
||||
format === 'word'
|
||||
? await generateProjectDossierDocx(model, [], true)
|
||||
@@ -80,6 +115,22 @@ function InvestorDossierReportsContent({
|
||||
return (
|
||||
<section id="relatorios" className="space-y-4 rounded-xl border p-4">
|
||||
<h2 className="text-lg font-semibold">Relatórios deste dossier</h2>
|
||||
{!requiresChoice && (
|
||||
<BusinessPlanWarnings
|
||||
metrics={{
|
||||
optionalTexts: [
|
||||
{
|
||||
label: 'SWOT',
|
||||
value: dossier.preparation_report?.swot.rows.some(
|
||||
(row) => row.text.trim(),
|
||||
)
|
||||
? 'preenchido'
|
||||
: '',
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<p>
|
||||
Dossier {dossier.case.title} · versão {dossier.case.version} ·
|
||||
oportunidade {dossier.context_opportunity ?? 'contexto comum'}.
|
||||
@@ -115,13 +166,69 @@ function InvestorDossierReportsContent({
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{stage && (
|
||||
<StageReportPreview dossier={dossier} stage={stage} />
|
||||
{(!stage || stage === 'S03') &&
|
||||
financialChoices.length > 0 && (
|
||||
<label className="grid min-w-0 gap-1">
|
||||
Plano financeiro a incluir
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={financialResultId}
|
||||
disabled={busy}
|
||||
onChange={(e) => {
|
||||
setFinancialResultId(e.target.value);
|
||||
setDownload(null);
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
{financialChoices.length === 1
|
||||
? 'Única versão preservada neste contexto'
|
||||
: 'Escolha uma versão — os valores não serão misturados'}
|
||||
</option>
|
||||
{financialChoices.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
Rascunho v{r.draft_version} ·{' '}
|
||||
{r.recorded_at} · contexto v
|
||||
{r.context_revision ??
|
||||
'por identificar'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{financialChoiceRequired && (
|
||||
<p role="status">
|
||||
Escolha a versão financeira a incluir. As restantes
|
||||
versões permanecem no histórico.
|
||||
</p>
|
||||
)}
|
||||
{!financialChoices.length &&
|
||||
dossier.results.some(
|
||||
(r) =>
|
||||
(r.context_opportunity ?? null) ===
|
||||
dossier.context_opportunity,
|
||||
) && (
|
||||
<p className="text-sm">
|
||||
As versões antigas não contêm todos os dados do
|
||||
relatório integral. Os originais permanecem
|
||||
disponíveis; use uma versão completa guardada
|
||||
para reunir as onze tabelas.
|
||||
</p>
|
||||
)}
|
||||
{report && (
|
||||
<details
|
||||
className="rounded border p-3"
|
||||
open={Boolean(stage)}
|
||||
>
|
||||
<summary>
|
||||
Conferir o relatório antes de exportar
|
||||
</summary>
|
||||
<DossierReportPreview report={report} />
|
||||
</details>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={busy}
|
||||
disabled={busy || financialChoiceRequired}
|
||||
onClick={() => exportReport('word')}
|
||||
>
|
||||
Preparar{' '}
|
||||
@@ -132,7 +239,7 @@ function InvestorDossierReportsContent({
|
||||
</button>
|
||||
<button
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={busy}
|
||||
disabled={busy || financialChoiceRequired}
|
||||
onClick={() => exportReport('html')}
|
||||
>
|
||||
Preparar versão para impressão/PDF
|
||||
@@ -158,7 +265,7 @@ function InvestorDossierReportsContent({
|
||||
</p>
|
||||
{!!entries.length && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<table className="w-full min-w-[48rem] text-left text-sm">
|
||||
<caption className="sr-only">
|
||||
Índice por etapa, versão e data
|
||||
</caption>
|
||||
@@ -226,46 +333,3 @@ function InvestorDossierReportsContent({
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function StageReportPreview({
|
||||
dossier,
|
||||
stage,
|
||||
}: {
|
||||
dossier: InvestorDossierReportInput;
|
||||
stage: string;
|
||||
}) {
|
||||
const report = createInvestorStageReport(dossier, stage);
|
||||
return (
|
||||
<article
|
||||
className="space-y-3 rounded border p-3"
|
||||
aria-label={`Relatório da etapa ${stage}`}
|
||||
>
|
||||
<h3 className="font-semibold">{report.title}</h3>
|
||||
<p className="text-sm">{report.version}</p>
|
||||
{report.sections.map((section) => (
|
||||
<section key={section.id} className="space-y-2">
|
||||
<h4 className="font-medium">{section.title}</h4>
|
||||
{section.paragraphs.map((text) => (
|
||||
<p key={text}>{text}</p>
|
||||
))}
|
||||
<dl className="space-y-2">
|
||||
{section.rows.map((row, index) => (
|
||||
<div key={index} className="break-words">
|
||||
<dt className="font-medium">{row.field}</dt>
|
||||
<dd>{row.value}</dd>
|
||||
<dd className="text-sm">
|
||||
{row.classification} · {row.origin}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
{report.limitations.map((text) => (
|
||||
<p className="text-sm" key={text}>
|
||||
{text}
|
||||
</p>
|
||||
))}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
|
||||
import {
|
||||
buildComplementaryTables,
|
||||
isMarketAnalysis,
|
||||
} from '@/lib/complementary-report';
|
||||
import { InvestmentReportTables } from './investment-report-tables';
|
||||
|
||||
export function MarketAnalysisPlan({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (p: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const a = plan.marketAnalysis ?? {
|
||||
baseYear: plan.reportAssumptions?.startYear ?? '',
|
||||
years: '3',
|
||||
segments: [],
|
||||
};
|
||||
if (!isMarketAnalysis(a))
|
||||
return (
|
||||
<p role="alert">
|
||||
A análise de mercado guardada tem uma estrutura desconhecida.
|
||||
Foi preservada; reveja o ficheiro antes de editar.
|
||||
</p>
|
||||
);
|
||||
const update = (patch: Partial<typeof a>) =>
|
||||
onChange({ ...plan, marketAnalysis: { ...a, ...patch } });
|
||||
const input = (
|
||||
label: string,
|
||||
value: string,
|
||||
change: (v: string) => void,
|
||||
type = 'text',
|
||||
) => (
|
||||
<label className="grid min-w-0 gap-1 text-sm">
|
||||
{label}
|
||||
<input
|
||||
className="min-w-0 rounded border p-2"
|
||||
type={type}
|
||||
step={type === 'number' ? 'any' : undefined}
|
||||
value={value}
|
||||
onChange={(e) => change(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
return (
|
||||
<details className="my-4 rounded border p-3">
|
||||
<summary>Análise de Mercado — segmentos e hipóteses</summary>
|
||||
<p className="my-2 text-sm">
|
||||
Obrigatório para completar esta tabela: ano-base, horizonte de 2
|
||||
a 10 anos e, por segmento, nome, clientes potenciais inteiros,
|
||||
crescimento anual e fonte ou hipótese identificada. Não são
|
||||
vendas nem procura confirmada. O horizonte sugerido de três anos
|
||||
é editável; não representa dados económicos.
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{input(
|
||||
'Ano-base de mercado',
|
||||
a.baseYear,
|
||||
(v) => update({ baseYear: v }),
|
||||
'number',
|
||||
)}
|
||||
{input(
|
||||
'Horizonte de mercado (anos)',
|
||||
a.years,
|
||||
(v) => update({ years: v }),
|
||||
'number',
|
||||
)}
|
||||
</div>
|
||||
{a.segments.map((s, i) => (
|
||||
<fieldset
|
||||
key={i}
|
||||
className="my-3 grid gap-3 rounded border p-3 sm:grid-cols-2"
|
||||
>
|
||||
<legend>Segmento {i + 1}</legend>
|
||||
{(
|
||||
[
|
||||
['label', 'Nome do segmento', 'text'],
|
||||
[
|
||||
'customers',
|
||||
'Clientes potenciais no ano-base',
|
||||
'number',
|
||||
],
|
||||
[
|
||||
'growthPercent',
|
||||
'Crescimento anual do segmento (%)',
|
||||
'number',
|
||||
],
|
||||
[
|
||||
'basis',
|
||||
'Fonte e data, ou hipótese ilustrativa',
|
||||
'text',
|
||||
],
|
||||
] as const
|
||||
).map(([key, label, type]) => (
|
||||
<div className="min-w-0" key={key}>
|
||||
{input(
|
||||
label,
|
||||
s[key],
|
||||
(v) =>
|
||||
update({
|
||||
segments: a.segments.map((r, j) =>
|
||||
j === i ? { ...r, [key]: v } : r,
|
||||
),
|
||||
}),
|
||||
type,
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
update({
|
||||
segments: a.segments.filter((_, j) => j !== i),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover segmento {i + 1}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="my-2 rounded border p-2"
|
||||
disabled={a.segments.length >= 100}
|
||||
onClick={() =>
|
||||
update({
|
||||
segments: [
|
||||
...a.segments,
|
||||
{
|
||||
label: '',
|
||||
customers: '',
|
||||
growthPercent: '',
|
||||
basis: '',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar segmento de mercado
|
||||
</button>
|
||||
<InvestmentReportTables
|
||||
tables={[
|
||||
buildComplementaryTables(
|
||||
{},
|
||||
{ ...plan, marketAnalysis: a },
|
||||
)[0],
|
||||
]}
|
||||
/>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ const labels: Record<string, string> = {
|
||||
internal_contact_id: 'Contacto interno',
|
||||
sector_id: 'Sector',
|
||||
subsector_id: 'Subsector',
|
||||
economic_activity_id: 'Atividade económica',
|
||||
economic_activity_id: 'Actividade económica',
|
||||
location_mode: 'Uma ou várias localizações',
|
||||
geographic_scope: 'Âmbito geográfico',
|
||||
multi_district_rationale: 'Justificação territorial',
|
||||
@@ -94,7 +94,7 @@ const labels: Record<string, string> = {
|
||||
real_estate: 'Imobiliário',
|
||||
land_rights: 'DUAT e direitos fundiários',
|
||||
business_transaction: 'Negócio',
|
||||
module_profile_version: 'Versão do contrato QA (seleção explícita)',
|
||||
module_profile_version: 'Versão do contrato QA (selecção explícita)',
|
||||
module_details: 'Condições do módulo',
|
||||
mode: 'Percurso: procura, oferta ou modalidade',
|
||||
conditions_status: 'Condições propostas ou compromisso documentado',
|
||||
@@ -1156,7 +1156,7 @@ export default function OpportunityCanonicalFields({
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Contrato original / por selecionar
|
||||
Contrato original / por seleccionar
|
||||
</option>
|
||||
{current && current !== version && (
|
||||
<option value={current}>
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { router } from '@inertiajs/react';
|
||||
import { control, button } from '@/pages/management/shared';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import PublicReference from './public-reference';
|
||||
import { publicReference } from '@/lib/public-presentation';
|
||||
|
||||
type Classification = {
|
||||
target_type: string;
|
||||
@@ -49,11 +51,11 @@ const typeLabels: Record<string, string> = {
|
||||
corridor: 'Corredor',
|
||||
location: 'Localização',
|
||||
cluster: 'Cluster',
|
||||
project: 'Projeto âncora',
|
||||
project: 'Projecto âncora',
|
||||
chain: 'Cadeia de valor',
|
||||
zone: 'Zona ou parque',
|
||||
sector: 'Setor',
|
||||
activity: 'Subsector ou atividade',
|
||||
sector: 'Sector',
|
||||
activity: 'Subsector ou actividade',
|
||||
};
|
||||
export const classificationStates: Record<string, string> = {
|
||||
draft: 'Rascunho',
|
||||
@@ -67,8 +69,8 @@ export const classificationStates: Record<string, string> = {
|
||||
const externalLabels: Record<string, string> = {
|
||||
not_assessed: 'Não determinado',
|
||||
pending: 'Pendente',
|
||||
documented_granted: 'Ato de concessão documentado',
|
||||
documented_denied: 'Ato de recusa documentado',
|
||||
documented_granted: 'Acto de concessão documentado',
|
||||
documented_denied: 'Acto de recusa documentado',
|
||||
expired: 'Caducado',
|
||||
};
|
||||
const help =
|
||||
@@ -211,7 +213,7 @@ export function ClassificationEditor({
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Selecionar referência
|
||||
Seleccionar referência
|
||||
</option>
|
||||
{row.related_id &&
|
||||
!(
|
||||
@@ -295,7 +297,7 @@ export function ClassificationEditor({
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Selecionar finalidade
|
||||
Seleccionar finalidade
|
||||
</option>
|
||||
{Object.entries(
|
||||
options.purposes,
|
||||
@@ -840,7 +842,7 @@ export function ClassificationSummary({
|
||||
territory: 'Enquadramento territorial',
|
||||
production: 'Organização produtiva',
|
||||
regulation: 'Regime regulatório',
|
||||
activity: 'Atividade económica',
|
||||
activity: 'Actividade económica',
|
||||
}).map(([dimension, label]) => (
|
||||
<section key={dimension}>
|
||||
<h3 className="font-semibold">{label}</h3>
|
||||
@@ -861,9 +863,15 @@ export function ClassificationSummary({
|
||||
{classificationStates[r.state] ??
|
||||
'Por determinar'}{' '}
|
||||
· {r.purpose_label ?? r.purpose} ·{' '}
|
||||
{r.source_reference || 'Fonte por indicar'}{' '}
|
||||
{r.citation} {r.production_stage} · Ato
|
||||
externo:{' '}
|
||||
{publicReference(r.source_reference) ? (
|
||||
<PublicReference
|
||||
value={r.source_reference}
|
||||
/>
|
||||
) : (
|
||||
'Referência pública não disponível'
|
||||
)}{' '}
|
||||
{publicReference(r.citation)}{' '}
|
||||
{r.production_stage} · Acto externo:{' '}
|
||||
{externalLabels[r.external_status] ??
|
||||
'Não determinado'}
|
||||
. Benefício ou capacidade disponível: não
|
||||
@@ -935,7 +943,7 @@ export function ClassificationFilters({
|
||||
},
|
||||
{
|
||||
key: 'subsector_id',
|
||||
label: 'Subsector ou atividade publicada',
|
||||
label: 'Subsector ou actividade publicada',
|
||||
choices: (options.targets.activity ?? []).map((r) => [
|
||||
String(r.id),
|
||||
r.label,
|
||||
@@ -962,7 +970,7 @@ export function ClassificationFilters({
|
||||
<legend>Classificação multidimensional — filtros combinados</legend>
|
||||
<p>
|
||||
Os filtros combinam-se por «e». Tipo, referência e finalidade
|
||||
identificam a mesma associação; cadeia, atividade e entidade
|
||||
identificam a mesma associação; cadeia, actividade e entidade
|
||||
podem constar de outras associações da mesma oportunidade. A
|
||||
pesquisa inclui apenas publicações públicas. Os vínculos
|
||||
anteriores continuam nos filtros próprios.
|
||||
|
||||
@@ -160,7 +160,7 @@ export default function OpportunityContactForm({
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<option value="">Por selecionar</option>
|
||||
<option value="">Por seleccionar</option>
|
||||
{investors.map((investor) => (
|
||||
<option key={investor.id} value={investor.id}>
|
||||
{investor.legal_name}
|
||||
@@ -213,7 +213,7 @@ export default function OpportunityContactForm({
|
||||
type="button"
|
||||
onClick={() => void save()}
|
||||
>
|
||||
Guardar contacto e selecionar
|
||||
Guardar contacto e seleccionar
|
||||
</button>
|
||||
</fieldset>
|
||||
<p id="contact-result" role="status" tabIndex={-1}>
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
type BusinessFinancialPlanInput,
|
||||
} from '@/lib/business-financial-plan';
|
||||
import type {
|
||||
PeriodInvestments,
|
||||
PeriodFinancing,
|
||||
PeriodAsset,
|
||||
} from '@/lib/period-investments';
|
||||
|
||||
export function PeriodInvestmentsEditor({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (p: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const c: PeriodInvestments = plan.periodInvestments ?? {
|
||||
enabled: false,
|
||||
financings: [],
|
||||
assets: [],
|
||||
};
|
||||
const save = (v: PeriodInvestments) =>
|
||||
onChange({ ...plan, periodInvestments: v });
|
||||
const fund = (i: number, p: Partial<PeriodFinancing>) =>
|
||||
save({
|
||||
...c,
|
||||
financings: c.financings.map((f, j) =>
|
||||
j === i ? { ...f, ...p } : f,
|
||||
),
|
||||
});
|
||||
const asset = (i: number, p: Partial<PeriodAsset>) =>
|
||||
save({
|
||||
...c,
|
||||
assets: c.assets.map((a, j) => (j === i ? { ...a, ...p } : a)),
|
||||
});
|
||||
const field = (
|
||||
label: string,
|
||||
value: string,
|
||||
change: (v: string) => void,
|
||||
type = 'text',
|
||||
) => (
|
||||
<label key={label} className="grid min-w-0 gap-1">
|
||||
{label}
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type={type}
|
||||
value={value}
|
||||
onChange={(e) => change(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
let ledger: ReturnType<
|
||||
typeof forecastBusinessPlan
|
||||
>['periodInvestmentLedger'];
|
||||
let error = '';
|
||||
try {
|
||||
ledger = forecastBusinessPlan(plan).periodInvestmentLedger;
|
||||
} catch (e) {
|
||||
error =
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Confira os movimentos por período.';
|
||||
}
|
||||
return (
|
||||
<details className="my-3 min-w-0 space-y-3 rounded border p-3">
|
||||
<summary className="font-semibold">
|
||||
Novos financiamentos e activos por período
|
||||
</summary>
|
||||
<p>
|
||||
Projecções opcionais, separadas dos valores de abertura. Escolha
|
||||
o regime no plano antes de preparar este incremento. Não executa
|
||||
pagamentos nem cria financiamento para eliminar caixa negativa.
|
||||
</p>
|
||||
<p>
|
||||
Aquisições integralmente reconhecidas e pagas no mesmo mês, sem
|
||||
pagamento anterior ao reconhecimento. Crédito e adiantamentos
|
||||
para activos excluídos. A depreciação começa na disponibilidade
|
||||
para uso declarada: primeiro mês proporcional aos dias,
|
||||
inclusive; quotas mensais equivalentes e última parcela
|
||||
complementar. Arredondamento acumulado ao centavo. O fim do
|
||||
horizonte não antecipa o fecho da vida útil.
|
||||
</p>
|
||||
<p>
|
||||
Regime do plano: {plan.accountingRegime || 'por escolher'}.
|
||||
Horizonte: {plan.periods ?? 12} meses. As agendas existentes
|
||||
continuam a tratar exclusivamente os valores de abertura; não
|
||||
repita nelas os novos movimentos. Juros reconhecidos e pagos são
|
||||
independentes e não são capitalizados automaticamente no activo.
|
||||
</p>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={c.enabled}
|
||||
disabled={!plan.accountingRegime}
|
||||
onChange={(e) => {
|
||||
if (
|
||||
e.target.checked &&
|
||||
!window.confirm(
|
||||
'Activar os novos movimentos declarados? Os montantes de abertura e as agendas de prazos e adiantamentos ficam preservados; não repita os mesmos movimentos nas agendas antigas.',
|
||||
)
|
||||
)
|
||||
return;
|
||||
save({ ...c, enabled: e.target.checked });
|
||||
}}
|
||||
/>
|
||||
Activar novos movimentos por período (adesão explícita)
|
||||
</label>
|
||||
<p>
|
||||
Desactivar conserva os dados deste incremento, sem os incluir no
|
||||
cálculo. Campos vazios não são zero.
|
||||
</p>
|
||||
{c.financings.map((f, i) => (
|
||||
<details key={i} className="min-w-0 rounded border p-3" open>
|
||||
<summary>
|
||||
Financiamento {i + 1} — {f.label || 'por identificar'}
|
||||
</summary>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{field('Identificador do financiamento', f.id, (v) =>
|
||||
fund(i, { id: v }),
|
||||
)}
|
||||
{field('Designação do financiamento', f.label, (v) =>
|
||||
fund(i, { label: v }),
|
||||
)}
|
||||
<label className="grid gap-1">
|
||||
Tipo de financiamento
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={f.kind}
|
||||
onChange={(e) =>
|
||||
fund(i, {
|
||||
kind: e.target
|
||||
.value as PeriodFinancing['kind'],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="bank">
|
||||
Empréstimo bancário
|
||||
</option>
|
||||
<option value="shareholder">Suprimento</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{f.drawdowns.map((d, j) => (
|
||||
<div
|
||||
key={j}
|
||||
className="my-2 grid gap-2 rounded border p-2 sm:grid-cols-3"
|
||||
aria-label={`Desembolso ${j + 1} do financiamento ${i + 1}`}
|
||||
>
|
||||
{field('Identificador do desembolso', d.id, (v) =>
|
||||
fund(i, {
|
||||
drawdowns: f.drawdowns.map((x, k) =>
|
||||
k === j ? { ...x, id: v } : x,
|
||||
),
|
||||
}),
|
||||
)}
|
||||
{field(
|
||||
'Data do desembolso',
|
||||
d.date,
|
||||
(v) =>
|
||||
fund(i, {
|
||||
drawdowns: f.drawdowns.map((x, k) =>
|
||||
k === j ? { ...x, date: v } : x,
|
||||
),
|
||||
}),
|
||||
'date',
|
||||
)}
|
||||
{field('Montante do desembolso', d.amount, (v) =>
|
||||
fund(i, {
|
||||
drawdowns: f.drawdowns.map((x, k) =>
|
||||
k === j ? { ...x, amount: v } : x,
|
||||
),
|
||||
}),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
fund(i, {
|
||||
drawdowns: f.drawdowns.filter(
|
||||
(_, k) => k !== j,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover desembolso {j + 1}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
disabled={f.drawdowns.length >= 60}
|
||||
onClick={() =>
|
||||
fund(i, {
|
||||
drawdowns: [
|
||||
...f.drawdowns,
|
||||
{ id: '', date: '', amount: '' },
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar desembolso ao financiamento {i + 1}
|
||||
</button>
|
||||
<details className="my-2 rounded border p-2">
|
||||
<summary>
|
||||
Agenda mensal do financiamento {i + 1}
|
||||
</summary>
|
||||
<p>
|
||||
Agendas por período, sem taxas ou condições
|
||||
bancárias presumidas. Cada mês exige os três
|
||||
montantes declarados, incluindo zero quando
|
||||
aplicável. O principal é limitado ao saldo deste
|
||||
financiamento, após desembolsos desse mês.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
fund(i, {
|
||||
agenda: Array.from(
|
||||
{ length: plan.periods ?? 12 },
|
||||
(_, m) =>
|
||||
f.agenda.find(
|
||||
(a) => a.month === m + 1,
|
||||
) ?? {
|
||||
month: m + 1,
|
||||
interestExpense: '',
|
||||
interestPaid: '',
|
||||
principal: '',
|
||||
},
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Completar meses em falta do financiamento {i + 1}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
fund(i, {
|
||||
agenda: f.agenda.map((a) => ({
|
||||
...a,
|
||||
interestExpense:
|
||||
a.interestExpense || '0',
|
||||
interestPaid: a.interestPaid || '0',
|
||||
principal: a.principal || '0',
|
||||
})),
|
||||
})
|
||||
}
|
||||
>
|
||||
Declarar zero nos campos vazios do financiamento{' '}
|
||||
{i + 1}
|
||||
</button>
|
||||
{f.agenda.map((a, j) => (
|
||||
<div
|
||||
key={j}
|
||||
className="my-2 grid gap-2 rounded border p-2 sm:grid-cols-3"
|
||||
aria-label={`Mês ${a.month} do financiamento ${i + 1}`}
|
||||
>
|
||||
<p>Mês {a.month}</p>
|
||||
{(
|
||||
[
|
||||
'interestExpense',
|
||||
'interestPaid',
|
||||
'principal',
|
||||
] as const
|
||||
).map((k) =>
|
||||
field(
|
||||
k === 'interestExpense'
|
||||
? `Juros reconhecidos, mês ${a.month}`
|
||||
: k === 'interestPaid'
|
||||
? `Juros pagos, mês ${a.month}`
|
||||
: `Principal, mês ${a.month}`,
|
||||
a[k],
|
||||
(v) =>
|
||||
fund(i, {
|
||||
agenda: f.agenda.map((x, n) =>
|
||||
n === j
|
||||
? { ...x, [k]: v }
|
||||
: x,
|
||||
),
|
||||
}),
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</details>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
financings: c.financings.filter(
|
||||
(_, j) => j !== i,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover financiamento {i + 1}
|
||||
</button>
|
||||
</details>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
disabled={!plan.accountingRegime || c.financings.length >= 60}
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
financings: [
|
||||
...c.financings,
|
||||
{
|
||||
id: '',
|
||||
label: '',
|
||||
kind: 'bank',
|
||||
drawdowns: [],
|
||||
agenda: Array.from(
|
||||
{ length: plan.periods ?? 12 },
|
||||
(_, i) => ({
|
||||
month: i + 1,
|
||||
interestExpense: '',
|
||||
interestPaid: '',
|
||||
principal: '',
|
||||
}),
|
||||
),
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar financiamento por período
|
||||
</button>
|
||||
{c.assets.map((a, i) => (
|
||||
<fieldset
|
||||
key={i}
|
||||
className="grid min-w-0 gap-2 rounded border p-3 sm:grid-cols-2"
|
||||
>
|
||||
<legend>Activo posterior {i + 1}</legend>
|
||||
{field('Identificador do activo', a.id, (v) =>
|
||||
asset(i, { id: v }),
|
||||
)}
|
||||
{field('Designação do activo', a.label, (v) =>
|
||||
asset(i, { label: v }),
|
||||
)}
|
||||
{field(
|
||||
'Reconhecimento do activo',
|
||||
a.recognitionDate,
|
||||
(v) => asset(i, { recognitionDate: v }),
|
||||
'date',
|
||||
)}
|
||||
{field(
|
||||
'Pagamento do activo',
|
||||
a.paymentDate,
|
||||
(v) => asset(i, { paymentDate: v }),
|
||||
'date',
|
||||
)}
|
||||
{field('Valor da aquisição', a.cost, (v) =>
|
||||
asset(i, { cost: v }),
|
||||
)}
|
||||
{field('Base depreciável do novo activo', a.base, (v) =>
|
||||
asset(i, { base: v }),
|
||||
)}
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={a.depreciable}
|
||||
onChange={(e) =>
|
||||
asset(i, { depreciable: e.target.checked })
|
||||
}
|
||||
/>
|
||||
Activo depreciável
|
||||
</label>
|
||||
{a.depreciable && (
|
||||
<>
|
||||
{field(
|
||||
'Vida útil do novo activo (meses)',
|
||||
a.lifeMonths,
|
||||
(v) => asset(i, { lifeMonths: v }),
|
||||
)}
|
||||
{field(
|
||||
'Disponibilidade para uso',
|
||||
a.availableDate,
|
||||
(v) => asset(i, { availableDate: v }),
|
||||
'date',
|
||||
)}
|
||||
{plan.accountingRegime === 'PGC-NIRF' &&
|
||||
field(
|
||||
'Fundamentação do método linear PGC-NIRF',
|
||||
a.linearBasis,
|
||||
(v) => asset(i, { linearBasis: v }),
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
assets: c.assets.filter((_, j) => j !== i),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover activo posterior {i + 1}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
disabled={!plan.accountingRegime || c.assets.length >= 60}
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
assets: [
|
||||
...c.assets,
|
||||
{
|
||||
id: '',
|
||||
label: '',
|
||||
recognitionDate: '',
|
||||
paymentDate: '',
|
||||
cost: '',
|
||||
base: '',
|
||||
lifeMonths: '',
|
||||
availableDate: '',
|
||||
linearBasis: '',
|
||||
depreciable: true,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar activo por período
|
||||
</button>
|
||||
{c.enabled && error && <p role="alert">{error}</p>}
|
||||
{ledger && (
|
||||
<section
|
||||
aria-label="Resumo dos novos movimentos por período"
|
||||
className="space-y-2"
|
||||
>
|
||||
<h4>Novos movimentos conferidos</h4>
|
||||
{ledger.financings.map((f) => (
|
||||
<p key={f.id}>
|
||||
{f.id} — {f.label}:{' '}
|
||||
{f.kind === 'bank'
|
||||
? 'empréstimo bancário'
|
||||
: 'suprimento'}
|
||||
; saldo no horizonte {f.monthly.at(-1)?.balance}{' '}
|
||||
{plan.currency}.{' '}
|
||||
{f.drawdowns
|
||||
.filter((d) => d.outsideHorizon)
|
||||
.map(
|
||||
(d) =>
|
||||
`Desembolso ${d.id} de ${d.amount} em ${d.date}: fora do horizonte.`,
|
||||
)
|
||||
.join(' ')}
|
||||
</p>
|
||||
))}
|
||||
{ledger.assets.map((a) => (
|
||||
<p key={a.id}>
|
||||
{a.id} — {a.label}: aquisição {a.cost}; base{' '}
|
||||
{a.base}; fracção inicial{' '}
|
||||
{a.firstFraction ?? 'não depreciável'}; último mês{' '}
|
||||
{a.lastMonth ?? 'não aplicável'}; base ainda não
|
||||
depreciada {a.remainingDepreciation} {plan.currency}
|
||||
.{' '}
|
||||
{a.outsideHorizon
|
||||
? 'Aquisição fora do horizonte, sem caixa ou reconhecimento antecipado.'
|
||||
: ''}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import CatalogueChoiceSelect from './catalogue-choice-select';
|
||||
import {
|
||||
describePlanCae,
|
||||
mozambiqueCaeSource,
|
||||
planCaeChoices,
|
||||
selectPlanCae,
|
||||
} from '@/lib/cae-mozambique';
|
||||
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
|
||||
|
||||
export function PlanEconomicClassification({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (plan: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const classification = describePlanCae(plan.economicClassification);
|
||||
return (
|
||||
<section
|
||||
className="my-4 min-w-0 space-y-3 rounded border p-3"
|
||||
aria-label="Classificação económica do plano"
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
Actividade económica — CAE de Moçambique
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
Escolha a subclasse correspondente à actividade efectivamente
|
||||
prevista. Quando houver alternativas, confirme a actividade
|
||||
principal; o sector do portal e as vendas projectadas não
|
||||
determinam automaticamente a CAE.
|
||||
</p>
|
||||
<CatalogueChoiceSelect
|
||||
label="Actividade CAE do plano"
|
||||
options={planCaeChoices}
|
||||
value={plan.economicClassification?.code ?? ''}
|
||||
onChange={(code) =>
|
||||
onChange({
|
||||
...plan,
|
||||
economicClassification: selectPlanCae(code),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p role="status">{classification.value}</p>
|
||||
<p className="text-sm">
|
||||
Escolha declarada pelo investidor, a confirmar documentalmente.
|
||||
Não altera cálculos, impostos, licenças ou financiamento. Pode
|
||||
continuar com «Não documentado».
|
||||
</p>
|
||||
<a
|
||||
className="text-sm underline"
|
||||
href={mozambiqueCaeSource.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Consultar CAE-Rev.2 — INE, 2008
|
||||
</a>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
correctionFieldHints,
|
||||
correctionGroupMatches,
|
||||
fieldLabelMatches,
|
||||
normaliseFieldLabel,
|
||||
revealCorrectionTarget,
|
||||
} from '@/lib/field-corrections';
|
||||
|
||||
type Correction = { message: string; targets: { id: string; label: string }[] };
|
||||
let nextId = 0;
|
||||
function labelOf(
|
||||
control: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement,
|
||||
) {
|
||||
const label = control.labels?.[0];
|
||||
if (label) {
|
||||
const copy = label.cloneNode(true) as HTMLElement;
|
||||
copy.querySelectorAll(
|
||||
'input,select,textarea,button,[role="alert"],.sr-only',
|
||||
).forEach((n) => n.remove());
|
||||
return (
|
||||
copy.textContent?.replace(/\s+/g, ' ').trim() ||
|
||||
control.getAttribute('aria-label') ||
|
||||
''
|
||||
);
|
||||
}
|
||||
return control.getAttribute('aria-label') || '';
|
||||
}
|
||||
/** Maps live, existing messages to real controls; no inferred financial validations. */
|
||||
export default function PortalCorrections() {
|
||||
const marker = useRef<HTMLDivElement>(null);
|
||||
const [items, setItems] = useState<Correction[]>([]);
|
||||
const previous = useRef('');
|
||||
useEffect(() => {
|
||||
const root = marker.current?.closest('#portal-content');
|
||||
if (!root) return;
|
||||
let pending = 0;
|
||||
const collect = () => {
|
||||
pending = 0;
|
||||
const controls = [
|
||||
...root.querySelectorAll<
|
||||
HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
|
||||
>('input:not([type="hidden"]),select,textarea'),
|
||||
].filter(
|
||||
(c) =>
|
||||
!c.disabled && !c.closest('[hidden],[aria-hidden="true"]'),
|
||||
);
|
||||
const names = controls.map((c) => ({
|
||||
control: c,
|
||||
label: labelOf(c),
|
||||
}));
|
||||
const target = (c: (typeof controls)[number], label: string) => {
|
||||
if (!c.id) c.id = `portal-correction-field-${++nextId}`;
|
||||
const group = c.closest('fieldset,[role="group"]');
|
||||
const context =
|
||||
group?.querySelector('legend')?.textContent?.trim() ||
|
||||
group?.getAttribute('aria-label') ||
|
||||
'';
|
||||
return {
|
||||
id: c.id,
|
||||
label: context ? `${label} — ${context}` : label,
|
||||
};
|
||||
};
|
||||
const grouped = new Map<string, Correction>();
|
||||
const add = (message: string, targets: Correction['targets']) => {
|
||||
if (!message || !targets.length) return;
|
||||
const item = grouped.get(message) ?? { message, targets: [] };
|
||||
for (const t of targets)
|
||||
if (!item.targets.some((a) => a.id === t.id))
|
||||
item.targets.push(t);
|
||||
grouped.set(message, item);
|
||||
};
|
||||
for (const { control, label } of names) {
|
||||
if (control.getAttribute('aria-invalid') !== 'true') continue;
|
||||
const messages = (
|
||||
control.getAttribute('aria-describedby') ?? ''
|
||||
)
|
||||
.split(/\s+/)
|
||||
.map((id) =>
|
||||
document.getElementById(id)?.textContent?.trim(),
|
||||
)
|
||||
.filter(Boolean);
|
||||
const local = control
|
||||
.closest('label')
|
||||
?.querySelector('[role="alert"]')
|
||||
?.textContent?.trim();
|
||||
add(
|
||||
messages.join(' ') || local || 'Confira o valor indicado.',
|
||||
[target(control, label || 'Campo indicado')],
|
||||
);
|
||||
}
|
||||
const availableLabels = names.map(({ label }) => label);
|
||||
const exactLabels = new Set(
|
||||
availableLabels.map(normaliseFieldLabel),
|
||||
);
|
||||
for (const node of root.querySelectorAll<HTMLElement>(
|
||||
'[data-correction-message],[role="alert"]',
|
||||
)) {
|
||||
if (
|
||||
node.closest(
|
||||
'[data-correction-summary],[hidden],[aria-hidden="true"]',
|
||||
)
|
||||
)
|
||||
continue;
|
||||
const message =
|
||||
node.dataset.correctionMessage ||
|
||||
node.textContent?.replace(/\s+/g, ' ').trim() ||
|
||||
'';
|
||||
if (!message) continue;
|
||||
const hints = correctionFieldHints(message, availableLabels);
|
||||
const matches = names.filter(
|
||||
({ label }) =>
|
||||
label &&
|
||||
hints.some((h) =>
|
||||
fieldLabelMatches(label, h, exactLabels),
|
||||
),
|
||||
);
|
||||
// Restrict explicit product/parcel/milestone/personnel diagnostics to the matching real group, if present.
|
||||
const index =
|
||||
/(?:produto|parcela|marco|função|necessidade|segmento)\s+(\d+)/i.exec(
|
||||
message,
|
||||
);
|
||||
const indexed = index
|
||||
? matches.filter(({ control }) => {
|
||||
const group = control.closest(
|
||||
'fieldset,[role="group"],[aria-label]',
|
||||
);
|
||||
const name =
|
||||
group?.getAttribute('aria-label') ||
|
||||
group?.querySelector('legend')?.textContent ||
|
||||
'';
|
||||
return correctionGroupMatches(message, name);
|
||||
})
|
||||
: [];
|
||||
add(
|
||||
message,
|
||||
(indexed.length ? indexed : matches).map(
|
||||
({ control, label }) => target(control, label),
|
||||
),
|
||||
);
|
||||
}
|
||||
const next = [...grouped.values()];
|
||||
const serial = JSON.stringify(next);
|
||||
if (serial !== previous.current) {
|
||||
previous.current = serial;
|
||||
setItems(next);
|
||||
}
|
||||
};
|
||||
const schedule = () => {
|
||||
if (!pending) pending = requestAnimationFrame(collect);
|
||||
};
|
||||
const observer = new MutationObserver((records) => {
|
||||
if (
|
||||
records.some(
|
||||
(r) =>
|
||||
!(
|
||||
r.target instanceof Element
|
||||
? r.target
|
||||
: r.target.parentElement
|
||||
)?.closest('[data-correction-summary]'),
|
||||
)
|
||||
)
|
||||
schedule();
|
||||
});
|
||||
observer.observe(root, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
characterData: true,
|
||||
attributes: true,
|
||||
attributeFilter: ['aria-invalid', 'aria-describedby', 'hidden'],
|
||||
});
|
||||
root.addEventListener('input', schedule);
|
||||
root.addEventListener('change', schedule);
|
||||
collect();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
root.removeEventListener('input', schedule);
|
||||
root.removeEventListener('change', schedule);
|
||||
if (pending) cancelAnimationFrame(pending);
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<div
|
||||
ref={marker}
|
||||
data-correction-summary
|
||||
className="mx-auto max-w-6xl px-4 print:hidden"
|
||||
>
|
||||
{items.length > 0 && (
|
||||
<section
|
||||
id="portal-corrections"
|
||||
aria-label="Falta preencher ou corrigir"
|
||||
className="my-3 space-y-3 rounded border border-amber-500 bg-amber-50 p-4 text-sm"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
Falta preencher ou corrigir
|
||||
</h2>
|
||||
<p>
|
||||
Use as ligações para abrir a secção e chegar ao campo
|
||||
indicado.
|
||||
</p>
|
||||
<ul className="space-y-3">
|
||||
{items.map((item) => (
|
||||
<li key={item.message}>
|
||||
<p>{item.message}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{item.targets.map((t) => (
|
||||
<a
|
||||
key={t.id}
|
||||
className="min-h-11 rounded border bg-white px-3 py-2 underline"
|
||||
href={`#${t.id}`}
|
||||
onClick={(e) => {
|
||||
const node =
|
||||
document.getElementById(
|
||||
t.id,
|
||||
);
|
||||
if (node) {
|
||||
e.preventDefault();
|
||||
revealCorrectionTarget(
|
||||
node,
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t.label}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { DossierReportPreview } from './dossier-report-preview';
|
||||
import {
|
||||
DossierExportGate,
|
||||
dossierExportFailure,
|
||||
@@ -7,6 +8,7 @@ import {
|
||||
import {
|
||||
createProjectDossierPrintHtml,
|
||||
createProjectDossierReport,
|
||||
createIntegralFinancialReport,
|
||||
dossierReportSections,
|
||||
generateProjectDossierDocx,
|
||||
generateProjectDossierPackage,
|
||||
@@ -58,6 +60,7 @@ export function ProjectDossierExport({
|
||||
currentCalculation = null,
|
||||
}: Props) {
|
||||
const [selectedSections, setSelectedSections] = useState(defaultSections);
|
||||
const [reportMode, setReportMode] = useState('dossier');
|
||||
const [attachments, setAttachments] = useState<DossierAttachment[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState('');
|
||||
@@ -127,13 +130,31 @@ export function ProjectDossierExport({
|
||||
);
|
||||
}
|
||||
|
||||
function model() {
|
||||
return createProjectDossierReport(draft, {
|
||||
selectedSections: selectedSectionSet,
|
||||
const report = useMemo(
|
||||
() =>
|
||||
reportMode === 'financial'
|
||||
? createIntegralFinancialReport(draft, {
|
||||
version,
|
||||
references,
|
||||
currentCalculation,
|
||||
})
|
||||
: createProjectDossierReport(draft, {
|
||||
selectedSections: selectedSectionSet,
|
||||
version,
|
||||
references,
|
||||
currentCalculation,
|
||||
}),
|
||||
[
|
||||
draft,
|
||||
reportMode,
|
||||
version,
|
||||
references,
|
||||
currentCalculation,
|
||||
});
|
||||
selectedSectionSet,
|
||||
],
|
||||
);
|
||||
function model() {
|
||||
return report;
|
||||
}
|
||||
|
||||
async function exportWord(): Promise<void> {
|
||||
@@ -272,7 +293,10 @@ export function ProjectDossierExport({
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<fieldset className="space-y-2">
|
||||
<fieldset
|
||||
className="space-y-2"
|
||||
disabled={reportMode === 'financial'}
|
||||
>
|
||||
<legend className="font-medium">
|
||||
Escolha as secções a incluir
|
||||
</legend>
|
||||
@@ -400,6 +424,26 @@ export function ProjectDossierExport({
|
||||
em zero. O relatório identifica pressupostos, estimativas e
|
||||
referências sem as apresentar como resultados confirmados.
|
||||
</p>
|
||||
<label className="grid min-w-0 gap-1">
|
||||
Conteúdo do relatório
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={reportMode}
|
||||
onChange={(e) => setReportMode(e.target.value)}
|
||||
disabled={Boolean(busy)}
|
||||
>
|
||||
<option value="dossier">
|
||||
Dossier e contexto — secções seleccionadas
|
||||
</option>
|
||||
<option value="financial">
|
||||
Relatório financeiro integral — onze tabelas
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<details className="rounded border p-3">
|
||||
<summary>Conferir o relatório antes de exportar</summary>
|
||||
<DossierReportPreview report={report} />
|
||||
</details>
|
||||
{notice && (
|
||||
<p role="status" className="text-sm">
|
||||
{notice}
|
||||
@@ -414,7 +458,11 @@ export function ProjectDossierExport({
|
||||
<button
|
||||
type="button"
|
||||
className="rounded bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50"
|
||||
disabled={Boolean(busy) || selectedSections.size === 0}
|
||||
disabled={
|
||||
Boolean(busy) ||
|
||||
(reportMode === 'dossier' &&
|
||||
selectedSections.size === 0)
|
||||
}
|
||||
onClick={() => void exportWord()}
|
||||
>
|
||||
{busy === 'word'
|
||||
@@ -424,7 +472,11 @@ export function ProjectDossierExport({
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-4 py-2 disabled:opacity-50"
|
||||
disabled={Boolean(busy) || selectedSections.size === 0}
|
||||
disabled={
|
||||
Boolean(busy) ||
|
||||
(reportMode === 'dossier' &&
|
||||
selectedSections.size === 0)
|
||||
}
|
||||
onClick={() => void exportPdf()}
|
||||
>
|
||||
{busy === 'pdf'
|
||||
|
||||
@@ -3,6 +3,9 @@ import {
|
||||
type ProjectMilestone,
|
||||
type TeamNeed,
|
||||
} from '@/lib/project-dossier';
|
||||
import { restoreBusinessPlanSnapshot } from '@/lib/business-financial-plan';
|
||||
import { buildComplementaryTables } from '@/lib/complementary-report';
|
||||
import { InvestmentReportTables } from './investment-report-tables';
|
||||
|
||||
const teamKeys = [
|
||||
'competency',
|
||||
@@ -28,15 +31,86 @@ function update<T extends Record<string, string>>(
|
||||
return rows.map((row, i) => (i === index ? { ...row, [key]: value } : row));
|
||||
}
|
||||
|
||||
function unreadable(value: string, rows: unknown[], optional: string[]) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value || '[]');
|
||||
return (
|
||||
!Array.isArray(parsed) ||
|
||||
parsed.length !== rows.length ||
|
||||
parsed.length > 100 ||
|
||||
parsed.some((row) =>
|
||||
optional.some(
|
||||
(key) => key in row && typeof row[key] !== 'string',
|
||||
),
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function SupplementaryFields({
|
||||
row,
|
||||
fields,
|
||||
change,
|
||||
}: {
|
||||
row: Record<string, string | undefined>;
|
||||
fields: readonly (readonly [string, string, string])[];
|
||||
change: (key: string, value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{fields.map(([key, label, type]) => (
|
||||
<label className="grid min-w-0 gap-1 text-sm" key={key}>
|
||||
{label}
|
||||
<input
|
||||
className="min-w-0 rounded border p-2"
|
||||
type={type}
|
||||
min={type === 'number' ? 0 : undefined}
|
||||
step={
|
||||
type === 'number'
|
||||
? key === 'monthly_salary'
|
||||
? '0.01'
|
||||
: '1'
|
||||
: undefined
|
||||
}
|
||||
value={row[key] ?? ''}
|
||||
onChange={(e) => change(key, e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectTeamPlanner({
|
||||
value,
|
||||
onChange,
|
||||
financialPlanSnapshot = '',
|
||||
projectCurrency = '',
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
financialPlanSnapshot?: string;
|
||||
projectCurrency?: string;
|
||||
}) {
|
||||
const rows = readRows<TeamNeed>(value, teamKeys);
|
||||
const persist = (next: TeamNeed[]) => onChange(JSON.stringify(next));
|
||||
if (
|
||||
unreadable(value, rows, [
|
||||
'department',
|
||||
'quantity',
|
||||
'monthly_salary',
|
||||
'start_month',
|
||||
'end_month',
|
||||
])
|
||||
)
|
||||
return (
|
||||
<p role="alert">
|
||||
O plano de equipa guardado contém linhas não reconhecidas. O
|
||||
original foi preservado e não será substituído por este editor.
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<section
|
||||
className="space-y-4"
|
||||
@@ -47,6 +121,12 @@ export function ProjectTeamPlanner({
|
||||
custo e prazo. Não é uma certificação nem uma correspondência
|
||||
automática a prestadores.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Para o mapa de pessoal: função, departamento, quantidade,
|
||||
remuneração mensal e meses inicial/final são necessários. Os
|
||||
restantes campos são opcionais; não confundir custo de formação
|
||||
ou contratação com salário.
|
||||
</p>
|
||||
{rows.map((row, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
@@ -55,6 +135,42 @@ export function ProjectTeamPlanner({
|
||||
<legend className="font-medium">
|
||||
Necessidade {index + 1}
|
||||
</legend>
|
||||
<SupplementaryFields
|
||||
row={row}
|
||||
fields={[
|
||||
[
|
||||
'department',
|
||||
'Departamento (mapa de pessoal)',
|
||||
'text',
|
||||
],
|
||||
[
|
||||
'quantity',
|
||||
'Quantidade de pessoas (inteiro)',
|
||||
'number',
|
||||
],
|
||||
[
|
||||
'monthly_salary',
|
||||
'Remuneração mensal por pessoa (moeda do projecto)',
|
||||
'number',
|
||||
],
|
||||
[
|
||||
'start_month',
|
||||
'Mês inicial no plano (1 = Janeiro do ano inicial)',
|
||||
'number',
|
||||
],
|
||||
['end_month', 'Mês final no plano', 'number'],
|
||||
]}
|
||||
change={(key, value) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
key as keyof TeamNeed,
|
||||
value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label className="text-sm">
|
||||
Competência ou função
|
||||
<input
|
||||
@@ -180,6 +296,17 @@ export function ProjectTeamPlanner({
|
||||
>
|
||||
Adicionar competência ou lacuna
|
||||
</button>
|
||||
<InvestmentReportTables
|
||||
tables={[
|
||||
buildComplementaryTables(
|
||||
{
|
||||
project_team_snapshot: value,
|
||||
currency: projectCurrency,
|
||||
},
|
||||
restoreBusinessPlanSnapshot(financialPlanSnapshot),
|
||||
)[2],
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -194,6 +321,13 @@ export function ProjectMilestonePlanner({
|
||||
const rows = readRows<ProjectMilestone>(value, milestoneKeys);
|
||||
const persist = (next: ProjectMilestone[]) =>
|
||||
onChange(JSON.stringify(next));
|
||||
if (unreadable(value, rows, ['start_date', 'responsible', 'department']))
|
||||
return (
|
||||
<p role="alert">
|
||||
O plano de marcos guardado contém linhas não reconhecidas. O
|
||||
original foi preservado e não será substituído por este editor.
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<section className="space-y-4" aria-label="Marcos de execução">
|
||||
<p className="text-sm text-slate-700">
|
||||
@@ -201,12 +335,35 @@ export function ProjectMilestonePlanner({
|
||||
valores são declarados; não alteram automaticamente o plano
|
||||
financeiro.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Para completar o relatório, indique título, início, término,
|
||||
responsável, departamento e orçamento. O montante realizado é
|
||||
opcional.
|
||||
</p>
|
||||
{rows.map((row, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
|
||||
>
|
||||
<legend className="font-medium">Marco {index + 1}</legend>
|
||||
<SupplementaryFields
|
||||
row={row}
|
||||
fields={[
|
||||
['start_date', 'Data de início', 'date'],
|
||||
['responsible', 'Responsável pelo marco', 'text'],
|
||||
['department', 'Departamento do marco', 'text'],
|
||||
]}
|
||||
change={(key, value) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
key as keyof ProjectMilestone,
|
||||
value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label className="text-sm">
|
||||
Marco ou resultado
|
||||
<input
|
||||
@@ -334,6 +491,14 @@ export function ProjectMilestonePlanner({
|
||||
>
|
||||
Adicionar marco
|
||||
</button>
|
||||
<InvestmentReportTables
|
||||
tables={[
|
||||
buildComplementaryTables(
|
||||
{ project_execution_snapshot: value },
|
||||
null,
|
||||
)[1],
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { BusinessPlanWarnings } from './business-plan-warnings';
|
||||
import {
|
||||
getProjectReadiness,
|
||||
readPlannedRiskResponses,
|
||||
@@ -88,6 +89,26 @@ export function ProjectReadiness({
|
||||
className="space-y-4"
|
||||
aria-labelledby="project-readiness-title"
|
||||
>
|
||||
<BusinessPlanWarnings
|
||||
metrics={{
|
||||
optionalTexts: [
|
||||
{
|
||||
label: 'Concorrência',
|
||||
value:
|
||||
typeof draft.competitor_assumption === 'string'
|
||||
? draft.competitor_assumption
|
||||
: '',
|
||||
},
|
||||
{
|
||||
label: 'Marketing',
|
||||
value:
|
||||
typeof draft.marketing_approach === 'string'
|
||||
? draft.marketing_approach
|
||||
: '',
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<h4
|
||||
id="project-readiness-title"
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { publicReference } from '@/lib/public-presentation';
|
||||
export default function PublicReference({ value }: { value?: string | null }) {
|
||||
const text = publicReference(value);
|
||||
if (!text) return null;
|
||||
if (/^https?:\/\//i.test(text))
|
||||
return (
|
||||
<a
|
||||
className="underline"
|
||||
href={text}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Consultar fonte — {new URL(text).hostname}
|
||||
</a>
|
||||
);
|
||||
return <>{text}</>;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import EvidenceDetails from './evidence-details';
|
||||
import { publicReference, publicSourceHref } from '@/lib/public-presentation';
|
||||
type Source = {
|
||||
title?: string | null;
|
||||
url?: string | null;
|
||||
source_date?: string | null;
|
||||
supports?: string | null;
|
||||
};
|
||||
export default function PublicSourceList({ sources }: { sources?: Source[] }) {
|
||||
const rows = new Map<
|
||||
string,
|
||||
{
|
||||
title: string;
|
||||
url?: string;
|
||||
date?: string | null;
|
||||
supports: string[];
|
||||
}
|
||||
>();
|
||||
for (const source of sources ?? []) {
|
||||
const url = publicSourceHref(source.url),
|
||||
title =
|
||||
publicReference(source.title) ||
|
||||
(url ? new URL(url).hostname : null);
|
||||
if (!title) continue;
|
||||
const key = JSON.stringify([url || title, source.source_date || '']);
|
||||
const row = rows.get(key) ?? {
|
||||
title,
|
||||
url,
|
||||
date: source.source_date,
|
||||
supports: [],
|
||||
};
|
||||
const support = publicReference(source.supports);
|
||||
if (support && !row.supports.includes(support))
|
||||
row.supports.push(support);
|
||||
rows.set(key, row);
|
||||
}
|
||||
if (!rows.size) return null;
|
||||
return (
|
||||
<EvidenceDetails title="Fontes e datas">
|
||||
<ul className="space-y-2">
|
||||
{[...rows.entries()].map(([key, row]) => (
|
||||
<li key={key}>
|
||||
{row.url ? (
|
||||
<a
|
||||
className="underline"
|
||||
href={row.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{row.title}
|
||||
</a>
|
||||
) : (
|
||||
<span>{row.title}</span>
|
||||
)}
|
||||
{row.date && <> · {row.date}</>}
|
||||
{row.supports.map((text) => (
|
||||
<p key={text}>{text}</p>
|
||||
))}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</EvidenceDetails>
|
||||
);
|
||||
}
|
||||
@@ -60,7 +60,7 @@ export default function SectorEntry({
|
||||
/>
|
||||
),
|
||||
)}
|
||||
<nav aria-label="Ações no setor" className="flex flex-wrap gap-3">
|
||||
<nav aria-label="Acções no sector" className="flex flex-wrap gap-3">
|
||||
{data.start_href ? (
|
||||
<Link
|
||||
className="rounded bg-emerald-800 px-4 py-3 text-white"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { publicReference } from '@/lib/public-presentation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { portalRequest } from '@/lib/portal-api';
|
||||
@@ -86,7 +87,7 @@ export function GeographicCoverage({
|
||||
</p>
|
||||
<p>
|
||||
Fonte de origem da localização:{' '}
|
||||
{coverage.origin_source_reference ||
|
||||
{publicReference(coverage.origin_source_reference) ||
|
||||
'referência não divulgada ou não indicada'}
|
||||
. Data da fonte:{' '}
|
||||
{publicationDate(coverage.origin_source_date) ?? 'desconhecida'}
|
||||
@@ -149,7 +150,7 @@ export function BusinessLocationSource({
|
||||
return (
|
||||
<p className="text-sm">
|
||||
Fonte de origem da localização:{' '}
|
||||
{record.location_source_reference ||
|
||||
{publicReference(record.location_source_reference) ||
|
||||
'referência não divulgada ou não indicada'}
|
||||
. Data da fonte:{' '}
|
||||
{publicationDate(record.location_source_date) ?? 'desconhecida'}.
|
||||
@@ -445,9 +446,10 @@ export default function SimilarBusinesses({
|
||||
{selected && (
|
||||
<p className="text-sm">
|
||||
Fonte da classificação na ficha de origem:{' '}
|
||||
{selected.source_reference || 'não indicada'}. A relação
|
||||
documental não comprova implantação, propriedade ou
|
||||
capacidade.
|
||||
{publicReference(selected.source_reference) ||
|
||||
'não indicada'}
|
||||
. A relação documental não comprova implantação, propriedade
|
||||
ou capacidade.
|
||||
</p>
|
||||
)}
|
||||
<Link href={effectiveCatalogueUrl} className="underline">
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
import {
|
||||
calculateAnnualReferencePlan,
|
||||
newAnnualReferencePlan,
|
||||
restoreAnnualExampleSnapshot,
|
||||
serializeAnnualExampleSnapshot,
|
||||
type AnnualReferencePlan,
|
||||
} from '@/lib/business-plan-guidance';
|
||||
import { businessPlanNumberError } from '@/lib/business-financial-plan';
|
||||
import { BusinessPlanWarnings } from './business-plan-warnings';
|
||||
|
||||
const annualLabels = {
|
||||
sales: 'Vendas previstas',
|
||||
directCosts: 'Custo directo das vendas',
|
||||
payroll: 'Folha de pagamento',
|
||||
payrollCharges: 'Encargos da folha de pagamento',
|
||||
otherOperatingExpenses: 'Outras despesas operacionais',
|
||||
interest: 'Juros',
|
||||
taxes: 'Impostos estimados do exemplo',
|
||||
cashReceived: 'Caixa recebida',
|
||||
cashSpent: 'Caixa gasta',
|
||||
vatReceived: 'IVA incluído nos recebimentos (montante do exemplo)',
|
||||
vatPaid: 'IVA incluído nos pagamentos (montante do exemplo)',
|
||||
} as const;
|
||||
const openingLabels = {
|
||||
openingCash: 'Caixa necessária',
|
||||
otherCurrentAssets: 'Outros activos correntes',
|
||||
longTermAssets: 'Activos de longo prazo',
|
||||
ownerCapital: 'Capital do proprietário disponível',
|
||||
investorCapital: 'Capital do investidor disponível',
|
||||
loans: 'Empréstimos disponíveis',
|
||||
additionalMoney: 'Dinheiro adicional angariado',
|
||||
} as const;
|
||||
function ExampleNumber({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
const error = businessPlanNumberError(value);
|
||||
return (
|
||||
<label className="grid gap-1 text-sm">
|
||||
{label}
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
className="min-w-0 rounded border p-2"
|
||||
value={value}
|
||||
aria-invalid={!!error}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
/>
|
||||
{error && (
|
||||
<span role="alert" className="text-red-800">
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
export function SimulationAnnualExample({
|
||||
currency,
|
||||
snapshot,
|
||||
onSnapshotChange,
|
||||
}: {
|
||||
currency: string;
|
||||
snapshot?: string;
|
||||
onSnapshotChange?: (snapshot: string) => void;
|
||||
}) {
|
||||
const recovered = restoreAnnualExampleSnapshot(snapshot);
|
||||
if (snapshot && !recovered)
|
||||
return (
|
||||
<p role="alert">
|
||||
Não foi possível recuperar o cenário de exemplo. O conteúdo
|
||||
guardado foi preservado; não será substituído.
|
||||
</p>
|
||||
);
|
||||
const plan = recovered ?? newAnnualReferencePlan();
|
||||
const setPlan = (
|
||||
update: (previous: AnnualReferencePlan) => AnnualReferencePlan,
|
||||
) => {
|
||||
onSnapshotChange?.(serializeAnnualExampleSnapshot(update(plan)));
|
||||
};
|
||||
let result: ReturnType<typeof calculateAnnualReferencePlan> | undefined;
|
||||
let error = '';
|
||||
try {
|
||||
result = calculateAnnualReferencePlan(plan);
|
||||
} catch (cause) {
|
||||
error =
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Reveja os campos do exemplo.';
|
||||
}
|
||||
const amount = (value: string | number | null) =>
|
||||
value === null
|
||||
? 'Por determinar'
|
||||
: Number(value).toLocaleString('pt-MZ', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
return (
|
||||
<section
|
||||
aria-label="Cenário anual de exemplo"
|
||||
className="my-4 space-y-4 rounded border border-sky-400 bg-sky-50 p-4"
|
||||
>
|
||||
<h4 className="text-lg font-semibold">
|
||||
Cenário anual de exemplo — editável
|
||||
</h4>
|
||||
<p className="text-sm">
|
||||
Dados sintéticos de demonstração, com totais do plano de
|
||||
referência e projecções ilustrativas. Moeda de apresentação:{' '}
|
||||
{currency || 'por seleccionar no plano'}. As edições deste
|
||||
ensaio acompanham o rascunho do simulador numa secção separada.
|
||||
Sem sessão, retome no mesmo navegador; com sessão autenticada,
|
||||
utilize o rascunho da sua conta para retomar noutro dispositivo.
|
||||
Estes valores não substituem os dados reais do investimento.
|
||||
</p>
|
||||
<p className="rounded border border-amber-400 p-3 text-sm">
|
||||
Linhas mensais por reconciliar. Conservam-se os totais anuais
|
||||
definidos pelo proprietário; não se distribuem valores pelos
|
||||
meses da fonte nem se completam as suas linhas em falta. A
|
||||
projecção mensal ilustrativa abaixo é um cálculo separado. Os
|
||||
impostos são montantes do exemplo, sem activar taxas fiscais.
|
||||
</p>
|
||||
<details open>
|
||||
<summary className="font-semibold">
|
||||
Despesas e activos iniciais
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{plan.startupExpenses.map((row, index) => (
|
||||
<ExampleNumber
|
||||
key={row.label}
|
||||
label={row.label}
|
||||
value={row.amount}
|
||||
onChange={(value) =>
|
||||
setPlan((previous) => ({
|
||||
...previous,
|
||||
startupExpenses:
|
||||
previous.startupExpenses.map(
|
||||
(entry, i) =>
|
||||
i === index
|
||||
? {
|
||||
...entry,
|
||||
amount: value,
|
||||
}
|
||||
: entry,
|
||||
),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{Object.entries(openingLabels).map(([key, label]) => (
|
||||
<ExampleNumber
|
||||
key={key}
|
||||
label={label}
|
||||
value={plan[key as keyof typeof openingLabels]}
|
||||
onChange={(value) =>
|
||||
setPlan((previous) => ({
|
||||
...previous,
|
||||
[key]: value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
{plan.years.map((year, index) => (
|
||||
<details key={year.year}>
|
||||
<summary className="font-semibold">
|
||||
Pressupostos anuais — {year.year}
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{Object.entries(annualLabels).map(([key, label]) => (
|
||||
<ExampleNumber
|
||||
key={key}
|
||||
label={label}
|
||||
value={year[key as keyof typeof annualLabels]}
|
||||
onChange={(value) =>
|
||||
setPlan((previous) => ({
|
||||
...previous,
|
||||
years: previous.years.map((entry, i) =>
|
||||
i === index
|
||||
? { ...entry, [key]: value }
|
||||
: entry,
|
||||
),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded border border-red-400 bg-red-50 p-3 text-red-900"
|
||||
>
|
||||
{error} Os valores introduzidos permanecem nos campos.
|
||||
</p>
|
||||
)}
|
||||
{result && (
|
||||
<>
|
||||
<dl className="grid gap-3 sm:grid-cols-2">
|
||||
{[
|
||||
[
|
||||
'Despesas totais de arranque',
|
||||
result.startupExpenses,
|
||||
],
|
||||
['Total de activos iniciais', result.assets],
|
||||
[
|
||||
'Financiamento total requerido',
|
||||
result.requiredFunding,
|
||||
],
|
||||
[
|
||||
'Financiamento disponível',
|
||||
result.availableFunding,
|
||||
],
|
||||
].map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd className="font-semibold">
|
||||
{amount(value)} {currency}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<caption className="py-2 text-left font-semibold">
|
||||
Resultados anuais do exemplo{' '}
|
||||
{currency && `(${currency})`}
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Resultado</th>
|
||||
{result.years.map((year) => (
|
||||
<th key={year.year}>{year.year}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(
|
||||
[
|
||||
'sales',
|
||||
'directCosts',
|
||||
'grossMargin',
|
||||
'grossMarginPercent',
|
||||
'operatingExpenses',
|
||||
'operatingProfit',
|
||||
'netProfit',
|
||||
'monthlyFixedCosts',
|
||||
'monthlyBreakEven',
|
||||
'cashFlow',
|
||||
'closingCash',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<tr key={key}>
|
||||
<th className="py-1 font-medium">
|
||||
{
|
||||
{
|
||||
sales: 'Vendas',
|
||||
directCosts:
|
||||
'Custo directo das vendas',
|
||||
grossMargin: 'Margem bruta',
|
||||
grossMarginPercent:
|
||||
'Margem bruta (%)',
|
||||
operatingExpenses:
|
||||
'Despesas operacionais',
|
||||
operatingProfit:
|
||||
'Lucro antes de juros e impostos',
|
||||
netProfit: 'Lucro líquido',
|
||||
monthlyFixedCosts:
|
||||
'Custo fixo mensal estimado',
|
||||
monthlyBreakEven:
|
||||
'Ponto de equilíbrio mensal',
|
||||
cashFlow:
|
||||
'Fluxo líquido de caixa',
|
||||
closingCash:
|
||||
'Saldo de caixa',
|
||||
}[key]
|
||||
}
|
||||
</th>
|
||||
{result.years.map((year) => (
|
||||
<td key={year.year}>
|
||||
{amount(year[key])}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{result.years.map((year, index) => (
|
||||
<div key={year.year}>
|
||||
<p>
|
||||
Balanço projectado: activos{' '}
|
||||
{amount(year.closingAssets)}, passivos{' '}
|
||||
{amount(year.closingLiabilities)} e capital{' '}
|
||||
{amount(year.closingCapital)}. Diferença:{' '}
|
||||
{amount(year.balanceDifference)} {currency}.
|
||||
Valores a receber: {amount(year.receivables)};
|
||||
obrigações operacionais:{' '}
|
||||
{amount(year.operatingLiabilities)}.
|
||||
</p>
|
||||
<details>
|
||||
<summary>
|
||||
Distribuição mensal ilustrativa —{' '}
|
||||
{year.year}
|
||||
</summary>
|
||||
<p>
|
||||
Esta simulação distribui os totais anuais
|
||||
pelo perfil sazonal agregado do exemplo.
|
||||
Despesas fixas são repartidas por igual;
|
||||
recebimentos e pagamentos sem IVA seguem
|
||||
vendas e despesas, respectivamente. Os
|
||||
centavos remanescentes são distribuídos
|
||||
pelas maiores fracções. Não representa
|
||||
recuperação dos meses da referência.
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<caption>
|
||||
Projecção mensal ({currency})
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Mês',
|
||||
'Vendas',
|
||||
'Custos directos',
|
||||
'Lucro líquido',
|
||||
'Recebimentos',
|
||||
'Pagamentos',
|
||||
'Caixa',
|
||||
'Diferença do balanço',
|
||||
].map((label) => (
|
||||
<th key={label}>{label}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{year.illustrativeMonths.map(
|
||||
(month) => (
|
||||
<tr key={month.month}>
|
||||
<th>{month.month}</th>
|
||||
{(
|
||||
[
|
||||
'sales',
|
||||
'directCosts',
|
||||
'netProfit',
|
||||
'cashReceived',
|
||||
'cashSpent',
|
||||
'closingCash',
|
||||
'balanceDifference',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<td key={key}>
|
||||
{amount(
|
||||
month[key],
|
||||
)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
),
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
<h5 className="font-semibold">
|
||||
Avisos — {year.year}
|
||||
</h5>
|
||||
<BusinessPlanWarnings
|
||||
metrics={{
|
||||
currency,
|
||||
fundingGap:
|
||||
index === 0
|
||||
? Number(result.fundingGap)
|
||||
: undefined,
|
||||
netProfit: Number(year.netProfit),
|
||||
sales: Number(year.sales),
|
||||
directCosts: Number(year.directCosts),
|
||||
monthlyBreakEven: year.monthlyBreakEven,
|
||||
monthlyExpenses:
|
||||
Number(year.operatingExpenses) / 12,
|
||||
cash: Number(year.closingCash),
|
||||
growthPercent:
|
||||
year.growthPercent ?? undefined,
|
||||
ownAndInvestorCapital:
|
||||
index === 0
|
||||
? Number(plan.ownerCapital) +
|
||||
Number(plan.investorCapital)
|
||||
: undefined,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<p className="text-sm">
|
||||
O balanço pressupõe mobilizar{' '}
|
||||
{amount(result.capitalToMobilise)} {currency} de capital
|
||||
ainda em falta. Não é financiamento confirmado. Os
|
||||
saldos iniciais a receber e de obrigações operacionais
|
||||
são zero neste cenário; activos e empréstimos mantêm-se
|
||||
constantes. As obrigações incluem custos, despesas,
|
||||
juros e impostos reconhecidos e ainda não pagos. Os
|
||||
montantes de IVA são dados do exemplo, sem inferência de
|
||||
taxas fiscais.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Margem bruta = vendas − custo directo. Lucro líquido =
|
||||
margem bruta − despesas operacionais − juros − impostos.
|
||||
Ponto de equilíbrio = (despesas operacionais ÷ 12) ÷
|
||||
(margem bruta ÷ vendas), sem arredondar os valores
|
||||
intermédios. Caixa final = caixa anterior + recebimentos
|
||||
− pagamentos.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
import { WarningLimitsEditor } from './warning-limits-editor';
|
||||
import { SupplierAdvancesEditor } from '@/components/supplier-advances';
|
||||
import { PeriodInvestmentsEditor } from '@/components/period-investments';
|
||||
import CurrencySelect from '@/components/currency-select';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import {
|
||||
compareBusinessScenarios,
|
||||
businessPlanNumberError,
|
||||
exportBusinessPlanCsv,
|
||||
forecastBusinessPlan,
|
||||
financialPlanImportMessage,
|
||||
MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH,
|
||||
restoreBusinessPlanSnapshot,
|
||||
serializeBusinessPlanSnapshot,
|
||||
@@ -17,6 +22,19 @@ import {
|
||||
simulationCurrencyOptions,
|
||||
} from '@/lib/simulation-contract';
|
||||
import { buildFinancialFiscalBridge } from '@/lib/financial-fiscal-bridge';
|
||||
import { BusinessPlanWarnings } from '@/components/business-plan-warnings';
|
||||
import { SimulationAnnualExample } from '@/components/simulation-annual-example';
|
||||
import { IntegralFinancialPlan } from '@/components/integral-financial-plan';
|
||||
import { MarketAnalysisPlan } from '@/components/market-analysis-plan';
|
||||
import { FinancialRatiosPlan } from '@/components/financial-ratios-plan';
|
||||
import { PlanEconomicClassification } from '@/components/plan-economic-classification';
|
||||
import { FinancialPlanDetails } from '@/components/financial-plan-details';
|
||||
import { FinancialDayTerms } from '@/components/financial-day-terms';
|
||||
import { StartupAssetRequirements } from '@/components/startup-asset-requirements';
|
||||
import {
|
||||
forecastErrorShownInReport,
|
||||
startupErrorMessage,
|
||||
} from '@/lib/financial-issue-presentation';
|
||||
|
||||
const emptyPlan: BusinessFinancialPlanInput = {
|
||||
currency: '',
|
||||
@@ -74,23 +92,48 @@ function MoneyInput({
|
||||
value,
|
||||
onChange,
|
||||
allowNegative = false,
|
||||
step = '0.01',
|
||||
optional = false,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
allowNegative?: boolean;
|
||||
step?: string;
|
||||
optional?: boolean;
|
||||
}) {
|
||||
const errorId = useId();
|
||||
const [touched, setTouched] = useState(false);
|
||||
const error =
|
||||
touched && (!optional || value.trim() !== '')
|
||||
? businessPlanNumberError(value, { allowNegative })
|
||||
: '';
|
||||
return (
|
||||
<label className="block text-sm font-medium">
|
||||
{label}
|
||||
<input
|
||||
type="number"
|
||||
min={allowNegative ? undefined : '0'}
|
||||
step="0.01"
|
||||
step={step}
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
onChange={(event) => {
|
||||
setTouched(true);
|
||||
onChange(event.target.value);
|
||||
}}
|
||||
onBlur={() => setTouched(true)}
|
||||
aria-invalid={!!error}
|
||||
aria-describedby={error ? errorId : undefined}
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
/>
|
||||
{error && (
|
||||
<span
|
||||
id={errorId}
|
||||
role="alert"
|
||||
className="mt-1 block text-sm text-red-800"
|
||||
>
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -116,6 +159,7 @@ export function SimulationBusinessPlan({
|
||||
);
|
||||
const [workingPlan, setWorkingPlan] =
|
||||
useState<BusinessFinancialPlanInput | null>(null);
|
||||
const [showExample, setShowExample] = useState(false);
|
||||
useEffect(() => setWorkingPlan(null), [snapshot]);
|
||||
if (hasOversizedStoredSnapshot) {
|
||||
return (
|
||||
@@ -157,10 +201,7 @@ export function SimulationBusinessPlan({
|
||||
try {
|
||||
const source = await file.text();
|
||||
const imported = restoreBusinessPlanSnapshot(source);
|
||||
if (!imported)
|
||||
throw new Error(
|
||||
'O ficheiro não contém um plano JSON reconhecido pelo InvestMoz.',
|
||||
);
|
||||
if (!imported) throw new Error(financialPlanImportMessage(source));
|
||||
savePlan(imported);
|
||||
setSnapshotError('');
|
||||
} catch (cause) {
|
||||
@@ -252,7 +293,7 @@ export function SimulationBusinessPlan({
|
||||
unitVariableCostByPeriod: 'unitVariableCost',
|
||||
};
|
||||
const plan = workingPlan ??
|
||||
restoreBusinessPlanSnapshot(snapshot) ?? {
|
||||
restoreBusinessPlanSnapshot(snapshot, { editable: true }) ?? {
|
||||
...emptyPlan,
|
||||
currency: projectCurrency,
|
||||
};
|
||||
@@ -857,7 +898,11 @@ export function SimulationBusinessPlan({
|
||||
const fiscalBridge = result ? buildFinancialFiscalBridge(result) : null;
|
||||
|
||||
return (
|
||||
<details className="rounded-lg border border-slate-300 p-4" open>
|
||||
<details
|
||||
id="business-financial-plan"
|
||||
className="rounded-lg border border-slate-300 p-4"
|
||||
open
|
||||
>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Plano financeiro empresarial (pressupostos editáveis)
|
||||
</summary>
|
||||
@@ -887,6 +932,40 @@ export function SimulationBusinessPlan({
|
||||
separados. Não calcula impostos, não converte moedas e não
|
||||
substitui um plano contabilístico validado.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2 text-sm"
|
||||
onClick={() => setShowExample((previous) => !previous)}
|
||||
>
|
||||
{showExample
|
||||
? 'Fechar cenário de exemplo'
|
||||
: 'Carregar cenário anual de exemplo'}
|
||||
</button>
|
||||
{showExample && (
|
||||
<SimulationAnnualExample
|
||||
currency={currency}
|
||||
snapshot={plan.annualExampleSnapshot}
|
||||
onSnapshotChange={(annualExampleSnapshot) =>
|
||||
savePlan({ ...plan, annualExampleSnapshot })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<PlanEconomicClassification plan={plan} onChange={savePlan} />
|
||||
<FinancialPlanDetails plan={plan} onChange={savePlan} />
|
||||
<FinancialDayTerms plan={plan} onChange={savePlan} />
|
||||
<SupplierAdvancesEditor plan={plan} onChange={savePlan} />
|
||||
<PeriodInvestmentsEditor plan={plan} onChange={savePlan} />
|
||||
<WarningLimitsEditor plan={plan} onChange={savePlan} />
|
||||
<StartupAssetRequirements
|
||||
plan={plan}
|
||||
onChange={savePlan}
|
||||
showError={
|
||||
!forecastErrorShownInReport(plan, startupErrorMessage(plan))
|
||||
}
|
||||
/>
|
||||
<IntegralFinancialPlan plan={plan} onChange={savePlan} />
|
||||
<MarketAnalysisPlan plan={plan} onChange={savePlan} />
|
||||
<FinancialRatiosPlan plan={plan} onChange={savePlan} />
|
||||
<div className="my-3 flex flex-wrap items-end gap-3 rounded border p-3">
|
||||
<label className="grid gap-1 text-sm">
|
||||
Importar plano financeiro InvestMoz (.json, até 60 KB)
|
||||
@@ -930,6 +1009,17 @@ export function SimulationBusinessPlan({
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<MoneyInput
|
||||
optional
|
||||
label="Crescimento anual pretendido (%)"
|
||||
value={plan.annualGrowthPercent ?? ''}
|
||||
onChange={(value) => update('annualGrowthPercent', value)}
|
||||
/>
|
||||
<p className="text-sm">
|
||||
A meta de crescimento pode exceder 100%, com aviso. É uma
|
||||
hipótese declarada; as agendas de vendas introduzidas mantêm
|
||||
os seus valores.
|
||||
</p>
|
||||
|
||||
<p className="text-sm text-slate-700">
|
||||
O plano financeiro aceita moedas ISO suportadas com duas
|
||||
@@ -1012,12 +1102,14 @@ export function SimulationBusinessPlan({
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<MoneyInput
|
||||
label="Saldo de caixa inicial"
|
||||
value={plan.openingCash}
|
||||
allowNegative
|
||||
onChange={(value) => update('openingCash', value)}
|
||||
/>
|
||||
{!plan.startupAssetRequirements && (
|
||||
<MoneyInput
|
||||
label="Saldo de caixa inicial"
|
||||
value={plan.openingCash}
|
||||
allowNegative
|
||||
onChange={(value) => update('openingCash', value)}
|
||||
/>
|
||||
)}
|
||||
<label className="block text-sm font-medium">
|
||||
Horizonte (meses)
|
||||
<input
|
||||
@@ -1092,25 +1184,18 @@ export function SimulationBusinessPlan({
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
{product.monthlyUnitsByPeriod
|
||||
? 'Unidades mensais base'
|
||||
: 'Unidades por mes'}
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.001"
|
||||
value={product.monthlyUnits}
|
||||
onChange={(event) =>
|
||||
updateProduct(
|
||||
index,
|
||||
'monthlyUnits',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
/>
|
||||
</label>
|
||||
<MoneyInput
|
||||
label={
|
||||
product.monthlyUnitsByPeriod
|
||||
? 'Unidades mensais base'
|
||||
: 'Unidades por mes'
|
||||
}
|
||||
step="0.001"
|
||||
value={product.monthlyUnits}
|
||||
onChange={(value) =>
|
||||
updateProduct(index, 'monthlyUnits', value)
|
||||
}
|
||||
/>
|
||||
<MoneyInput
|
||||
label="Preço por unidade"
|
||||
value={product.unitPrice}
|
||||
@@ -1838,13 +1923,22 @@ export function SimulationBusinessPlan({
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<MoneyInput
|
||||
label="Despesas operacionais reconhecidas"
|
||||
value={plan.monthlyOperatingExpenses}
|
||||
onChange={(value) =>
|
||||
update('monthlyOperatingExpenses', value)
|
||||
}
|
||||
/>
|
||||
{!plan.operatingExpenseLines ? (
|
||||
<MoneyInput
|
||||
label="Despesas operacionais reconhecidas"
|
||||
value={plan.monthlyOperatingExpenses}
|
||||
onChange={(value) =>
|
||||
update('monthlyOperatingExpenses', value)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<p>
|
||||
Despesas operacionais: calculadas a partir das
|
||||
linhas discriminadas acima. Os pagamentos conservam
|
||||
a sua agenda própria; o total e a agenda agregados
|
||||
anteriores ficam preservados.
|
||||
</p>
|
||||
)}
|
||||
<MoneyInput
|
||||
label="Pagamento de despesas operacionais"
|
||||
value={plan.monthlyOperatingPayments}
|
||||
@@ -1875,6 +1969,11 @@ export function SimulationBusinessPlan({
|
||||
</p>
|
||||
)}
|
||||
{moneyScheduleFields
|
||||
.filter(
|
||||
({ key }) =>
|
||||
!plan.operatingExpenseLines ||
|
||||
key !== 'monthlyOperatingExpensesByPeriod',
|
||||
)
|
||||
.filter(
|
||||
({ key }) =>
|
||||
!plan.useSupplierPaymentTerms ||
|
||||
@@ -2448,11 +2547,13 @@ export function SimulationBusinessPlan({
|
||||
)}
|
||||
</details>
|
||||
|
||||
{error && (
|
||||
<p role="alert" className="my-3 text-sm text-red-800">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{error &&
|
||||
error !== startupErrorMessage(plan) &&
|
||||
!forecastErrorShownInReport(plan, error) && (
|
||||
<p role="alert" className="my-3 text-sm text-red-800">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{result && isSimulationCurrency(currency) && (
|
||||
<div className="mt-4 space-y-3">
|
||||
<h4 className="font-semibold">Resumo ({currency})</h4>
|
||||
@@ -2478,24 +2579,34 @@ export function SimulationBusinessPlan({
|
||||
>
|
||||
Exportar plano em CSV
|
||||
</button>
|
||||
<p
|
||||
role={
|
||||
result.fundingStatus === 'balanced'
|
||||
? 'status'
|
||||
: 'alert'
|
||||
}
|
||||
className={
|
||||
result.fundingStatus === 'balanced'
|
||||
? 'rounded bg-emerald-50 p-3 text-sm'
|
||||
: 'rounded bg-amber-50 p-3 text-sm'
|
||||
}
|
||||
>
|
||||
{result.fundingStatus === 'balanced'
|
||||
? 'As fontes de financiamento reconciliam com os usos iniciais.'
|
||||
: result.fundingStatus === 'shortfall'
|
||||
? `Falta financiar ${result.fundingGap} ${currency} dos usos iniciais.`
|
||||
: `As fontes excedem os usos iniciais em ${result.fundingGap.replace('-', '')} ${currency}.`}
|
||||
</p>
|
||||
{!plan.reportAssumptions &&
|
||||
plan.reportSource !== 'annual_example' && (
|
||||
<BusinessPlanWarnings
|
||||
limits={plan.warningLimits}
|
||||
metrics={{
|
||||
currency,
|
||||
fundingGap: Number(result.fundingGap),
|
||||
growthPercent:
|
||||
plan.annualGrowthPercent?.trim()
|
||||
? Number(plan.annualGrowthPercent)
|
||||
: undefined,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{result.fundingStatus !== 'shortfall' && (
|
||||
<p
|
||||
role="status"
|
||||
className={
|
||||
result.fundingStatus === 'balanced'
|
||||
? 'rounded bg-emerald-50 p-3 text-sm'
|
||||
: 'rounded bg-amber-50 p-3 text-sm'
|
||||
}
|
||||
>
|
||||
{result.fundingStatus === 'balanced'
|
||||
? 'As fontes de financiamento reconciliam com os usos iniciais.'
|
||||
: `As fontes excedem os usos iniciais em ${result.fundingGap.replace('-', '')} ${currency}.`}
|
||||
</p>
|
||||
)}
|
||||
<dl className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{[
|
||||
['Fundo de maneio líquido', result.workingCapital],
|
||||
@@ -2966,9 +3077,10 @@ export function SimulationBusinessPlan({
|
||||
<output className="block rounded bg-amber-50 p-3 text-sm">
|
||||
Compras a fornecedores ainda por pagar no fim do
|
||||
horizonte: {result.supplierPaymentsOutstandingAtEnd}{' '}
|
||||
{currency}. Os pagamentos sao calculados pelas
|
||||
encomendas e prazos declarados; nao representam
|
||||
credito confirmado pelo fornecedor.
|
||||
{currency}.{' '}
|
||||
{plan.supplierAdvances?.purchases
|
||||
? 'Obrigação bruta das compras identificadas, após aplicações e liquidações. Os adiantamentos activos e o líquido por liquidar estão discriminados por operação acima.'
|
||||
: 'Os pagamentos são calculados pelas encomendas e prazos declarados; não representam crédito confirmado pelo fornecedor.'}
|
||||
</output>
|
||||
)}
|
||||
{result.conversion && (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusCorrectionId } from '@/lib/field-corrections';
|
||||
import FiscalOperationPicker from './fiscal-operation-picker';
|
||||
import { SimulationIrpcAnnual } from '@/components/simulation-irpc-annual';
|
||||
import DemographicContext from '@/components/demographic-context';
|
||||
@@ -273,6 +274,13 @@ const fieldGuidance: Record<
|
||||
clarify:
|
||||
'Pode começar por descrever o que pretende produzir ou prestar.',
|
||||
},
|
||||
project_summary: {
|
||||
why: 'Reúne os objectivos, a missão e as chaves para o sucesso que pretende comunicar aos parceiros.',
|
||||
example:
|
||||
'Exemplo apenas de organização do texto: Objectivos. Missão. Chaves para o sucesso.',
|
||||
clarify:
|
||||
'Descreva as suas escolhas em texto livre. Não precisa de adoptar a estrutura ou os valores do exemplo TEMPO.',
|
||||
},
|
||||
project_problem: {
|
||||
why: 'Uma necessidade concreta ajuda a explicar a razão do projecto.',
|
||||
example:
|
||||
@@ -3298,6 +3306,21 @@ export function SimulationForm() {
|
||||
>
|
||||
{current.title}
|
||||
</h3>
|
||||
{errors.business_plan_snapshot && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded border border-red-400 bg-red-50 p-3 text-red-900"
|
||||
>
|
||||
<a
|
||||
className="underline"
|
||||
href="#business-financial-plan"
|
||||
>
|
||||
{errors.business_plan_snapshot}
|
||||
</a>{' '}
|
||||
Os dados permanecem no rascunho; corrija o plano
|
||||
financeiro para continuar.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
data-form-help-open
|
||||
@@ -3458,6 +3481,10 @@ export function SimulationForm() {
|
||||
{current.id === 'team' && (
|
||||
<>
|
||||
<ProjectTeamPlanner
|
||||
projectCurrency={String(draft.currency ?? '')}
|
||||
financialPlanSnapshot={String(
|
||||
draft.business_plan_snapshot ?? '',
|
||||
)}
|
||||
value={String(draft.project_team_snapshot ?? '')}
|
||||
onChange={(value) =>
|
||||
change('project_team_snapshot', value)
|
||||
@@ -5105,13 +5132,9 @@ export function SimulationForm() {
|
||||
),
|
||||
),
|
||||
);
|
||||
window.requestAnimationFrame(
|
||||
() =>
|
||||
document
|
||||
.getElementById(
|
||||
`field-${item.key}`,
|
||||
)
|
||||
?.focus(),
|
||||
setOpenedTool(null);
|
||||
focusCorrectionId(
|
||||
`field-${item.key}`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -5206,7 +5229,7 @@ export function SimulationForm() {
|
||||
{draft.purpose === 'simulate_only' && (
|
||||
<div
|
||||
className="space-y-2 rounded border p-3"
|
||||
aria-label="Ações do simulador"
|
||||
aria-label="Acções do simulador"
|
||||
>
|
||||
<p>
|
||||
Abrir cálculo apresenta as ferramentas financeiras
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
|
||||
import {
|
||||
calculateStartupAssetRequirements,
|
||||
startupAmount,
|
||||
} from '@/lib/startup-asset-requirements';
|
||||
import { newReportAssumptions } from '@/lib/integral-financial-report';
|
||||
|
||||
export function StartupAssetRequirements({
|
||||
plan,
|
||||
onChange,
|
||||
showError = true,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (plan: BusinessFinancialPlanInput) => void;
|
||||
showError?: boolean;
|
||||
}) {
|
||||
const a =
|
||||
plan.reportAssumptions ?? newReportAssumptions(plan.periods ?? 12);
|
||||
const target = plan.startupAssetRequirements;
|
||||
let budget:
|
||||
| ReturnType<typeof calculateStartupAssetRequirements>
|
||||
| undefined,
|
||||
error = '';
|
||||
if (target)
|
||||
try {
|
||||
budget = calculateStartupAssetRequirements(plan);
|
||||
} catch (cause) {
|
||||
error =
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Confira os dados de arranque.';
|
||||
}
|
||||
const field = (label: string, value: string, save: (s: string) => void) => (
|
||||
<label className="grid gap-1 text-sm">
|
||||
{label}
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
className="min-w-0 rounded border p-2"
|
||||
value={value}
|
||||
onChange={(e) => save(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
return (
|
||||
<section
|
||||
className="my-3 space-y-3 rounded border p-3"
|
||||
aria-label="Caixa e activos necessários ao arranque"
|
||||
>
|
||||
{!target ? (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
...plan,
|
||||
startupAssetRequirements: {
|
||||
cashRequired: '',
|
||||
otherCurrentAssetsRequired: '',
|
||||
longTermAssetsRequired: '',
|
||||
priorAssetInvestment: plan.assetInvestment,
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
Distinguir necessidades de arranque dos recursos disponíveis
|
||||
</button>
|
||||
) : target.priorAssetInvestment !== undefined ? (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
...plan,
|
||||
assetInvestment: target.priorAssetInvestment!,
|
||||
startupAssetRequirements: undefined,
|
||||
})
|
||||
}
|
||||
>
|
||||
Retirar necessidades e repor investimento anterior (
|
||||
{target.priorAssetInvestment || 'por preencher'}{' '}
|
||||
{plan.currency})
|
||||
</button>
|
||||
) : null}
|
||||
{target && (
|
||||
<>
|
||||
<p>
|
||||
A caixa requerida é a reserva pretendida depois das
|
||||
despesas e aquisições iniciais. A caixa disponível é o
|
||||
saldo declarado antes de novo financiamento. Fontes
|
||||
planeadas não são recebimentos realizados. Os activos
|
||||
disponíveis são os que já existem, na mesma base de
|
||||
valorização declarada.
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{field(
|
||||
'Caixa requerida após o arranque',
|
||||
target.cashRequired,
|
||||
(value) =>
|
||||
onChange({
|
||||
...plan,
|
||||
startupAssetRequirements: {
|
||||
...target,
|
||||
cashRequired: value,
|
||||
},
|
||||
}),
|
||||
)}
|
||||
{field(
|
||||
'Caixa disponível antes de novo financiamento',
|
||||
plan.openingCash,
|
||||
(value) =>
|
||||
onChange({ ...plan, openingCash: value }),
|
||||
)}
|
||||
{field(
|
||||
'Outros activos correntes requeridos',
|
||||
target.otherCurrentAssetsRequired,
|
||||
(value) =>
|
||||
onChange({
|
||||
...plan,
|
||||
startupAssetRequirements: {
|
||||
...target,
|
||||
otherCurrentAssetsRequired: value,
|
||||
},
|
||||
}),
|
||||
)}
|
||||
{field(
|
||||
'Outros activos correntes disponíveis',
|
||||
a.openingOtherAssets,
|
||||
(value) =>
|
||||
onChange({
|
||||
...plan,
|
||||
reportAssumptions: {
|
||||
...a,
|
||||
openingOtherAssets: value,
|
||||
},
|
||||
}),
|
||||
)}
|
||||
{field(
|
||||
'Activos de longo prazo requeridos',
|
||||
target.longTermAssetsRequired,
|
||||
(value) =>
|
||||
onChange({
|
||||
...plan,
|
||||
startupAssetRequirements: {
|
||||
...target,
|
||||
longTermAssetsRequired: value,
|
||||
},
|
||||
}),
|
||||
)}
|
||||
{field(
|
||||
'Activos de longo prazo disponíveis',
|
||||
a.openingFixedAssets,
|
||||
(value) =>
|
||||
onChange({
|
||||
...plan,
|
||||
reportAssumptions: {
|
||||
...a,
|
||||
openingFixedAssets: value,
|
||||
},
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
<p>
|
||||
Existências e recebíveis iniciais já planeados conservam
|
||||
os campos próprios e integram os activos correntes, sem
|
||||
serem contados duas vezes. As necessidades são mínimos;
|
||||
não se presumem vendas de activos excedentários. A
|
||||
depreciação mantém a base e a vida útil declaradas.
|
||||
</p>
|
||||
{showError && error && <p role="alert">{error}</p>}
|
||||
{budget && (
|
||||
<>
|
||||
<p>
|
||||
Total de activos requeridos:{' '}
|
||||
{startupAmount(budget.totalRequiredAssets)}{' '}
|
||||
{plan.currency}. Requisitos brutos, incluindo
|
||||
despesas de arranque:{' '}
|
||||
{startupAmount(budget.grossRequirements)}{' '}
|
||||
{plan.currency}. Aquisições adicionais
|
||||
calculadas:{' '}
|
||||
{startupAmount(budget.assetInvestment)}{' '}
|
||||
{plan.currency}.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
...plan,
|
||||
assetInvestment: startupAmount(
|
||||
budget!.assetInvestment,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Adoptar as aquisições calculadas no cenário
|
||||
</button>
|
||||
<p>
|
||||
A adopção altera apenas o investimento em
|
||||
activos, com repartição entre correntes e longo
|
||||
prazo. Não cria financiamento nem substitui a
|
||||
caixa disponível.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import PublicReference from './public-reference';
|
||||
import { publicReference, uniquePresentation } from '@/lib/public-presentation';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import DemographicContext from './demographic-context';
|
||||
import TerritorialSources, {
|
||||
@@ -98,38 +100,97 @@ export function LocationList({
|
||||
</dl>
|
||||
<DemographicContext
|
||||
key={location.id}
|
||||
territoryId={location.path
|
||||
.filter((t) => ['province', 'district'].includes(t.location_type))
|
||||
.at(-1)?.id}
|
||||
territoryId={
|
||||
location.path
|
||||
.filter((t) =>
|
||||
['province', 'district'].includes(
|
||||
t.location_type,
|
||||
),
|
||||
)
|
||||
.at(-1)?.id
|
||||
}
|
||||
/>
|
||||
{location.coordinates.map((point) => (
|
||||
<p key={point.geometry_id}>
|
||||
{uniquePresentation(location.coordinates, (p) =>
|
||||
JSON.stringify([
|
||||
p.geometry_id,
|
||||
p.source_reference,
|
||||
p.source_date,
|
||||
]),
|
||||
).map((point) => (
|
||||
<p
|
||||
key={JSON.stringify([
|
||||
point.geometry_id,
|
||||
point.source_reference,
|
||||
point.source_date,
|
||||
])}
|
||||
>
|
||||
Coordenadas documentadas (
|
||||
{location.location_type === 'site'
|
||||
? 'local cadastrado; não confirma a implantação da oportunidade'
|
||||
: 'referência territorial; não representa a implantação'}
|
||||
): {point.geometry.coordinates[1]},{' '}
|
||||
{point.geometry.coordinates[0]} · Fonte:{' '}
|
||||
{point.source_reference ?? 'Não indicada'}
|
||||
{' · Data da fonte: '}
|
||||
{point.source_date ?? 'Não documentada'}
|
||||
{point.geometry.coordinates[0]}
|
||||
{publicReference(point.source_reference) && (
|
||||
<>
|
||||
{' '}
|
||||
· Fonte:{' '}
|
||||
<PublicReference
|
||||
value={point.source_reference}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{point.source_date && (
|
||||
<> · Data: {point.source_date}</>
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
{!location.coordinates.length && (
|
||||
<p>Coordenadas não documentadas.</p>
|
||||
)}
|
||||
{publicReference(location.source_reference) && (
|
||||
<p className="text-sm">
|
||||
{publicReference(location.source_reference) && (
|
||||
<>
|
||||
Fonte da relação:{' '}
|
||||
<PublicReference
|
||||
value={location.source_reference}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Fonte da relação:{' '}
|
||||
{location.source_reference ?? 'Não indicada'}
|
||||
{' · Data da fonte: '}
|
||||
{location.source_date ?? 'Não documentada'}
|
||||
Data da fonte:{' '}
|
||||
{location.source_date?.trim() || 'Não documentada'}
|
||||
</p>
|
||||
{location.boundaries?.map((boundary) => (
|
||||
<p key={boundary.geometry_id}>
|
||||
Polígono cadastrado · Fonte:{' '}
|
||||
{boundary.source_reference ?? 'Não indicada'} ·
|
||||
Data: {boundary.source_date ?? 'Não documentada'}. O
|
||||
cadastro não certifica limites oficiais.
|
||||
{uniquePresentation(location.boundaries ?? [], (b) =>
|
||||
JSON.stringify([
|
||||
b.geometry_id,
|
||||
b.source_reference,
|
||||
b.source_date,
|
||||
]),
|
||||
).map((boundary) => (
|
||||
<p
|
||||
key={JSON.stringify([
|
||||
boundary.geometry_id,
|
||||
boundary.source_reference,
|
||||
boundary.source_date,
|
||||
])}
|
||||
>
|
||||
Polígono cadastrado
|
||||
{publicReference(boundary.source_reference) && (
|
||||
<>
|
||||
{' '}
|
||||
· Fonte:{' '}
|
||||
<PublicReference
|
||||
value={boundary.source_reference}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{boundary.source_date && (
|
||||
<> · Data: {boundary.source_date}</>
|
||||
)}
|
||||
. O cadastro não certifica limites oficiais.
|
||||
</p>
|
||||
))}
|
||||
{!location.boundaries?.length && (
|
||||
@@ -251,7 +312,7 @@ export default function StructureGeographyPanel({
|
||||
className="underline"
|
||||
href={`/carteira/${member.dossier_id}?from=${dossierId}`}
|
||||
>
|
||||
{member.code} · {member.title}
|
||||
{member.title}
|
||||
</Link>
|
||||
</h3>
|
||||
<p>
|
||||
@@ -259,7 +320,15 @@ export default function StructureGeographyPanel({
|
||||
{member.validation_status === 'validated'
|
||||
? 'validada no cadastro'
|
||||
: 'documental de planeamento; validação pendente'}{' '}
|
||||
· Fonte: {member.source_reference}
|
||||
{publicReference(member.source_reference) && (
|
||||
<>
|
||||
{' '}
|
||||
· Fonte:{' '}
|
||||
<PublicReference
|
||||
value={member.source_reference}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<LocationList locations={member.locations} />
|
||||
{!member.locations.length && (
|
||||
@@ -282,7 +351,13 @@ export default function StructureGeographyPanel({
|
||||
{item.validation_status === 'validated'
|
||||
? 'validada no cadastro'
|
||||
: 'relação documental de planeamento; validação pendente'}{' '}
|
||||
· Fonte: {item.source_reference}
|
||||
{publicReference(item.source_reference) && (
|
||||
<>
|
||||
{' '}
|
||||
· Fonte:{' '}
|
||||
<PublicReference value={item.source_reference} />
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
{cluster && (
|
||||
@@ -292,7 +367,7 @@ export default function StructureGeographyPanel({
|
||||
</h3>
|
||||
{geography.chains?.map((chain) => (
|
||||
<p key={chain.id}>
|
||||
{chain.code} · {chain.name} ·{' '}
|
||||
{chain.name} ·{' '}
|
||||
{(
|
||||
{
|
||||
input: 'Insumos',
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
type BusinessFinancialPlanInput,
|
||||
} from '@/lib/business-financial-plan';
|
||||
import {
|
||||
advanceLabels,
|
||||
advanceEventLabels,
|
||||
advanceDocumentLabel,
|
||||
type SupplierAdvances,
|
||||
type AccountingRegime,
|
||||
type SupplierAdvanceOperation,
|
||||
} from '@/lib/supplier-advances';
|
||||
|
||||
export function SupplierAdvancesEditor({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (plan: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const c: SupplierAdvances = plan.supplierAdvances ?? {
|
||||
regime: '',
|
||||
purchases: false,
|
||||
services: false,
|
||||
operations: [],
|
||||
};
|
||||
const save = (next: SupplierAdvances) =>
|
||||
onChange({ ...plan, supplierAdvances: next });
|
||||
const update = (index: number, patch: Partial<SupplierAdvanceOperation>) =>
|
||||
save({
|
||||
...c,
|
||||
operations: c.operations.map((o, i) =>
|
||||
i === index ? { ...o, ...patch } : o,
|
||||
),
|
||||
});
|
||||
let result: ReturnType<typeof forecastBusinessPlan> | undefined;
|
||||
let diagnostic = '';
|
||||
try {
|
||||
result = forecastBusinessPlan(plan);
|
||||
} catch (e) {
|
||||
diagnostic =
|
||||
e instanceof Error ? e.message : 'Reveja os dados do plano.';
|
||||
}
|
||||
return (
|
||||
<details className="my-3 min-w-0 space-y-3 rounded border p-3">
|
||||
<summary className="font-semibold">
|
||||
Adiantamentos por operação
|
||||
</summary>
|
||||
<p>
|
||||
Projecções de mercadorias e serviços adquiridos. O pagamento
|
||||
antecipado fica no activo; a aplicação exige reconhecimento e
|
||||
factura da mesma operação e parcela no PGC-PE. No PGC-NIRF, pode
|
||||
usar factura ou acordo formal datado e identificado. Não há nova
|
||||
saída de caixa na aplicação. A devolução reduz o adiantamento e
|
||||
não constitui receita.
|
||||
</p>
|
||||
<p>
|
||||
A agenda seleccionada substitui integralmente os pagamentos
|
||||
manuais e os prazos em dias da categoria, conservados inactivos.
|
||||
Distribua o reconhecimento económico completo por operações,
|
||||
incluindo as sem adiantamento. Não converte saldos de abertura.
|
||||
Serviços: utilize apenas se todas as despesas operacionais forem
|
||||
serviços elegíveis.
|
||||
</p>
|
||||
<p>
|
||||
Sem IVA, diferenças cambiais, perdas ou penalizações
|
||||
automatizados; isso não pressupõe taxa zero. Novos activos,
|
||||
empréstimos e contratos com transferência de controlo ou
|
||||
obrigação incondicional antes da entrega estão fora deste
|
||||
incremento. Os movimentos são previsões, não pagamentos
|
||||
executados.
|
||||
</p>
|
||||
<label className="grid gap-1">
|
||||
Regime contabilístico do plano
|
||||
<select
|
||||
className="w-full rounded border p-2"
|
||||
value={plan.accountingRegime ?? ''}
|
||||
onChange={(e) => {
|
||||
const regime = e.target.value as AccountingRegime | '';
|
||||
const previous = plan.accountingRegime ?? c.regime;
|
||||
if (
|
||||
previous &&
|
||||
regime !== previous &&
|
||||
!window.confirm(
|
||||
'Mudar o regime declarado do plano? Confira os fundamentos e os resultados recalculados antes de guardar. Os históricos anteriores mantêm-se intactos.',
|
||||
)
|
||||
)
|
||||
return;
|
||||
onChange({
|
||||
...plan,
|
||||
accountingRegime: regime || undefined,
|
||||
supplierAdvances: { ...c, regime },
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="">Regime do plano por indicar</option>
|
||||
<option value="PGC-PE">PGC-PE</option>
|
||||
<option value="PGC-NIRF">PGC-NIRF</option>
|
||||
</select>
|
||||
</label>
|
||||
{!plan.accountingRegime && c.regime === 'PGC-PE' && (
|
||||
<p>
|
||||
Este plano anterior conserva PGC-PE apenas na agenda de
|
||||
adiantamentos. Confirme acima para o declarar ao nível do
|
||||
plano; nenhum regime geral foi atribuído automaticamente.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
O regime é declarado para esta projecção e para os tratamentos
|
||||
suportados; não é uma certificação contabilística integral. O
|
||||
pagamento do remanescente continua a exigir a factura.
|
||||
</p>
|
||||
{(['purchases', 'services'] as const).map((kind) => (
|
||||
<fieldset
|
||||
key={kind}
|
||||
className="min-w-0 space-y-2 rounded border p-3"
|
||||
>
|
||||
<legend>{advanceLabels[kind]}</legend>
|
||||
<label className="grid gap-1">
|
||||
Agenda de {advanceLabels[kind]}
|
||||
<select
|
||||
className="w-full rounded border p-2"
|
||||
value={c[kind] ? 'operations' : 'previous'}
|
||||
onChange={(e) => {
|
||||
if (
|
||||
e.target.value === 'operations' &&
|
||||
!window.confirm(
|
||||
`Activar adiantamentos por operação para ${advanceLabels[kind]}? Esta agenda substitui todos os pagamentos da categoria; os anteriores ficam guardados e não serão somados.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
save({
|
||||
...c,
|
||||
[kind]: e.target.value === 'operations',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="previous">
|
||||
Agenda anterior preservada
|
||||
</option>
|
||||
<option value="operations">
|
||||
Operações e adiantamentos (adesão explícita)
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{c.operations.map((o, i) =>
|
||||
o.kind !== kind ? null : (
|
||||
<div
|
||||
key={i}
|
||||
className="min-w-0 space-y-3 rounded border p-3"
|
||||
role="group"
|
||||
aria-label={`Operação ${i + 1} de ${advanceLabels[kind]}`}
|
||||
>
|
||||
<div className="grid min-w-0 gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{(
|
||||
[
|
||||
['Operação', 'originId'],
|
||||
['Parcela', 'parcelId'],
|
||||
['Fornecedor', 'supplier'],
|
||||
[
|
||||
'Valor reconhecido da operação/parcela',
|
||||
'amount',
|
||||
],
|
||||
[
|
||||
'Data de reconhecimento',
|
||||
'recognitionDate',
|
||||
],
|
||||
[
|
||||
'Data da factura correspondente',
|
||||
'invoiceDate',
|
||||
],
|
||||
] as const
|
||||
).map(([label, key]) => (
|
||||
<label
|
||||
key={key}
|
||||
className="grid min-w-0 gap-1"
|
||||
>
|
||||
{label}
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type={
|
||||
key.endsWith('Date')
|
||||
? 'date'
|
||||
: 'text'
|
||||
}
|
||||
value={o[key]}
|
||||
onChange={(e) =>
|
||||
update(i, {
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{plan.accountingRegime === 'PGC-NIRF' && (
|
||||
<fieldset className="min-w-0 space-y-2 rounded border p-2">
|
||||
<legend>
|
||||
Acordo formal correspondente
|
||||
(opcional)
|
||||
</legend>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={
|
||||
o.formalAgreement !==
|
||||
undefined
|
||||
}
|
||||
onChange={(e) =>
|
||||
update(i, {
|
||||
formalAgreement: e
|
||||
.target.checked
|
||||
? {
|
||||
date: '',
|
||||
reference: '',
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Identificar acordo formal desta
|
||||
operação/parcela
|
||||
</label>
|
||||
{o.formalAgreement && (
|
||||
<div className="grid min-w-0 gap-2 sm:grid-cols-2">
|
||||
<label className="grid gap-1">
|
||||
Data do acordo formal
|
||||
<input
|
||||
type="date"
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={
|
||||
o.formalAgreement
|
||||
.date
|
||||
}
|
||||
onChange={(e) =>
|
||||
update(i, {
|
||||
formalAgreement:
|
||||
{
|
||||
...o.formalAgreement!,
|
||||
date: e
|
||||
.target
|
||||
.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Referência do acordo formal
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={
|
||||
o.formalAgreement
|
||||
.reference
|
||||
}
|
||||
onChange={(e) =>
|
||||
update(i, {
|
||||
formalAgreement:
|
||||
{
|
||||
...o.formalAgreement!,
|
||||
reference:
|
||||
e
|
||||
.target
|
||||
.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Identifique o acordo efectivamente
|
||||
correspondente ao fornecimento
|
||||
reconhecido. Uma proposta ou
|
||||
encomenda não é automaticamente um
|
||||
acordo formal. A aplicação só pode
|
||||
ocorrer a partir do reconhecimento e
|
||||
da data do fundamento identificado.
|
||||
</p>
|
||||
</fieldset>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Sem data confirmada, deixe-a em branco. Não
|
||||
se presume coincidência entre
|
||||
recepção/prestação e factura. A aplicação
|
||||
exige reconhecimento e o fundamento
|
||||
permitido pelo regime; não se pressupõe uma
|
||||
factura em falta. Reconhecimento fora do
|
||||
horizonte conserva o adiantamento no activo.
|
||||
</p>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={o.ordinaryContract}
|
||||
onChange={(e) =>
|
||||
update(i, {
|
||||
ordinaryContract:
|
||||
e.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Contrato ordinário: sem transferência de
|
||||
controlo nem obrigação incondicional de
|
||||
pagamento antes da entrega/prestação
|
||||
</label>
|
||||
{o.events.map((e, j) => (
|
||||
<div
|
||||
key={j}
|
||||
className="grid min-w-0 gap-2 rounded border p-2 sm:grid-cols-2"
|
||||
role="group"
|
||||
aria-label={`Movimento ${j + 1}`}
|
||||
>
|
||||
<label className="grid gap-1">
|
||||
Movimento
|
||||
<select
|
||||
className="w-full rounded border p-2"
|
||||
value={e.kind}
|
||||
onChange={(v) =>
|
||||
update(i, {
|
||||
events: o.events.map(
|
||||
(a, k) =>
|
||||
k === j
|
||||
? {
|
||||
...a,
|
||||
kind: v
|
||||
.target
|
||||
.value as typeof e.kind,
|
||||
}
|
||||
: a,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
{Object.entries(
|
||||
advanceEventLabels,
|
||||
).map(([value, label]) => (
|
||||
<option
|
||||
key={value}
|
||||
value={value}
|
||||
>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{(
|
||||
[
|
||||
['Identificador', 'id'],
|
||||
['Data', 'date'],
|
||||
['Montante', 'amount'],
|
||||
] as const
|
||||
).map(([label, key]) => (
|
||||
<label
|
||||
key={key}
|
||||
className="grid min-w-0 gap-1"
|
||||
>
|
||||
{label}
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type={
|
||||
key === 'date'
|
||||
? 'date'
|
||||
: 'text'
|
||||
}
|
||||
value={e[key]}
|
||||
onChange={(v) =>
|
||||
update(i, {
|
||||
events: o.events.map(
|
||||
(a, k) =>
|
||||
k === j
|
||||
? {
|
||||
...a,
|
||||
[key]: v
|
||||
.target
|
||||
.value,
|
||||
}
|
||||
: a,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() =>
|
||||
update(i, {
|
||||
events: o.events.filter(
|
||||
(_, k) => k !== j,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover movimento {j + 1}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<p className="text-sm">
|
||||
Os movimentos são processados por data; no
|
||||
mesmo dia, na ordem apresentada. Aplicação
|
||||
exige reconhecimento e o fundamento
|
||||
permitido pelo regime. O pagamento do
|
||||
remanescente exige factura e reconhecimento.
|
||||
O pagamento do remanescente não pode voltar
|
||||
a pagar o adiantamento associado.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={o.events.length >= 60}
|
||||
onClick={() =>
|
||||
update(i, {
|
||||
events: [
|
||||
...o.events,
|
||||
{
|
||||
id: '',
|
||||
kind: 'advance',
|
||||
date: '',
|
||||
amount: '',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar movimento
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
operations: c.operations.filter(
|
||||
(_, k) => k !== i,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover operação {i + 1}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={c.operations.length >= 120}
|
||||
onClick={() =>
|
||||
save({
|
||||
...c,
|
||||
operations: [
|
||||
...c.operations,
|
||||
{
|
||||
kind,
|
||||
originId: '',
|
||||
parcelId: '',
|
||||
supplier: '',
|
||||
amount: '',
|
||||
recognitionDate: '',
|
||||
invoiceDate: '',
|
||||
ordinaryContract: false,
|
||||
events: [],
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar operação de {advanceLabels[kind]}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
{diagnostic && (c.purchases || c.services) && (
|
||||
<p role="alert">{diagnostic}</p>
|
||||
)}
|
||||
{result?.supplierAdvanceLedger && (
|
||||
<section
|
||||
aria-label="Saldos dos adiantamentos por operação"
|
||||
className="space-y-3"
|
||||
>
|
||||
<h4 className="font-semibold">
|
||||
Obrigação, adiantamento e líquido por liquidar
|
||||
</h4>
|
||||
{result.supplierAdvanceLedger.operations.map((o) => (
|
||||
<div
|
||||
key={JSON.stringify([
|
||||
o.kind,
|
||||
o.originId,
|
||||
o.parcelId,
|
||||
])}
|
||||
className="min-w-0 rounded border p-2"
|
||||
>
|
||||
<p className="font-medium">
|
||||
{o.originId}/{o.parcelId} — {o.supplier}
|
||||
</p>
|
||||
<p>
|
||||
Reconhecimento:{' '}
|
||||
{o.recognitionDate || 'por confirmar'}. Factura:{' '}
|
||||
{o.invoiceDate || 'por confirmar'}.{' '}
|
||||
{o.recognitionOutsideHorizon
|
||||
? 'Reconhecimento fora do horizonte ou por confirmar; saldo conservado.'
|
||||
: ''}
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table
|
||||
aria-label={`Saldos de ${o.originId}/${o.parcelId}`}
|
||||
className="w-full text-sm"
|
||||
>
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Mês',
|
||||
'Obrigação bruta',
|
||||
'Adiantamento activo',
|
||||
'Líquido por liquidar',
|
||||
].map((h) => (
|
||||
<th
|
||||
key={h}
|
||||
className="p-2 text-left"
|
||||
>
|
||||
{h}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{o.monthly.map((m) => (
|
||||
<tr key={m.month}>
|
||||
<td className="p-2">
|
||||
{m.month}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{m.obligation}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{m.advance}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{m.netDue}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{plan.accountingRegime === 'PGC-NIRF' && (
|
||||
<p>
|
||||
{o.monthly
|
||||
.map(
|
||||
(m) =>
|
||||
`Mês ${m.month}: ${advanceDocumentLabel(m.documentaryStatus ?? '')}`,
|
||||
)
|
||||
.join('; ')}
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
{o.events.map((e) => (
|
||||
<p key={e.id}>
|
||||
{advanceEventLabels[e.kind]} — {e.date}:{' '}
|
||||
{e.amount} {plan.currency}.{' '}
|
||||
{e.outsideHorizon
|
||||
? 'Fora do horizonte, sem caixa neste plano.'
|
||||
: ''}{' '}
|
||||
{e.applicationBasis
|
||||
? `Fundamento: ${e.applicationBasis.kind === 'formal_agreement' ? 'acordo formal' : 'factura'} ${e.applicationBasis.reference}, de ${e.applicationBasis.date}.`
|
||||
: ''}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
import { publicReference, uniquePresentation } from '@/lib/public-presentation';
|
||||
import PublicReference from './public-reference';
|
||||
import { usePage } from '@inertiajs/react';
|
||||
import EvidenceDetails from './evidence-details';
|
||||
|
||||
export type TerritorialSourceEvidence = {
|
||||
@@ -15,28 +18,68 @@ export default function TerritorialSources({
|
||||
}: {
|
||||
sources?: TerritorialSourceEvidence[];
|
||||
}) {
|
||||
if (!sources?.length) return null;
|
||||
const management = usePage().url.startsWith('/management/');
|
||||
const visible = uniquePresentation(
|
||||
(sources ?? []).filter(
|
||||
(row) =>
|
||||
management ||
|
||||
publicReference(row.source_reference) ||
|
||||
publicReference(row.source_quote) ||
|
||||
publicReference(row.supports),
|
||||
),
|
||||
(row) =>
|
||||
JSON.stringify([
|
||||
row.association,
|
||||
row.role,
|
||||
management
|
||||
? row.source_reference
|
||||
: publicReference(row.source_reference),
|
||||
publicReference(row.source_quote),
|
||||
publicReference(row.supports),
|
||||
...(management ? [row.traceability] : []),
|
||||
]),
|
||||
);
|
||||
if (!visible.length) return null;
|
||||
return (
|
||||
<EvidenceDetails title="Fontes das relações territoriais">
|
||||
{sources.map((source, i) => (
|
||||
{visible.map((source, i) => (
|
||||
<article className="border-t pt-3" key={i}>
|
||||
<h3 className="font-semibold">
|
||||
{source.role} — {source.association}
|
||||
</h3>
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{source.source_reference ??
|
||||
'ligação ao exemplar por recuperar'}
|
||||
</p>
|
||||
<p>{source.source_quote ?? source.supports}</p>
|
||||
{(management ||
|
||||
publicReference(source.source_reference)) && (
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{management ? (
|
||||
source.source_reference
|
||||
) : (
|
||||
<PublicReference
|
||||
value={source.source_reference}
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{(publicReference(source.source_quote) ||
|
||||
publicReference(source.supports)) && (
|
||||
<p>
|
||||
{publicReference(source.source_quote) ||
|
||||
publicReference(source.supports)}
|
||||
</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 && (
|
||||
{(management ||
|
||||
publicReference(source.traceability)) && (
|
||||
<p>{source.traceability}</p>
|
||||
)}
|
||||
{(management
|
||||
? source.existing_validation
|
||||
: publicReference(source.existing_validation)) && (
|
||||
<p>{source.existing_validation}</p>
|
||||
)}
|
||||
</EvidenceDetails>
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
|
||||
import {
|
||||
defaultPlanWarningLimits,
|
||||
isPlanWarningLimits,
|
||||
type PlanWarningLimits,
|
||||
} from '@/lib/business-plan-guidance';
|
||||
const fields: [keyof PlanWarningLimits, string][] = [
|
||||
['grossMarginPercent', 'Margem bruta de aviso (%)'],
|
||||
['cashExpenseMonths', 'Cobertura de despesas em caixa (meses)'],
|
||||
['annualGrowthPercent', 'Crescimento anual de aviso (%)'],
|
||||
['creditDays', 'Prazo de recebimento de aviso (dias)'],
|
||||
['debtAssetsPercent', 'D\u00edvida sobre activos de aviso (%)'],
|
||||
];
|
||||
export function WarningLimitsEditor({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (p: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const root = useRef<HTMLFieldSetElement>(null);
|
||||
const [error, setError] = useState('');
|
||||
return (
|
||||
<details className="my-4 rounded border p-3">
|
||||
<summary>Limites dos avisos</summary>
|
||||
<p className="my-2 text-sm">
|
||||
{
|
||||
'Ajuste os limiares dos avisos de planeamento. Os valores financeiros e os erros de preenchimento mant\u00eam-se. O prazo em dias aplica-se quando foi indicado nesse formato.'
|
||||
}
|
||||
</p>
|
||||
<p role="status">
|
||||
{plan.warningLimits
|
||||
? 'Limites personalizados guardados neste plano.'
|
||||
: 'Limites habituais do simulador.'}
|
||||
</p>
|
||||
<fieldset
|
||||
key={JSON.stringify(plan.warningLimits)}
|
||||
ref={root}
|
||||
className="my-3 grid gap-3 sm:grid-cols-2"
|
||||
>
|
||||
<legend className="sr-only">Limiares de planeamento</legend>
|
||||
{fields.map(([key, label]) => (
|
||||
<label key={key} className="grid gap-1 text-sm">
|
||||
{label}
|
||||
<input
|
||||
className="min-w-0 rounded border p-2"
|
||||
type="number"
|
||||
step="any"
|
||||
name={key}
|
||||
defaultValue={
|
||||
(plan.warningLimits ??
|
||||
defaultPlanWarningLimits)[key]
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-red-800">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() => {
|
||||
const next = Object.fromEntries(
|
||||
fields.map(([key]) => [
|
||||
key,
|
||||
root.current?.querySelector<HTMLInputElement>(
|
||||
`input[name="${key}"]`,
|
||||
)?.valueAsNumber,
|
||||
]),
|
||||
);
|
||||
if (!isPlanWarningLimits(next)) {
|
||||
setError(
|
||||
'Preencha os cinco limites com n\u00fameros finitos; meses e dias devem ser n\u00e3o negativos.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setError('');
|
||||
onChange({ ...plan, warningLimits: next });
|
||||
}}
|
||||
>
|
||||
Aplicar limites ao plano
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() => {
|
||||
const next = { ...plan };
|
||||
delete next.warningLimits;
|
||||
setError('');
|
||||
onChange(next);
|
||||
}}
|
||||
>
|
||||
Repor limites habituais
|
||||
</button>
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user