This commit is contained in:
2026-11-23 10:40:48 +02:00
921 changed files with 182589 additions and 895 deletions
@@ -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>
);
}
+1 -1
View File
@@ -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 && (
+31 -8
View File
@@ -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>
);
}
+98 -23
View File
@@ -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>
);
}
@@ -1,3 +1,4 @@
import PortalCorrections from '@/components/portal-corrections';
import SearchFeedback from '@/components/search-feedback';
import { searchTerritoryHref } from '@/lib/search-territory';
import { Link, usePage } from '@inertiajs/react';
@@ -170,6 +171,7 @@ function PortalNavigationContent({ children }: { children: ReactNode }) {
</div>
}
<SearchFeedback />
{!printable && <PortalCorrections />}
{children}
</div>
<aside
@@ -0,0 +1,351 @@
// Amounts transcribed from the immutable original PN tables T003, T005, T012 and T013. Never used as balancing entries.
export const annualExampleOriginalDetail = {
sourceSha256:
'4f1e1dbc90c8a4888291201898f306c06e2e687843a754a04a9a8a56f459ab99',
sales: [
{
label: 'Publicidade',
annual: ['2137', '3000', '3500'],
monthly2025: [
'100',
'110',
'121',
'133',
'140',
'161',
'177',
'195',
'215',
'237',
'261',
'287',
],
},
{
label: 'Intermediação Comercial',
annual: ['5336', '6000', '6500'],
monthly2025: [
'250',
'275',
'302',
'332',
'365',
'402',
'442',
'486',
'535',
'588',
'647',
'712',
],
},
{
label: 'Comercialização de Commodities',
annual: ['3211', '4000', '4250'],
monthly2025: [
'150',
'165',
'182',
'200',
'220',
'242',
'266',
'293',
'322',
'354',
'389',
'428',
],
},
{
label: 'Formação',
annual: ['201', '250', '275'],
monthly2025: [
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'18',
'20',
'22',
'24',
'26',
],
},
],
costs: [
{
label: 'Publicidade',
annual: ['1595', '2500', '3000'],
monthly2025: [
'75',
'82',
'90',
'99',
'109',
'120',
'132',
'145',
'160',
'176',
'194',
'213',
],
},
{
label: 'Intermediação Comercial',
annual: ['4273', '5500', '6000'],
monthly2025: [
'200',
'220',
'242',
'266',
'293',
'322',
'354',
'389',
'428',
'471',
'518',
'570',
],
},
{
label: 'Comercialização de Commodities',
annual: ['3211', '3750', '4000'],
monthly2025: [
'150',
'165',
'182',
'200',
'220',
'242',
'266',
'293',
'322',
'354',
'389',
'428',
],
},
{
label: 'Formação',
annual: ['139', '450', '475'],
monthly2025: [
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'18',
],
},
{
label: 'Marketing',
annual: ['1077', '1100', '1200'],
monthly2025: [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
],
},
],
departments: [
{
label: 'DIrecção Comercial',
annual: ['300', '400', '400'],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'annual-and-monthly',
},
{
label: 'Direcção de Admin e Finanças',
annual: ['300', '400', '400'],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'annual-and-monthly',
},
{
label: 'Serviços',
annual: ['300', '400', '400'],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'annual-and-monthly',
},
{
label: 'Marketing',
annual: ['300', null, null],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'sum-of-documented-months',
},
{
label: 'Revista Tempo',
annual: ['300', null, null],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'sum-of-documented-months',
},
{
label: 'Gsetão de Projectos',
annual: ['300', null, null],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'sum-of-documented-months',
},
{
label: 'Gabinete Juridico',
annual: ['300', null, null],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'sum-of-documented-months',
},
],
salesTotals: [
'680',
'748',
'824',
'905',
'990',
'1095',
'1203',
'1324',
'1458',
'1604',
'1765',
'1941',
],
costTotals: [
'586',
'644',
'710',
'781',
'860',
'945',
'1038',
'1142',
'1257',
'1383',
'1520',
'1672',
],
people: {
annual: ['1', '1', '1'],
monthly2025: [
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
],
},
} as const;
@@ -0,0 +1,64 @@
import { annualExampleOriginalDetail as source } from './annual-example-original-detail.ts';
import type { AnnualReferencePlan } from './business-plan-guidance.ts';
import { reportMoney } from './integral-financial-report.ts';
const cents = (s: string) => {
const [a, b = ''] = s.split('.');
return BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
};
export function reconcileOriginalExample(plan: AnnualReferencePlan) {
const sum = (
rows: readonly { annual: readonly (string | null)[] }[],
year: number,
) =>
rows.reduce(
(n, r) =>
n + (r.annual[year] === null ? 0n : cents(r.annual[year]!)),
0n,
);
return {
years: plan.years.map((y, i) => ({
year: y.year,
sales: reportMoney(cents(y.sales)),
knownSales: reportMoney(sum(source.sales, i)),
salesDifference: reportMoney(cents(y.sales) - sum(source.sales, i)),
costs: reportMoney(cents(y.directCosts)),
knownCosts: reportMoney(sum(source.costs, i)),
costDifference: reportMoney(
cents(y.directCosts) - sum(source.costs, i),
),
payroll: reportMoney(cents(y.payroll)),
knownPayroll: reportMoney(sum(source.departments, i)),
payrollDifference: reportMoney(
cents(y.payroll) - sum(source.departments, i),
),
missingDepartments: source.departments
.filter((r) => r.annual[i] === null)
.map((r) => r.label),
})),
months: source.salesTotals.map((total, i) => {
const sales = source.sales.reduce(
(n, r) => n + cents(r.monthly2025[i]!),
0n,
);
const costs = source.costs.reduce(
(n, r) =>
n +
(r.monthly2025[i] === null ? 0n : cents(r.monthly2025[i]!)),
0n,
);
return {
period: `2025-${String(i + 1).padStart(2, '0')}`,
sourceSales: reportMoney(cents(total!)),
knownSales: reportMoney(sales),
salesDifference: reportMoney(cents(total!) - sales),
sourceCosts: reportMoney(cents(source.costTotals[i]!)),
knownCosts: reportMoney(costs),
costDifference: reportMoney(
cents(source.costTotals[i]!) - costs,
),
};
}),
needed: 'Vendas por serviço que somem 14.537/21.500/23.875 e custos por serviço que somem 12.538/16.200/18.325; distribuição mensal coerente dessas linhas; remuneração de Marketing, Revista Tempo, Gestão de Projectos e Gabinete Jurídico em 2026 e 2027 (total conjunto ainda por repartir: 1.600 em cada ano). As diferenças são diagnóstico documental, não rubricas financeiras.',
};
}
+430
View File
@@ -0,0 +1,430 @@
import {
calculateAnnualReferencePlan,
calculateDecisionRatios,
restoreAnnualExampleSnapshot,
businessPlanWarnings,
} from './business-plan-guidance.ts';
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
import {
reportMoney,
type InvestmentReportTable,
} from './integral-financial-report.ts';
import { buildComplementaryTables } from './complementary-report.ts';
import { annualExampleOriginalDetail as original } from './annual-example-original-detail.ts';
import { reconcileOriginalExample } from './annual-example-reconciliation.ts';
/** Presentation adapter only: uses the approved annual calculation, never converts it into investor movements. */
export function buildAnnualExampleTables(
input: BusinessFinancialPlanInput,
): InvestmentReportTable[] {
const plan = restoreAnnualExampleSnapshot(input.annualExampleSnapshot);
if (!plan)
throw new Error(
'Carregue e guarde primeiro o cenário anual de exemplo.',
);
const result = calculateAnnualReferencePlan(plan);
const notes = [
`Exemplo sintético; projecções ilustrativas em ${input.currency || 'moeda por seleccionar'}. Não são dados reais do investidor.`,
'Totais anuais preservados. A distribuição dos 36 meses é ilustrativa e reconciliada, não uma reprodução das linhas mensais inconsistentes do documento.',
];
const make = (
id: string,
title: string,
headers: string[],
rows: string[][],
): InvestmentReportTable => ({
id,
title,
headers,
rows: rows.map((row) =>
row.map((v, i) =>
i > 0 && /^-?\d+(?:\.\d{1,2})?$/.test(v)
? `${v.split('.')[0]}.${(v.split('.')[1] ?? '').padEnd(2, '0')}`
: v,
),
),
notes: id === 'startup' ? [...notes] : [],
issues: [],
});
const headers = ['Rubrica', ...plan.years.map((y) => String(y.year))];
const value = (n: number) => n.toFixed(2);
const row = (
label: string,
get: (y: (typeof result.years)[number], i: number) => string,
) => [label, ...result.years.map(get)];
const startup = make(
'startup',
'Start-up — exemplo',
['Rubrica', 'Montante'],
[
...plan.startupExpenses.map((r) => [r.label, r.amount]),
['Despesas de arranque', result.startupExpenses],
['Caixa necessária', plan.openingCash],
['Outros activos correntes', plan.otherCurrentAssets],
['Activos de longo prazo', plan.longTermAssets],
['Total de activos', result.assets],
['Requisitos totais', result.requiredFunding],
],
);
const sales = make('sales', 'Previsão de Vendas — exemplo', headers, [
row('Vendas totais', (y) => y.sales),
row('Custo directo', (y) => y.directCosts),
]);
sales.notes.push(
'Linhas por serviço do original não reconciliam com os totais anuais aceites. Mantêm-se agregadas; não se inventa a diferença por produto.',
);
const funding = make(
'funding',
'Financiamento — exemplo',
['Rubrica', 'Montante'],
[
['Capital do proprietário', plan.ownerCapital],
['Capital do investidor', plan.investorCapital],
['Empréstimos', plan.loans],
['Dinheiro adicional angariado', plan.additionalMoney],
[
'Financiamento disponível declarado no exemplo',
result.availableFunding,
],
['Caixa requerida (objectivo do cenário)', plan.openingCash],
[
'Caixa efectivamente disponível antes do financiamento',
'Não documentado no exemplo original',
],
['Financiamento necessário', result.requiredFunding],
[
'Capital por mobilizar — hipótese, não financiamento confirmado',
result.capitalToMobilise,
],
['Diferença por financiar', result.fundingGap],
],
);
const breakeven = make(
'break-even',
'Ponto de Equilíbrio — exemplo',
headers,
[
row('Receita mensal de equilíbrio', (y) =>
y.monthlyBreakEven === null
? 'Por determinar'
: value(y.monthlyBreakEven),
),
row('Custos fixos mensais', (y) => value(y.monthlyFixedCosts)),
],
);
const profit = make('profit-loss', 'Lucros e Perdas — exemplo', headers, [
row('Vendas', (y) => y.sales),
row('Custo directo', (y) => y.directCosts),
row('Margem bruta', (y) => y.grossMargin),
row('Despesas operacionais', (y) => y.operatingExpenses),
row('Resultado operacional', (y) => y.operatingProfit),
row('Juros', (_, i) => plan.years[i].interest),
row('Imposto estimado', (_, i) => plan.years[i].taxes),
row('Lucro líquido', (y) => y.netProfit),
]);
const cash = make('cashflow', 'Fluxo de Caixa — exemplo', headers, [
row('Caixa recebida', (_, i) => plan.years[i].cashReceived),
row('Caixa gasta', (_, i) => plan.years[i].cashSpent),
row('Fluxo líquido', (y) => y.cashFlow),
row('Caixa final', (y) => y.closingCash),
]);
const balance = make('balance', 'Balanço — exemplo', headers, [
row('Caixa líquida', (y) => y.closingCash),
row('Recebíveis líquidos', (y) => y.receivables),
row('Outros activos correntes', () => plan.otherCurrentAssets),
row('Activos fixos líquidos', () => plan.longTermAssets),
row('Total do activo', (y) => y.closingAssets),
row('Obrigações operacionais', (y) => y.operatingLiabilities),
row('Saldo fiscal estimado', (y) => y.vatBalance),
row('Total do passivo', (y) => y.closingLiabilities),
row('Capital e resultados', (y) => y.closingCapital),
row('Diferença do balanço', (y) => y.balanceDifference),
]);
balance.notes.push(
'Capital por mobilizar é hipótese de projecção explicitamente identificada; não é uma fonte obtida nem uma compensação contabilística.',
);
const cents = (s: string) => {
const negative = s.startsWith('-');
const [a, b = ''] = s.replace('-', '').split('.');
const n = BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
return negative ? -n : n;
};
const projectedCapital =
cents(result.availableFunding) +
cents(result.capitalToMobilise) -
cents(plan.loans);
const ratios = result.years.map((y, i) => {
try {
return calculateDecisionRatios(
{
cash: y.closingCash,
receivables: y.receivables,
inventory: '0',
otherCurrentAssets: plan.otherCurrentAssets,
longTermAssets: plan.longTermAssets,
accumulatedDepreciation: '0',
currentLiabilities: reportMoney(
cents(y.operatingLiabilities) + cents(y.vatBalance),
),
longTermLiabilities: plan.loans,
paidCapital: reportMoney(projectedCapital),
retainedResults: reportMoney(
cents(y.closingCapital) -
projectedCapital -
cents(y.netProfit),
),
periodResult: y.netProfit,
},
y.sales,
i ? result.years[i - 1].sales : undefined,
);
} catch {
return {
salesGrowth:
y.growthPercent === null ? null : y.growthPercent / 100,
currentLiquidity: null,
debtAssets: null,
netMargin:
y.netMarginPercent === null
? null
: y.netMarginPercent / 100,
returnOnEquity: null,
};
}
});
const ratio = make(
'ratios',
'Rácios financeiros — exemplo',
headers,
(
[
['salesGrowth', 'Crescimento das vendas', true],
['currentLiquidity', 'Liquidez corrente', false],
['debtAssets', 'Endividamento', true],
['netMargin', 'Margem líquida', true],
['returnOnEquity', 'Retorno do capital', true],
] as const
).map(([key, label, percent]) => [
label,
...ratios.map((r) =>
r?.[key] == null
? 'Por determinar'
: `${value(r[key]! * (percent ? 100 : 1)).replace('.', ',')}${percent ? '%' : '×'}`,
),
]),
);
const marketInput = {
...input,
marketAnalysis: {
baseYear: '2025',
years: '5',
segments: [
['Publicidade', '100000', '45'],
['Marketing Digital', '800', '50'],
['Intermediação Comercial', '150', '50'],
['eCommerce', '50000', '65'],
['Consultoria Financeira', '10', '75'],
['Formação', '500', '75'],
['Comunicação', '100', '15'],
['Eventos', '10', '5'],
].map(([label, customers, growthPercent]) => ({
label,
customers,
growthPercent,
basis: 'Hipótese ilustrativa do documento PN, tabela T002; não é procura demonstrada.',
})),
},
};
const market = buildComplementaryTables({}, marketInput)[0];
market.notes.push(
'Linha Desenvolvimento de aplicativos sem base numérica legível no original: não introduzida como zero. Projecções recalculadas pelas fórmulas do modelo; não se copiam totais inconsistentes.',
);
const milestones = make(
'milestones',
'Marcos — exemplo',
[
'Marco',
'Início',
'Término',
'Orçamento',
'Responsável',
'Departamento',
],
[
'Produzir Portal',
'Produzir Plano de Negócios',
'Contratar Pessoal Administrativo',
'Contratar Pessoal Vendas',
'Contratar Gestores do Portal',
].map((label) => [
label,
'2026-07-01',
'2026-07-31',
'0.00',
'Osmane Nala (exemplo do documento)',
'DG',
]),
);
const personnel = make('personnel', 'Pessoal — exemplo', headers, [
row('Folha de pagamento agregada', (_, i) => plan.years[i].payroll),
row('Encargos da folha', (_, i) => plan.years[i].payrollCharges),
]);
personnel.notes.push(
'O original não reconcilia remunerações por departamento com a folha agregada. Preservados os totais anuais aceites; quantidade e repartição por função permanecem por determinar, sem inventar trabalhadores ou salários.',
);
for (const y of result.years)
profit.notes.push(
...businessPlanWarnings({
currency: input.currency,
sales: Number(y.sales),
directCosts: Number(y.directCosts),
netProfit: Number(y.netProfit),
monthlyExpenses: y.monthlyFixedCosts,
monthlyBreakEven: y.monthlyBreakEven,
cash: Number(y.closingCash),
growthPercent: y.growthPercent ?? undefined,
assets: Number(y.closingAssets),
liabilities: Number(y.closingLiabilities),
ownAndInvestorCapital:
Number(plan.ownerCapital) + Number(plan.investorCapital),
fundingGap:
y.year === result.years[0].year
? Number(result.fundingGap)
: undefined,
}).map((w) => `Aviso não bloqueante — ${y.year}: ${w.message}`),
);
type Month = (typeof result.years)[number]['illustrativeMonths'][number];
const months = result.years.flatMap((y) => y.illustrativeMonths);
const detailedHeaders = [
'Rubrica',
...result.years.flatMap((y) =>
y.illustrativeMonths.map(
(m) => `${y.year}-${String(m.month).padStart(2, '0')}`,
),
),
...headers.slice(1),
];
const expand = (
table: InvestmentReportTable,
fields: Record<string, (m: Month) => string>,
) => {
table.headers = detailedHeaders;
table.rows = table.rows.map((r) => [
r[0],
...months.map((m) => fields[r[0]]?.(m) ?? 'Por determinar'),
...r.slice(1),
]);
};
expand(sales, {
'Vendas totais': (m) => m.sales,
'Custo directo': (m) => m.directCosts,
});
expand(profit, {
Vendas: (m) => m.sales,
'Custo directo': (m) => m.directCosts,
'Margem bruta': (m) => m.grossMargin,
'Despesas operacionais': (m) => m.operatingExpenses,
'Resultado operacional': (m) => m.operatingProfit,
Juros: (m) => m.interest,
'Imposto estimado': (m) => m.taxes,
'Lucro líquido': (m) => m.netProfit,
});
expand(cash, {
'Caixa recebida': (m) => m.cashReceived,
'Caixa gasta': (m) => m.cashSpent,
'Fluxo líquido': (m) => m.cashFlow,
'Caixa final': (m) => m.closingCash,
});
expand(balance, {
'Caixa líquida': (m) => m.closingCash,
'Recebíveis líquidos': (m) => m.receivables,
'Outros activos correntes': () => plan.otherCurrentAssets,
'Activos fixos líquidos': () => plan.longTermAssets,
'Total do activo': (m) => m.closingAssets,
'Obrigações operacionais': (m) => m.operatingLiabilities,
'Saldo fiscal estimado': (m) => m.vatBalance,
'Total do passivo': (m) => m.closingLiabilities,
'Capital e resultados': (m) => m.closingCapital,
'Diferença do balanço': (m) => m.balanceDifference,
});
expand(personnel, {
'Folha de pagamento agregada': (m) => m.payroll,
'Encargos da folha': (m) => m.payrollCharges,
});
const originalRow = (
kind: string,
r: {
label: string;
annual: readonly (string | null)[];
monthly2025: readonly (string | null)[];
},
) => [
`${kind} — ${r.label}`,
...months.map((_, i) =>
i < 12 && r.monthly2025[i] !== null
? reportMoney(BigInt(r.monthly2025[i]!) * 100n)
: 'Não documentado',
),
...r.annual.map((v) =>
v === null ? 'Não documentado' : reportMoney(BigInt(v) * 100n),
),
];
sales.rows.push(
...original.sales.map((r) =>
originalRow('Vendas documentadas no original', r),
),
...original.costs.map((r) =>
originalRow('Custo documentado no original', r),
),
);
personnel.rows.push(
...original.departments.map((r) =>
originalRow('Departamento documentado', r),
),
);
personnel.rows.push([
'Trabalhadores documentados (sem inferir pessoas por departamento)',
...months.map((_, i) => (i < 12 ? '1' : 'Não documentado')),
'1',
'1',
'1',
]);
sales.notes = sales.notes.filter(
(n) => !n.startsWith('Linhas por serviço'),
);
personnel.notes = personnel.notes.filter(
(n) => !n.startsWith('O original não reconcilia'),
);
sales.notes.push(
'Linhas documentadas reproduzem o original para conferência, não são novas parcelas ou ajustamentos dos totais calculados. As células não documentadas não são zero. Os totais mensais calculados são projecções ilustrativas conciliadas com os anuais.',
);
personnel.notes.push(
'Sete departamentos estão documentados no quadro mensal: 7 × 25 = 175 por mês e 2.100 em 2025. Não são sete trabalhadores: o original declara uma pessoa. As quatro linhas anuais omitidas em 2025 resultam da soma dos meses documentados. Não se presume a repartição de 2026/2027.',
);
const reconciliation = reconcileOriginalExample(plan);
for (const year of reconciliation.years) {
sales.notes.push(
`${year.year}: a soma das linhas de vendas documentadas é ${year.knownSales}; o total anual do cenário é ${year.sales}; diferença documental ${year.salesDifference}. Custos documentados ${year.knownCosts}, total ${year.costs}, diferença ${year.costDifference}. Estas diferenças não são rubricas financeiras.`,
);
if (year.missingDepartments.length)
personnel.notes.push(
`${year.year}: ${year.missingDepartments.join(', ')} não têm remuneração anual documentada; as linhas conhecidas somam ${year.knownPayroll}, para uma folha total de ${year.payroll}. Faltam dados para repartir ${year.payrollDifference}; não é um ajustamento contabilístico.`,
);
}
sales.notes.push(
`No primeiro mês original, as linhas de vendas somam ${reconciliation.months[0].knownSales}, mas o total é ${reconciliation.months[0].sourceSales}; os custos documentados somam ${reconciliation.months[0].knownCosts}, para um subtotal de ${reconciliation.months[0].sourceCosts}. Nenhuma linha foi criada para absorver as diferenças.`,
);
return [
startup,
market,
sales,
milestones,
personnel,
funding,
breakeven,
profit,
cash,
balance,
ratio,
];
}
File diff suppressed because it is too large Load Diff
+689
View File
@@ -0,0 +1,689 @@
export type PlanWarningLimits = {
grossMarginPercent: number;
cashExpenseMonths: number;
annualGrowthPercent: number;
creditDays: number;
debtAssetsPercent: number;
};
export const defaultPlanWarningLimits: PlanWarningLimits = {
grossMarginPercent: 15,
cashExpenseMonths: 1,
annualGrowthPercent: 100,
creditDays: 90,
debtAssetsPercent: 70,
};
export function isPlanWarningLimits(
value: unknown,
): value is PlanWarningLimits {
if (!value || typeof value !== 'object' || Array.isArray(value))
return false;
const limits = value as Record<string, unknown>;
return (
Object.keys(limits).length === 5 &&
Object.keys(defaultPlanWarningLimits).every(
(key) =>
typeof limits[key] === 'number' &&
Number.isFinite(limits[key]) &&
(!['cashExpenseMonths', 'creditDays'].includes(key) ||
Number(limits[key]) >= 0),
)
);
}
export type PlanWarning = { id: string; message: string };
export type PlanWarningMetrics = {
optionalTexts?: { label: string; value: string }[];
fundingGap?: number;
currency?: string;
netProfit?: number;
sales?: number;
directCosts?: number;
monthlyBreakEven?: number | null;
monthlyExpenses?: number;
cash?: number;
growthPercent?: number;
creditDays?: number;
liabilities?: number;
assets?: number;
ownAndInvestorCapital?: number;
};
/** Guidance only: warnings never change the inputs or determine validity. */
export function businessPlanWarnings(
metrics: PlanWarningMetrics,
limits: PlanWarningLimits = defaultPlanWarningLimits,
): PlanWarning[] {
const warnings: PlanWarning[] = [];
const add = (id: string, message: string) => warnings.push({ id, message });
if (metrics.optionalTexts?.some((field) => !field.value.trim()))
add(
'optional-texts',
'Pode completar estas secções para um relatório mais convincente.',
);
if ((metrics.fundingGap ?? 0) > 0)
add(
'funding',
`O financiamento indicado não cobre o investimento necessário. Faltam ${metrics.fundingGap!.toLocaleString('pt-MZ', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}${metrics.currency ? ` ${metrics.currency}` : ''}.`,
);
if (metrics.netProfit !== undefined && metrics.netProfit < 0)
add(
'loss',
'Neste ano o negócio dá prejuízo. Reveja as vendas ou os custos, ou confirme que é o esperado.',
);
if (
metrics.sales !== undefined &&
metrics.sales > 0 &&
metrics.directCosts !== undefined
) {
if (
(100 * (metrics.sales - metrics.directCosts)) / metrics.sales <
limits.grossMarginPercent
)
add(
'margin',
'A margem bruta é baixa e deixa pouca folga para cobrir as despesas.',
);
if (
metrics.monthlyBreakEven != null &&
metrics.monthlyBreakEven > metrics.sales / 12
)
add(
'break-even',
'As vendas mensais médias não atingem o ponto de equilíbrio. O negócio só cobre os custos com mais vendas.',
);
}
if (
metrics.cash !== undefined &&
metrics.monthlyExpenses !== undefined &&
metrics.cash < metrics.monthlyExpenses * limits.cashExpenseMonths
)
add(
'cash',
limits.cashExpenseMonths === 1
? 'A caixa disponível cobre menos de um mês de despesas. Considere reforçar o financiamento.'
: `A caixa disponível cobre menos de ${limits.cashExpenseMonths.toLocaleString('pt-MZ')} meses de despesas. Considere reforçar o financiamento.`,
);
if (
metrics.growthPercent !== undefined &&
metrics.growthPercent > limits.annualGrowthPercent
)
add(
'growth',
'O crescimento indicado é muito elevado. Confirme que é realista.',
);
if (
metrics.creditDays !== undefined &&
metrics.creditDays > limits.creditDays
)
add(
'credit',
'Prazos de recebimento longos pressionam a caixa. Confirme o prazo indicado.',
);
if (
metrics.assets !== undefined &&
metrics.assets > 0 &&
metrics.liabilities !== undefined &&
(metrics.liabilities / metrics.assets) * 100 > limits.debtAssetsPercent
)
add(
'debt',
'O peso das dívidas é elevado e pode dificultar o acesso a crédito.',
);
if (metrics.ownAndInvestorCapital === 0)
add(
'capital',
'Não indicou capital próprio nem de investidor. Todo o financiamento vem de empréstimos ou fica por definir.',
);
return warnings;
}
export type AnnualReferencePlan = {
startupExpenses: { label: string; amount: string }[];
openingCash: string;
otherCurrentAssets: string;
longTermAssets: string;
ownerCapital: string;
investorCapital: string;
loans: string;
additionalMoney: string;
years: {
year: number;
sales: string;
directCosts: string;
payroll: string;
payrollCharges: string;
otherOperatingExpenses: string;
interest: string;
taxes: string;
cashReceived: string;
cashSpent: string;
vatReceived: string;
vatPaid: string;
}[];
};
/** Values explicitly supplied by the owner; currency must be chosen in the form. */
export function newAnnualReferencePlan(): AnnualReferencePlan {
return {
startupExpenses: [
{ label: 'Constituição da sociedade', amount: '25000' },
{ label: 'Material de escritório', amount: '50000' },
{ label: 'Seguros', amount: '0' },
{ label: 'Rendas', amount: '0' },
{ label: 'Computadores', amount: '250000' },
{ label: 'Desenvolvimento do portal', amount: '1000000' },
],
openingCash: '90000',
otherCurrentAssets: '150000',
longTermAssets: '260250',
ownerCapital: '0',
investorCapital: '0',
loans: '0',
additionalMoney: '0',
years: [
{
year: 2025,
sales: '14537',
directCosts: '12538',
payroll: '2100',
payrollCharges: '315',
otherOperatingExpenses: '0',
interest: '0',
taxes: '0',
cashReceived: '16539',
cashSpent: '15783',
vatReceived: '2471',
vatPaid: '2471',
},
{
year: 2026,
sales: '21500',
directCosts: '16200',
payroll: '2800',
payrollCharges: '420',
otherOperatingExpenses: '0',
interest: '0',
taxes: '624',
cashReceived: '24930',
cashSpent: '23923',
vatReceived: '3655',
vatPaid: '3655',
},
{
year: 2027,
sales: '23875',
directCosts: '18325',
payroll: '2800',
payrollCharges: '420',
otherOperatingExpenses: '0',
interest: '0',
taxes: '699',
cashReceived: '27857',
cashSpent: '26122',
vatReceived: '4059',
vatPaid: '4059',
},
],
};
}
/** Preserve incomplete numeric drafts as entered, but accept only the example's schema. */
export function restoreAnnualExampleSnapshot(
snapshot?: string,
): AnnualReferencePlan | null {
if (!snapshot || snapshot.length > 12000) return null;
try {
const decoded = JSON.parse(snapshot);
if (
decoded.version !== 1 ||
decoded.kind !== 'synthetic-annual-example'
)
return null;
const plan = decoded.plan;
const template = newAnnualReferencePlan();
const numericDraft = (value: unknown) =>
typeof value === 'string' && value.length <= 40;
for (const key of [
'openingCash',
'otherCurrentAssets',
'longTermAssets',
'ownerCapital',
'investorCapital',
'loans',
'additionalMoney',
] as const)
if (!numericDraft(plan[key])) return null;
if (
!Array.isArray(plan.startupExpenses) ||
plan.startupExpenses.length !== template.startupExpenses.length ||
plan.startupExpenses.some(
(row: { label: unknown; amount: unknown }, i: number) =>
row.label !== template.startupExpenses[i].label ||
!numericDraft(row.amount),
)
)
return null;
if (
!Array.isArray(plan.years) ||
plan.years.length !== template.years.length ||
plan.years.some(
(row: Record<string, unknown>, i: number) =>
row.year !== template.years[i].year ||
Object.keys(template.years[i]).some(
(key) => key !== 'year' && !numericDraft(row[key]),
),
)
)
return null;
// Do not accept unrelated fields or investor data into this example.
if (
JSON.stringify(Object.keys(plan).sort()) !==
JSON.stringify(Object.keys(template).sort()) ||
plan.years.some(
(row: Record<string, unknown>, i: number) =>
JSON.stringify(Object.keys(row).sort()) !==
JSON.stringify(Object.keys(template.years[i]).sort()),
) ||
plan.startupExpenses.some(
(row: Record<string, unknown>) =>
Object.keys(row).sort().join(',') !== 'amount,label',
)
)
return null;
return plan as AnnualReferencePlan;
} catch {
return null;
}
}
export function serializeAnnualExampleSnapshot(
plan: AnnualReferencePlan,
): string {
const snapshot = JSON.stringify({
version: 1,
kind: 'synthetic-annual-example',
plan,
});
if (!restoreAnnualExampleSnapshot(snapshot))
throw new Error('Não foi possível guardar o cenário de exemplo.');
return snapshot;
}
function money(value: string): bigint {
if (value.length > 40 || !/^\d+(?:\.\d{1,2})?$/.test(value.trim()))
throw new Error(
value.trim() === ''
? 'Preencha este campo para continuar.'
: Number(value) < 0
? 'Este valor não pode ser negativo.'
: 'Introduza apenas números (ex.: 25.000).',
);
const [whole, fraction = ''] = value.trim().split('.');
return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
}
function decimal(value: bigint): string {
const abs = value < 0n ? -value : value;
return `${value < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`;
}
export type DecisionBalanceInput = {
cash: string;
receivables: string;
inventory: string;
otherCurrentAssets: string;
longTermAssets: string;
accumulatedDepreciation: string;
currentLiabilities: string;
longTermLiabilities: string;
paidCapital: string;
retainedResults: string;
periodResult: string;
};
/** Exact monetary reconciliation; no balancing entry or rounding tolerance. */
export function checkDecisionBalance(input: DecisionBalanceInput) {
const signed = (value: string) =>
value.startsWith('-') ? -money(value.slice(1)) : money(value);
const currentAssets =
money(input.cash) +
money(input.receivables) +
money(input.inventory) +
money(input.otherCurrentAssets);
const netLongTermAssets =
money(input.longTermAssets) - money(input.accumulatedDepreciation);
if (netLongTermAssets < 0n)
throw new Error(
'A depreciação acumulada não pode exceder os activos de longo prazo.',
);
const assets = currentAssets + netLongTermAssets;
const liabilities =
money(input.currentLiabilities) + money(input.longTermLiabilities);
const capital =
money(input.paidCapital) +
signed(input.retainedResults) +
signed(input.periodResult);
const difference = assets - liabilities - capital;
return {
currentAssets: decimal(currentAssets),
netLongTermAssets: decimal(netLongTermAssets),
assets: decimal(assets),
liabilities: decimal(liabilities),
capital: decimal(capital),
liabilitiesAndCapital: decimal(liabilities + capital),
difference: decimal(difference),
balanced: difference === 0n,
error:
difference === 0n
? null
: `Os valores não estão equilibrados: os activos diferem dos passivos e capital em ${decimal(difference < 0n ? -difference : difference)}. Reveja os dados introduzidos.`,
};
}
/** Ratios use reconciled statement data; an absent/zero denominator is unknown. */
export function calculateDecisionRatios(
input: DecisionBalanceInput,
sales: string,
previousSales?: string,
) {
const balance = checkDecisionBalance(input);
if (!balance.balanced) throw new Error(balance.error!);
const ratio = (numerator: string, denominator: string) =>
Number(denominator) === 0
? null
: Number(numerator) / Number(denominator);
const revenue = decimal(money(sales));
const previous =
previousSales === undefined ? null : decimal(money(previousSales));
const profit = input.periodResult.startsWith('-')
? decimal(-money(input.periodResult.slice(1)))
: decimal(money(input.periodResult));
return {
salesGrowth:
previous === null || Number(previous) === 0
? null
: Number(revenue) / Number(previous) - 1,
currentLiquidity: ratio(
balance.currentAssets,
decimal(money(input.currentLiabilities)),
),
debtAssets: ratio(balance.liabilities, balance.assets),
netMargin: ratio(profit, revenue),
returnOnEquity: ratio(profit, balance.capital),
};
}
/** Illustrative allocation, in cents; never a reconstruction of historical months. */
function allocateMonths(total: bigint, weights: bigint[]) {
const denominator = weights.reduce((sum, value) => sum + value, 0n);
const effective = denominator === 0n ? weights.map(() => 1n) : weights;
const divisor = denominator === 0n ? BigInt(weights.length) : denominator;
const rows = effective.map((weight, index) => ({
index,
amount: (total * weight) / divisor,
remainder: (total * weight) % divisor,
}));
let remaining = total - rows.reduce((sum, row) => sum + row.amount, 0n);
for (const row of [...rows].sort((a, b) =>
a.remainder === b.remainder
? a.index - b.index
: a.remainder > b.remainder
? -1
: 1,
)) {
if (remaining === 0n) break;
row.amount += 1n;
remaining -= 1n;
}
return rows.map((row) => row.amount);
}
export function calculateAnnualReferencePlan(plan: AnnualReferencePlan) {
const startupExpenses = plan.startupExpenses.reduce(
(sum, row) => sum + money(row.amount),
0n,
);
const openingCash = money(plan.openingCash);
const assets =
openingCash +
money(plan.otherCurrentAssets) +
money(plan.longTermAssets);
const requiredFunding = startupExpenses + assets;
const availableFunding =
money(plan.ownerCapital) +
money(plan.investorCapital) +
money(plan.loans) +
money(plan.additionalMoney);
// A projection of the required capital is not confirmation of financing.
const capitalToMobilise =
requiredFunding > availableFunding
? requiredFunding - availableFunding
: 0n;
const projectedCapital =
availableFunding + capitalToMobilise - money(plan.loans);
let cash =
openingCash + availableFunding + capitalToMobilise - requiredFunding;
let receivables = 0n;
let operatingLiabilities = 0n;
let vatBalance = 0n;
let accumulatedResults = -startupExpenses;
const years = plan.years.map((year, index) => {
const sales = money(year.sales),
costs = money(year.directCosts);
if (sales === 0n && costs > 0n)
throw new Error(
'Indique as vendas previstas para calcular a margem e o ponto de equilíbrio.',
);
if (sales > 0n && costs >= sales)
throw new Error(
'Com este custo variável não há margem para cobrir os custos fixos. Reveja o custo variável ou o preço.',
);
const grossMargin = sales - costs;
const operatingExpenses =
money(year.payroll) +
money(year.payrollCharges) +
money(year.otherOperatingExpenses);
const operatingProfit = grossMargin - operatingExpenses;
const netProfit =
operatingProfit - money(year.interest) - money(year.taxes);
const cashFlow = money(year.cashReceived) - money(year.cashSpent);
const openingYearCash = cash;
const openingReceivables = receivables;
const openingLiabilities = operatingLiabilities;
const openingResults = accumulatedResults;
const openingVatBalance = vatBalance;
const vatReceived = money(year.vatReceived);
const vatPaid = money(year.vatPaid);
if (
vatReceived > money(year.cashReceived) ||
vatPaid > money(year.cashSpent)
)
throw new Error(
'O IVA de caixa não pode exceder os respectivos recebimentos ou pagamentos.',
);
receivables += sales - (money(year.cashReceived) - vatReceived);
operatingLiabilities +=
costs +
operatingExpenses +
money(year.interest) +
money(year.taxes) -
(money(year.cashSpent) - vatPaid);
accumulatedResults += netProfit;
vatBalance += vatReceived - vatPaid;
cash += cashFlow;
const closingAssets =
cash +
receivables +
money(plan.otherCurrentAssets) +
money(plan.longTermAssets);
const closingCapital = projectedCapital + accumulatedResults;
const closingLiabilities =
operatingLiabilities + money(plan.loans) + vatBalance;
// Explicit model assumptions: repeat the example's aggregate seasonal
// profile; allocate cash net of VAT proportionally to accrued amounts.
const salesWeights = [
680n,
748n,
824n,
905n,
990n,
1095n,
1203n,
1324n,
1458n,
1604n,
1765n,
1941n,
];
const costWeights = [
586n,
644n,
710n,
781n,
860n,
945n,
1038n,
1142n,
1257n,
1383n,
1520n,
1672n,
];
const monthlySales = allocateMonths(sales, salesWeights);
const monthlyCosts = allocateMonths(costs, costWeights);
const equalWeights = salesWeights.map(() => 1n);
const monthlyExpenses = [
year.payroll,
year.payrollCharges,
year.otherOperatingExpenses,
year.interest,
year.taxes,
].map((value) => allocateMonths(money(value), equalWeights));
const accrued = monthlyCosts.map(
(value, i) =>
value + monthlyExpenses.reduce((sum, row) => sum + row[i], 0n),
);
const receipts = allocateMonths(
money(year.cashReceived) - vatReceived,
monthlySales,
);
const payments = allocateMonths(
money(year.cashSpent) - vatPaid,
accrued,
);
const vatReceipts = allocateMonths(vatReceived, salesWeights);
const vatPayments = allocateMonths(vatPaid, salesWeights);
let monthCash = openingYearCash,
monthReceivables = openingReceivables,
monthLiabilities = openingLiabilities,
monthResults = openingResults;
let monthVatBalance = openingVatBalance;
const illustrativeMonths = monthlySales.map((revenue, i) => {
const profit = revenue - accrued[i];
const received = receipts[i] + vatReceipts[i];
const spent = payments[i] + vatPayments[i];
monthCash += received - spent;
monthReceivables += revenue - receipts[i];
monthLiabilities += accrued[i] - payments[i];
monthResults += profit;
monthVatBalance += vatReceipts[i] - vatPayments[i];
const monthAssets =
monthCash +
monthReceivables +
money(plan.otherCurrentAssets) +
money(plan.longTermAssets);
return {
month: i + 1,
sales: decimal(revenue),
directCosts: decimal(monthlyCosts[i]),
grossMargin: decimal(revenue - monthlyCosts[i]),
payroll: decimal(monthlyExpenses[0][i]),
payrollCharges: decimal(monthlyExpenses[1][i]),
otherOperatingExpenses: decimal(monthlyExpenses[2][i]),
operatingExpenses: decimal(
monthlyExpenses[0][i] +
monthlyExpenses[1][i] +
monthlyExpenses[2][i],
),
operatingProfit: decimal(
profit + monthlyExpenses[3][i] + monthlyExpenses[4][i],
),
interest: decimal(monthlyExpenses[3][i]),
taxes: decimal(monthlyExpenses[4][i]),
netProfit: decimal(profit),
cashReceived: decimal(received),
cashSpent: decimal(spent),
cashFlow: decimal(received - spent),
closingCash: decimal(monthCash),
receivables: decimal(monthReceivables),
operatingLiabilities: decimal(monthLiabilities),
vatBalance: decimal(monthVatBalance),
closingAssets: decimal(monthAssets),
closingLiabilities: decimal(
monthLiabilities + monthVatBalance + money(plan.loans),
),
closingCapital: decimal(projectedCapital + monthResults),
balanceDifference: decimal(
monthAssets -
monthLiabilities -
monthVatBalance -
money(plan.loans) -
projectedCapital -
monthResults,
),
};
});
// Keep the unrounded gross-margin fraction in the break-even formula.
const monthlyBreakEven =
grossMargin > 0n
? (Number(operatingExpenses) * Number(sales)) /
(1200 * Number(grossMargin))
: null;
const previousSales =
index > 0 ? money(plan.years[index - 1].sales) : null;
const growthPercent =
previousSales !== null && previousSales > 0n
? (Number(sales - previousSales) / Number(previousSales)) * 100
: null;
return {
year: year.year,
sales: decimal(sales),
directCosts: decimal(costs),
grossMargin: decimal(grossMargin),
grossMarginPercent:
sales > 0n ? (Number(grossMargin) / Number(sales)) * 100 : null,
operatingExpenses: decimal(operatingExpenses),
operatingProfit: decimal(operatingProfit),
netProfit: decimal(netProfit),
netMarginPercent:
sales > 0n ? (Number(netProfit) / Number(sales)) * 100 : null,
cashFlow: decimal(cashFlow),
closingCash: decimal(cash),
receivables: decimal(receivables),
operatingLiabilities: decimal(operatingLiabilities),
closingAssets: decimal(closingAssets),
closingCapital: decimal(closingCapital),
closingLiabilities: decimal(closingLiabilities),
vatBalance: decimal(vatBalance),
balanceDifference: decimal(
closingAssets - closingLiabilities - closingCapital,
),
illustrativeMonths,
monthlyFixedCosts: Number(operatingExpenses) / 1200,
monthlyBreakEven,
growthPercent,
};
});
return {
startupExpenses: decimal(startupExpenses),
assets: decimal(assets),
requiredFunding: decimal(requiredFunding),
availableFunding: decimal(availableFunding),
capitalToMobilise: decimal(capitalToMobilise),
fundingGap: decimal(
requiredFunding > availableFunding
? requiredFunding - availableFunding
: 0n,
),
years,
monthlyStatus: 'por reconciliar' as const,
};
}
File diff suppressed because it is too large Load Diff
+60
View File
@@ -0,0 +1,60 @@
import { mozambiqueCaeSubclasses } from './cae-mozambique-data.ts';
export const mozambiqueCaeSource = {
revision: 'CAE-Rev.2',
title: 'Classificação das Actividades Económicas de Moçambique — INE, 2008',
url: 'https://www.ine.gov.mz/documents/20119/280028/Classificacao%20Das%20Actividades%20Economicas%20de%20Mocambique%20-CAE-REV.2.pdf/2d0e4657-e55c-3254-e815-5d0a8cb513bd?download=true&t=1725451130089&version=1.0',
sha256: 'cb3dee56db5b2c3f12e3071615725051828a9e1eba17662aa5e78d5f3356b0fc',
} as const;
export type PlanCaeSelection = {
code: string;
revision: string;
sourceSha256: string;
};
export const planCaeChoices = mozambiqueCaeSubclasses.map((node) => ({
value: node.code,
label: `${node.code} — ${node.label}`,
keywords: /hotéis/i.test(node.label) ? ['hotel'] : [],
}));
/** An explicit choice only; a sector, product name or forecast never assigns a CAE. */
export function selectPlanCae(code: string): PlanCaeSelection | undefined {
if (!code) return undefined;
if (!mozambiqueCaeSubclasses.some((node) => node.code === code))
throw Error('Seleccione uma subclasse da referência CAE apresentada.');
return {
code,
revision: mozambiqueCaeSource.revision,
sourceSha256: mozambiqueCaeSource.sha256,
};
}
export function describePlanCae(selection: unknown) {
if (selection === undefined || selection === null)
return {
value: 'Não documentado',
source: mozambiqueCaeSource.title,
confirmed: false,
};
const item = selection as Partial<PlanCaeSelection>;
const node = mozambiqueCaeSubclasses.find(
(node) => node.code === item.code,
);
if (
!node ||
item.revision !== mozambiqueCaeSource.revision ||
item.sourceSha256 !== mozambiqueCaeSource.sha256
)
return {
value: 'Classificação guardada por conferir — escolha novamente na referência oficial',
source: mozambiqueCaeSource.title,
confirmed: false,
};
return {
value: `${node.code} — ${node.label}`,
source: `${mozambiqueCaeSource.title}, página PDF ${node.page}. ${mozambiqueCaeSource.url}#page=${node.page}`,
confirmed: true,
};
}
+29
View File
@@ -14,6 +14,7 @@ const catalogueKeys: Record<string, string[]> = {
'legal_regime',
'development_status',
'availability_status',
'activity',
'province',
],
'/oportunidades': [
@@ -49,6 +50,34 @@ const catalogueKeys: Record<string, string[]> = {
'subsector_id',
],
};
/** Remove actual filter keys, including indexed arrays and dependent selections. */
export function catalogueFilterHref(
pageUrl: string,
keys: string[],
remove?: string,
): string {
const url = new URL(pageUrl, 'https://portal.invalid');
const dependencies: Record<string, string[]> = {
province_id: ['district_id', 'admin_post_id', 'locality_id'],
district_id: ['admin_post_id', 'locality_id'],
admin_post_id: ['locality_id'],
sector: ['subsector_id', 'chain_id'],
};
const selected = new Set(
remove ? [remove, ...(dependencies[remove] ?? [])] : keys,
);
const presentKeys = Array.from(url.searchParams.keys());
for (const key of presentKeys)
if (
selected.has(key) ||
[...selected].some((base) =>
key.startsWith(base.replace(/\[\]$/, '') + '['),
)
)
url.searchParams.delete(key);
url.searchParams.delete('page');
return url.pathname + url.search;
}
function family(path: string): string {
if (path.startsWith('/management/portfolio')) return '/carteira';
if (path.startsWith('/management/investment/zones')) return '/zonas';
+520
View File
@@ -0,0 +1,520 @@
import {
forecastBusinessPlan,
businessPlanNumberError,
type BusinessFinancialPlanInput,
} from './business-financial-plan.ts';
import {
reportMoney,
displayReportMoney,
type InvestmentReportTable,
} from './integral-financial-report.ts';
import {
readRows,
type ProjectMilestone,
type TeamNeed,
} from './project-dossier.ts';
const unknown = 'Por determinar';
function structuredRows<T>(raw: string, keys: string[], optional: string[]) {
const rows = readRows<T>(raw, keys).filter((r) =>
optional.every(
(k) =>
!(k in (r as object)) ||
typeof (r as Record<string, unknown>)[k] === 'string',
),
);
try {
const parsed: unknown = JSON.parse(raw || '[]');
return {
rows,
valid:
Array.isArray(parsed) &&
parsed.length === rows.length &&
rows.length <= 100,
};
} catch {
return { rows, valid: false };
}
}
const amount = (s: string | undefined) => {
if (!s || !/^\d+(?:\.\d{1,2})?$/.test(s))
throw Error(
'Indique montantes não negativos com até duas casas decimais.',
);
const [a, b = ''] = s.split('.');
return BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
};
const integer = (s: string | undefined, min: number, max: number) => {
if (
!s ||
!/^\d+$/.test(s) ||
!Number.isSafeInteger(Number(s)) ||
Number(s) < min ||
Number(s) > max
)
throw Error(`Indique um inteiro entre ${min} e ${max}.`);
return Number(s);
};
// Decorate existing parsers without changing accepted values or arithmetic.
const fieldAmount = (value: string | undefined, field: string) => {
try {
return amount(value);
} catch {
throw Error(
`«${field}»: ${businessPlanNumberError(value ?? '') || 'Introduza um montante não negativo com até duas casas decimais (ex.: 25000.00).'}`,
);
}
};
const fieldInteger = (
value: string | undefined,
field: string,
min: number,
max: number,
) => {
try {
return integer(value, min, max);
} catch {
throw Error(
`«${field}»: ${businessPlanNumberError(value ?? '') || `Introduza um número inteiro entre ${min} e ${max}.`}`,
);
}
};
const requireField = (value: string | undefined, field: string) => {
if (!value?.trim())
throw Error(`«${field}»: Preencha este campo para continuar.`);
};
const date = (s: string) =>
/^\d{4}-\d{2}-\d{2}$/.test(s) &&
Number.isFinite(Date.parse(s)) &&
new Date(s).toISOString().slice(0, 10) === s;
const table = (
id: string,
title: string,
headers: string[],
): InvestmentReportTable => ({
id,
title,
headers,
rows: [],
issues: [],
notes: [
'Informação declarada ou hipótese identificada pelo investidor; não confirma procura, contratação ou execução.',
],
});
export function isMarketAnalysis(
value: unknown,
): value is NonNullable<BusinessFinancialPlanInput['marketAnalysis']> {
if (!value || typeof value !== 'object' || Array.isArray(value))
return false;
const m = value as Record<string, unknown>;
return (
typeof m.baseYear === 'string' &&
typeof m.years === 'string' &&
Array.isArray(m.segments) &&
m.segments.length <= 100 &&
m.segments.every(
(s) =>
s &&
typeof s === 'object' &&
['label', 'customers', 'growthPercent', 'basis'].every(
(k) => typeof s[k] === 'string' && s[k].length <= 2000,
),
)
);
}
export function buildComplementaryTables(
draft: Record<string, string | string[]>,
plan: BusinessFinancialPlanInput | null,
) {
const market = table('market-analysis', 'Análise de Mercado', ['Segmento']);
const milestones = table('milestones', 'Marcos', [
'Marco',
'Início',
'Término',
'Responsável',
'Departamento',
'Orçamento',
'Realizado',
]);
const staff = table('personnel', 'Pessoal', ['Função / departamento']);
const m = plan?.marketAnalysis;
const declaredCurrency =
String(draft.currency ?? '') || plan?.currency || unknown;
const sameCurrency =
!draft.currency || !plan?.currency || draft.currency === plan.currency;
milestones.notes.push(`Moeda dos montantes: ${declaredCurrency}.`);
staff.notes.push(`Moeda das remunerações: ${declaredCurrency}.`);
if (!sameCurrency)
staff.issues.push(
`Pessoal / Moeda das remunerações (${declaredCurrency}) difere de Plano financeiro / Moeda (${plan?.currency}). Confira a moeda e os montantes de origem e corrija apenas os campos incorrectos. Enquanto forem moedas diferentes, a reconciliação fica por determinar, sem conversão automática.`,
);
market.notes.push(
'O total é a soma aritmética dos segmentos, sem deduplicação de clientes. Confirme eventuais sobreposições antes de o interpretar como dimensão única do mercado.',
);
try {
if (!isMarketAnalysis(m) || !m.segments.length)
throw Error(
'Indique segmentos, clientes potenciais, crescimento e fonte ou hipótese para completar a análise; os dados guardados não serão substituídos automaticamente.',
);
const year = fieldInteger(
m.baseYear,
'Ano-base de mercado',
1900,
9999,
),
years = fieldInteger(m.years, 'Horizonte de mercado (anos)', 2, 10);
if (year + years - 1 > 9999)
throw Error(
'«Horizonte de mercado (anos)»: Reduza o horizonte ou o ano-base para não exceder o ano 9999.',
);
market.headers.push(
...Array.from({ length: years }, (_, i) => String(year + i)),
'Crescimento anual composto',
);
const totals = Array(years).fill(0) as number[];
for (const [i, s] of m.segments.entries()) {
try {
requireField(s.label, 'Nome do segmento');
requireField(s.basis, 'Fonte e data, ou hipótese ilustrativa');
let clients = fieldInteger(
s.customers,
'Clientes potenciais no ano-base',
0,
Number.MAX_SAFE_INTEGER,
);
if (
typeof s.growthPercent !== 'string' ||
!/^-?\d+(?:\.\d{1,4})?$/.test(s.growthPercent) ||
!Number.isFinite(Number(s.growthPercent)) ||
Number(s.growthPercent) < -100
)
throw Error(
`«Crescimento anual do segmento (%)»: ${businessPlanNumberError(s.growthPercent ?? '', { allowNegative: true }) || 'Introduza uma percentagem igual ou superior a −100%, com até quatro casas decimais.'}`,
);
const growth = Number(s.growthPercent),
series = [clients];
const [whole, fraction = ''] = s.growthPercent
.replace('-', '')
.split('.');
const growthUnits =
(BigInt(whole) * 10000n + BigInt(fraction.padEnd(4, '0'))) *
(s.growthPercent.startsWith('-') ? -1n : 1n);
for (let y = 1; y < years; y++) {
const next =
(BigInt(clients) * (1000000n + growthUnits) + 500000n) /
1000000n;
clients = Number(next);
if (!Number.isSafeInteger(clients))
throw Error(
'A projecção excede a precisão de clientes inteiros.',
);
series.push(clients);
}
series.forEach((n, y) => (totals[y] += n));
if (totals.some((n) => !Number.isSafeInteger(n)))
throw Error(
'O total excede a precisão de clientes inteiros.',
);
const cagr =
series[0] === 0
? unknown
: (
((series.at(-1)! / series[0]) **
(1 / (years - 1)) -
1) *
100
)
.toFixed(2)
.replace('.', ',') + '%';
market.rows.push([s.label, ...series.map(String), cagr]);
market.notes.push(`${s.label}: ${s.basis}`);
if (growth > 100)
market.notes.push(
`${s.label}: crescimento superior a 100%; aviso não bloqueante.`,
);
} catch (e) {
market.issues.push(
`Segmento ${i + 1}: ${(e as Error).message}`,
);
market.rows.push([
s?.label || `Segmento ${i + 1}`,
...Array(years + 1).fill(unknown),
]);
}
}
const complete = market.issues.length === 0;
const cagr =
complete && totals[0] > 0
? (
((totals.at(-1)! / totals[0]) ** (1 / (years - 1)) - 1) *
100
)
.toFixed(2)
.replace('.', ',') + '%'
: unknown;
market.rows.push([
'Total de clientes potenciais',
...totals.map((n) => (complete ? String(n) : unknown)),
cagr,
]);
market.notes.push(
'Clientes potenciais não são vendas. Projecção anual por segmento: ano anterior × (1 + crescimento/100), arredondada à pessoa; crescimento composto calculado entre primeiro e último ano. Nenhuma transferência automática para receitas.',
);
} catch (e) {
market.issues.push((e as Error).message);
}
const raw = String(draft.project_execution_snapshot ?? '');
const milestoneData = structuredRows<ProjectMilestone>(
raw,
['title', 'due_date', 'status', 'planned_amount', 'actual_amount'],
['start_date', 'responsible', 'department'],
);
const rows = milestoneData.rows;
let budget = 0n,
actual = 0n,
budgetComplete = rows.length > 0 && milestoneData.valid,
actualComplete = rows.length > 0 && milestoneData.valid;
if (!milestoneData.valid)
milestones.issues.push(
'Há linhas de marcos não reconhecidas; os totais permanecem por determinar. O original foi preservado.',
);
if (!rows.length)
milestones.issues.push(
raw && raw !== '[]'
? 'O plano de marcos não tem uma estrutura reconhecida; conserve e reveja o original.'
: 'Adicione os marcos aplicáveis para completar a tabela.',
);
for (const [i, r] of rows.entries()) {
let planned = unknown,
realised = unknown;
try {
budget += fieldAmount(r.planned_amount, 'Montante planeado');
planned = reportMoney(amount(r.planned_amount));
} catch (e) {
budgetComplete = false;
milestones.issues.push(
`Marcos / Marco ${i + 1}: ${(e as Error).message}`,
);
}
if (r.actual_amount !== '') {
try {
actual += fieldAmount(r.actual_amount, 'Montante realizado');
realised = reportMoney(amount(r.actual_amount));
} catch (e) {
actualComplete = false;
milestones.issues.push(
`Marcos / Marco ${i + 1}: ${(e as Error).message}`,
);
}
} else actualComplete = false;
for (const [value, label] of [
[r.title, 'Marco ou resultado'],
[r.responsible, 'Responsável pelo marco'],
[r.department, 'Departamento do marco'],
]) {
if (!value?.trim())
milestones.issues.push(
`Marcos / Marco ${i + 1} / «${label}»: Preencha este campo para continuar.`,
);
}
for (const [value, label] of [
[r.start_date, 'Data de início'],
[r.due_date, 'Prazo previsto'],
]) {
if (!date(value ?? ''))
milestones.issues.push(
`Marcos / Marco ${i + 1} / «${label}»: ${!value ? 'Preencha este campo para continuar.' : 'Introduza uma data válida.'}`,
);
}
if (
date(r.start_date ?? '') &&
date(r.due_date) &&
r.start_date! > r.due_date
)
milestones.issues.push(
`Marcos / Marco ${i + 1} / «Prazo previsto»: A data de término não pode ser anterior à data de início.`,
);
milestones.rows.push([
r.title || unknown,
r.start_date || unknown,
r.due_date || unknown,
r.responsible || unknown,
r.department || unknown,
planned,
realised,
]);
}
milestones.rows.push([
'Total',
'',
'',
'',
'',
budgetComplete ? reportMoney(budget) : unknown,
actualComplete ? reportMoney(actual) : unknown,
]);
milestones.notes.push(
'Título, datas, responsável, departamento e orçamento são necessários para completar cada marco; realizado é opcional e vazio não significa zero. Orçamentos não são somados automaticamente ao investimento nem à tesouraria.',
);
const teamData = structuredRows<TeamNeed>(
String(draft.project_team_snapshot ?? ''),
['competency', 'state', 'action', 'estimated_cost', 'due_date'],
[
'department',
'quantity',
'monthly_salary',
'start_month',
'end_month',
],
);
const team = teamData.rows;
const periods = plan?.periods ?? 12;
const year = Number(plan?.reportAssumptions?.startYear);
const calendar =
Number.isInteger(year) &&
year >= 1900 &&
year + Math.floor((periods - 1) / 12) <= 9999;
const labels = Array.from({ length: periods }, (_, i) =>
calendar
? `${year + Math.floor(i / 12)}-${String((i % 12) + 1).padStart(2, '0')}`
: `Mês ${i + 1}`,
);
const years = [
...new Set(
labels.map((l, i) =>
calendar ? l.slice(0, 4) : `Ano ${Math.floor(i / 12) + 1}`,
),
),
];
staff.headers.push(
...labels,
...years.map((y, i) => (periods < (i + 1) * 12 ? `${y} (parcial)` : y)),
);
const totals = Array(periods).fill(0n) as bigint[];
let complete = team.length > 0 && teamData.valid,
headcount = 0;
if (!teamData.valid)
staff.issues.push(
'Há linhas de pessoal não reconhecidas; os totais permanecem por determinar. O original foi preservado.',
);
if (!plan)
staff.issues.push(
'O plano financeiro não está disponível para definir o horizonte e reconciliar a despesa de pessoal.',
);
if (!team.length)
staff.issues.push(
'Adicione funções e respectivas quantidades/remunerações para completar o mapa de pessoal.',
);
for (const [i, r] of team.entries()) {
try {
requireField(r.competency, 'Competência ou função');
requireField(r.department, 'Departamento (mapa de pessoal)');
const quantityError = businessPlanNumberError(r.quantity ?? '', {
integer: true,
});
if (quantityError)
throw Error(
`«Quantidade de pessoas (inteiro)»: ${quantityError}`,
);
const count = fieldInteger(
r.quantity,
'Quantidade de pessoas (inteiro)',
0,
1000000,
),
salary = fieldAmount(
r.monthly_salary,
'Remuneração mensal por pessoa (moeda do projecto)',
),
start = fieldInteger(
r.start_month,
'Mês inicial no plano (1 = Janeiro do ano inicial)',
1,
periods,
),
end = fieldInteger(
r.end_month,
'Mês final no plano',
1,
periods,
);
if (start > end)
throw Error(
'«Mês final no plano»: O mês final não pode ser anterior ao mês inicial. Corrija o mês final ou o mês inicial.',
);
headcount += count;
const values = totals.map((_, j) =>
j + 1 >= start && j + 1 <= end ? salary * BigInt(count) : 0n,
);
values.forEach((v, j) => (totals[j] += v));
const annual = years.map((_, y) =>
values.slice(y * 12, y * 12 + 12).reduce((a, b) => a + b, 0n),
);
staff.rows.push([
`${r.competency} / ${r.department} (${count} pessoas × ${displayReportMoney(reportMoney(salary))}/mês; meses ${start}–${end})`,
...values.map(reportMoney),
...annual.map(reportMoney),
]);
} catch (e) {
complete = false;
staff.issues.push(`Função ${i + 1}: ${(e as Error).message}`);
staff.rows.push([
r.competency || `Função ${i + 1}`,
...Array(periods + years.length).fill(unknown),
]);
}
}
const annual = years.map((_, y) =>
totals.slice(y * 12, y * 12 + 12).reduce((a, b) => a + b, 0n),
);
staff.rows.push([
'Folha salarial prevista',
...[...totals, ...annual].map((v) =>
complete ? reportMoney(v) : unknown,
),
]);
staff.notes.push(
`Postos declarados nas linhas: ${complete ? headcount : unknown}; não representa pessoas únicas nem postos simultâneos. Remuneração mensal por pessoa × quantidade × meses activos; sem encargos presumidos. Competências, resposta, custo de formação/contratação e prazo são opcionais para este mapa e não substituem salários.`,
);
staff.notes.push(
calendar
? 'Calendário: Janeiro do ano inicial do plano financeiro.'
: 'Ano inicial do plano em falta: meses relativos, sem datas presumidas.',
);
if (plan && complete && sameCurrency) {
try {
const f = forecastBusinessPlan(plan);
const expected = f.rows.map((month) =>
amount(month.payrollExpense),
);
const differences = totals.map((v, i) => v - expected[i]);
staff.rows.push([
'Diferença face à despesa de pessoal no plano',
...differences.map(reportMoney),
...years.map((_, y) =>
reportMoney(
differences
.slice(y * 12, y * 12 + 12)
.reduce((a, b) => a + b, 0n),
),
),
]);
if (differences.some((v) => v !== 0n))
staff.issues.push(
'O mapa de pessoal diverge da despesa de pessoal do plano. Reveja os pressupostos; nenhum valor financeiro foi sobrescrito.',
);
} catch {
staff.issues.push(
'Não foi possível reconciliar com o plano financeiro; reveja os dados do plano.',
);
}
} else
staff.issues.push(
'Reconciliação com o plano financeiro por determinar.',
);
return [market, milestones, staff];
}
+9 -3
View File
@@ -39,9 +39,15 @@ function one(rows: Row[], age: string, residence = 'all'): Row | undefined {
export const populationLabel = (n: number | null) =>
n === null
? 'Sem dados'
: new Intl.NumberFormat('pt-MZ', { maximumFractionDigits: 0 }).format(
n,
);
: new Intl.NumberFormat('pt-MZ', {
maximumFractionDigits: 0,
useGrouping: 'always',
}).format(n);
// Formatting only: never write rounded values back to evidence or calculations.
export const populationValueLabel = (value: string) =>
/^-?\d+(\.\d+)?$/.test(value) && Number.isFinite(Number(value))
? populationLabel(Number(value))
: 'Sem dados';
export const percentageLabel = (n: number | null) =>
n === null
? 'Sem dados'
+202
View File
@@ -0,0 +1,202 @@
/** Presentation routing for existing diagnostics only; never validates or edits values. */
export const normaliseFieldLabel = (value: string) =>
value
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, ' ')
.trim();
const routes: [RegExp, string[]][] = [
[
/unidades.*produto|quantidade.*produto/,
['Unidades por mes', 'Unidades mensais base'],
],
[/preco.*produto|preco por unidade/, ['Preço por unidade']],
[/custo variavel.*produto/, ['Custo variável por unidade']],
[/prazo.*dias/, ['Prazo (dias)', 'Prazo contratual (dias)']],
[
/preencha.*montantes.*relatorio/,
[
'Activos fixos anteriores (valor líquido)',
'Outros activos anteriores',
'Capital e resultados anteriores',
],
],
[
/capital discriminado|capital proprio.*coincide|capital do proprietario/,
[
'Capital próprio',
'Capital do proprietário',
'Capital do investidor',
'Capital adicional angariado',
],
],
[
/saldos de abertura|capital e resultados anteriores/,
[
'Capital e resultados anteriores',
'Saldo de caixa inicial',
'Activos fixos anteriores (valor líquido)',
'Outros activos anteriores',
'Existências iniciais',
'Valores a receber',
'Valores a pagar',
],
],
[
/depreciacao.*excede|base depreciavel/,
[
'Base depreciável contabilística',
'Vida útil (meses)',
'Aquisição de activos',
'Activos fixos anteriores (valor líquido)',
],
],
[
/reembolso.*excede|divida declarada/,
['Reembolso de capital', 'Empréstimo recebido', 'Suprimentos'],
],
[
/existencias iniciais.*produto/,
['Existências iniciais', 'Existências iniciais do produto'],
],
[
/stock insuficiente|existencias insuficientes/,
[
'Existências iniciais',
'Encomenda',
'Prazo de recepcao',
'Unidades por mes',
],
],
[
/aquisicoes.*necessidades|arranque.*aquisicao/,
[
'Aquisição de activos',
'Caixa requerida',
'Outros activos correntes requeridos',
'Activos de longo prazo requeridos',
],
],
[/ano inicial/, ['Ano inicial']],
[/fonte.*pressuposto fiscal/, ['Fonte ou pressuposto fiscal']],
[
/imposto estimado.*pagamento fiscal/,
['Imposto estimado', 'Pagamento fiscal'],
],
[
/recebimentos manuais|natureza.*cobrancas/,
['Natureza dos recebimentos manuais', 'Recebimentos mensais'],
],
[
/mapa de pessoal|folha salarial/,
[
'Quantidade',
'Remuneração mensal',
'Meses activos',
'Custo mensal de pessoal',
'Moeda do custo',
],
],
[
/percentagem.*recebiveis|cobrancas.*recebiveis/,
[
'Percentagem do saldo inicial',
'Percentagem de cobrança dos valores a receber de abertura',
],
],
[/recuperacao.*mes|mes unico/, ['Mês']],
[/moeda.*pessoal|moeda da folha/, ['Moeda do custo', 'Moeda do plano']],
[
/ficheiro|snapshot|importa/,
['Importar plano financeiro InvestMoz (.json, até 60 KB)'],
],
];
export function correctionFieldHints(
message: string,
availableLabels?: string[],
): string[] {
const normal = normaliseFieldLabel(message);
const quoted = [...message.matchAll(/«([^»]+)»/g)].map((m) => m[1]);
const exact = quoted.filter((h) =>
availableLabels?.some(
(label) => normaliseFieldLabel(label) === normaliseFieldLabel(h),
),
);
if (exact.length) return exact;
const mapped = routes
.filter(([pattern]) => pattern.test(normal))
.flatMap(([, labels]) => labels);
const prefix = message.split(':')[0].split('/').at(-1)?.trim() ?? '';
return [
...new Set([
...quoted,
...mapped,
...(prefix.length >= 4 ? [prefix] : []),
]),
];
}
export function fieldLabelMatches(
label: string,
hint: string,
availableLabels?: string[] | Set<string>,
): boolean {
const a = normaliseFieldLabel(label),
b = normaliseFieldLabel(hint);
if (
availableLabels instanceof Set
? availableLabels.has(b)
: availableLabels?.some((value) => normaliseFieldLabel(value) === b)
)
return a === b;
return (
!!a &&
!!b &&
(a === b ||
(b.length >= 7 && (a.startsWith(b + ' ') || b.startsWith(a + ' '))))
);
}
/** Match repeated groups by kind as well as index; personnel uses Necessidade in the editor. */
export function correctionGroupMatches(
message: string,
groupName: string,
): boolean {
const match =
/\b(produto|parcela|marco|funcao|necessidade|segmento)\s+(\d+)\b/.exec(
normaliseFieldLabel(message),
);
if (!match) return true;
const kind =
match[1] === 'funcao' || match[1] === 'necessidade'
? '(?:funcao|necessidade)'
: match[1];
return new RegExp(`\\b${kind}\\s+${match[2]}\\b`).test(
normaliseFieldLabel(groupName),
);
}
export function revealCorrectionTarget(target: HTMLElement): void {
const control = target.matches(
'input,select,textarea,button,[contenteditable="true"]',
)
? target
: (target.querySelector<HTMLElement>(
'input:not([type="hidden"]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),[contenteditable="true"]',
) ?? target);
for (
let node: HTMLElement | null = control.parentElement;
node;
node = node.parentElement
)
if (node instanceof HTMLDetailsElement) node.open = true;
control.scrollIntoView({ block: 'center', behavior: 'auto' });
control.focus({ preventScroll: true });
}
export function focusCorrectionId(id: string): void {
let attempts = 0;
const locate = () => {
const target = document.getElementById(id);
if (target) revealCorrectionTarget(target);
else if (++attempts < 10) requestAnimationFrame(locate);
};
requestAnimationFrame(locate);
}
+205
View File
@@ -0,0 +1,205 @@
export type DayTermKind = 'sales' | 'purchases' | 'services';
export type DayTermOperation = {
originId: string;
parcelId: string;
kind: DayTermKind;
month: number;
amount: string;
recognitionBasis: 'monthly' | 'date' | 'unknown';
recognitionDate: string;
originBasis: 'recognition' | 'date' | 'unknown';
originDate: string;
termDays: string;
};
export type DayTerms = {
sales: boolean;
purchases: boolean;
services: boolean;
operations: DayTermOperation[];
};
export const dayTermLabels: Record<DayTermKind, string> = {
sales: 'Vendas e prestações',
purchases: 'Mercadorias recebidas',
services: 'Serviços adquiridos reconhecidos',
};
export function isDayTerms(value: unknown): value is DayTerms {
if (!value || typeof value !== 'object') return false;
const c = value as DayTerms;
return (
['sales', 'purchases', 'services'].every(
(k) => typeof c[k as DayTermKind] === 'boolean',
) &&
Array.isArray(c.operations) &&
c.operations.length <= 240 &&
c.operations.every(
(o) =>
o &&
Object.hasOwn(dayTermLabels, o.kind) &&
Number.isSafeInteger(o.month) &&
o.month >= 1 &&
o.month <= 60 &&
[
'originId',
'parcelId',
'amount',
'recognitionDate',
'originDate',
'termDays',
].every(
(k) =>
typeof o[k as keyof DayTermOperation] === 'string' &&
String(o[k as keyof DayTermOperation]).length <= 160,
) &&
['monthly', 'date', 'unknown'].includes(o.recognitionBasis) &&
['recognition', 'date', 'unknown'].includes(o.originBasis),
)
);
}
function civilDate(value: string): Date | null {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const d = new Date(value + 'T00:00:00.000Z');
return Number.isFinite(d.getTime()) &&
d.toISOString().slice(0, 10) === value
? d
: null;
}
const iso = (d: Date) => d.toISOString().slice(0, 10);
/** Only opted-in channels replace their complete cash agenda. No legacy input is mutated. */
export function buildDayTermSchedule(
config: DayTerms,
year: number,
periods: number,
recognized: Record<DayTermKind, (bigint | null)[]>,
parseAmount: (value: string, label: string) => bigint,
) {
if (!isDayTerms(config))
throw new Error(
'Prazos em dias: estrutura inválida. Reveja operações e parcelas.',
);
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
throw new Error(
'Prazos em dias — Ano inicial: indique o ano do relatório entre 1900 e 9993.',
);
const schedules: Record<DayTermKind, bigint[]> = {
sales: Array(periods).fill(0n),
purchases: Array(periods).fill(0n),
services: Array(periods).fill(0n),
};
const amounts: Record<DayTermKind, bigint[]> = {
sales: Array(periods).fill(0n),
purchases: Array(periods).fill(0n),
services: Array(periods).fill(0n),
};
const seen = new Set<string>();
const origins = new Map<string, string>();
const events = config.operations
.filter((o) => config[o.kind])
.map((o) => {
const label = `Prazos em dias — ${dayTermLabels[o.kind]}, origem ${o.originId || 'por preencher'}, parcela ${o.parcelId || 'por preencher'}`;
const fail = (message: string): never => {
throw new Error(`${label}: ${message}`);
};
if (!o.originId.trim() || !o.parcelId.trim())
fail('preencha a origem e a parcela para impedir duplicações.');
const key = JSON.stringify([
o.kind,
o.originId.trim(),
o.parcelId.trim(),
]);
if (seen.has(key))
fail(
'parcela duplicada; conserve apenas um movimento da mesma origem/parcela.',
);
seen.add(key);
if (o.month > periods)
fail(
'mês de reconhecimento fora do horizonte; reveja o mês ou use a agenda manual.',
);
const start = new Date(Date.UTC(year, o.month - 1, 1));
const recognition =
o.recognitionBasis === 'monthly'
? new Date(Date.UTC(year, o.month, 0))
: o.recognitionBasis === 'date'
? civilDate(o.recognitionDate)
: null;
if (!recognition)
fail(
'data de reconhecimento insuficiente ou inválida; indique uma data ou escolha explicitamente a aproximação mensal. Operação excluída do cálculo automático.',
);
const r = recognition!;
if (
r.getUTCFullYear() !== start.getUTCFullYear() ||
r.getUTCMonth() !== start.getUTCMonth()
)
fail(
'data de reconhecimento não pertence ao mês económico indicado; corrija a data ou o mês.',
);
const origin =
o.originBasis === 'recognition'
? r
: o.originBasis === 'date'
? civilDate(o.originDate)
: null;
if (!origin)
fail(
'data de origem do prazo insuficiente ou inválida; indique o evento contratual ou escolha reconhecimento. Operação excluída do cálculo automático.',
);
if (o.kind === 'sales' && iso(origin!) !== iso(r))
fail(
'origem do recebimento deve ser a venda/prestação reconhecida; corrija a origem.',
);
if (!/^\d+$/.test(o.termDays) || Number(o.termDays) > 365)
fail(
'Prazo (dias): indique um inteiro entre 0 e 365; vazio não significa zero.',
);
const due = new Date(origin!.getTime());
due.setUTCDate(due.getUTCDate() + Number(o.termDays));
if (due < r)
fail(
'vencimento anterior ao reconhecimento: antecipação excluída de F20-A. Use a agenda manual existente; adiantamentos identificados dependem de F20-B.',
);
const amount = parseAmount(o.amount, `${label} — Montante`);
const originKey = JSON.stringify([o.kind, o.originId.trim()]);
const identity = JSON.stringify([
o.month,
iso(r),
o.recognitionBasis,
]);
if (origins.has(originKey) && origins.get(originKey) !== identity)
fail(
'parcelas da mesma origem têm reconhecimentos diferentes; confira origem, mês e data.',
);
origins.set(originKey, identity);
amounts[o.kind][o.month - 1] += amount;
const dueMonth =
(due.getUTCFullYear() - year) * 12 + due.getUTCMonth() + 1;
if (dueMonth <= periods) schedules[o.kind][dueMonth - 1] += amount;
return {
...o,
amount: amount.toString(),
recognition: iso(r),
origin: iso(origin!),
due: iso(due),
dueMonth,
approximate: o.recognitionBasis === 'monthly',
outsideHorizon: dueMonth > periods,
};
});
for (const kind of Object.keys(dayTermLabels) as DayTermKind[]) {
if (!config[kind]) continue;
for (let i = 0; i < periods; i++) {
if (recognized[kind][i] === null)
throw new Error(
`Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: reconhecimento indeterminado; preencha a agenda económica antes de activar este modo.`,
);
if (amounts[kind][i] !== recognized[kind][i])
throw new Error(
`Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: a soma dos montantes das origens/parcelas deve coincidir com o valor reconhecido. Corrija a distribuição; não some uma coorte às operações já individualizadas.`,
);
}
}
return { schedules, events };
}
+26 -4
View File
@@ -86,11 +86,16 @@ function assertForecastReconciles(forecast: Forecast): void {
);
previousOpeningReceivables = openingReceivablesBalance;
totalOpeningReceivablesCollections += openingReceivablesCollections;
const advanceRefund = cents(
forecast.supplierAdvanceLedger?.monthly[row.month - 1].refunded ??
'0',
);
const otherCollections =
row.otherCollections === null
? cents(String(row.cashCollections)) -
salesCollections -
openingReceivablesCollections
openingReceivablesCollections -
advanceRefund
: cents(String(row.otherCollections));
if (otherCollections < 0n)
throw new Error(
@@ -100,7 +105,10 @@ function assertForecastReconciles(forecast: Forecast): void {
const collections = cents(String(row.cashCollections));
if (
collections !==
salesCollections + openingReceivablesCollections + otherCollections
salesCollections +
openingReceivablesCollections +
otherCollections +
advanceRefund
)
throw new Error(
'As cobranças mensais não reconciliam com as suas origens.',
@@ -113,7 +121,9 @@ function assertForecastReconciles(forecast: Forecast): void {
cents(String(row.operatingPayments)) -
cents(String(row.payrollPayments)) -
cents(String(row.interestPayment)) -
cents(String(row.principalRepayment));
cents(String(row.principalRepayment)) +
cents(row.newBorrowings ?? '0') -
cents(row.assetAcquisitions ?? '0');
if (netCashFlow !== cents(String(row.netCashFlow)))
throw new Error(
'O fluxo líquido mensal não reconcilia com recebimentos e pagamentos.',
@@ -260,8 +270,20 @@ export function buildFinancialFiscalBridge(forecast: Forecast) {
(row.salesCollections === null
? 0n
: cents(row.salesCollections)) -
cents(row.openingReceivablesCollections),
cents(row.openingReceivablesCollections) -
cents(
forecast.supplierAdvanceLedger?.monthly[
row.month - 1
].refunded ?? '0',
),
),
...(forecast.supplierAdvanceLedger
? {
supplierAdvanceRefunds:
forecast.supplierAdvanceLedger.monthly[row.month - 1]
.refunded,
}
: {}),
collections: row.cashCollections,
collectionsTotal: row.cashCollections,
salesReceivablesBalance: row.salesReceivablesClosing,
@@ -0,0 +1,115 @@
import {
buildIntegralFinancialTables,
displayReportMoney,
isReportAssumptions,
type InvestmentReportTable,
} from './integral-financial-report.ts';
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
/** The local startup editor owns this error when report tables are unavailable. */
export function startupErrorMessage(plan: BusinessFinancialPlanInput): string {
if (plan.startupAssetRequirements)
try {
calculateStartupAssetRequirements(plan);
} catch (cause) {
return cause instanceof Error
? cause.message
: 'Confira os dados de arranque.';
}
return '';
}
/** Do not hide a forecast error when the report editor itself cannot show the tables. */
export function forecastErrorShownInReport(
plan: BusinessFinancialPlanInput,
error: string,
) {
return (
plan.reportSource !== 'annual_example' &&
(!plan.reportAssumptions ||
isReportAssumptions(plan.reportAssumptions)) &&
buildIntegralFinancialTables(plan).some((table) =>
table.issues.includes(error),
)
);
}
/** Presentation only: preserve the validation result, source issue and every financial value. */
export function financialIssueMessage(issue: string): string {
const shortage =
/^Mês (\d+): existências insuficientes para as vendas declaradas\.$/.exec(
issue,
);
if (shortage)
return `Balanço Projectado / Existências — mês ${shortage[1]}: stock insuficiente para as vendas declaradas. Confira «Existências iniciais», «Encomenda», «Prazo de recepcao» e «Unidades por mes» em «Planear stock por produto», ou as compras agregadas quando esse for o modo escolhido. Consulte a falta por produto no mapa de existências e corrija os pressupostos; as vendas não são reduzidas automaticamente.`;
if (
issue ===
'Existem períodos não reconciliados; reveja as rubricas indicadas.'
)
return 'Balanço Projectado / Diferença do balanço: existem períodos não reconciliados. Consulte os meses desta linha e os diagnósticos específicos apresentados, incluindo existências, depreciação e dívida. Corrija os campos de origem indicados; a diferença, por si só, não identifica um único campo errado e não é compensada automaticamente.';
if (
issue ===
'A soma das cobranças declaradas de recebíveis de abertura não pode exceder 100%.'
)
return 'Fluxo de Caixa / Parcelas adicionais de recebíveis de abertura: a soma excede 100%. Corrija os campos «Percentagem do saldo inicial» das parcelas; inclua também a percentagem da cobrança única, se seleccionada. Não altere o saldo inicial apenas para fazer coincidir a distribuição.';
if (
issue ===
'A soma das liquidações declaradas de valores a pagar não pode exceder 100%.'
)
return 'Fluxo de Caixa / Liquidação de valores a pagar de abertura: a soma excede 100%. Corrija os campos «Percentagem do saldo inicial» dos pagamentos; o total não pode exceder 100%.';
if (issue === 'Cada recuperação deve ter um mês único dentro do horizonte.')
return 'Fluxo de Caixa / Recuperação de vendas vencidas: confira os campos «Mês». Cada recuperação deve ter um mês diferente, dentro do horizonte do plano. Corrija o mês repetido ou remova a linha duplicada; as percentagens são aplicadas ao saldo vencido, não somadas como parcelas do saldo inicial.';
if (
issue ===
'O capital discriminado não corresponde ao capital introduzido. Confira os campos de financiamento.'
)
return 'Financiamento — Capital próprio: este valor não coincide com a soma de Capital do proprietário, Capital do investidor e Capital adicional angariado. Corrija o Capital próprio ou a discriminação em «Crescimento, despesas discriminadas, capital e dividendos».';
if (
issue ===
'A soma das existencias iniciais por produto deve coincidir com as existencias iniciais do plano.'
)
return 'Balanço / Existências iniciais: este valor não coincide com a soma das existências iniciais por produto em «Planear stock por produto». Corrija o total do plano ou as linhas dos produtos.';
if (
issue ===
'As aquisições do cenário não correspondem às necessidades de activos. Confira os valores e adopte as aquisições calculadas.'
)
return 'Arranque / Aquisição de activos: este valor não coincide com as aquisições calculadas em «Caixa e activos necessários ao arranque». Confira os activos requeridos e disponíveis e adopte as aquisições calculadas, ou corrija os pressupostos.';
const opening =
/^Saldos de abertura não reconciliados: diferença (-?\d+\.\d{2})\./.exec(
issue,
);
if (opening)
return `Balanço projectado / Saldos de abertura: diferença ${displayReportMoney(opening[1])}. Confira «Capital e resultados anteriores» face aos saldos anteriores de caixa, activos, existências, valores a receber e valores a pagar. A diferença não permite identificar automaticamente qual saldo está errado; corrija os campos de origem, sem compensação automática.`;
if (
issue ===
'O mapa de pessoal diverge da despesa de pessoal do plano. Reveja os pressupostos; nenhum valor financeiro foi sobrescrito.'
)
return 'Mapa de pessoal / Folha salarial prevista: este valor não coincide com «Pessoal» em Lucros e perdas («Custo mensal de pessoal» no editor). Confira quantidade, remuneração mensal e meses activos de cada função, ou a despesa de pessoal do plano. Consulte a linha «Diferença face à despesa de pessoal no plano»; nenhum valor financeiro foi sobrescrito.';
return issue;
}
/** Group identical issues across tables; callers keep the original issues for validity checks. */
export function financialIssuesForDisplay(tables: InvestmentReportTable[]) {
const groups = new Map<string, { message: string; tables: string[] }>();
for (const table of tables) {
for (const issue of table.issues) {
if (
issue ===
'Existem períodos não reconciliados; reveja as rubricas indicadas.' &&
table.issues.some((detail) =>
detail.startsWith(
'Saldos de abertura não reconciliados: diferença ',
),
)
)
continue;
const message = financialIssueMessage(issue);
const group = groups.get(message) ?? { message, tables: [] };
if (!group.tables.includes(table.title))
group.tables.push(table.title);
groups.set(message, group);
}
}
return [...groups.values()];
}
@@ -0,0 +1,77 @@
/** Explain a rejected snapshot only; never relax the snapshot validator. */
export function financialPlanImportMessage(source: string): string {
const fallback =
'Importação / Plano financeiro: o ficheiro não contém um plano JSON reconhecido pelo InvestMoz. Seleccione um plano exportado pelo portal; o plano actual foi conservado.';
try {
const decoded = JSON.parse(source);
const plan = decoded?.plan;
if (
!plan ||
!Number.isSafeInteger(plan.periods) ||
plan.periods < 1 ||
plan.periods > 60
)
return fallback;
if (
plan.useSupplierPaymentTerms === true &&
plan.useProductInventorySchedule !== true
)
return 'Importação / Fluxo de Caixa / Calcular pagamentos pelo prazo do fornecedor: este modo exige «Planear stock por produto». Active o stock por produto ou desactive os prazos do fornecedor no plano de origem e volte a importar. O plano actual foi conservado.';
const schedules: [string, unknown][] = [
[
'Fluxo de Caixa / Compras para existências',
plan.inventoryPurchaseSchedule,
],
[
'Fluxo de Caixa / Pagamento de compras/variáveis',
plan.monthlyVariableCostPaymentsByPeriod,
],
[
'Lucros e Perdas / Despesas operacionais reconhecidas',
plan.monthlyOperatingExpensesByPeriod,
],
[
'Fluxo de Caixa / Pagamento de despesas operacionais',
plan.monthlyOperatingPaymentsByPeriod,
],
[
'Lucros e Perdas / Custo de pessoal reconhecido',
plan.monthlyPayrollExpenseByPeriod,
],
[
'Fluxo de Caixa / Pagamento de pessoal',
plan.monthlyPayrollPaymentsByPeriod,
],
];
if (Array.isArray(plan.products))
plan.products.forEach(
(product: Record<string, unknown>, index: number) => {
if (!product || typeof product !== 'object') return;
schedules.push(
[
`Previsão de Vendas / Unidades do produto ${index + 1}`,
product.monthlyUnitsByPeriod,
],
[
`Previsão de Vendas / Preço do produto ${index + 1}`,
product.unitPriceByPeriod,
],
[
`Lucros e Perdas / Custo variável do produto ${index + 1}`,
product.unitVariableCostByPeriod,
],
);
},
);
for (const [label, schedule] of schedules) {
if (
Array.isArray(schedule) &&
(schedule.length < plan.periods || schedule.length > 60)
)
return `Importação / ${label}: a agenda contém ${schedule.length} meses; deve cobrir os ${plan.periods} meses do horizonte e ter no máximo 60. Corrija a agenda no plano de origem e volte a importar. O plano actual foi conservado.`;
}
} catch {
return fallback;
}
return fallback;
}
+237
View File
@@ -0,0 +1,237 @@
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
import {
businessPlanWarnings,
type PlanWarningMetrics,
} from './business-plan-guidance.ts';
import {
displayReportMoney,
type InvestmentReportTable,
} from './integral-financial-report.ts';
/** Only use determined values from the same tables/version, never replace missing amounts by zero. */
export function financialPlanWarningMetrics(
plan: BusinessFinancialPlanInput,
tables: InvestmentReportTable[],
) {
const periods = plan.periods ?? 12;
const read = (id: string, label: string, column: number) => {
const t = tables.find((t) => t.id === id);
if (!t || t.issues.length) return undefined;
const value = t.rows.find((r) => r[0] === label)?.[column];
return value && /^-?\d+(?:\.\d{1,2})?$/.test(value)
? Number(value)
: undefined;
};
return Array.from({ length: Math.ceil(periods / 12) }, (_, year) => {
const col = periods + year + 1;
const count = Math.min(12, periods - year * 12);
const sales = read('sales', 'Vendas totais', col);
const costs = read('profit-loss', 'Custo directo', col);
const operating = read('profit-loss', 'Despesas operacionais', col);
const payroll = read('profit-loss', 'Pessoal', col);
const depreciation = read('profit-loss', 'Depreciação', col);
const fixed =
operating !== undefined &&
payroll !== undefined &&
depreciation !== undefined
? operating + payroll + depreciation
: undefined;
const previous = year
? read('sales', 'Vendas totais', col - 1)
: undefined;
const metrics: PlanWarningMetrics = {
currency: plan.currency,
creditDays: inputCreditDays(plan.creditTermDays),
fundingGap:
year === 0
? (read(
'funding',
'Falta para a reserva requerida (projecção)',
1,
) ?? read('funding', 'Diferença por financiar', 1))
: undefined,
netProfit: read('profit-loss', 'Lucro líquido', col),
sales,
directCosts: costs,
monthlyExpenses: fixed === undefined ? undefined : fixed / count,
monthlyBreakEven:
sales &&
costs !== undefined &&
fixed !== undefined &&
sales > costs
? fixed / count / ((sales - costs) / sales)
: undefined,
cash: read('cashflow', 'Caixa final', col),
growthPercent:
previous && sales !== undefined && count === 12
? (sales / previous - 1) * 100
: year === 0 && plan.annualGrowthPercent?.trim()
? Number(plan.annualGrowthPercent)
: undefined,
assets: read('balance', 'Total do activo', col),
liabilities: read('balance', 'Total do passivo', col),
ownAndInvestorCapital: /^\d+(?:\.\d{1,2})?$/.test(plan.equity)
? Number(plan.equity)
: undefined,
};
return {
year: Number(plan.reportAssumptions?.startYear) + year,
metrics,
count,
};
});
}
/** Presentation of already-calculated monthly values; never produces or changes amounts. */
function periodGuidance(
plan: BusinessFinancialPlanInput,
tables: InvestmentReportTable[],
) {
if (plan.reportSource === 'annual_example') return [];
const salesTable = tables.find((t) => t.id === 'sales');
const costsTable = tables.find((t) => t.id === 'profit-loss');
const read = (
table: InvestmentReportTable | undefined,
label: string,
col: number,
) => {
if (!table || table.issues.length) return undefined;
const value = table?.rows.find((row) => row[0] === label)?.[col];
return typeof value === 'string' && /^-?\d+\.\d{2}$/.test(value)
? BigInt(value.replace('.', ''))
: undefined;
};
const noContribution: string[] = [],
missingSales: string[] = [];
for (let col = 1; col <= (plan.periods ?? 12); col++) {
const sales = read(salesTable, 'Vendas totais', col),
cost = read(costsTable, 'Custo directo', col);
const period = (salesTable?.headers[col] ?? `Mês ${col}`).replace(
/^(\d{4})-(\d{2})$/,
'$2/$1',
);
if (
sales !== undefined &&
sales > 0n &&
cost !== undefined &&
cost >= sales
)
noContribution.push(period);
if (
sales === 0n &&
[
'Custo directo',
'Despesas operacionais',
'Pessoal',
'Depreciação',
'Juros',
'Imposto estimado',
].some((label) => {
const value = read(costsTable, label, col);
return value !== undefined && value > 0n;
})
)
missingSales.push(period);
}
return [
...(noContribution.length
? [
{
id: 'period-no-contribution',
message: `Com este custo variável não há margem para cobrir os custos fixos. Reveja o custo variável ou o preço. Períodos a rever: ${noContribution.join(', ')}.`,
},
]
: []),
...(missingSales.length
? [
{
id: 'period-sales-required',
message: `Indique as vendas previstas para calcular a margem e o ponto de equilíbrio. Períodos a rever: ${missingSales.join(', ')}.`,
},
]
: []),
];
}
export function financialPlanWarnings(
plan: BusinessFinancialPlanInput,
tables: InvestmentReportTable[],
) {
const periodWarnings = periodGuidance(plan, tables);
const annualWarnings = financialPlanWarningMetrics(plan, tables).flatMap(
({ year, metrics, count }) => {
// The warning helper compares a full year's sales to a monthly threshold.
const adjusted = {
...metrics,
sales:
metrics.sales === undefined
? undefined
: (metrics.sales * 12) / count,
directCosts:
metrics.directCosts === undefined
? undefined
: (metrics.directCosts * 12) / count,
};
const warnings = businessPlanWarnings(
adjusted,
plan.warningLimits,
).map((w) => ({
...w,
id: `${year}-${w.id}`,
message: `${year}: ${w.message}`,
}));
if (
inputCreditDays(plan.creditTermDays) === undefined &&
(plan.salesCollectionLagMonths ?? 0) > 3
)
warnings.push({
id: `${year}-credit`,
message: `${year}: O prazo de recebimento é superior a três meses no modelo mensal e pressiona a caixa. Confirme o prazo indicado.`,
});
return warnings;
},
);
const cashflow = tables.find((table) => table.id === 'cashflow');
const closing = cashflow?.rows.find((row) => row[0] === 'Caixa final');
if (!cashflow || cashflow.issues.length || !closing)
return [...annualWarnings, ...periodWarnings];
const months = [
'Janeiro',
'Fevereiro',
'Março',
'Abril',
'Maio',
'Junho',
'Julho',
'Agosto',
'Setembro',
'Outubro',
'Novembro',
'Dezembro',
];
const monthlyWarnings = closing
.slice(1, (plan.periods ?? 12) + 1)
.flatMap((value, index) => {
const period = cashflow.headers[index + 1];
const calendar = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(period ?? '');
if (
!calendar ||
!/^-\d+\.\d{2}$/.test(value) ||
BigInt(value.replace('.', '')) >= 0n
)
return [];
return [
{
id: `cash-negative-${period}`,
message: `O saldo de caixa fica negativo em ${months[Number(calendar[2]) - 1]} de ${calendar[1]}: ${displayReportMoney(value)} ${plan.currency}. Reveja os pagamentos, os prazos de crédito ou o financiamento.`,
},
];
});
return [...annualWarnings, ...periodWarnings, ...monthlyWarnings];
}
function inputCreditDays(value: string | undefined) {
return value && /^\d+$/.test(value) && Number(value) <= 365
? Number(value)
: undefined;
}
+176
View File
@@ -0,0 +1,176 @@
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
import {
buildIntegralFinancialTables,
type InvestmentReportTable,
} from './integral-financial-report.ts';
const unknown = 'Por determinar';
const cents = (value: string | undefined): bigint | null => {
if (typeof value !== 'string' || !value || !/^-?\d+\.\d{2}$/.test(value))
return null;
const [a, b] = value.replace('-', '').split('.');
return (BigInt(a) * 100n + BigInt(b)) * (value.startsWith('-') ? -1n : 1n);
};
const declaration = (value: string | undefined) => {
if (
typeof value !== 'string' ||
!value ||
!/^\d+(?:\.\d{1,2})?$/.test(value)
)
return null;
const [a, b = ''] = value.split('.');
return BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
};
/** Approved formulas, rounded only for display; exact statement cents remain unchanged. */
function quotient(n: bigint | null, d: bigint | null, percent: boolean) {
if (n === null || d === null || d === 0n) return unknown;
const sign = n < 0n !== d < 0n ? '-' : '';
const numerator = (n < 0n ? -n : n) * (percent ? 10000n : 100n),
denominator = d < 0n ? -d : d;
const rounded = (numerator + denominator / 2n) / denominator;
return `${rounded === 0n ? '' : sign}${rounded / 100n},${String(rounded % 100n).padStart(2, '0')}${percent ? '%' : '×'}`;
}
export function buildFinancialRatiosTable(
plan: BusinessFinancialPlanInput,
source = buildIntegralFinancialTables(plan),
): InvestmentReportTable {
const balance = source.find((t) => t.id === 'balance'),
sales = source.find((t) => t.id === 'sales'),
profit = source.find((t) => t.id === 'profit-loss');
const headers = balance?.headers.length
? balance.headers
: (sales?.headers ?? ['Indicador']);
const result: InvestmentReportTable = {
id: 'ratios',
title: 'Rácios financeiros',
headers: ['Indicador', ...headers.slice(1)],
rows: [],
issues: [],
notes: [
'Projecções derivadas das mesmas demonstrações; não são indicadores realizados. Fórmulas aprovadas: crescimento = vendas/vendas anteriores − 1; liquidez = activo corrente/passivo corrente; endividamento = passivo/activo; margem líquida = lucro líquido/vendas; retorno do capital = lucro líquido/capital e resultados de fecho.',
'Fluxos anuais são as somas do ano; saldos anuais são os de fecho. Rácios anuais são recalculados, nunca somados ou promediados. Anos parciais não são anualizados; crescimento exige períodos de igual duração. Primeiro período, dados ausentes e denominador zero permanecem por determinar.',
'Activo e passivo correntes são montantes declarados para classificação, não novos movimentos. Não se presumem vencimentos dos empréstimos, outros activos ou subvenções. Inconsistências no balanço bloqueiam os indicadores que dele dependem, sem bloquear os que dependem apenas de vendas/resultados válidos.',
],
};
const cell = (
t: InvestmentReportTable | undefined,
label: string,
i: number,
) => cents(t?.rows.find((r) => r[0] === label)?.[i + 1]);
const rows = Object.fromEntries(
[
'Crescimento das vendas',
'Liquidez corrente',
'Endividamento (passivo/activo)',
'Margem líquida',
'Retorno do capital',
].map((k) => [k, [k]]),
) as Record<string, string[]>;
const periods = plan.periods ?? 12,
settings = plan.ratioCurrentBalances;
const blockedPeriods: string[] = [];
const classificationIssues = new Set<string>();
const settingsValid =
settings &&
Array.isArray(settings.assetsByMonth) &&
Array.isArray(settings.liabilitiesByMonth);
for (let i = 0; i < headers.length - 1; i++) {
const yearIndex = i - periods,
end = i < periods ? i : Math.min(periods, (yearIndex + 1) * 12) - 1;
const length = i < periods ? 1 : Math.min(12, periods - yearIndex * 12);
const previous =
i < periods ? (i === 0 ? -1 : i - 1) : yearIndex === 0 ? -1 : i - 1;
const previousLength = i < periods ? 1 : 12;
const revenue = cell(sales, 'Vendas totais', i),
net = cell(profit, 'Lucro líquido', i);
const salesValid = !!sales && !sales.issues.length;
const profitValid = !!profit && !profit.issues.length;
const prior =
previous < 0 ? null : cell(sales, 'Vendas totais', previous);
rows['Crescimento das vendas'].push(
salesValid &&
length === previousLength &&
prior !== null &&
prior > 0n &&
revenue !== null
? quotient(revenue - prior, prior, true)
: unknown,
);
rows['Margem líquida'].push(
salesValid && profitValid ? quotient(net, revenue, true) : unknown,
);
const assets = cell(balance, 'Total do activo', i),
liabilities = cell(balance, 'Total do passivo', i),
capital = cell(balance, 'Capital e resultados', i);
const consistent =
!!balance &&
!balance.issues.length &&
cell(balance, 'Diferença do balanço', i) === 0n &&
assets !== null &&
liabilities !== null &&
capital !== null &&
assets - liabilities - capital === 0n;
rows['Endividamento (passivo/activo)'].push(
consistent && assets! > 0n
? quotient(liabilities, assets, true)
: unknown,
);
rows['Retorno do capital'].push(
consistent && profitValid ? quotient(net, capital, true) : unknown,
);
const currentAssets = settingsValid
? declaration(settings.assetsByMonth[end])
: null,
currentLiabilities = settingsValid
? declaration(settings.liabilitiesByMonth[end])
: null;
const validCurrent =
currentAssets !== null &&
currentLiabilities !== null &&
assets !== null &&
liabilities !== null &&
currentAssets <= assets &&
currentLiabilities <= liabilities;
rows['Liquidez corrente'].push(
consistent && validCurrent
? quotient(currentAssets, currentLiabilities, false)
: unknown,
);
if (!consistent) blockedPeriods.push(headers[i + 1]);
if (!validCurrent) {
for (const [label, value, total] of [
['Activo corrente', currentAssets, assets],
['Passivo corrente', currentLiabilities, liabilities],
] as const) {
if (value === null)
classificationIssues.add(
`Rácios financeiros / ${label} — mês ${end + 1}: preencha um montante não negativo com até duas casas decimais; indique zero apenas quando aplicável.`,
);
else if (total !== null && value > total)
classificationIssues.add(
`Rácios financeiros / ${label} — mês ${end + 1}: o montante excede o total correspondente do balanço. Corrija este campo de classificação; não altere o balanço para acomodar a classificação.`,
);
}
}
if (capital !== null && capital < 0n)
result.notes.push(
`${headers[i + 1]}: capital negativo; o retorno conserva o sinal matemático e exige interpretação desta situação.`,
);
}
result.rows = Object.values(rows);
if (blockedPeriods.length)
result.issues.push(
`Balanço inconsistente ou indeterminado: liquidez, endividamento e retorno do capital não calculados em ${blockedPeriods.join(', ')}.`,
);
result.issues.push(...classificationIssues);
if (!sales || sales.issues.length)
result.issues.push(
'Vendas indeterminadas: crescimento e margem não calculados.',
);
if (!profit || profit.issues.length)
result.issues.push(
'Resultados indeterminados: margem e retorno do capital não calculados.',
);
return result;
}
File diff suppressed because it is too large Load Diff
+68 -2
View File
@@ -8,6 +8,7 @@ import type {
DossierReportModel,
DossierReportRow,
} from './project-dossier-report.ts';
import { createIntegralFinancialReport } from './project-dossier-report.ts';
export type PreparationReport = {
case_id: string;
@@ -337,11 +338,71 @@ export function investorDossierReportIndex(
return entries.sort((a, b) => a.stage.localeCompare(b.stage));
}
export function investorFinancialReportChoices(
input: InvestorDossierReportInput,
) {
return input.results.filter(
(r) =>
(r.context_opportunity ?? null) === input.context_opportunity &&
typeof r.preparation_snapshot?.business_plan_snapshot ===
'string' &&
r.preparation_snapshot.business_plan_snapshot.trim() !== '',
);
}
export function createInvestorDossierReport(
input: InvestorDossierReportInput,
generatedAt = new Date().toISOString(),
options: {
financialResultId?: string;
omitIntegralFinancial?: boolean;
} = {},
): DossierReportModel {
const index = investorDossierReportIndex(input);
const choices = options.omitIntegralFinancial
? []
: investorFinancialReportChoices(input);
if (
options.financialResultId &&
!choices.some((r) => r.id === options.financialResultId)
)
throw Error(
'O plano financeiro escolhido não pertence a este contexto ou não foi preservado nesta versão.',
);
if (choices.length > 1 && !options.financialResultId)
throw Error(
'Escolha a versão financeira a incluir; os valores de versões diferentes não são misturados.',
);
const chosen = options.financialResultId
? choices.find((r) => r.id === options.financialResultId)
: choices.length === 1
? choices[0]
: undefined;
const integral = chosen
? createIntegralFinancialReport(
{
...chosen.preparation_snapshot,
currency: chosen.currency ?? '',
project_title: input.case.title,
},
{
generatedAt,
version: `Plano guardado v${chosen.draft_version} · contexto v${chosen.context_revision ?? 'por identificar'}`,
},
)
: null;
if (integral && chosen) {
integral.sections[0].paragraphs.unshift(
`Plano preservado em ${chosen.recorded_at}, rascunho v${chosen.draft_version}. As onze tabelas desta secção correspondem apenas à versão escolhida; os outros registos financeiros do dossier mantêm a sua origem e não são somados a este plano.`,
);
if (
chosen.context_revision !== input.investment_context?.revision ||
chosen.context_state === 'review_required'
)
integral.sections[0].paragraphs.unshift(
'Versão histórica: o contexto mudou. Os valores foram preservados e exigem conferência antes de utilização.',
);
}
const supply = input.supply_aggregates?.at(-1);
const row = (
field: string,
@@ -552,6 +613,7 @@ export function createInvestorDossierReport(
'O índice referencia os originais; não incorpora automaticamente os seus anexos nem envia dados a entidades externas.',
],
sections: [
...(integral?.sections ?? []),
{
id: 'supply',
title: 'Actividades existentes — análise agregada',
@@ -764,17 +826,21 @@ export function createInvestorStageReport(
input: InvestorDossierReportInput,
stageCode: string,
generatedAt = new Date().toISOString(),
financialResultId?: string,
): DossierReportModel {
const step = input.steps.find((item) => item.code === stageCode);
if (!step) throw new Error('Etapa não encontrada neste dossier.');
const report = createInvestorDossierReport(input, generatedAt);
const report = createInvestorDossierReport(input, generatedAt, {
financialResultId: stageCode === 'S03' ? financialResultId : undefined,
omitIntegralFinancial: stageCode !== 'S03',
});
const entries = investorDossierReportIndex(input).filter((entry) =>
entry.stage.split(', ').includes(stageCode),
);
const origins = new Set(entries.map((entry) => entry.href));
const specificSections = new Set([
...(stageCode === 'S02' ? ['market'] : []),
...(stageCode === 'S03' ? ['finance'] : []),
...(stageCode === 'S03' ? ['finance', 'financial-report'] : []),
...(['S06', 'S07'].includes(stageCode) ? ['sources'] : []),
]);
return {
+7
View File
@@ -2,6 +2,7 @@ export type NavigationFocus = {
case_id: string;
step_code: string | null;
version: number;
opportunity?: string | null;
};
const key = (actor: number) => `investmoz-navigation-focus:${actor}`;
/** A per-tab hint, never authority to access a dossier. Recheck the server listing. */
@@ -27,6 +28,12 @@ export function readNavigationFocus(
case_id: value.case_id,
step_code: value.step_code,
version: value.version,
...(value.opportunity === null ||
(typeof value.opportunity === 'string' &&
value.opportunity.length > 0 &&
value.opportunity.length <= 100)
? { opportunity: value.opportunity }
: {}),
};
} catch {
return null;
+365
View File
@@ -0,0 +1,365 @@
export type PeriodFinancing = {
id: string;
label: string;
kind: 'bank' | 'shareholder';
drawdowns: { id: string; date: string; amount: string }[];
agenda: {
month: number;
interestExpense: string;
interestPaid: string;
principal: string;
}[];
};
export type PeriodAsset = {
id: string;
label: string;
recognitionDate: string;
paymentDate: string;
cost: string;
depreciable: boolean;
base: string;
lifeMonths: string;
availableDate: string;
linearBasis: string;
};
export type PeriodInvestments = {
enabled: boolean;
financings: PeriodFinancing[];
assets: PeriodAsset[];
};
const text = (v: unknown) => typeof v === 'string' && v.length <= 160;
export function isPeriodInvestments(v: unknown): v is PeriodInvestments {
if (!v || typeof v !== 'object') return false;
const c = v as PeriodInvestments;
return (
typeof c.enabled === 'boolean' &&
Array.isArray(c.assets) &&
c.assets.length <= 60 &&
Array.isArray(c.financings) &&
c.financings.length <= 60 &&
c.assets.every(
(a) =>
a &&
[
'id',
'label',
'recognitionDate',
'paymentDate',
'cost',
'base',
'lifeMonths',
'availableDate',
'linearBasis',
].every((k) => text(a[k as keyof PeriodAsset])) &&
typeof a.depreciable === 'boolean',
) &&
c.financings.every(
(f) =>
f &&
text(f.id) &&
text(f.label) &&
['bank', 'shareholder'].includes(f.kind) &&
Array.isArray(f.drawdowns) &&
f.drawdowns.length <= 60 &&
f.drawdowns.every(
(d) => d && text(d.id) && text(d.date) && text(d.amount),
) &&
Array.isArray(f.agenda) &&
f.agenda.length <= 60 &&
f.agenda.every(
(a) =>
a &&
Number.isSafeInteger(a.month) &&
a.month >= 1 &&
a.month <= 60 &&
['interestExpense', 'interestPaid', 'principal'].every(
(k) => text(a[k as keyof typeof a]),
),
),
)
);
}
export const periodMoney = (v: bigint) =>
`${v < 0n ? '-' : ''}${(v < 0n ? -v : v) / 100n}.${String((v < 0n ? -v : v) % 100n).padStart(2, '0')}`;
const positive = (v: bigint) => (v > 0n ? v : 0n);
function date(v: string, label: string) {
const d = new Date(v + 'T00:00:00Z');
if (
!/^\d{4}-\d{2}-\d{2}$/.test(v) ||
!Number.isFinite(d.getTime()) ||
d.toISOString().slice(0, 10) !== v
)
throw Error(
`${label}: indique uma data individual válida; não se presume o dia pela factura ou pagamento.`,
);
return d;
}
/** New cohorts only. Exact rational cumulative rounding leaves legacy depreciation untouched. */
export function buildPeriodInvestments(
config: PeriodInvestments,
regime: unknown,
year: number,
periods: number,
cents: (v: string, label: string) => bigint,
) {
if (!isPeriodInvestments(config))
throw Error('Movimentos por período: estrutura inválida.');
if (!['PGC-PE', 'PGC-NIRF'].includes(String(regime)))
throw Error(
'Movimentos por período — Regime: escolha explicitamente PGC-PE ou PGC-NIRF no plano.',
);
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
throw Error(
'Movimentos por período — Ano inicial: preencha o ano do relatório entre 1900 e 9993.',
);
const index = (d: Date) =>
(d.getUTCFullYear() - year) * 12 + d.getUTCMonth() + 1;
const rows = Array.from({ length: periods }, (_, i) => ({
month: i + 1,
borrowings: 0n,
bankBalance: 0n,
shareholderBalance: 0n,
principal: 0n,
interestExpense: 0n,
interestPaid: 0n,
interestLiabilities: 0n,
interestAssets: 0n,
acquisitions: 0n,
depreciation: 0n,
grossAssets: 0n,
netAssets: 0n,
}));
const unique = (set: Set<string>, id: string, label: string) => {
if (!id.trim() || set.has(id.trim()))
throw Error(
`${label}: identificador em falta ou duplicado; corrija a origem, sem duplicar movimentos.`,
);
set.add(id.trim());
};
const fundingIds = new Set<string>();
const financings = config.financings.map((f) => {
const label = `Movimentos por período — Financiamento ${f.id || 'por identificar'}`;
unique(fundingIds, f.id, label);
if (!f.label.trim())
throw Error(`${label} — Designação: preencha este campo.`);
const draws = new Set<string>();
const drawdowns = f.drawdowns.map((d) => {
unique(draws, d.id, label + ' — Desembolso');
const when = date(d.date, label + ' — Data do desembolso');
const month = index(when);
if (month < 1)
throw Error(
`${label}: desembolso anterior ao plano; não converter saldos de abertura.`,
);
const amount = cents(d.amount, label + ' — Montante do desembolso');
if (amount <= 0n)
throw Error(
`${label}: montante do desembolso deve ser positivo.`,
);
return { ...d, month, amount, outsideHorizon: month > periods };
});
const months = new Set<number>();
const agenda = f.agenda.map((a) => {
if (months.has(a.month))
throw Error(
`${label}: mês duplicado na agenda; corrija as parcelas.`,
);
months.add(a.month);
return {
month: a.month,
interestExpense: cents(
a.interestExpense,
label + ` — Juros reconhecidos, mês ${a.month}`,
),
interestPaid: cents(
a.interestPaid,
label + ` — Juros pagos, mês ${a.month}`,
),
principal: cents(
a.principal,
label + ` — Principal, mês ${a.month}`,
),
};
});
for (let m = 1; m <= periods; m++)
if (!months.has(m))
throw Error(
`${label}: declare a agenda completa de juros e principal, incluindo zero quando aplicável, no mês ${m}.`,
);
let balance = 0n,
interestBalance = 0n;
const monthly = [];
for (let m = 1; m <= 60; m++) {
const borrowed = drawdowns
.filter((d) => d.month === m)
.reduce((s, d) => s + d.amount, 0n);
const a = agenda.find((a) => a.month === m);
const principal = a?.principal ?? 0n;
balance += borrowed;
if (principal > balance)
throw Error(
`${label} — Principal, mês ${m}: reembolso excede a dívida disponível deste financiamento; não use saldo de outro empréstimo.`,
);
balance -= principal;
interestBalance +=
(a?.interestExpense ?? 0n) - (a?.interestPaid ?? 0n);
if (m <= periods) {
const r = rows[m - 1];
r.borrowings += borrowed;
r.principal += principal;
r.interestExpense += a!.interestExpense;
r.interestPaid += a!.interestPaid;
r.interestLiabilities += positive(interestBalance);
r.interestAssets += positive(-interestBalance);
if (f.kind === 'bank') r.bankBalance += balance;
else r.shareholderBalance += balance;
monthly.push({
month: m,
borrowings: periodMoney(borrowed),
principal: periodMoney(principal),
interestExpense: periodMoney(a!.interestExpense),
interestPaid: periodMoney(a!.interestPaid),
balance: periodMoney(balance),
interestBalance: periodMoney(interestBalance),
});
}
}
return {
...f,
drawdowns: drawdowns.map((d) => ({
...d,
amount: periodMoney(d.amount),
})),
monthly,
};
});
const assetIds = new Set<string>();
const assets = config.assets.map((a) => {
const label = `Movimentos por período — Activo ${a.id || 'por identificar'}`;
unique(assetIds, a.id, label);
if (!a.label.trim())
throw Error(`${label} — Designação: preencha este campo.`);
const recognized = date(a.recognitionDate, label + ' — Reconhecimento'),
paid = date(a.paymentDate, label + ' — Pagamento');
const month = index(recognized);
if (month < 1)
throw Error(
`${label}: aquisição anterior ao plano; preserve os activos iniciais.`,
);
if (paid < recognized)
throw Error(
`${label}: pagamento antecipado excluído, mesmo no mesmo mês; corrija as datas sem converter o adiantamento em pagamento normal.`,
);
if (index(paid) !== month)
throw Error(
`${label}: reconhecimento e pagamento têm de ocorrer no mesmo período; crédito para activos fora deste incremento.`,
);
const cost = cents(a.cost, label + ' — Valor da aquisição'),
base = cents(a.base, label + ' — Base depreciável');
if (cost <= 0n || base > cost)
throw Error(
`${label}: valor positivo e base depreciável não superior ao custo são necessários.`,
);
if (!a.depreciable && base !== 0n)
throw Error(
`${label}: activo não depreciável exige base zero expressamente declarada.`,
);
let start = 0,
life = 0,
days = 1,
availableDays = 1;
if (a.depreciable) {
const available = date(
a.availableDate,
label + ' — Disponibilidade para uso',
);
if (available < recognized)
throw Error(
`${label}: disponibilidade para uso anterior ao reconhecimento; confira as datas.`,
);
if (
!/^\d+$/.test(a.lifeMonths) ||
!Number.isSafeInteger(Number(a.lifeMonths)) ||
Number(a.lifeMonths) < 1
)
throw Error(
`${label} — Vida útil: indique um número inteiro positivo de meses.`,
);
if (regime === 'PGC-NIRF' && !a.linearBasis.trim())
throw Error(
`${label} — Fundamentação linear: indique por que o método linear é adequado a este activo PGC-NIRF.`,
);
start = index(available);
life = Number(a.lifeMonths);
days = new Date(
Date.UTC(
available.getUTCFullYear(),
available.getUTCMonth() + 1,
0,
),
).getUTCDate();
availableDays = days - available.getUTCDate() + 1;
}
const endMonth = a.depreciable
? start + life - (availableDays === days ? 1 : 0)
: null;
const denominator = BigInt(life || 1) * BigInt(days);
let priorTarget = 0n,
gross = 0n;
const monthly = rows.map((r) => {
const acquired = r.month === month ? cost : 0n;
gross += acquired;
let target = 0n;
if (a.depreciable && r.month >= start) {
const k = r.month - start;
const units = BigInt(availableDays) + BigInt(k) * BigInt(days);
const capped = units > denominator ? denominator : units;
target = (base * capped + denominator / 2n) / denominator;
}
const depreciation = target - priorTarget;
priorTarget = target;
r.acquisitions += acquired;
r.depreciation += depreciation;
r.grossAssets += gross;
r.netAssets += gross - target;
return {
month: r.month,
acquisition: periodMoney(acquired),
depreciation: periodMoney(depreciation),
accumulated: periodMoney(target),
net: periodMoney(gross - target),
};
});
return {
...a,
cost: periodMoney(cost),
base: periodMoney(base),
acquisitionMonth: month,
firstMonth: start || null,
lastMonth: endMonth,
firstFraction: a.depreciable ? `${availableDays}/${days}` : null,
outsideHorizon: month > periods,
remainingDepreciation: periodMoney(
month > periods ? base : base - priorTarget,
),
monthly,
};
});
return {
regime: String(regime),
financings,
assets,
monthly: rows.map(
(r) =>
Object.fromEntries(
Object.entries(r).map(([k, v]) => [
k,
typeof v === 'bigint' ? periodMoney(v) : v,
]),
) as { month: number } & Record<
Exclude<keyof typeof r, 'month'>,
string
>,
),
};
}
+83 -3
View File
@@ -16,7 +16,9 @@ import {
TextRun,
WidthType,
} from 'docx';
import { financialIssuesForDisplay } from './financial-issue-presentation.ts';
import JSZip from 'jszip';
import { investmentReportTableSlices } from './integral-financial-report.ts';
import {
classifyDossierAttachment,
MAX_EMBEDDED_TEXT_BYTES,
@@ -448,8 +450,55 @@ export async function generateProjectDossierDocx(
children.push(
new Paragraph({ children: [new TextRun({ text: paragraph })] }),
);
const table = sectionTable(section);
if (table) children.push(table);
if (section.id === 'finance' || section.id === 'financial-report') {
const table = sectionTable(section);
if (table) children.push(table);
} else {
for (const row of section.rows)
children.push(
new Paragraph({
children: [
new TextRun({ text: `${row.field}: `, bold: true }),
new TextRun({ text: row.value }),
new TextRun({
text: `${row.classification}. ${row.origin}`,
break: 1,
size: 18,
}),
],
}),
);
}
for (const issue of financialIssuesForDisplay(section.tables ?? [])) {
children.push(
new Paragraph({ text: issue.message, keepNext: true }),
);
children.push(
new Paragraph({
text: `Tabelas afectadas: ${issue.tables.join('; ')}.`,
keepNext: true,
}),
);
}
for (const entry of section.tables ?? []) {
children.push(
new Paragraph({
text: entry.title,
heading: HeadingLevel.HEADING_2,
keepNext: true,
}),
);
for (const note of entry.notes)
children.push(new Paragraph({ text: note, keepNext: true }));
for (const slice of investmentReportTableSlices(entry)) {
// Word merges adjacent tables and then repeats the first
// table's period header on subsequent pages.
children.push(
new Paragraph({ spacing: { before: 0, after: 0 } }),
);
children.push(tableForDocx(slice.headers, slice.rows));
}
}
if (!section.rows.length && !section.paragraphs.length)
children.push(
new Paragraph('Não há informação fornecida nesta secção.'),
@@ -609,7 +658,7 @@ export async function createProjectDossierPrintHtml(
content.push(`<section><h2>${escapeHtml(section.title)}</h2>`);
for (const paragraph of section.paragraphs)
content.push(`<p>${escapeHtml(paragraph)}</p>`);
if (section.rows.length)
if (section.id === 'financial-report' && section.rows.length)
content.push(
htmlTable(
['Campo', 'Conteúdo', 'Classificação / origem'],
@@ -620,6 +669,37 @@ export async function createProjectDossierPrintHtml(
]),
),
);
for (const issue of financialIssuesForDisplay(section.tables ?? [])) {
content.push(`<p>${escapeHtml(issue.message)}</p>`);
content.push(
`<p>Tabelas afectadas: ${escapeHtml(issue.tables.join('; '))}.</p>`,
);
}
for (const entry of section.tables ?? []) {
content.push(`<h3>${escapeHtml(entry.title)}</h3>`);
for (const note of entry.notes)
content.push(`<p>${escapeHtml(note)}</p>`);
for (const slice of investmentReportTableSlices(entry))
content.push(htmlTable(slice.headers, slice.rows));
}
if (section.rows.length && section.id !== 'financial-report') {
if (section.id === 'finance')
content.push(
htmlTable(
['Campo', 'Conteúdo', 'Classificação / origem'],
section.rows.map((row) => [
row.field,
row.value,
`${row.classification}. ${row.origin}`,
]),
),
);
else
for (const row of section.rows)
content.push(
`<p><strong>${escapeHtml(row.field)}:</strong> ${escapeHtml(row.value)}<br><small>${escapeHtml(row.classification)}. ${escapeHtml(row.origin)}</small></p>`,
);
}
if (section.id === 'annexes') {
const selected = attachments.filter((item) => item.include);
if (!selected.length)
+261 -2
View File
@@ -1,5 +1,17 @@
import { displayValue } from './display-value.ts';
import { describePlanCae } from './cae-mozambique.ts';
import { buildComplementaryTables } from './complementary-report.ts';
import { buildFinancialRatiosTable } from './financial-ratios-report.ts';
import {
buildIntegralFinancialTables,
displayReportMoney,
reportMoney,
type InvestmentReportTable,
} from './integral-financial-report.ts';
import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { financialPlanWarnings } from './financial-plan-warnings.ts';
import { buildAnnualExampleTables } from './annual-example-report.ts';
import { pathStates } from './investor-path.ts';
import {
buildProjectDossierRows,
@@ -34,6 +46,7 @@ export const dossierReportSections = [
export type DossierReportSectionId =
| (typeof dossierReportSections)[number]['id']
| 'financial-report'
| 'supply';
export type DossierReference = {
version: number;
@@ -60,6 +73,7 @@ export type DossierReportRow = {
classification: string;
};
export type DossierReportSection = {
tables?: InvestmentReportTable[];
id: DossierReportSectionId;
title: string;
private: boolean;
@@ -127,7 +141,7 @@ export function formatDossierReportValue(
}
if (field === 'Reconciliação do financiamento') {
const states: Record<string, string> = {
shortfall: 'Financiamento insuficiente',
shortfall: 'Financiamento insuficiente — aviso não bloqueante',
surplus: 'Fontes superiores aos usos previstos',
balanced: 'Fontes e usos equilibrados',
unknown: 'Informação insuficiente',
@@ -512,6 +526,124 @@ function makeSections(
}
const finance = sections.get('finance');
const financialPlan = restoreBusinessPlanSnapshot(
text(draft, 'business_plan_snapshot'),
);
if (finance) {
const cae = describePlanCae(financialPlan?.economicClassification);
finance.rows.push({
field: 'Classificação CAE do plano',
value: cae.value,
classification: cae.confirmed
? 'Escolha declarada pelo investidor; a confirmar documentalmente'
: 'Não documentado ou por conferir',
origin: cae.source,
});
}
const complementaryTables = buildComplementaryTables(draft, financialPlan);
for (const [i, id] of ['market', 'execution', 'team'].entries()) {
const section = sections.get(id as DossierReportSectionId);
if (section) section.tables = [complementaryTables[i]];
}
if (
finance &&
financialPlan?.reportAssumptions &&
financialPlan.reportSource !== 'annual_example'
) {
finance.tables = buildIntegralFinancialTables(financialPlan);
finance.paragraphs.push(
...financialPlanWarnings(financialPlan, finance.tables).map(
(w) => `Aviso não bloqueante — ${w.message}`,
),
);
finance.tables.push(
buildFinancialRatiosTable(financialPlan, finance.tables),
);
const periods = financialPlan.periods ?? 12;
const cell = (id: string, label: string) =>
finance.tables
?.find((table) => table.id === id)
?.rows.find((row) => row[0] === label);
const sumRows = (id: string, labels: string[]) => {
let total = 0n;
for (const label of labels) {
const values = cell(id, label)?.slice(1, periods + 1);
if (
!values ||
values.length !== periods ||
values.some((value) => !/^-?\d+\.\d{2}$/.test(value))
)
return null;
total += values.reduce(
(sum, value) => sum + BigInt(value.replace('.', '')),
0n,
);
}
return reportMoney(total);
};
const gap = cell('funding', 'Diferença por financiar')?.[1];
const values: Record<string, string | undefined | null> = {
'Caixa final projectada': cell('cashflow', 'Caixa final')?.[
periods
],
'Pagamentos no horizonte': sumRows('cashflow', [
'Pagamentos de compras',
'Pagamentos operacionais',
'Pagamentos de pessoal',
'Juros pagos',
'Capital reembolsado',
...(financialPlan.dividendsByPeriod
? ['Dividendos distribuídos']
: []),
'Pagamento de obrigações iniciais',
'Pagamento fiscal estimado',
]),
'Resultado antes de impostos': sumRows('profit-loss', [
'Lucro líquido',
'Imposto estimado',
]),
'Diferença entre usos e fontes': gap,
};
for (const row of finance.rows) {
if (row.field in values) {
const value = values[row.field];
row.value = value
? `${displayReportMoney(value)} ${financialPlan.currency}`
: 'Por determinar — complete os dados complementares do relatório';
row.origin =
'Mesmas tabelas financeiras do relatório, incluindo complementos declarados';
row.classification =
'Projecção calculada; não é valor realizado';
} else if (row.field === 'Reconciliação do financiamento') {
row.value =
!gap || !/^-?\d+\.\d{2}$/.test(gap)
? 'Informação insuficiente'
: formatDossierReportValue(
row.field,
Number(gap) > 0
? 'shortfall'
: Number(gap) < 0
? 'surplus'
: 'balanced',
);
} else if (
row.field === 'Fórmula e valores substituídos' &&
row.origin.includes('Métodos do plano financeiro')
) {
row.value =
'Facturação: quantidade × preço por produto. Caixa final: caixa de abertura após fontes, usos e arranque + recebimentos − pagamentos, incluindo pagamentos fiscais estimados. Os totais usam os mesmos meses e pressupostos das tabelas abaixo.';
}
}
const net = sumRows('profit-loss', ['Lucro líquido']);
finance.rows.push({
field: 'Resultado líquido no horizonte',
value: net
? `${displayReportMoney(net)} ${financialPlan.currency}`
: 'Por determinar',
origin: 'Soma dos mesmos resultados mensais da tabela Lucros e Perdas; arranque reconhecido na abertura',
classification: 'Projecção calculada; não é valor realizado',
});
}
if (
finance &&
['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(
@@ -531,7 +663,54 @@ function makeSections(
});
}
}
if (finance && currentCalculation) {
if (finance && financialPlan?.reportSource === 'annual_example') {
finance.rows = finance.rows
.filter((row) => row.field === 'Classificação CAE do plano')
.map((row) => ({
...row,
classification:
'Contexto do investimento preservado; não é a classificação do exemplo sintético',
}));
finance.paragraphs = [
'Exemplo sintético anual editável, da mesma versão guardada do plano. Não representa dados reais do investidor nem financiamento confirmado. As entradas do investidor permanecem preservadas.',
'Aviso não bloqueante — O detalhe original por serviço e departamento contém diferenças documentais ainda não reconciliadas. Os totais calculados usam os anuais aprovados; as linhas originais são identificadas separadamente e não são somadas como ajustamentos. A reprodução integral dos dados originais não está validada.',
];
try {
const example = buildAnnualExampleTables(financialPlan);
finance.tables = example.filter(
(t) =>
!['market-analysis', 'milestones', 'personnel'].includes(
t.id,
),
);
for (const [sectionId, tableId] of [
['market', 'market-analysis'],
['execution', 'milestones'],
['team', 'personnel'],
] as const) {
const section = sections.get(sectionId);
if (section) {
section.tables = example.filter((t) => t.id === tableId);
section.rows = [];
section.paragraphs = [
'Dados sintéticos de referência do exemplo anual; não são dados reais do investidor.',
];
}
}
} catch (error) {
finance.tables = [];
finance.paragraphs.push(
error instanceof Error
? error.message
: 'Não foi possível recuperar o exemplo.',
);
}
}
if (
finance &&
currentCalculation &&
financialPlan?.reportSource !== 'annual_example'
) {
const snapshot = currentCalculation.snapshot;
const result =
snapshot &&
@@ -755,6 +934,86 @@ export function createProjectDossierReport(
};
}
export const integralFinancialTableIds = [
'startup',
'market-analysis',
'sales',
'milestones',
'personnel',
'funding',
'break-even',
'profit-loss',
'cashflow',
'balance',
'ratios',
] as const;
/** One saved scenario, one report; existing statement builders remain the source. */
export function createIntegralFinancialReport(
draft: Record<string, string | string[]>,
options: Omit<
Parameters<typeof createProjectDossierReport>[1],
'selectedSections'
> = {},
): DossierReportModel {
const report = createProjectDossierReport(draft, {
...options,
selectedSections: new Set(['market', 'finance', 'team', 'execution']),
});
const tables = report.sections.flatMap((s) => s.tables ?? []);
const finance = report.sections.find((s) => s.id === 'finance');
const planCurrency = restoreBusinessPlanSnapshot(
text(draft, 'business_plan_snapshot'),
)?.currency;
const declaredCurrency = text(draft, 'currency');
const summary = new Set([
'Classificação CAE do plano',
'Moeda do plano',
'Horizonte',
'Facturação no horizonte',
'Cobranças no horizonte',
'Pagamentos no horizonte',
'Resultado antes de impostos',
'Caixa final projectada',
'Reconciliação do financiamento',
'Diferença entre usos e fontes',
'Resultado líquido no horizonte',
]);
const ordered = integralFinancialTableIds.flatMap((id) => {
const t = tables.find((t) => t.id === id);
return t ? [t] : [];
});
return {
...report,
sections: [
{
id: 'financial-report',
title: 'Relatório financeiro integral',
private: true,
paragraphs: [
...(planCurrency &&
declaredCurrency &&
planCurrency !== declaredCurrency
? [
`Moedas diferentes: o plano financeiro mantém ${planCurrency}; o projecto declara ${declaredCurrency}. Confira os dados complementares antes de comparar montantes. Não foi feita conversão.`,
]
: []),
`Tabelas incluídas: ${ordered.length} de 11. Os valores provêm do mesmo plano e dos dados complementares guardados.`,
'Projecções para avaliar o investimento; não são contas realizadas nem confirmação de financiamento. Campos em falta e indicadores indeterminados mantêm-se identificados.',
...(finance?.paragraphs.filter(
(p) =>
p.startsWith('Aviso não bloqueante') ||
p.startsWith('Exemplo sintético anual'),
) ?? []),
],
rows:
finance?.rows.filter((row) => summary.has(row.field)) ?? [],
tables: ordered,
},
],
};
}
export function classifyDossierAttachment(
file: Pick<File, 'name' | 'type' | 'size'>,
): DossierAttachmentKind {
+16
View File
@@ -74,6 +74,11 @@ import {
} from './project-readiness.ts';
export type TeamNeed = {
department?: string;
quantity?: string;
monthly_salary?: string;
start_month?: string;
end_month?: string;
competency: string;
state: 'available' | 'gap' | 'unknown';
action: string;
@@ -82,6 +87,9 @@ export type TeamNeed = {
};
export type ProjectMilestone = {
start_date?: string;
responsible?: string;
department?: string;
title: string;
due_date: string;
status: 'planned' | 'in_progress' | 'completed';
@@ -561,6 +569,14 @@ export function buildProjectDossierRows(
const forecast = forecastBusinessPlan(businessPlan);
const source =
'Estimativa calculada pelo plano financeiro a partir de pressupostos declarados; não é demonstração contabilística nem resultado confirmado';
if (businessPlan.annualGrowthPercent?.trim()) {
rows.push([
'Plano financeiro',
'Crescimento anual pretendido',
`${businessPlan.annualGrowthPercent}%`,
'Meta declarada pelo utilizador; não substitui as agendas de vendas introduzidas',
]);
}
rows.push(
[
'Plano financeiro',
+20 -6
View File
@@ -26,6 +26,20 @@ function value(draft: ReadinessDraft, key: string): string {
return typeof current === 'string' ? current.trim() : '';
}
function statusLabel(status: string): string {
const labels: Record<string, string> = {
yes: 'Sim',
no: 'Não',
partial: 'Parcialmente',
unknown: 'Por confirmar',
not_applicable: 'Não aplicável',
in_process: 'Em curso',
not_started: 'Por iniciar',
confirmed: 'Confirmado',
};
return labels[status] ?? 'Não indicado';
}
function rows(
draft: ReadinessDraft,
key: string,
@@ -80,7 +94,7 @@ export function getProjectReadiness(
kind: 'missing',
title: 'Clientes ainda pouco definidos',
origin: customerStatus
? `Estado declarado: ${customerStatus}. Não foi indicada uma descrição de clientes ou beneficiários.`
? `Estado declarado: ${statusLabel(customerStatus)}. Não foi indicada uma descrição de clientes ou beneficiários.`
: 'Não foi indicada uma descrição de clientes ou beneficiários.',
affected: 'Procura e receitas previstas.',
consequence:
@@ -98,7 +112,7 @@ export function getProjectReadiness(
id: 'market-source',
kind: 'unverified',
title: 'Hipótese de mercado sem fonte ou data',
origin: `Foi registada informação de mercado sem origem/data confirmada${customerStatus ? `; estado declarado da conversa com clientes: ${customerStatus}` : ''}.`,
origin: `Foi registada informação de mercado sem origem/data confirmada${customerStatus ? `; estado declarado da conversa com clientes: ${statusLabel(customerStatus)}` : ''}.`,
affected: 'Procura, preço e projecções de vendas.',
consequence:
'A hipótese pode não representar informação actual ou verificável.',
@@ -117,7 +131,7 @@ export function getProjectReadiness(
kind: 'missing',
title: 'Custos do projecto por detalhar',
origin: costStatus
? `Estado declarado: ${costStatus}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}`
? `Estado declarado: ${statusLabel(costStatus)}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}`
: 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.',
affected: 'Investimento necessário, margem e tesouraria.',
consequence: 'O capital necessário pode estar subestimado.',
@@ -141,7 +155,7 @@ export function getProjectReadiness(
: 'missing',
title: 'Prazo de recebimentos por esclarecer',
origin: collectionStatus
? `Estado declarado sobre o prazo de recebimento: ${collectionStatus}.`
? `Estado declarado sobre o prazo de recebimento: ${statusLabel(collectionStatus)}.`
: 'Existe um plano/valor de vendas, mas não foi indicado se o prazo de recebimento é conhecido.',
affected: 'Fluxo de caixa e capital de giro.',
consequence:
@@ -162,7 +176,7 @@ export function getProjectReadiness(
id: 'location',
kind: territory && locationReason ? 'unverified' : 'missing',
title: 'Adequação da localização por esclarecer',
origin: `Estado declarado: ${locationStatus || 'não indicado'}. ${territory ? 'Há uma localização seleccionada.' : 'Não foi seleccionada uma localização territorial.'} ${locationReason ? '' : 'Falta explicar os critérios considerados.'}`,
origin: `Estado declarado: ${statusLabel(locationStatus)}. ${territory ? 'Há uma localização seleccionada.' : 'Não foi seleccionada uma localização territorial.'} ${locationReason ? '' : 'Falta explicar os critérios considerados.'}`,
affected:
'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
consequence:
@@ -205,7 +219,7 @@ export function getProjectReadiness(
origin:
sought > secured
? 'O montante indicado como necessário excede os recursos declarados como mobilizados.'
: `Estado do financiamento declarado: ${fundingStatus || 'não indicado'}; os montantes e condições não permitem confirmar recursos disponíveis.`,
: `Estado do financiamento declarado: ${statusLabel(fundingStatus)}; os montantes e condições não permitem confirmar recursos disponíveis.`,
affected: 'Calendário de investimento e implementação.',
consequence:
'Os recursos podem não estar disponíveis quando forem necessários.',
+88
View File
@@ -0,0 +1,88 @@
/** Public presentation only. Originals, source records and management fields stay intact. */
export function publicReference(
value: string | null | undefined,
): string | null {
const text = value?.trim();
if (!text) return null;
if (/^(?:javascript|data|vbscript|file):/i.test(text)) return null;
if (/^https?:\/\//i.test(text)) {
try {
const u = new URL(text);
if (
u.username ||
u.password ||
/^(?:localhost|127\.|10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|\[?::1)/i.test(
u.hostname,
)
)
return null;
} catch {
return null;
}
if (
/(?:\/(?:outputs|resources\/js|node_modules|tests)\/|\.(?:tsx?|jsx?|sql|py|cjs|mjs)(?:[?#]|$))/i.test(
new URL(text).pathname,
)
)
return null;
return text;
}
if (
/(?:[A-Z]:[\\/]|\\\\|file:\/\/|(?:^|[\s/])(?:outputs|resources|storage|vendor|node_modules|docs|tests|app)[\\/]|\b(?:localhost|127\.0\.0\.\d|0\.0\.0\.0)\b|\.(?:tsx?|jsx?|py|php|sql|md|json|log|cjs|mjs|docx?|xlsx?|xlsm|emf)(?:\b|$)|\b(?:MASTER|AUD|QA|REQ|ME|PN)[-_ ](?:[A-Z]*\d|[A-Z0-9]{6,})|\bgit\s+(?:commit|branch|diff)\b)/i.test(
text,
)
)
return null;
return text;
}
export function uniquePresentation<T>(
rows: readonly T[],
key: (row: T) => string,
): T[] {
const seen = new Set<string>();
return rows.filter((row) => {
const id = key(row);
if (seen.has(id)) return false;
seen.add(id);
return true;
});
}
export function publicLocation(
path: { name: string; location_type?: string }[] | undefined,
fallback: (string | null | undefined)[] = [],
): string {
const names = (path?.length ? path.map((p) => p.name) : fallback).filter(
(v): v is string => !!v?.trim(),
);
return (
names.map((v) => v.trim()).join(' · ') || 'Localização por confirmar'
);
}
export function publicSourceHref(
value: string | null | undefined,
): string | undefined {
const text = publicReference(value);
return text && /^https?:\/\//i.test(text) ? text : undefined;
}
/** Replace known editorial cross-reference codes with their published names. */
export function publicPortfolioText(
value: string,
names: Record<string, string>,
): string {
const codes = Object.keys(names)
.filter(Boolean)
.sort((a, b) => b.length - a.length);
if (!codes.length) return value;
const escaped = codes.map((code) =>
code.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
);
return value.replace(
new RegExp(
`(?<![\\p{L}\\p{N}_])(${escaped.join('|')})(?![\\p{L}\\p{N}_])`,
'gu',
),
(code) => names[code],
);
}
+24
View File
@@ -3,6 +3,10 @@ import { landStatusVisible } from './investment-land-preparation.ts';
import { csvCell } from './csv.js';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
import {
forecastBusinessPlan,
restoreBusinessPlanSnapshot,
} from './business-financial-plan.ts';
export type SimulationDraft = Record<string, string | string[]>;
export const projectQuestionnaireVersion =
@@ -1801,6 +1805,26 @@ export function validateSimulationDraft(
errors.total_investment =
'A soma do capital, dívida e subvenções deve corresponder ao investimento total.';
}
if (
sectionId === 'financial' &&
typeof draft.business_plan_snapshot === 'string' &&
draft.business_plan_snapshot
) {
const plan = restoreBusinessPlanSnapshot(draft.business_plan_snapshot);
if (!plan)
errors.business_plan_snapshot =
'Não foi possível recuperar o plano financeiro. Reveja os dados guardados.';
else {
try {
forecastBusinessPlan(plan);
} catch (cause) {
errors.business_plan_snapshot =
cause instanceof Error
? cause.message
: 'Reveja os dados do plano financeiro antes de continuar.';
}
}
}
return errors;
}
@@ -0,0 +1,70 @@
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
const money = (value: string | undefined, label: string) => {
if (!value || !/^\d+(?:\.\d{1,2})?$/.test(value))
throw Error(
`Indique ${label}, com até duas casas decimais; use zero apenas quando conhecido.`,
);
const [a, b = ''] = value.split('.');
return BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
};
const positive = (n: bigint) => (n > 0n ? n : 0n);
export const startupAmount = (n: bigint) =>
`${n / 100n}.${String(n % 100n).padStart(2, '0')}`;
/** Requirements are targets; the existing cash equation still uses available opening balances and declared financing. */
export function calculateStartupAssetRequirements(
plan: BusinessFinancialPlanInput,
) {
const target = plan.startupAssetRequirements;
if (!target)
throw Error('Indique as necessidades de caixa e activos do arranque.');
const cashRequired = money(target.cashRequired, 'a caixa requerida');
const currentRequired = money(
target.otherCurrentAssetsRequired,
'os activos correntes requeridos',
);
const fixedRequired = money(
target.longTermAssetsRequired,
'os activos de longo prazo requeridos',
);
const cashAvailable = money(
plan.openingCash,
'a caixa disponível antes do financiamento',
);
const currentAvailable = money(
plan.reportAssumptions?.openingOtherAssets,
'os outros activos correntes disponíveis',
);
const fixedAvailable = money(
plan.reportAssumptions?.openingFixedAssets,
'os activos de longo prazo disponíveis',
);
// Inventory and receivables are already initial uses in the approved engine, not acquisitions to count twice.
const currentAlreadyPlanned =
money(plan.inventory, 'as existências iniciais planeadas') +
money(plan.receivables, 'os recebíveis iniciais planeados');
const currentAcquisition = positive(
currentRequired - currentAvailable - currentAlreadyPlanned,
);
const fixedAcquisition = positive(fixedRequired - fixedAvailable);
const startupExpenses = (
plan.reportAssumptions?.startupExpenses ?? []
).reduce((sum, r) => sum + money(r.amount, r.label), 0n);
return {
cashRequired,
currentRequired,
fixedRequired,
cashAvailable,
currentAvailable,
fixedAvailable,
currentAlreadyPlanned,
currentAcquisition,
fixedAcquisition,
assetInvestment: currentAcquisition + fixedAcquisition,
totalRequiredAssets: cashRequired + currentRequired + fixedRequired,
grossRequirements:
startupExpenses + cashRequired + currentRequired + fixedRequired,
startupExpenses,
};
}
+417
View File
@@ -0,0 +1,417 @@
export type AdvanceKind = 'purchases' | 'services';
export type AdvanceEventKind = 'advance' | 'apply' | 'refund' | 'settle';
export type AccountingRegime = 'PGC-PE' | 'PGC-NIRF';
export type SupplierAdvanceOperation = {
originId: string;
parcelId: string;
supplier: string;
kind: AdvanceKind;
amount: string;
recognitionDate: string;
invoiceDate: string;
formalAgreement?: { date: string; reference: string };
ordinaryContract: boolean;
events: {
id: string;
kind: AdvanceEventKind;
date: string;
amount: string;
}[];
};
export type SupplierAdvances = {
regime: '' | AccountingRegime;
purchases: boolean;
services: boolean;
operations: SupplierAdvanceOperation[];
};
export const advanceLabels = {
purchases: 'Mercadorias',
services: 'Serviços adquiridos',
};
export const advanceEventLabels = {
advance: 'Pagamento antecipado',
apply: 'Aplicação do adiantamento',
refund: 'Devolução do adiantamento',
settle: 'Pagamento do remanescente',
};
export function advanceDocumentLabel(status: string) {
const labels: Record<string, string> = {
not_recognized: 'Ainda não reconhecido',
invoice: 'Fornecimento facturado',
formal_agreement: 'Fornecimento formalmente acordado',
pending_documentation:
'Fornecimento reconhecido, documentação por confirmar',
};
return labels[status] ?? 'Por confirmar';
}
const text = (v: unknown) => typeof v === 'string' && v.length <= 160;
export function isSupplierAdvances(v: unknown): v is SupplierAdvances {
if (!v || typeof v !== 'object') return false;
const c = v as SupplierAdvances;
return (
['', 'PGC-PE', 'PGC-NIRF'].includes(c.regime) &&
typeof c.purchases === 'boolean' &&
typeof c.services === 'boolean' &&
Array.isArray(c.operations) &&
c.operations.length <= 120 &&
c.operations.every(
(o) =>
o &&
['purchases', 'services'].includes(o.kind) &&
typeof o.ordinaryContract === 'boolean' &&
(o.formalAgreement === undefined ||
(o.formalAgreement &&
text(o.formalAgreement.date) &&
text(o.formalAgreement.reference))) &&
[
'originId',
'parcelId',
'supplier',
'amount',
'recognitionDate',
'invoiceDate',
].every((k) => text(o[k as keyof SupplierAdvanceOperation])) &&
Array.isArray(o.events) &&
o.events.length <= 60 &&
o.events.every(
(e) =>
e &&
text(e.id) &&
text(e.date) &&
text(e.amount) &&
Object.hasOwn(advanceEventLabels, e.kind),
),
)
);
}
function date(value: string): Date | null {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const d = new Date(value + 'T00:00:00Z');
return Number.isFinite(d.getTime()) &&
d.toISOString().slice(0, 10) === value
? d
: null;
}
const money = (n: bigint) => `${n / 100n}.${String(n % 100n).padStart(2, '0')}`;
/** Projected events only. No accounting postings or actual payments are executed. */
export function buildSupplierAdvances(
config: SupplierAdvances,
year: number,
periods: number,
recognized: Record<AdvanceKind, (bigint | null)[]>,
parse: (value: string, label: string) => bigint,
) {
if (!isSupplierAdvances(config))
throw Error('Adiantamentos: estrutura inválida.');
if (!['PGC-PE', 'PGC-NIRF'].includes(config.regime))
throw Error(
'Adiantamentos: seleccione explicitamente PGC-PE ou PGC-NIRF.',
);
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
throw Error(
'Adiantamentos: preencha o ano inicial do relatório entre 1900 e 9993.',
);
const index = (d: Date) =>
(d.getUTCFullYear() - year) * 12 + d.getUTCMonth();
const start = new Date(Date.UTC(year, 0, 1));
const end = new Date(Date.UTC(year, periods, 1));
const sums = {
purchases: Array<bigint>(periods).fill(0n),
services: Array<bigint>(periods).fill(0n),
};
const payments = {
purchases: Array<bigint>(periods).fill(0n),
services: Array<bigint>(periods).fill(0n),
};
const refunds = Array<bigint>(periods).fill(0n);
const paid = Array<bigint>(periods).fill(0n);
const applied = Array<bigint>(periods).fill(0n);
const settled = Array<bigint>(periods).fill(0n);
const balances = Array.from({ length: periods }, () => ({
advance: 0n,
obligation: 0n,
netDue: 0n,
}));
const seen = new Set<string>();
const origins = new Map<string, string>();
const operations = config.operations
.filter((o) => config[o.kind])
.map((o) => {
const label = `Adiantamentos — ${o.originId || 'operação por preencher'}/${o.parcelId || 'parcela por preencher'}`;
const fail = (message: string): never => {
throw Error(`${label}: ${message}`);
};
if (!o.originId.trim() || !o.parcelId.trim() || !o.supplier.trim())
fail('identifique operação, parcela e fornecedor.');
if (!o.ordinaryContract)
fail(
'confirme contrato ordinário; contratos especiais estão excluídos.',
);
const key = JSON.stringify([
o.kind,
o.originId.trim(),
o.parcelId.trim(),
]);
if (seen.has(key)) fail('operação/parcela duplicada.');
seen.add(key);
const originKey = JSON.stringify([o.kind, o.originId.trim()]);
const identity = JSON.stringify([
o.supplier.trim(),
o.recognitionDate,
o.invoiceDate,
...(config.regime === 'PGC-NIRF'
? [
o.formalAgreement?.date ?? '',
o.formalAgreement?.reference.trim() ?? '',
]
: []),
]);
if (origins.has(originKey) && origins.get(originKey) !== identity)
fail(
'parcelas da mesma operação devem conservar fornecedor, reconhecimento e factura.',
);
origins.set(originKey, identity);
const amount = parse(o.amount, `${label} — valor da operação`);
if (amount <= 0n)
fail('indique um valor positivo para a operação.');
const recognition = o.recognitionDate
? date(o.recognitionDate)
: null;
const invoice = o.invoiceDate ? date(o.invoiceDate) : null;
const agreement =
config.regime === 'PGC-NIRF' && o.formalAgreement
? date(o.formalAgreement.date)
: null;
if (
config.regime === 'PGC-NIRF' &&
o.formalAgreement &&
(!agreement || !o.formalAgreement.reference.trim())
)
fail(
'acordo formal exige data válida e referência identificada da mesma operação; não basta orçamento ou encomenda.',
);
if (o.recognitionDate && !recognition)
fail('data de reconhecimento inválida.');
if (o.invoiceDate && !invoice) fail('data de factura inválida.');
if (recognition && recognition < start)
fail(
'saldos anteriores não podem ser individualizados por inferência; use apenas operações novas do plano.',
);
if (recognition && index(recognition) < periods)
sums[o.kind][index(recognition)] += amount;
const ids = new Set<string>();
const events = o.events
.map((e, order) => {
if (!e.id.trim() || ids.has(e.id.trim()))
fail('identifique cada movimento sem duplicações.');
ids.add(e.id.trim());
const when = date(e.date);
if (!when || when < start)
fail(
'data de movimento insuficiente, inválida ou anterior ao plano.',
);
const value = parse(
e.amount,
`${label} — ${advanceEventLabels[e.kind]}`,
);
if (value <= 0n)
fail('os movimentos devem ter montantes positivos.');
return { ...e, value, when: when!, order };
})
.sort(
(a, b) =>
a.when.getTime() - b.when.getTime() ||
a.order - b.order,
);
let advance = 0n,
obligation = 0n,
isRecognized = false,
eventIndex = 0;
const audit: {
id: string;
kind: AdvanceEventKind;
date: string;
amount: string;
outsideHorizon: boolean;
advance: string;
obligation: string;
netDue: string;
applicationBasis?: {
kind: 'invoice' | 'formal_agreement';
date: string;
reference: string;
};
}[] = [];
const process = (e: (typeof events)[number]) => {
if (!isRecognized && recognition && recognition <= e.when) {
obligation = amount;
isRecognized = true;
}
const m = index(e.when);
const inside = m >= 0 && m < periods;
let applicationBasis:
| {
kind: 'invoice' | 'formal_agreement';
date: string;
reference: string;
}
| undefined;
if (e.kind === 'advance') {
if (isRecognized)
fail(
'pagamento após reconhecimento deve ser remanescente, não novo adiantamento.',
);
advance += e.value;
if (inside) {
payments[o.kind][m] += e.value;
paid[m] += e.value;
}
} else if (e.kind === 'apply') {
const hasInvoice = !!invoice && invoice <= e.when;
const hasAgreement = !!agreement && agreement <= e.when;
if (!isRecognized || (!hasInvoice && !hasAgreement))
fail(
config.regime === 'PGC-NIRF'
? 'aplicação exige reconhecimento e factura ou acordo formal correspondente já datado e identificado, sem antecipar datas.'
: 'aplicação exige reconhecimento e factura correspondente, sem antecipar datas.',
);
if (config.regime === 'PGC-NIRF')
applicationBasis = hasInvoice
? {
kind: 'invoice',
date: o.invoiceDate,
reference: o.originId + '/' + o.parcelId,
}
: {
kind: 'formal_agreement',
date: o.formalAgreement!.date,
reference: o.formalAgreement!.reference,
};
if (e.value > advance || e.value > obligation)
fail(
'aplicação excede o saldo da mesma parcela ou a obrigação reconhecida.',
);
advance -= e.value;
obligation -= e.value;
if (inside) applied[m] += e.value;
} else if (e.kind === 'refund') {
if (e.value > advance)
fail(
'devolução excede o adiantamento não utilizado da mesma parcela.',
);
advance -= e.value;
if (inside) refunds[m] += e.value;
} else {
const netDue =
obligation > advance ? obligation - advance : 0n;
if (!isRecognized || !invoice || invoice > e.when)
fail(
'pagamento do remanescente exige reconhecimento e factura.',
);
if (e.value > netDue)
fail(
'pagamento excede o líquido por liquidar; não volte a pagar o adiantamento associado.',
);
obligation -= e.value;
if (inside) {
payments[o.kind][m] += e.value;
settled[m] += e.value;
}
}
audit.push({
id: e.id,
kind: e.kind,
date: e.date,
amount: money(e.value),
outsideHorizon: !inside,
advance: money(advance),
obligation: money(obligation),
netDue: money(
obligation > advance ? obligation - advance : 0n,
),
...(applicationBasis ? { applicationBasis } : {}),
});
};
const monthly = [];
for (let m = 0; m < periods; m++) {
const boundary = new Date(Date.UTC(year, m + 1, 1));
while (
eventIndex < events.length &&
events[eventIndex].when < boundary
)
process(events[eventIndex++]);
if (!isRecognized && recognition && recognition < boundary) {
obligation = amount;
isRecognized = true;
}
const netDue = obligation > advance ? obligation - advance : 0n;
balances[m].advance += advance;
balances[m].obligation += obligation;
balances[m].netDue += netDue;
monthly.push({
month: m + 1,
advance: money(advance),
obligation: money(obligation),
netDue: money(netDue),
recognized: isRecognized,
...(config.regime === 'PGC-NIRF'
? {
documentaryStatus: !isRecognized
? 'not_recognized'
: invoice && invoice < boundary
? 'invoice'
: agreement && agreement < boundary
? 'formal_agreement'
: 'pending_documentation',
}
: {}),
});
}
// Validate future events as well; they never leak into the last month of cash.
while (eventIndex < events.length) process(events[eventIndex++]);
return {
originId: o.originId,
parcelId: o.parcelId,
supplier: o.supplier,
kind: o.kind,
amount: money(amount),
recognitionDate: o.recognitionDate,
invoiceDate: o.invoiceDate,
...(config.regime === 'PGC-NIRF' && o.formalAgreement
? { formalAgreement: o.formalAgreement }
: {}),
recognitionOutsideHorizon: !recognition || recognition >= end,
monthly,
events: audit,
};
});
for (const kind of ['purchases', 'services'] as const) {
if (!config[kind]) continue;
for (let m = 0; m < periods; m++) {
if (
recognized[kind][m] === null ||
sums[kind][m] !== recognized[kind][m]
)
throw Error(
`Adiantamentos — ${advanceLabels[kind]}, mês ${m + 1}: distribua exactamente o reconhecimento económico por operações/parcelas, sem repetir valores nem converter dados desconhecidos em zero.`,
);
}
}
return {
payments,
refunds,
operations,
monthly: balances.map((b, i) => ({
month: i + 1,
advance: money(b.advance),
obligation: money(b.obligation),
netDue: money(b.netDue),
paid: money(paid[i]),
applied: money(applied[i]),
refunded: money(refunds[i]),
settled: money(settled[i]),
})),
};
}
+228 -117
View File
@@ -1,10 +1,19 @@
import { InstitutionView, type InstitutionDetails } from "@/components/funding-institution";
import { financialCategories, financialTypes } from "@/components/funding-classification";
import { Link, useForm } from "@inertiajs/react";
import { Frame, card, button } from "@/pages/investment/shared";
import { type Programme, windowLabels } from "./shared";
import { useRef, useState } from "react";
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
import {
InstitutionView,
type InstitutionDetails,
} from '@/components/funding-institution';
import {
financialCategories,
financialTypes,
} from '@/components/funding-classification';
import { Link, useForm } from '@inertiajs/react';
import { Frame, card, button } from '@/pages/investment/shared';
import { type Programme, windowLabels } from './shared';
import { useRef, useState } from 'react';
import {
TerritoryFields,
type TerritoryOption,
} from '@/components/investment-territory';
export default function FundingIndex(props: Parameters<typeof Index>[0]) {
return <Index key={JSON.stringify(props.filters)} {...props} />;
@@ -54,35 +63,41 @@ function Index({
territorySelection?: TerritoryOption[];
criteriaErrors?: Record<string, string[]>;
}) {
const [notice, setNotice] = useState("");
const [notice, setNotice] = useState('');
const [searchTerritory, setSearchTerritory] = useState(territorySelection);
const form = useForm({
category: filters.category ?? "",
institution_type: filters.institution_type ?? "",
location_mode: filters.location_mode ?? "coverage",
include_historical: filters.include_historical ?? "0",
context: filters.context ?? "",
opportunity: filters.opportunity ?? "",
need: filters.need ?? "",
q: filters.q ?? "",
kind: filters.kind ?? "",
sector: filters.sector ?? "",
territory: filters.territory ?? "",
province_id: filters.province_id ?? "",
district_id: filters.district_id ?? "",
admin_post_id: filters.admin_post_id ?? "",
locality_id: filters.locality_id ?? "",
category: filters.category ?? '',
institution_type: filters.institution_type ?? '',
location_mode: filters.location_mode ?? 'coverage',
include_historical: filters.include_historical ?? '0',
context: filters.context ?? '',
opportunity: filters.opportunity ?? '',
need: filters.need ?? '',
q: filters.q ?? '',
kind: filters.kind ?? '',
sector: filters.sector ?? '',
territory: filters.territory ?? '',
province_id: filters.province_id ?? '',
district_id: filters.district_id ?? '',
admin_post_id: filters.admin_post_id ?? '',
locality_id: filters.locality_id ?? '',
certainty:
filters.certainty ??
(filters.location_mode === "physical" ? "documented" : "include_unknown"),
state: filters.state ?? "",
(filters.location_mode === 'physical'
? 'documented'
: 'include_unknown'),
state: filters.state ?? '',
});
const applied = useRef(JSON.stringify(form.data));
const criteriaChanged = JSON.stringify(form.data) !== applied.current;
const searchReady = Boolean(
form.data.need && (form.data.territory || form.data.province_id),
);
const typeAllowed = (category: string, type: string) =>
!category ||
category === "other" ||
category === 'other' ||
!type ||
type === "other" ||
type === 'other' ||
(categoryTypes[category] ?? []).includes(type);
return (
<Frame title="Instituições financeiras, fundos e programas de apoio">
@@ -95,25 +110,34 @@ function Index({
A minha selecção
</Link>
<p>
Encontre bancos, seguradoras, fundos e outros parceiros financeiros. Explore as
soluções e os contactos adequados ao seu investimento.
Encontre bancos, seguradoras, fundos e outros parceiros
financeiros. Explore as soluções e os contactos adequados ao seu
investimento.
</p>
<form
className={`${card} flex flex-wrap gap-4 [&_select]:w-full [&_select]:max-w-full [&_select]:min-w-0 [&>label]:w-full [&>label]:max-w-full [&>label]:min-w-0 sm:[&>label]:w-auto`}
onSubmit={(e) => {
e.preventDefault();
form.get("/fundos");
if (!searchReady) return;
form.get('/fundos');
}}
>
{Object.keys(criteriaErrors).length > 0 && (
<aside className="basis-full rounded border border-amber-600 p-3" role="alert">
<h2 className="font-semibold">Reveja esta combinação de critérios</h2>
{Object.entries(criteriaErrors).map(([key, messages]) => (
<p key={key}>{messages.join(" ")}</p>
))}
<aside
className="basis-full rounded border border-amber-600 p-3"
role="alert"
>
<h2 className="font-semibold">
Reveja esta combinação de critérios
</h2>
{Object.entries(criteriaErrors).map(
([key, messages]) => (
<p key={key}>{messages.join(' ')}</p>
),
)}
<p>
A pesquisa não foi executada. Corrija os critérios indicados e volte a
pesquisar.
A pesquisa não foi executada. Corrija os critérios
indicados e volte a pesquisar.
</p>
</aside>
)}
@@ -128,15 +152,16 @@ function Index({
</p>
))}
{form.data.kind &&
form.data.kind !== "institution" &&
form.data.kind !== 'institution' &&
(form.data.category ||
form.data.institution_type ||
form.data.location_mode === "physical") && (
form.data.location_mode === 'physical') && (
<aside className="basis-full rounded border p-3">
<p>
Categoria, tipo de instituição e presença física não identificam um
fundo ou programa. Reveja o tipo de registo ou retire apenas estes
critérios incompatíveis.
Categoria, tipo de instituição e presença física
não identificam um fundo ou programa. Reveja o
tipo de registo ou retire apenas estes critérios
incompatíveis.
</p>
<button
type="button"
@@ -144,16 +169,17 @@ function Index({
onClick={() => {
form.setData({
...form.data,
category: "",
institution_type: "",
location_mode: "coverage",
category: '',
institution_type: '',
location_mode: 'coverage',
});
setNotice(
"Critérios de instituição retirados por sua escolha. Local, sector, necessidade e janela foram preservados.",
'Critérios de instituição retirados por sua escolha. Local, sector, necessidade e janela foram preservados.',
);
}}
>
Manter o fundo/programa e rever os critérios de instituição
Manter o fundo/programa e rever os critérios de
instituição
</button>
</aside>
)}
@@ -164,24 +190,31 @@ function Index({
value={form.data.category}
onChange={(e) => {
const category = e.target.value;
const valid = typeAllowed(category, form.data.institution_type);
const valid = typeAllowed(
category,
form.data.institution_type,
);
if (!valid)
setNotice(
"O tipo anterior não pertence à nova categoria e foi retirado. Escolha um dos tipos aplicáveis.",
'O tipo anterior não pertence à nova categoria e foi retirado. Escolha um dos tipos aplicáveis.',
);
form.setData({
...form.data,
category,
institution_type: valid ? form.data.institution_type : "",
institution_type: valid
? form.data.institution_type
: '',
});
}}
>
<option value="">Todas</option>
{Object.entries(financialCategories).map(([id, label]) => (
<option key={id} value={id}>
{label}
</option>
))}
{Object.entries(financialCategories).map(
([id, label]) => (
<option key={id} value={id}>
{label}
</option>
),
)}
</select>
</label>
<label>
@@ -189,7 +222,9 @@ function Index({
<select
className="block rounded border p-2"
value={form.data.institution_type}
onChange={(e) => form.setData("institution_type", e.target.value)}
onChange={(e) =>
form.setData('institution_type', e.target.value)
}
>
<option value="">Todos</option>
{Object.entries(financialTypes)
@@ -202,7 +237,7 @@ function Index({
<option key={id} value={id}>
{typeAllowed(form.data.category, id)
? label
: "Incompatível: " + label}
: 'Incompatível: ' + label}
</option>
))}
</select>
@@ -210,19 +245,23 @@ function Index({
<label>
<input
type="checkbox"
checked={form.data.include_historical === "1"}
checked={form.data.include_historical === '1'}
onChange={(e) =>
form.setData("include_historical", e.target.checked ? "1" : "0")
form.setData(
'include_historical',
e.target.checked ? '1' : '0',
)
}
/>
Incluir instituições históricas/fundidas, identificadas como tal
Incluir instituições históricas/fundidas, identificadas como
tal
</label>
<label>
Necessidade do processo
<select
className="block rounded border p-2"
value={form.data.need}
onChange={(e) => form.setData("need", e.target.value)}
onChange={(e) => form.setData('need', e.target.value)}
>
<option value="">Todas / por identificar</option>
{Object.entries(needs).map(([id, label]) => (
@@ -233,20 +272,24 @@ function Index({
</select>
</label>
<label>
Palavras-chave
Palavras-chave (opcional)
<input
className="block rounded border p-2"
value={form.data.q}
maxLength={150}
onChange={(e) => form.setData("q", e.target.value)}
onChange={(e) => form.setData('q', e.target.value)}
/>
<span className="block text-sm">
Refine pelo nome ou descrição; este campo não substitui
a localização, categoria ou finalidade.
</span>
</label>
<label>
Tipo de registo a consultar
<select
className="block rounded border p-2"
value={form.data.kind}
onChange={(e) => form.setData("kind", e.target.value)}
onChange={(e) => form.setData('kind', e.target.value)}
>
<option value="">Todos</option>
{Object.entries(kinds).map(([key, name]) => (
@@ -261,7 +304,7 @@ function Index({
<select
className="block rounded border p-2"
value={form.data.sector}
onChange={(e) => form.setData("sector", e.target.value)}
onChange={(e) => form.setData('sector', e.target.value)}
>
<option value="">Todos</option>
{options.sectors.map((item) => (
@@ -272,7 +315,9 @@ function Index({
</select>
</label>
<fieldset className="min-w-0 basis-full">
<legend>Local de interesse — seleccione até ao nível conhecido</legend>
<legend>
Local de interesse — seleccione até ao nível conhecido
</legend>
<label>
Localização a pesquisar
<select
@@ -283,40 +328,52 @@ function Index({
...form.data,
location_mode: e.target.value,
certainty:
e.target.value === "physical"
? "documented"
e.target.value === 'physical'
? 'documented'
: form.data.certainty,
})
}
>
<option value="physical">Sede, balcão ou presença física</option>
<option value="coverage">Cobertura do financiamento/produto</option>
<option value="physical">
Sede, balcão ou presença física
</option>
<option value="coverage">
Cobertura do financiamento/produto
</option>
</select>
</label>
<p className="mb-3 text-sm">
Escolha a província e, se necessário, o distrito. Sede e balcões identificam
onde pode contactar a instituição; a cobertura indica onde o financiamento
se aplica.
Escolha a província e, se necessário, o distrito. Sede e
balcões identificam onde pode contactar a instituição; a
cobertura indica onde o financiamento se aplica.
</p>
<TerritoryFields
initial={territorySelection}
initial={searchTerritory}
showMap={false}
onChange={(path) =>
form.setData({
...form.data,
territory: path.at(-1)?.id ?? "",
territory: path.at(-1)?.id ?? '',
province_id:
path.find((node) => node.location_type === "province")?.id ??
"",
path.find(
(node) =>
node.location_type === 'province',
)?.id ?? '',
district_id:
path.find((node) => node.location_type === "district")?.id ??
"",
path.find(
(node) =>
node.location_type === 'district',
)?.id ?? '',
admin_post_id:
path.find((node) => node.location_type === "admin_post")?.id ??
"",
path.find(
(node) =>
node.location_type === 'admin_post',
)?.id ?? '',
locality_id:
path.find((node) => node.location_type === "locality")?.id ??
"",
path.find(
(node) =>
node.location_type === 'locality',
)?.id ?? '',
})
}
/>
@@ -326,9 +383,13 @@ function Index({
<select
className="block rounded border p-2"
value={form.data.certainty}
onChange={(e) => form.setData("certainty", e.target.value)}
onChange={(e) =>
form.setData('certainty', e.target.value)
}
>
<option value="include_unknown">Incluir e assinalar</option>
<option value="include_unknown">
Incluir e assinalar
</option>
<option value="documented">
Apenas âmbito documentado para os filtros escolhidos
</option>
@@ -339,7 +400,7 @@ function Index({
<select
className="block rounded border p-2"
value={form.data.state}
onChange={(e) => form.setData("state", e.target.value)}
onChange={(e) => form.setData('state', e.target.value)}
>
<option value="">Qualquer estado</option>
{Object.entries(windowLabels).map(([key, label]) => (
@@ -349,52 +410,95 @@ function Index({
))}
</select>
</label>
<button className={button} disabled={form.processing}>
{!searchReady && (
<p id="funding-search-minimum" role="status">
Escolha a localização a pesquisar e a necessidade do
processo antes de pesquisar.
</p>
)}
<button
className={button}
disabled={form.processing || !searchReady}
aria-describedby={
!searchReady ? 'funding-search-minimum' : undefined
}
>
Pesquisar
</button>
</form>
{criteriaChanged && (
<p role="status">
Alterou os critérios. Clique em Pesquisar para os aplicar. Os resultados
anteriores ficam separados abaixo.
Alterou os critérios. Clique em Pesquisar para os aplicar.
Os resultados anteriores ficam separados abaixo.
</p>
)}
<details
open={!criteriaChanged && Object.keys(criteriaErrors).length === 0}
open={
!criteriaChanged && Object.keys(criteriaErrors).length === 0
}
className="space-y-3"
>
<summary>
{Object.keys(criteriaErrors).length
? "Pesquisa não executada — critérios inválidos"
? 'Pesquisa não executada — critérios inválidos'
: criteriaChanged
? "Resultados da pesquisa anterior — não correspondem aos critérios por aplicar"
: "Resultados correspondentes à pesquisa"}
? 'Resultados da pesquisa anterior — não correspondem aos critérios por aplicar'
: 'Resultados correspondentes à pesquisa'}
</summary>
<p className="text-sm">
Explore as instituições e soluções adequadas ao seu investimento. Use os filtros
para encontrar a informação de que precisa.
Explore as instituições e soluções adequadas ao seu
investimento. Use os filtros para encontrar a informação de
que precisa.
</p>
{items.data.length === 0 && Object.keys(criteriaErrors).length === 0 && (
<p>
Não foram encontradas instituições, fundos ou programas publicados que
correspondam a todos os critérios desta pesquisa.
</p>
)}
{items.data.length === 0 &&
Object.keys(criteriaErrors).length === 0 && (
<div className="grid gap-3">
<p>
Não foram encontradas instituições, fundos ou
programas publicados que correspondam a todos os
critérios desta pesquisa.
</p>
{!criteriaChanged &&
filters.location_mode === 'physical' &&
filters.province_id && (
<button
type="button"
className={button}
onClick={() => {
form.setData({
...form.data,
territory: '',
province_id: '',
district_id: '',
admin_post_id: '',
locality_id: '',
});
setSearchTerritory([]);
setNotice(
'Escolha outra província no local a pesquisar. Categoria, tipo e finalidade foram conservados; a localização do investimento no dossier mantém-se.',
);
}}
>
Procurar instituição noutra província
</button>
)}
</div>
)}
{items.data.map((item) => (
<article className={card} key={item.id}>
<h2 className="text-xl font-semibold">
<Link
className="underline"
href={`/fundos/${item.id}?${new URLSearchParams(Object.entries(filters).filter((entry): entry is [string, string] => typeof entry[1] === "string"))}`}
href={`/fundos/${item.id}?${new URLSearchParams(Object.entries(filters).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))}`}
>
{item.payload.title}
</Link>
</h2>
{item.payload.kind === "institution" ? (
{item.payload.kind === 'institution' ? (
<InstitutionView
compact
physicalTerritory={
filters.location_mode === "physical"
filters.location_mode === 'physical'
? filters.territory
: undefined
}
@@ -408,25 +512,30 @@ function Index({
) : (
<>
<p>{item.payload.summary}</p>
<p>Entidade gestora: {item.payload.manager_name}</p>
{Object.entries(item.filter_explanation ?? {}).map(
([key, message]) => (
<p key={key}>{message}</p>
),
)}
<p>
Entidade gestora:{' '}
{item.payload.manager_name}
</p>
{Object.entries(
item.filter_explanation ?? {},
).map(([key, message]) => (
<p key={key}>{message}</p>
))}
</>
)}
{item.payload.kind === "institution" &&
item.payload.windows.length === 0 ? null : item.payload.windows.length ===
0 ? (
{item.payload.kind === 'institution' &&
item.payload.windows.length === 0 ? null : item.payload
.windows.length === 0 ? (
<p>
Não existe uma janela de candidatura confirmada para este programa.
Não existe uma janela de candidatura confirmada
para este programa.
</p>
) : (
<ul>
{item.payload.windows.map((window) => (
<li key={window.code}>
{window.title}: {windowLabels[window.state]}
{window.title}:{' '}
{windowLabels[window.state]}
</li>
))}
</ul>
@@ -439,10 +548,12 @@ function Index({
<Link
key={index}
href={link.url}
aria-current={link.active ? "page" : undefined}
aria-current={link.active ? 'page' : undefined}
className="underline"
>
{link.label.replace(/&laquo;/g, "«").replace(/&raquo;/g, "»")}
{link.label
.replace(/&laquo;/g, '«')
.replace(/&raquo;/g, '»')}
</Link>
) : null,
)}
@@ -272,7 +272,7 @@ export default function BusinessMarketplace({
zone: 'Regime de zona',
sector: 'Setor associado',
activity:
'Subsector ou atividade',
'Subsector ou actividade',
} as Record<string, string>
)[id] ?? id,
})),
@@ -299,7 +299,7 @@ export default function BusinessMarketplace({
],
[
'subsector_id',
'Subsector ou atividade',
'Subsector ou actividade',
classificationOptions.targets
.activity ?? [],
],
@@ -361,7 +361,10 @@ export default function BusinessMarketplace({
)}
<ul className="grid gap-4 md:grid-cols-2">
{results.data.map((record) => (
<li className={card} key={record.id}>
<li
className={`${card} flex min-w-0 flex-col gap-3 [overflow-wrap:anywhere]`}
key={record.id}
>
<p>
{businessModalities[record.modality] ??
'Modalidade por indicar'}
@@ -400,6 +403,17 @@ export default function BusinessMarketplace({
{record.objective}
</p>
)}
<nav
aria-label={`Acções de ${record.title}`}
className="mt-auto flex flex-wrap gap-3"
>
<Link
className="underline"
href={`/negocios/${record.slug}${returnQuery ? `?${returnQuery}` : ''}`}
>
Consultar ficha
</Link>
</nav>
</li>
))}
</ul>
@@ -1175,7 +1175,6 @@ export default function Catalogue({
className="catalogue-territorial-link"
>
<span className="text-sm">
{d.content.code} ·{' '}
{d.cluster_id
? 'Cluster'
: d.corridor_id
@@ -8,7 +8,20 @@ import {
type CompanyAnswers,
} from '@/lib/company-comparison';
const comparisonIntroduction =
'Compare alternativas para discutir a constituição; não existe uma forma universalmente preferível.';
type Question = { label: string; options: Record<string, string> };
const questionThemes: Record<string, string> = {
purpose: 'Organização do pedido',
participants: 'Titulares, sócios e accionistas',
participation: 'Participações',
capital: 'Capital e contribuições',
management: 'Gestão',
responsibility: 'Responsabilidade limitada',
listing: 'Negociação em Bolsa',
regulated: 'Regras profissionais ou sectoriais',
preferred: 'Alternativa a aprofundar',
};
type Result = {
engine_version: string;
source: {
@@ -134,10 +147,7 @@ function Comparator(props: Props) {
</Link>
</p>
)}
<p>
Compare a estrutura pretendida e os pontos a esclarecer antes de
preparar o acto constitutivo.
</p>
<p>{comparisonIntroduction}</p>
{saved && (
<p>
{historical
@@ -178,32 +188,46 @@ function Comparator(props: Props) {
{Object.entries(definition.questions).map(
([key, question]) =>
active.includes(key) ? (
<label key={key} className="grid gap-1">
{question.label}
<select
className={input}
name={`answers[${key}]`}
value={answers[key] ?? 'unknown'}
disabled={busy}
onChange={(e) => {
setAnswers({
...answers,
[key]: e.target.value,
});
setDirty(true);
operation.current =
createOperationKey();
}}
>
{Object.entries(
question.options,
).map(([code, label]) => (
<option key={code} value={code}>
{label}
</option>
))}
</select>
</label>
<fieldset
key={key}
className="min-w-0 rounded border p-3"
>
<legend className="px-1 font-semibold">
{questionThemes[key] ??
question.label}
</legend>
<label className="grid gap-1">
{question.label}
<select
className={input}
name={`answers[${key}]`}
value={
answers[key] ?? 'unknown'
}
disabled={busy}
onChange={(e) => {
setAnswers({
...answers,
[key]: e.target.value,
});
setDirty(true);
operation.current =
createOperationKey();
}}
>
{Object.entries(
question.options,
).map(([code, label]) => (
<option
key={code}
value={code}
>
{label}
</option>
))}
</select>
</label>
</fieldset>
) : (
<input
key={key}
@@ -282,13 +306,14 @@ function Comparator(props: Props) {
<h2 className="text-lg font-semibold">
Alternativas e pontos a conferir
</h2>
<p>{result.route}</p>
{result.route.trim() !== comparisonIntroduction && (
<p>{result.route}</p>
)}
{result.pending.length > 0 && (
<p>
Por esclarecer:{' '}
{result.pending
.map((key) => result.questions[key]?.label ?? key)
.join(' · ')}
Há {result.pending.length} temas por esclarecer nas
respostas. Pode completar os campos acima para
aprofundar a comparação.
</p>
)}
<div className="grid gap-4 md:grid-cols-2">
+23 -1
View File
@@ -24,6 +24,7 @@ function DemographySelection({
territories,
sectors,
sectorReadings = [],
entrySector,
}: {
evidence: DemographicAnalysis;
filters: {
@@ -44,6 +45,7 @@ function DemographySelection({
href: string;
analysis: SectorAnalysis;
}[];
entrySector?: string | null;
}) {
const [selected, setSelected] = useState(filters.territories ?? []);
const [province, setProvince] = useState('');
@@ -211,6 +213,13 @@ function DemographySelection({
</div>
</form>
<DemographicEvidence evidence={evidence} />
{filters.sector === 'tourism' && (
<p>
Os dados de população constituem contexto territorial. Não
há nesta consulta estatísticas sectoriais de Turismo que
permitam avaliar a procura turística por distrito.
</p>
)}
{evidence.territories.length > 0 && (
<section className="space-y-3 rounded border p-4">
<h2 className="text-xl font-semibold">
@@ -227,7 +236,11 @@ function DemographySelection({
className="block py-2 underline"
href={
'/investimentos/iniciar?source=' +
encodeURIComponent('territory:' + t.id)
encodeURIComponent('territory:' + t.id) +
(entrySector
? '&sector=' +
encodeURIComponent(entrySector)
: '')
}
>
Preparar ideia em {t.name}
@@ -235,6 +248,15 @@ function DemographySelection({
))}
</section>
)}
{filters.sector &&
filters.sector !== 'general' &&
sectorReadings.length === 0 && (
<p>
Não há ideias documentadas compatíveis com o sector
seleccionado nesta consulta. Pode preparar a sua própria
ideia, sem substituir o sector escolhido.
</p>
)}
{sectorReadings.map((reading) => (
<section key={reading.href} className="space-y-3">
<h2 className="text-xl font-semibold">{reading.title}</h2>
+19 -5
View File
@@ -1,3 +1,5 @@
import PublicReference from '@/components/public-reference';
import { publicReference } from '@/lib/public-presentation';
import { ProactiveSummary } from '@/components/proactive-investment';
import DemographicContext from '@/components/demographic-context';
import EducationalGuides from '@/components/educational-guides';
@@ -186,9 +188,13 @@ export default function Detail({
/>
<DemographicContext
key={c.primary_territory_path?.at(-1)?.id}
territoryId={c.primary_territory_path
?.filter((t) => ['province', 'district'].includes(t.location_type))
.at(-1)?.id}
territoryId={
c.primary_territory_path
?.filter((t) =>
['province', 'district'].includes(t.location_type),
)
.at(-1)?.id
}
/>
{c.primary_territory_path &&
c.primary_territory_path.length > 0 && (
@@ -282,7 +288,15 @@ export default function Detail({
{z.association_type === 'official'
? 'Associação documental validada'
: 'Relação ' + z.association_type}{' '}
· Fonte: {z.source_reference}
{publicReference(z.source_reference) && (
<>
{' '}
· Fonte:{' '}
<PublicReference
value={z.source_reference}
/>
</>
)}
</p>
))}
<p>
@@ -335,7 +349,7 @@ export default function Detail({
['Modelo de negócio', c.profile.business_model],
['Requisitos', c.profile.requirements],
['Riscos', c.profile.risks],
['Fonte', c.profile.source_reference],
['Fonte', publicReference(c.profile.source_reference)],
].map(([label, text]) => (
<div key={label}>
<h3 className="font-bold">{label}</h3>
+3 -2
View File
@@ -1,3 +1,4 @@
import { publicReference } from '@/lib/public-presentation';
import { useState } from 'react';
import { api, button, card } from './shared';
@@ -81,7 +82,7 @@ export default function ZoneMap({ id }: { id: string }) {
<g key={f.id}>
<title>
{f.properties.purpose} ·{' '}
{f.properties.source}
{publicReference(f.properties.source)}
</title>
{rings(f.geometry.coordinates).map((ring, i) =>
ring.length === 1 ? (
@@ -113,7 +114,7 @@ export default function ZoneMap({ id }: { id: string }) {
{features.map((f) => (
<li key={f.id}>
{f.properties.purpose} · Fonte:{' '}
{f.properties.source} · Data:{' '}
{publicReference(f.properties.source)} · Data:{' '}
{f.properties.observed_at}
</li>
))}
+43 -42
View File
@@ -1,3 +1,6 @@
import PublicSourceList from '@/components/public-source-list';
import PublicReference from '@/components/public-reference';
import { publicReference } from '@/lib/public-presentation';
import ParkDetailsEditor, {
ParkDetailsPublic,
emptyParkDetails,
@@ -585,7 +588,7 @@ function Editor({
)}
{!management && <PartnershipSourceLinks type="zone" id={z.id} />}
<p>
{z.code} ·{' '}
{management && <>{z.code} · </>}
{z.category === 'industrial_park'
? 'Parque industrial'
: z.category.toUpperCase()}{' '}
@@ -1792,8 +1795,15 @@ function Editor({
{area.value ?? 'Não informado'}{' '}
{area.value == null ? '' : area.unit} ·{' '}
{label(area.status)} · Fonte:{' '}
{area.source_reference ||
'Não informada'}{' '}
{publicReference(
area.source_reference,
) ? (
<PublicReference
value={area.source_reference}
/>
) : (
'Referência pública não disponível'
)}{' '}
·{' '}
{area.source_date ??
'Data não informada'}
@@ -1802,37 +1812,8 @@ function Editor({
</ul>
</section>
)}
{zoneExtensionsAvailable && !!z.source_evidence?.length && (
<section className={card}>
<h2 className="font-bold">
Fontes e o que comprovam
</h2>
<ul>
{z.source_evidence.map((evidence) => (
<li key={evidence.url}>
<a
className="underline"
href={evidence.url}
target="_blank"
rel="noreferrer"
>
{evidence.title}
</a>
{evidence.source_date
? ` · ${evidence.source_date}`
: ' · data não indicada'}{' '}
· {evidence.source_type} ·{' '}
{evidence.supports}
</li>
))}
</ul>
<p>
Esta informação descreve o que a fonte declara;
não confirma vigência legal, benefícios, estado
operacional ou disponibilidade para
investimento.
</p>
</section>
{zoneExtensionsAvailable && (
<PublicSourceList sources={z.source_evidence} />
)}
{z.historical_territory?.name && (
<p>
@@ -1868,16 +1849,26 @@ function Editor({
{label(activity.focus)} ·{' '}
{activity.source_date ??
'Data não informada'}
{activity.source_reference
? ` · ${activity.source_reference}`
: ''}
{publicReference(
activity.source_reference,
) && (
<>
{' '}
·{' '}
<PublicReference
value={
activity.source_reference
}
/>
</>
)}
</li>
))}
</ul>
</section>
) : null}
{!z.activities?.length && (
<p>Atividades: não informadas.</p>
<p>Actividades: não informadas.</p>
)}
{!z.resources?.length && (
<p>
@@ -1908,9 +1899,19 @@ function Editor({
·{' '}
{resource.source_date ??
'Data não informada'}
{resource.source_reference
? ` · ${resource.source_reference}`
: ''}
{publicReference(
resource.source_reference,
) && (
<>
{' '}
·{' '}
<PublicReference
value={
resource.source_reference
}
/>
</>
)}
</p>
))}
</section>
@@ -2217,7 +2218,7 @@ function DetailFields({
)}
{kind === 'activities' && (
<label className="grid gap-1">
Atividade económica documentada
Actividade económica documentada
<select
className={input}
value={detail.economic_activity_id ?? ''}
+53 -44
View File
@@ -1,3 +1,5 @@
import PublicSourceList from '@/components/public-source-list';
import { publicLocation } from '@/lib/public-presentation';
import InvestmentZoneInstallation, {
type ParkInstallationPlan,
} from '@/components/investment-zone-installation';
@@ -68,6 +70,7 @@ export default function Zones({
detailsInstallation,
records,
filters,
groupAvailability = {},
management,
zoneExtensionsAvailable = false,
territorySelection = [],
@@ -94,6 +97,9 @@ export default function Zones({
activity?: string;
};
management: boolean;
groupAvailability?: Partial<
Record<'zee' | 'zfi' | 'industrial_park', number>
>;
zoneExtensionsAvailable?: boolean;
territorySelection?: TerritoryOption[];
}) {
@@ -282,6 +288,14 @@ export default function Zones({
maxLength={120}
/>
</Field>
{!records.total && (
<p role="status" className="md:col-span-3">
Não há resultados publicados para este grupo e os
filtros seleccionados. Pode alterar o grupo ou remover
filtros; isto não demonstra ausência de actividade no
território.
</p>
)}
<Field label="Grupo">
<select
className={input}
@@ -289,10 +303,20 @@ export default function Zones({
defaultValue={filters.category ?? ''}
>
<option value="">Todas</option>
<option value="zee">ZEE</option>
<option value="zfi">ZFI</option>
<option value="zee">
ZEE
{groupAvailability.zee != null &&
` — ${groupAvailability.zee} registos`}
</option>
<option value="zfi">
ZFI
{groupAvailability.zfi != null &&
` — ${groupAvailability.zfi} registos`}
</option>
<option value="industrial_park">
Parque industrial
{groupAvailability.industrial_park != null &&
` — ${groupAvailability.industrial_park} registos`}
</option>
</select>
</Field>
@@ -460,36 +484,42 @@ export default function Zones({
{zone.name}
</Link>
</h2>
<Link
className="underline"
href={catalogueDetailHref(
`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`,
exportParams.toString(),
pageUrl,
)}
<nav
aria-label={`Acções de ${zone.name}`}
className="flex flex-wrap items-center gap-3"
>
Consultar ficha
</Link>
{!management && (
<Link
className="ml-4 underline"
href={searchTerritoryHref(
`/oportunidades?${new URLSearchParams({ [zone.category === 'zee' ? 'zee_id' : zone.category === 'zfi' ? 'zfi_id' : 'park_id']: zone.id })}`,
className="underline"
href={catalogueDetailHref(
`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`,
exportParams.toString(),
pageUrl,
)}
>
Ver oportunidades associadas
Consultar ficha
</Link>
)}
{!management && (
<Link
className="underline"
href={searchTerritoryHref(
`/oportunidades?${new URLSearchParams({ [zone.category === 'zee' ? 'zee_id' : zone.category === 'zfi' ? 'zfi_id' : 'park_id']: zone.id })}`,
pageUrl,
)}
>
Ver oportunidades associadas
</Link>
)}
</nav>
<p>
{zone.code} ·{' '}
{management && <>{zone.code} · </>}
{zone.category === 'industrial_park'
? 'Parque industrial'
: zone.category.toUpperCase()}{' '}
·{' '}
{[zone.district, zone.province]
.filter(Boolean)
.join(', ') || 'Localização por confirmar'}
{publicLocation(zone.territory_path, [
zone.province,
zone.district,
])}
</p>
{zone.legal_regime && (
<p>
@@ -540,35 +570,14 @@ export default function Zones({
.join(' · ')}
</p>
) : null}
{!!zone.source_evidence?.length && (
<p>
Fonte:{' '}
{zone.source_evidence.map((source, index) => (
<span key={source.url}>
{index > 0 ? ' · ' : ''}
<a
className="underline"
href={source.url}
target="_blank"
rel="noreferrer"
>
{source.title}
</a>
{source.source_date
? ` (${source.source_date})`
: ' (data da fonte não informada)'}{' '}
— {source.supports}
</span>
))}
</p>
)}
<PublicSourceList sources={zone.source_evidence} />
{zone.category === 'industrial_park' && (
<p>
{zone.resources?.length
? `${zone.resources.length} recursos descritos; consulte o âmbito e a fonte na ficha.`
: 'Infraestruturas, serviços, acessos e capacidades: não informados.'}{' '}
{!zone.activities?.length &&
'Atividades: não informadas.'}
'Actividades: não informadas.'}
</p>
)}
<p>{zone.description}</p>
+9 -16
View File
@@ -1,7 +1,15 @@
import { Head, Link, router } from '@inertiajs/react';
import { useEffect, useState } from 'react';
import { PortalMenu } from '@/components/portal-menu';
import { fiscalForms, fiscalFormFields, fiscalPreparationIssues, newFiscalPreparation, readFiscalPreparation, type FiscalFormKind, type FiscalPreparation } from '@/lib/fiscal-form-preparation';
import {
fiscalForms,
fiscalFormFields,
fiscalPreparationIssues,
newFiscalPreparation,
readFiscalPreparation,
type FiscalFormKind,
type FiscalPreparation,
} from '@/lib/fiscal-form-preparation';
const input =
'mt-1 block w-full rounded border border-slate-400 bg-white p-3 text-slate-900';
@@ -112,7 +120,6 @@ export default function FiscalForms({
</select>
</label>
<h2 className="text-xl font-bold">{source.title}</h2>
<p>{source.coverage}</p>
<nav
aria-label="Etapas de preenchimento"
className="flex flex-wrap gap-2 print:hidden"
@@ -426,20 +433,6 @@ export default function FiscalForms({
{notice}
</p>
)}
<details className="rounded border p-4">
<summary className="cursor-pointer font-semibold">
Exemplar e cobertura
</summary>
<p>{source.source}</p>
<p className="text-sm break-all">SHA256: {source.hash}</p>
<p>{source.coverage}</p>
<p>
Os cálculos e correspondências já disponíveis no
simulador permanecem separados desta introdução manual.
Não se executam fórmulas nem se transportam valores
entre edições automaticamente.
</p>
</details>
<div className="flex flex-wrap gap-4 print:hidden">
<Link href="/simulador-fiscal" className="underline">
Consultar cálculos e preparação M20/M22 no simulador
+113 -31
View File
@@ -1,4 +1,5 @@
import { Link, useForm, usePage } from '@inertiajs/react';
import { publicPortfolioText } from '@/lib/public-presentation';
import { searchTerritoryHref } from '@/lib/search-territory';
import { catalogueDetailHref } from '@/lib/catalogue-context';
import { Management } from '../management/shared';
@@ -12,13 +13,23 @@ import {
export default function Index({
records,
management,
publicReferenceNames = {},
filters,
territorySelection = [],
sectors = [],
publishedOpportunities = null,
}: {
records: Paginated<Dossier>;
management: boolean;
publicReferenceNames?: Record<string, string>;
sectors?: string[];
publishedOpportunities?: Paginated<{
id: number;
title: string;
slug: string;
summary: string | null;
location: string;
}> | null;
filters: {
q?: string;
kind?: string;
@@ -113,10 +124,11 @@ export default function Index({
{records.data.map((r) => (
<article
key={r.id}
className="space-y-3 rounded-xl border p-5"
className="flex min-w-0 flex-col gap-3 rounded-xl border p-5 [overflow-wrap:anywhere]"
>
<p className="text-sm">
{kind(r)} · {r.content.code}
{kind(r)}
{management && ` · ${r.content.code}`}
{management &&
` · ${r.publication_status === 'published' ? 'Publicado' : 'Rascunho'}`}
</p>
@@ -137,9 +149,13 @@ export default function Index({
</Link>
</h2>
<p>
{r.content.description ??
r.content.focus ??
r.content.anchors}
{publicPortfolioText(
r.content.description ??
r.content.focus ??
r.content.anchors ??
'',
publicReferenceNames,
)}
</p>
{(r.content.location || r.content.region) && (
<p>
@@ -155,37 +171,47 @@ export default function Index({
</span>
</p>
)}
<Link
className="underline"
href={catalogueDetailHref(
`${base}/${r.id}`,
new URLSearchParams(
Object.entries(filters).filter(
([, value]) => Boolean(value),
) as [string, string][],
).toString(),
url,
)}
<nav
aria-label={`Acções de ${r.title}`}
className="mt-auto flex flex-wrap items-center gap-3"
>
Consultar ficha
</Link>
{!management &&
(r.corridor_id || r.cluster_id || r.project_id) && (
<Link
className="ml-4 underline"
href={searchTerritoryHref(
`/oportunidades?${new URLSearchParams(r.corridor_id ? { corridor_id: r.corridor_id } : r.cluster_id ? { cluster_id: r.cluster_id } : { project_id: r.project_id! })}`,
url,
)}
>
Ver oportunidades associadas
</Link>
)}
<Link
className="underline"
href={catalogueDetailHref(
`${base}/${r.id}`,
new URLSearchParams(
Object.entries(filters).filter(
([, value]) => Boolean(value),
) as [string, string][],
).toString(),
url,
)}
>
Consultar ficha
</Link>
{!management &&
(r.corridor_id ||
r.cluster_id ||
r.project_id) && (
<Link
className="underline"
href={searchTerritoryHref(
`/oportunidades?${new URLSearchParams(r.corridor_id ? { corridor_id: r.corridor_id } : r.cluster_id ? { cluster_id: r.cluster_id } : { project_id: r.project_id! })}`,
url,
)}
>
Ver oportunidades associadas
</Link>
)}
</nav>
</article>
))}
</div>
{!records.data.length && (
<div className="space-y-3 rounded-xl border p-5" role="status">
<div
className="flex min-w-0 flex-col gap-3 rounded-xl border p-5 [overflow-wrap:anywhere]"
role="status"
>
<p>
Ainda não existem fichas publicadas para esta pesquisa.
Os filtros activos foram mantidos.
@@ -218,6 +244,62 @@ export default function Index({
</div>
)}
<Pagination page={records} />
{!management && publishedOpportunities && (
<section
className="space-y-4"
aria-label="Oportunidades publicadas nesta consulta"
>
<h2 className="text-2xl font-semibold">
Oportunidades publicadas nesta consulta
</h2>
<p>
Consulte as oportunidades sem repetir a pesquisa. São
respeitados os filtros de texto, sector e localização; a
selecção de corredores, clusters ou projectos limita
esta lista às associações documentadas.
</p>
{publishedOpportunities.data.length === 0 && (
<p role="status">
Não há oportunidades publicadas com correspondência
documentada para os filtros desta consulta. Isto não
demonstra inexistência de oportunidades: rascunhos e
localizações não documentadas não são incluídos por
inferência.
</p>
)}
<div className="grid gap-4 md:grid-cols-2">
{publishedOpportunities.data.map((opportunity) => (
<article
key={opportunity.id}
className="flex min-w-0 flex-col gap-3 rounded-xl border p-5 [overflow-wrap:anywhere]"
>
<h3 className="text-xl font-semibold">
<Link
className="underline"
href={catalogueDetailHref(
`/oportunidades/${opportunity.slug}`,
new URLSearchParams(
Object.entries(filters).filter(
([, value]) =>
Boolean(value),
) as [string, string][],
).toString(),
url,
)}
>
{opportunity.title}
</Link>
</h3>
{opportunity.summary && (
<p>{opportunity.summary}</p>
)}
<p>{opportunity.location}</p>
</article>
))}
</div>
<Pagination page={publishedOpportunities} />
</section>
)}
</Frame>
);
}
+35 -5
View File
@@ -1,3 +1,8 @@
import PublicReference from '@/components/public-reference';
import {
publicReference,
publicPortfolioText,
} from '@/lib/public-presentation';
import { Link, useForm, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { catalogueReturnHref } from '@/lib/catalogue-context';
@@ -30,6 +35,7 @@ export default function Show(props: Props) {
}
type Props = {
publicReferenceNames?: Record<string, string>;
editorialEnabled?: boolean;
competitiveness?: ApprovedCompetitiveness | null;
complements?: ComplementOption[];
@@ -65,6 +71,7 @@ type Props = {
};
function Editor({
publicReferenceNames = {},
editorialEnabled = false,
competitiveness,
complements = [],
@@ -104,9 +111,19 @@ function Editor({
Voltar à pesquisa
</Link>
<p>
{kind(record)} · {record.content.code}
{kind(record)}
{management && ` · ${record.content.code}`}
</p>
<p className="text-sm">Fonte: {record.source}</p>
{(management || publicReference(record.source)) && (
<p className="text-sm">
Fonte:{' '}
{management ? (
record.source
) : (
<PublicReference value={record.source} />
)}
</p>
)}
{competitiveness && (
<ClusterCompetitivenessPublic analysis={competitiveness} />
)}
@@ -150,7 +167,8 @@ function Editor({
Referência de projecto âncora
</h2>
<p>
{anchorProject.code} · {anchorProject.name}
{management && `${anchorProject.code} · `}
{anchorProject.name}
</p>
<p>
Estado registado:{' '}
@@ -234,7 +252,16 @@ function Editor({
>
{z.name}
</Link>{' '}
· {z.association_type} · Fonte: {z.source_reference}
· {z.association_type}
{publicReference(z.source_reference) && (
<>
{' '}
· Fonte:{' '}
<PublicReference
value={z.source_reference}
/>
</>
)}
</p>
))}
</section>
@@ -491,7 +518,10 @@ function Editor({
{labels[key] ?? key}
</dt>
<dd className="mt-1 whitespace-pre-line">
{value}
{publicPortfolioText(
value,
publicReferenceNames,
)}
</dd>
</div>
))}