Files
Investidor-V2/resources/js/components/project-planning.tsx
T
Claude 2cecb28c36
tests / ci (push) Waiting to run
Plano de pessoal: a folha salarial do mapa de pessoal passa a ser a fonte do custo de pessoal
O mapa de pessoal (passo Equipa) e o «Custo mensal de pessoal» do plano
financeiro eram duas fontes independentes; o portal só avisava que
divergiam. O mapa passa a calcular a folha salarial mês a mês e, enquanto o
plano tiver outro valor, oferece duas acções expressas: usar como custo
mensal de pessoal, ou como custo e pagamento no próprio mês. Depois da
escolha a diferença desaparece e o passo confirma que coincidem. Um mapa
incompleto ou noutra moeda nunca é adoptado; os pagamentos só mudam quando
o investidor o pede.

Os campos numéricos do mapa de pessoal, da análise de mercado, dos
investimentos por período e das importações em regime de remissão passam a
usar o mesmo campo decimal do simulador.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
2026-12-04 23:41:09 +02:00

553 lines
21 KiB
TypeScript

import { DecimalInput } from '@/components/decimal-input';
import {
readRows,
type ProjectMilestone,
type TeamNeed,
} from '@/lib/project-dossier';
import { restoreBusinessPlanSnapshot } from '@/lib/business-financial-plan';
import {
buildComplementaryTables,
teamPayrollSchedule,
} from '@/lib/complementary-report';
import { InvestmentReportTables } from './investment-report-tables';
const teamKeys = [
'competency',
'state',
'action',
'estimated_cost',
'due_date',
] as const;
const milestoneKeys = [
'title',
'due_date',
'status',
'planned_amount',
'actual_amount',
] as const;
function update<T extends Record<string, string>>(
rows: T[],
index: number,
key: keyof T,
value: string,
): T[] {
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}
{type === 'number' ? (
<DecimalInput
className="min-w-0 rounded border p-2"
value={row[key] ?? ''}
onValueChange={(value) => change(key, value)}
/>
) : (
<input
className="min-w-0 rounded border p-2"
type={type}
value={row[key] ?? ''}
onChange={(e) => change(key, e.target.value)}
/>
)}
</label>
))}
</>
);
}
export function ProjectTeamPlanner({
value,
onChange,
financialPlanSnapshot = '',
projectCurrency = '',
onAdoptPayroll,
}: {
value: string;
onChange: (value: string) => void;
financialPlanSnapshot?: string;
projectCurrency?: string;
/** Writes the map's monthly payroll into the financial plan, on the investor's request. */
onAdoptPayroll?: (schedule: string[], payments: boolean) => void;
}) {
const rows = readRows<TeamNeed>(value, teamKeys);
const plan = restoreBusinessPlanSnapshot(financialPlanSnapshot);
const sameCurrency =
!projectCurrency ||
!plan?.currency ||
plan.currency === projectCurrency;
const payroll =
plan && sameCurrency
? teamPayrollSchedule(value, plan.periods ?? 12)
: null;
const adopted =
payroll !== null &&
payroll.every((amount, month) => {
const current =
plan?.monthlyPayrollExpenseByPeriod?.[month] ??
plan?.monthlyPayrollExpense ??
'';
return Number(current || 0) === Number(amount);
});
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"
aria-label="Necessidades de equipa e competências"
>
<p className="text-sm text-slate-700">
Registe competências declaradas, lacunas, resposta prevista,
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}
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
>
<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
className="mt-1 w-full rounded border p-2"
value={row.competency}
onChange={(e) =>
persist(
update(
rows,
index,
'competency',
e.target.value,
),
)
}
/>
</label>
<label className="text-sm">
Disponibilidade
<select
className="mt-1 w-full rounded border p-2"
value={row.state}
onChange={(e) =>
persist(
update(
rows,
index,
'state',
e.target.value,
),
)
}
>
<option value="unknown">Por avaliar</option>
<option value="available">
Disponível (declarado)
</option>
<option value="gap">Lacuna identificada</option>
</select>
</label>
<label className="text-sm">
Resposta planeada
<input
className="mt-1 w-full rounded border p-2"
placeholder="Formação, contratação, parceria…"
value={row.action}
onChange={(e) =>
persist(
update(
rows,
index,
'action',
e.target.value,
),
)
}
/>
</label>
<label className="text-sm">
Custo estimado (moeda do projecto)
<DecimalInput
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.estimated_cost}
onValueChange={(value) =>
persist(
update(
rows,
index,
'estimated_cost',
value,
),
)
}
/>
</label>
<label className="text-sm">
Prazo previsto
<input
type="date"
className="mt-1 w-full rounded border p-2"
value={row.due_date}
onChange={(e) =>
persist(
update(
rows,
index,
'due_date',
e.target.value,
),
)
}
/>
</label>
<button
type="button"
className="justify-self-start rounded border px-3 py-2 text-sm"
onClick={() =>
persist(rows.filter((_, i) => i !== index))
}
>
Remover necessidade {index + 1}
</button>
</fieldset>
))}
<button
type="button"
className="rounded border px-3 py-2"
onClick={() =>
persist([
...rows,
{
competency: '',
state: 'unknown',
action: '',
estimated_cost: '',
due_date: '',
},
])
}
>
Adicionar competência ou lacuna
</button>
<InvestmentReportTables
tables={[
buildComplementaryTables(
{
project_team_snapshot: value,
currency: projectCurrency,
},
plan,
)[2],
]}
/>
{onAdoptPayroll && payroll && !adopted && (
<div className="space-y-2 rounded border border-amber-300 bg-amber-50 p-3 text-sm">
<p>
O mapa de pessoal é a fonte da folha salarial. Para que
o plano financeiro use os mesmos valores, escolha uma
das opções. Só muda o que escolher.
</p>
<div className="flex flex-wrap gap-2">
<button
type="button"
className="rounded border px-3 py-2"
onClick={() => onAdoptPayroll(payroll, false)}
>
Usar como custo mensal de pessoal
</button>
<button
type="button"
className="rounded border px-3 py-2"
onClick={() => onAdoptPayroll(payroll, true)}
>
Usar como custo e pagamento (pago no próprio mês)
</button>
</div>
</div>
)}
{onAdoptPayroll && payroll && adopted && (
<p className="text-sm text-emerald-800">
O custo de pessoal do plano financeiro coincide com este
mapa de pessoal.
</p>
)}
</section>
);
}
export function ProjectMilestonePlanner({
value,
onChange,
}: {
value: string;
onChange: (value: string) => void;
}) {
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">
Compare datas e montantes planeados com o realizado. Estes
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
className="mt-1 w-full rounded border p-2"
value={row.title}
onChange={(e) =>
persist(
update(
rows,
index,
'title',
e.target.value,
),
)
}
/>
</label>
<label className="text-sm">
Prazo previsto
<input
type="date"
className="mt-1 w-full rounded border p-2"
value={row.due_date}
onChange={(e) =>
persist(
update(
rows,
index,
'due_date',
e.target.value,
),
)
}
/>
</label>
<label className="text-sm">
Estado
<select
className="mt-1 w-full rounded border p-2"
value={row.status}
onChange={(e) =>
persist(
update(
rows,
index,
'status',
e.target.value,
),
)
}
>
<option value="planned">Planeado</option>
<option value="in_progress">Em curso</option>
<option value="completed">
Concluído (declarado)
</option>
</select>
</label>
<label className="text-sm">
Montante planeado
<DecimalInput
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.planned_amount}
onValueChange={(value) =>
persist(
update(
rows,
index,
'planned_amount',
value,
),
)
}
/>
</label>
<label className="text-sm">
Montante realizado
<DecimalInput
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.actual_amount}
onValueChange={(value) =>
persist(
update(rows, index, 'actual_amount', value),
)
}
/>
</label>
<button
type="button"
className="justify-self-start rounded border px-3 py-2 text-sm"
onClick={() =>
persist(rows.filter((_, i) => i !== index))
}
>
Remover marco {index + 1}
</button>
</fieldset>
))}
<button
type="button"
className="rounded border px-3 py-2"
onClick={() =>
persist([
...rows,
{
title: '',
due_date: '',
status: 'planned',
planned_amount: '',
actual_amount: '',
},
])
}
>
Adicionar marco
</button>
<InvestmentReportTables
tables={[
buildComplementaryTables(
{ project_execution_snapshot: value },
null,
)[1],
]}
/>
</section>
);
}