feat(qa): complete market milestones and personnel report tables

This commit is contained in:
2026-11-20 12:45:14 +02:00
parent f3148d1674
commit 4fb9296f70
14 changed files with 1041 additions and 7 deletions
@@ -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)