Files
Investidor-V2/resources/js/components/project-planning.tsx
T

505 lines
19 KiB
TypeScript

import {
readRows,
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',
'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}
<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"
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)
<input
type="number"
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.estimated_cost}
onChange={(e) =>
persist(
update(
rows,
index,
'estimated_cost',
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>
<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,
},
restoreBusinessPlanSnapshot(financialPlanSnapshot),
)[2],
]}
/>
</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
<input
type="number"
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.planned_amount}
onChange={(e) =>
persist(
update(
rows,
index,
'planned_amount',
e.target.value,
),
)
}
/>
</label>
<label className="text-sm">
Montante realizado
<input
type="number"
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.actual_amount}
onChange={(e) =>
persist(
update(
rows,
index,
'actual_amount',
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 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>
);
}