Files
Investidor-V2/resources/js/components/warning-limits-editor.tsx
T

105 lines
4.1 KiB
TypeScript

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>
);
}