449 lines
23 KiB
TypeScript
449 lines
23 KiB
TypeScript
import {
|
|
forecastBusinessPlan,
|
|
type BusinessFinancialPlanInput,
|
|
} from '@/lib/business-financial-plan';
|
|
import {
|
|
advanceLabels,
|
|
advanceEventLabels,
|
|
type SupplierAdvances,
|
|
type SupplierAdvanceOperation,
|
|
} from '@/lib/supplier-advances';
|
|
|
|
export function SupplierAdvancesEditor({
|
|
plan,
|
|
onChange,
|
|
}: {
|
|
plan: BusinessFinancialPlanInput;
|
|
onChange: (plan: BusinessFinancialPlanInput) => void;
|
|
}) {
|
|
const c: SupplierAdvances = plan.supplierAdvances ?? {
|
|
regime: '',
|
|
purchases: false,
|
|
services: false,
|
|
operations: [],
|
|
};
|
|
const save = (next: SupplierAdvances) =>
|
|
onChange({ ...plan, supplierAdvances: next });
|
|
const update = (index: number, patch: Partial<SupplierAdvanceOperation>) =>
|
|
save({
|
|
...c,
|
|
operations: c.operations.map((o, i) =>
|
|
i === index ? { ...o, ...patch } : o,
|
|
),
|
|
});
|
|
let result: ReturnType<typeof forecastBusinessPlan> | undefined;
|
|
let diagnostic = '';
|
|
try {
|
|
result = forecastBusinessPlan(plan);
|
|
} catch (e) {
|
|
diagnostic =
|
|
e instanceof Error ? e.message : 'Reveja os dados do plano.';
|
|
}
|
|
return (
|
|
<details className="my-3 min-w-0 space-y-3 rounded border p-3">
|
|
<summary className="font-semibold">
|
|
Adiantamentos por operação — PGC-PE
|
|
</summary>
|
|
<p>
|
|
Projecções de mercadorias e serviços adquiridos. O pagamento
|
|
antecipado fica no activo; a aplicação exige reconhecimento e
|
|
factura da mesma operação e parcela, sem nova saída de caixa. A
|
|
devolução reduz o adiantamento e não constitui receita.
|
|
</p>
|
|
<p>
|
|
A agenda seleccionada substitui integralmente os pagamentos
|
|
manuais e os prazos em dias da categoria, conservados inactivos.
|
|
Distribua o reconhecimento económico completo por operações,
|
|
incluindo as sem adiantamento. Não converte saldos de abertura.
|
|
Serviços: utilize apenas se todas as despesas operacionais forem
|
|
serviços elegíveis.
|
|
</p>
|
|
<p>
|
|
Sem IVA, diferenças cambiais, perdas ou penalizações
|
|
automatizados; isso não pressupõe taxa zero. Novos activos,
|
|
empréstimos e contratos com transferência de controlo ou
|
|
obrigação incondicional antes da entrega estão fora deste
|
|
incremento. Os movimentos são previsões, não pagamentos
|
|
executados.
|
|
</p>
|
|
<label className="grid gap-1">
|
|
Referencial dos adiantamentos
|
|
<select
|
|
className="w-full rounded border p-2"
|
|
value={c.regime}
|
|
onChange={(e) =>
|
|
save({
|
|
...c,
|
|
regime: e.target
|
|
.value as SupplierAdvances['regime'],
|
|
})
|
|
}
|
|
>
|
|
<option value="">
|
|
Seleccione o regime aplicável ao plano
|
|
</option>
|
|
<option value="PGC-PE">PGC-PE</option>
|
|
</select>
|
|
</label>
|
|
{(['purchases', 'services'] as const).map((kind) => (
|
|
<fieldset
|
|
key={kind}
|
|
className="min-w-0 space-y-2 rounded border p-3"
|
|
>
|
|
<legend>{advanceLabels[kind]}</legend>
|
|
<label className="grid gap-1">
|
|
Agenda de {advanceLabels[kind]}
|
|
<select
|
|
className="w-full rounded border p-2"
|
|
value={c[kind] ? 'operations' : 'previous'}
|
|
onChange={(e) => {
|
|
if (
|
|
e.target.value === 'operations' &&
|
|
!window.confirm(
|
|
`Activar adiantamentos por operação para ${advanceLabels[kind]}? Esta agenda substitui todos os pagamentos da categoria; os anteriores ficam guardados e não serão somados.`,
|
|
)
|
|
)
|
|
return;
|
|
save({
|
|
...c,
|
|
[kind]: e.target.value === 'operations',
|
|
});
|
|
}}
|
|
>
|
|
<option value="previous">
|
|
Agenda anterior preservada
|
|
</option>
|
|
<option value="operations">
|
|
Operações e adiantamentos (adesão explícita)
|
|
</option>
|
|
</select>
|
|
</label>
|
|
{c.operations.map((o, i) =>
|
|
o.kind !== kind ? null : (
|
|
<div
|
|
key={i}
|
|
className="min-w-0 space-y-3 rounded border p-3"
|
|
role="group"
|
|
aria-label={`Operação ${i + 1} de ${advanceLabels[kind]}`}
|
|
>
|
|
<div className="grid min-w-0 gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
|
{(
|
|
[
|
|
['Operação', 'originId'],
|
|
['Parcela', 'parcelId'],
|
|
['Fornecedor', 'supplier'],
|
|
[
|
|
'Valor reconhecido da operação/parcela',
|
|
'amount',
|
|
],
|
|
[
|
|
'Data de reconhecimento',
|
|
'recognitionDate',
|
|
],
|
|
[
|
|
'Data da factura correspondente',
|
|
'invoiceDate',
|
|
],
|
|
] as const
|
|
).map(([label, key]) => (
|
|
<label
|
|
key={key}
|
|
className="grid min-w-0 gap-1"
|
|
>
|
|
{label}
|
|
<input
|
|
className="w-full min-w-0 rounded border p-2"
|
|
type={
|
|
key.endsWith('Date')
|
|
? 'date'
|
|
: 'text'
|
|
}
|
|
value={o[key]}
|
|
onChange={(e) =>
|
|
update(i, {
|
|
[key]: e.target.value,
|
|
})
|
|
}
|
|
/>
|
|
</label>
|
|
))}
|
|
</div>
|
|
<p className="text-sm">
|
|
Sem data confirmada, deixe-a em branco. Não
|
|
se presume coincidência entre
|
|
recepção/prestação e factura; a aplicação
|
|
permanece impedida enquanto faltar um desses
|
|
eventos. Reconhecimento fora do horizonte
|
|
conserva o adiantamento no activo.
|
|
</p>
|
|
<label className="flex items-start gap-2">
|
|
<input
|
|
type="checkbox"
|
|
checked={o.ordinaryContract}
|
|
onChange={(e) =>
|
|
update(i, {
|
|
ordinaryContract:
|
|
e.target.checked,
|
|
})
|
|
}
|
|
/>
|
|
Contrato ordinário: sem transferência de
|
|
controlo nem obrigação incondicional de
|
|
pagamento antes da entrega/prestação
|
|
</label>
|
|
{o.events.map((e, j) => (
|
|
<div
|
|
key={j}
|
|
className="grid min-w-0 gap-2 rounded border p-2 sm:grid-cols-2"
|
|
role="group"
|
|
aria-label={`Movimento ${j + 1}`}
|
|
>
|
|
<label className="grid gap-1">
|
|
Movimento
|
|
<select
|
|
className="w-full rounded border p-2"
|
|
value={e.kind}
|
|
onChange={(v) =>
|
|
update(i, {
|
|
events: o.events.map(
|
|
(a, k) =>
|
|
k === j
|
|
? {
|
|
...a,
|
|
kind: v
|
|
.target
|
|
.value as typeof e.kind,
|
|
}
|
|
: a,
|
|
),
|
|
})
|
|
}
|
|
>
|
|
{Object.entries(
|
|
advanceEventLabels,
|
|
).map(([value, label]) => (
|
|
<option
|
|
key={value}
|
|
value={value}
|
|
>
|
|
{label}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
{(
|
|
[
|
|
['Identificador', 'id'],
|
|
['Data', 'date'],
|
|
['Montante', 'amount'],
|
|
] as const
|
|
).map(([label, key]) => (
|
|
<label
|
|
key={key}
|
|
className="grid min-w-0 gap-1"
|
|
>
|
|
{label}
|
|
<input
|
|
className="w-full min-w-0 rounded border p-2"
|
|
type={
|
|
key === 'date'
|
|
? 'date'
|
|
: 'text'
|
|
}
|
|
value={e[key]}
|
|
onChange={(v) =>
|
|
update(i, {
|
|
events: o.events.map(
|
|
(a, k) =>
|
|
k === j
|
|
? {
|
|
...a,
|
|
[key]: v
|
|
.target
|
|
.value,
|
|
}
|
|
: a,
|
|
),
|
|
})
|
|
}
|
|
/>
|
|
</label>
|
|
))}
|
|
<button
|
|
type="button"
|
|
className="rounded border px-3 py-2"
|
|
onClick={() =>
|
|
update(i, {
|
|
events: o.events.filter(
|
|
(_, k) => k !== j,
|
|
),
|
|
})
|
|
}
|
|
>
|
|
Remover movimento {j + 1}
|
|
</button>
|
|
</div>
|
|
))}
|
|
<p className="text-sm">
|
|
Os movimentos são processados por data; no
|
|
mesmo dia, na ordem apresentada. Aplicação e
|
|
pagamento exigem a factura e o
|
|
reconhecimento. O pagamento do remanescente
|
|
não pode voltar a pagar o adiantamento
|
|
associado.
|
|
</p>
|
|
<button
|
|
type="button"
|
|
className="rounded border px-3 py-2"
|
|
disabled={o.events.length >= 60}
|
|
onClick={() =>
|
|
update(i, {
|
|
events: [
|
|
...o.events,
|
|
{
|
|
id: '',
|
|
kind: 'advance',
|
|
date: '',
|
|
amount: '',
|
|
},
|
|
],
|
|
})
|
|
}
|
|
>
|
|
Adicionar movimento
|
|
</button>{' '}
|
|
<button
|
|
type="button"
|
|
className="rounded border px-3 py-2"
|
|
onClick={() =>
|
|
save({
|
|
...c,
|
|
operations: c.operations.filter(
|
|
(_, k) => k !== i,
|
|
),
|
|
})
|
|
}
|
|
>
|
|
Remover operação {i + 1}
|
|
</button>
|
|
</div>
|
|
),
|
|
)}
|
|
<button
|
|
type="button"
|
|
className="rounded border px-3 py-2"
|
|
disabled={c.operations.length >= 120}
|
|
onClick={() =>
|
|
save({
|
|
...c,
|
|
operations: [
|
|
...c.operations,
|
|
{
|
|
kind,
|
|
originId: '',
|
|
parcelId: '',
|
|
supplier: '',
|
|
amount: '',
|
|
recognitionDate: '',
|
|
invoiceDate: '',
|
|
ordinaryContract: false,
|
|
events: [],
|
|
},
|
|
],
|
|
})
|
|
}
|
|
>
|
|
Adicionar operação de {advanceLabels[kind]}
|
|
</button>
|
|
</fieldset>
|
|
))}
|
|
{diagnostic && (c.purchases || c.services) && (
|
|
<p role="alert">{diagnostic}</p>
|
|
)}
|
|
{result?.supplierAdvanceLedger && (
|
|
<section
|
|
aria-label="Saldos dos adiantamentos por operação"
|
|
className="space-y-3"
|
|
>
|
|
<h4 className="font-semibold">
|
|
Obrigação, adiantamento e líquido por liquidar
|
|
</h4>
|
|
{result.supplierAdvanceLedger.operations.map((o) => (
|
|
<div
|
|
key={JSON.stringify([
|
|
o.kind,
|
|
o.originId,
|
|
o.parcelId,
|
|
])}
|
|
className="min-w-0 rounded border p-2"
|
|
>
|
|
<p className="font-medium">
|
|
{o.originId}/{o.parcelId} — {o.supplier}
|
|
</p>
|
|
<p>
|
|
Reconhecimento:{' '}
|
|
{o.recognitionDate || 'por confirmar'}. Factura:{' '}
|
|
{o.invoiceDate || 'por confirmar'}.{' '}
|
|
{o.recognitionOutsideHorizon
|
|
? 'Reconhecimento fora do horizonte ou por confirmar; saldo conservado.'
|
|
: ''}
|
|
</p>
|
|
<div className="overflow-x-auto">
|
|
<table
|
|
aria-label={`Saldos de ${o.originId}/${o.parcelId}`}
|
|
className="w-full text-sm"
|
|
>
|
|
<thead>
|
|
<tr>
|
|
{[
|
|
'Mês',
|
|
'Obrigação bruta',
|
|
'Adiantamento activo',
|
|
'Líquido por liquidar',
|
|
].map((h) => (
|
|
<th
|
|
key={h}
|
|
className="p-2 text-left"
|
|
>
|
|
{h}
|
|
</th>
|
|
))}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{o.monthly.map((m) => (
|
|
<tr key={m.month}>
|
|
<td className="p-2">
|
|
{m.month}
|
|
</td>
|
|
<td className="p-2">
|
|
{m.obligation}
|
|
</td>
|
|
<td className="p-2">
|
|
{m.advance}
|
|
</td>
|
|
<td className="p-2">
|
|
{m.netDue}
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
{o.events.map((e) => (
|
|
<p key={e.id}>
|
|
{advanceEventLabels[e.kind]} — {e.date}:{' '}
|
|
{e.amount} {plan.currency}.{' '}
|
|
{e.outsideHorizon
|
|
? 'Fora do horizonte, sem caixa neste plano.'
|
|
: ''}
|
|
</p>
|
|
))}
|
|
</div>
|
|
))}
|
|
</section>
|
|
)}
|
|
</details>
|
|
);
|
|
}
|