feat(qa): complete market milestones and personnel report tables
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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,84 @@ 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 = '',
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
financialPlanSnapshot?: 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 +119,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 +133,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 +294,14 @@ export function ProjectTeamPlanner({
|
||||
>
|
||||
Adicionar competência ou lacuna
|
||||
</button>
|
||||
<InvestmentReportTables
|
||||
tables={[
|
||||
buildComplementaryTables(
|
||||
{ project_team_snapshot: value },
|
||||
restoreBusinessPlanSnapshot(financialPlanSnapshot),
|
||||
)[2],
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -194,6 +316,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 +330,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 +486,14 @@ export function ProjectMilestonePlanner({
|
||||
>
|
||||
Adicionar marco
|
||||
</button>
|
||||
<InvestmentReportTables
|
||||
tables={[
|
||||
buildComplementaryTables(
|
||||
{ project_execution_snapshot: value },
|
||||
null,
|
||||
)[1],
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ 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';
|
||||
|
||||
const emptyPlan: BusinessFinancialPlanInput = {
|
||||
currency: '',
|
||||
@@ -940,6 +941,7 @@ export function SimulationBusinessPlan({
|
||||
/>
|
||||
)}
|
||||
<IntegralFinancialPlan plan={plan} onChange={savePlan} />
|
||||
<MarketAnalysisPlan 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)
|
||||
|
||||
@@ -3473,6 +3473,9 @@ export function SimulationForm() {
|
||||
{current.id === 'team' && (
|
||||
<>
|
||||
<ProjectTeamPlanner
|
||||
financialPlanSnapshot={String(
|
||||
draft.business_plan_snapshot ?? '',
|
||||
)}
|
||||
value={String(draft.project_team_snapshot ?? '')}
|
||||
onChange={(value) =>
|
||||
change('project_team_snapshot', value)
|
||||
|
||||
@@ -82,6 +82,16 @@ function validCurrency(value: string): boolean {
|
||||
}
|
||||
|
||||
export type BusinessFinancialPlanInput = {
|
||||
marketAnalysis?: {
|
||||
baseYear: string;
|
||||
years: string;
|
||||
segments: {
|
||||
label: string;
|
||||
customers: string;
|
||||
growthPercent: string;
|
||||
basis: string;
|
||||
}[];
|
||||
};
|
||||
reportAssumptions?: {
|
||||
startYear: string;
|
||||
openingFixedAssets: string;
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
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);
|
||||
};
|
||||
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(
|
||||
'A moeda do projecto difere da moeda do plano financeiro. 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 = integer(m.baseYear, 1900, 9999),
|
||||
years = integer(m.years, 2, 10);
|
||||
if (year + years - 1 > 9999)
|
||||
throw Error('O horizonte de mercado excede 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 {
|
||||
if (!s.label?.trim() || !s.basis?.trim())
|
||||
throw Error('Indique nome e fonte ou hipótese.');
|
||||
let clients = integer(s.customers, 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(
|
||||
'Indique crescimento igual ou superior a −100%.',
|
||||
);
|
||||
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 += amount(r.planned_amount);
|
||||
planned = reportMoney(amount(r.planned_amount));
|
||||
} catch {
|
||||
budgetComplete = false;
|
||||
milestones.issues.push(
|
||||
`Marco ${i + 1}: orçamento em falta ou inválido.`,
|
||||
);
|
||||
}
|
||||
if (r.actual_amount !== '') {
|
||||
try {
|
||||
actual += amount(r.actual_amount);
|
||||
realised = reportMoney(amount(r.actual_amount));
|
||||
} catch {
|
||||
actualComplete = false;
|
||||
milestones.issues.push(`Marco ${i + 1}: realizado inválido.`);
|
||||
}
|
||||
} else actualComplete = false;
|
||||
if (
|
||||
!r.title.trim() ||
|
||||
!r.responsible?.trim() ||
|
||||
!r.department?.trim() ||
|
||||
!date(r.start_date ?? '') ||
|
||||
!date(r.due_date) ||
|
||||
r.start_date! > r.due_date
|
||||
)
|
||||
milestones.issues.push(
|
||||
`Marco ${i + 1}: complete título, responsável, departamento e datas de início/término válidas e ordenadas.`,
|
||||
);
|
||||
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 {
|
||||
if (!r.competency.trim() || !r.department?.trim())
|
||||
throw Error('Indique função e departamento.');
|
||||
const count = integer(r.quantity, 0, 1000000),
|
||||
salary = amount(r.monthly_salary),
|
||||
start = integer(r.start_month, 1, periods),
|
||||
end = integer(r.end_month, 1, periods);
|
||||
if (start > end) throw Error('O mês final precede 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];
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { displayValue } from './display-value.ts';
|
||||
import { buildComplementaryTables } from './complementary-report.ts';
|
||||
import {
|
||||
buildIntegralFinancialTables,
|
||||
displayReportMoney,
|
||||
@@ -523,6 +524,11 @@ function makeSections(
|
||||
const financialPlan = restoreBusinessPlanSnapshot(
|
||||
text(draft, 'business_plan_snapshot'),
|
||||
);
|
||||
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) {
|
||||
finance.tables = buildIntegralFinancialTables(financialPlan);
|
||||
const periods = financialPlan.periods ?? 12;
|
||||
|
||||
@@ -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';
|
||||
|
||||
Reference in New Issue
Block a user