feat(finance): add explicit plan regime and PGC-NIRF advance basis in QA
This commit is contained in:
@@ -5,7 +5,9 @@ import {
|
||||
import {
|
||||
advanceLabels,
|
||||
advanceEventLabels,
|
||||
advanceDocumentLabel,
|
||||
type SupplierAdvances,
|
||||
type AccountingRegime,
|
||||
type SupplierAdvanceOperation,
|
||||
} from '@/lib/supplier-advances';
|
||||
|
||||
@@ -42,13 +44,15 @@ export function SupplierAdvancesEditor({
|
||||
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
|
||||
Adiantamentos por operação
|
||||
</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.
|
||||
factura da mesma operação e parcela no PGC-PE. No PGC-NIRF, pode
|
||||
usar factura ou acordo formal datado e identificado. Não há nova
|
||||
saída de caixa na aplicação. A devolução reduz o adiantamento e
|
||||
não constitui receita.
|
||||
</p>
|
||||
<p>
|
||||
A agenda seleccionada substitui integralmente os pagamentos
|
||||
@@ -67,24 +71,45 @@ export function SupplierAdvancesEditor({
|
||||
executados.
|
||||
</p>
|
||||
<label className="grid gap-1">
|
||||
Referencial dos adiantamentos
|
||||
Regime contabilístico do plano
|
||||
<select
|
||||
className="w-full rounded border p-2"
|
||||
value={c.regime}
|
||||
onChange={(e) =>
|
||||
save({
|
||||
...c,
|
||||
regime: e.target
|
||||
.value as SupplierAdvances['regime'],
|
||||
})
|
||||
}
|
||||
value={plan.accountingRegime ?? ''}
|
||||
onChange={(e) => {
|
||||
const regime = e.target.value as AccountingRegime | '';
|
||||
const previous = plan.accountingRegime ?? c.regime;
|
||||
if (
|
||||
previous &&
|
||||
regime !== previous &&
|
||||
!window.confirm(
|
||||
'Mudar o regime declarado do plano? Confira os fundamentos e os resultados recalculados antes de guardar. Os históricos anteriores mantêm-se intactos.',
|
||||
)
|
||||
)
|
||||
return;
|
||||
onChange({
|
||||
...plan,
|
||||
accountingRegime: regime || undefined,
|
||||
supplierAdvances: { ...c, regime },
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione o regime aplicável ao plano
|
||||
</option>
|
||||
<option value="">Regime do plano por indicar</option>
|
||||
<option value="PGC-PE">PGC-PE</option>
|
||||
<option value="PGC-NIRF">PGC-NIRF</option>
|
||||
</select>
|
||||
</label>
|
||||
{!plan.accountingRegime && c.regime === 'PGC-PE' && (
|
||||
<p>
|
||||
Este plano anterior conserva PGC-PE apenas na agenda de
|
||||
adiantamentos. Confirme acima para o declarar ao nível do
|
||||
plano; nenhum regime geral foi atribuído automaticamente.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
O regime é declarado para esta projecção e para os tratamentos
|
||||
suportados; não é uma certificação contabilística integral. O
|
||||
pagamento do remanescente continua a exigir a factura.
|
||||
</p>
|
||||
{(['purchases', 'services'] as const).map((kind) => (
|
||||
<fieldset
|
||||
key={kind}
|
||||
@@ -168,13 +193,101 @@ export function SupplierAdvancesEditor({
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{plan.accountingRegime === 'PGC-NIRF' && (
|
||||
<fieldset className="min-w-0 space-y-2 rounded border p-2">
|
||||
<legend>
|
||||
Acordo formal correspondente
|
||||
(opcional)
|
||||
</legend>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={
|
||||
o.formalAgreement !==
|
||||
undefined
|
||||
}
|
||||
onChange={(e) =>
|
||||
update(i, {
|
||||
formalAgreement: e
|
||||
.target.checked
|
||||
? {
|
||||
date: '',
|
||||
reference: '',
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Identificar acordo formal desta
|
||||
operação/parcela
|
||||
</label>
|
||||
{o.formalAgreement && (
|
||||
<div className="grid min-w-0 gap-2 sm:grid-cols-2">
|
||||
<label className="grid gap-1">
|
||||
Data do acordo formal
|
||||
<input
|
||||
type="date"
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={
|
||||
o.formalAgreement
|
||||
.date
|
||||
}
|
||||
onChange={(e) =>
|
||||
update(i, {
|
||||
formalAgreement:
|
||||
{
|
||||
...o.formalAgreement!,
|
||||
date: e
|
||||
.target
|
||||
.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Referência do acordo formal
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={
|
||||
o.formalAgreement
|
||||
.reference
|
||||
}
|
||||
onChange={(e) =>
|
||||
update(i, {
|
||||
formalAgreement:
|
||||
{
|
||||
...o.formalAgreement!,
|
||||
reference:
|
||||
e
|
||||
.target
|
||||
.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Identifique o acordo efectivamente
|
||||
correspondente ao fornecimento
|
||||
reconhecido. Uma proposta ou
|
||||
encomenda não é automaticamente um
|
||||
acordo formal. A aplicação só pode
|
||||
ocorrer a partir do reconhecimento e
|
||||
da data do fundamento identificado.
|
||||
</p>
|
||||
</fieldset>
|
||||
)}
|
||||
<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.
|
||||
recepção/prestação e factura. A aplicação
|
||||
exige reconhecimento e o fundamento
|
||||
permitido pelo regime; não se pressupõe uma
|
||||
factura em falta. Reconhecimento fora do
|
||||
horizonte conserva o adiantamento no activo.
|
||||
</p>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
@@ -286,11 +399,12 @@ export function SupplierAdvancesEditor({
|
||||
))}
|
||||
<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.
|
||||
mesmo dia, na ordem apresentada. Aplicação
|
||||
exige reconhecimento e o fundamento
|
||||
permitido pelo regime. O pagamento do
|
||||
remanescente exige factura e reconhecimento.
|
||||
O pagamento do remanescente não pode voltar
|
||||
a pagar o adiantamento associado.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
@@ -430,12 +544,26 @@ export function SupplierAdvancesEditor({
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{plan.accountingRegime === 'PGC-NIRF' && (
|
||||
<p>
|
||||
{o.monthly
|
||||
.map(
|
||||
(m) =>
|
||||
`Mês ${m.month}: ${advanceDocumentLabel(m.documentaryStatus ?? '')}`,
|
||||
)
|
||||
.join('; ')}
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
{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.'
|
||||
: ''}{' '}
|
||||
{e.applicationBasis
|
||||
? `Fundamento: ${e.applicationBasis.kind === 'formal_agreement' ? 'acordo formal' : 'factura'} ${e.applicationBasis.reference}, de ${e.applicationBasis.date}.`
|
||||
: ''}
|
||||
</p>
|
||||
))}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
buildSupplierAdvances,
|
||||
isSupplierAdvances,
|
||||
type SupplierAdvances,
|
||||
type AccountingRegime,
|
||||
} from './supplier-advances.ts';
|
||||
import {
|
||||
buildDayTermSchedule,
|
||||
@@ -97,6 +98,7 @@ export type BusinessFinancialPlanInput = {
|
||||
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
|
||||
dayTerms?: DayTerms;
|
||||
supplierAdvances?: SupplierAdvances;
|
||||
accountingRegime?: AccountingRegime;
|
||||
economicClassification?: {
|
||||
code: string;
|
||||
revision: string;
|
||||
@@ -217,27 +219,29 @@ export function serializeBusinessPlanSnapshot(
|
||||
): string {
|
||||
const snapshot = JSON.stringify({
|
||||
version:
|
||||
plan.supplierAdvances !== undefined
|
||||
? 21
|
||||
: plan.dayTerms !== undefined
|
||||
? 20
|
||||
: plan.startupAssetRequirements
|
||||
? 19
|
||||
: [
|
||||
'applyAnnualGrowth',
|
||||
'creditTermDays',
|
||||
'dividendsByPeriod',
|
||||
'operatingExpenseLines',
|
||||
'fundingBreakdown',
|
||||
'reportSource',
|
||||
].some(
|
||||
(key) =>
|
||||
plan[
|
||||
key as keyof BusinessFinancialPlanInput
|
||||
] !== undefined,
|
||||
)
|
||||
? 18
|
||||
: 17,
|
||||
plan.accountingRegime !== undefined
|
||||
? 22
|
||||
: plan.supplierAdvances !== undefined
|
||||
? 21
|
||||
: plan.dayTerms !== undefined
|
||||
? 20
|
||||
: plan.startupAssetRequirements
|
||||
? 19
|
||||
: [
|
||||
'applyAnnualGrowth',
|
||||
'creditTermDays',
|
||||
'dividendsByPeriod',
|
||||
'operatingExpenseLines',
|
||||
'fundingBreakdown',
|
||||
'reportSource',
|
||||
].some(
|
||||
(key) =>
|
||||
plan[
|
||||
key as keyof BusinessFinancialPlanInput
|
||||
] !== undefined,
|
||||
)
|
||||
? 18
|
||||
: 17,
|
||||
plan: {
|
||||
...plan,
|
||||
...(plan.useSupplierPaymentTerms === true
|
||||
@@ -323,7 +327,8 @@ export function restoreBusinessPlanSnapshot(
|
||||
decoded.version !== 18 &&
|
||||
decoded.version !== 19 &&
|
||||
decoded.version !== 20 &&
|
||||
decoded.version !== 21) ||
|
||||
decoded.version !== 21 &&
|
||||
decoded.version !== 22) ||
|
||||
!decoded.plan ||
|
||||
typeof decoded.plan !== 'object'
|
||||
)
|
||||
@@ -331,12 +336,13 @@ export function restoreBusinessPlanSnapshot(
|
||||
const plan = decoded.plan as Record<string, unknown>;
|
||||
if (
|
||||
plan.dayTerms !== undefined &&
|
||||
(![20, 21].includes(decoded.version) || !isDayTerms(plan.dayTerms))
|
||||
(![20, 21, 22].includes(decoded.version) ||
|
||||
!isDayTerms(plan.dayTerms))
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.supplierAdvances !== undefined &&
|
||||
(decoded.version !== 21 ||
|
||||
(![21, 22].includes(decoded.version) ||
|
||||
!isSupplierAdvances(plan.supplierAdvances))
|
||||
)
|
||||
return null;
|
||||
@@ -352,6 +358,31 @@ export function restoreBusinessPlanSnapshot(
|
||||
].some((key) => plan[key] !== undefined)
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.accountingRegime !== undefined &&
|
||||
(decoded.version !== 22 ||
|
||||
typeof plan.accountingRegime !== 'string' ||
|
||||
!['PGC-PE', 'PGC-NIRF'].includes(plan.accountingRegime))
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
decoded.version === 22 &&
|
||||
(typeof plan.accountingRegime !== 'string' ||
|
||||
!['PGC-PE', 'PGC-NIRF'].includes(plan.accountingRegime))
|
||||
)
|
||||
return null;
|
||||
const advances = plan.supplierAdvances as SupplierAdvances | undefined;
|
||||
if (
|
||||
advances?.regime === 'PGC-NIRF' &&
|
||||
(decoded.version !== 22 || plan.accountingRegime !== 'PGC-NIRF')
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.accountingRegime &&
|
||||
advances?.regime &&
|
||||
plan.accountingRegime !== advances.regime
|
||||
)
|
||||
return null;
|
||||
const shortText = (v: unknown) =>
|
||||
typeof v === 'string' && v.length <= 160;
|
||||
if (plan.startupAssetRequirements !== undefined) {
|
||||
@@ -472,7 +503,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
[12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
) &&
|
||||
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
|
||||
@@ -485,7 +516,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
plan.inventoryPurchaseSchedule !== null
|
||||
) {
|
||||
if (
|
||||
![12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
![12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
|
||||
@@ -510,14 +541,18 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[13, 14, 15, 16, 17, 20, 21].includes(Number(decoded.version)) &&
|
||||
[13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
) &&
|
||||
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
|
||||
plan.monthlyVariableCostPaymentsByPeriod !== null &&
|
||||
(![13, 14, 15, 16, 17, 20, 21].includes(Number(decoded.version)) ||
|
||||
(![13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
|
||||
plan.monthlyVariableCostPaymentsByPeriod.length <
|
||||
Number(plan.periods) ||
|
||||
@@ -582,7 +617,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
if (openingCollectionRate < 0n || openingCollectionRate > 100_000_000n)
|
||||
return null;
|
||||
if (
|
||||
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
)
|
||||
) {
|
||||
@@ -655,7 +690,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
)
|
||||
) {
|
||||
@@ -694,7 +729,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
const schedule = plan[field];
|
||||
if (
|
||||
schedule !== undefined &&
|
||||
(![11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
(![11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(schedule) ||
|
||||
@@ -784,7 +819,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
const costSchedule = productData.unitVariableCostByPeriod;
|
||||
const validMoneySchedule = (values: unknown) =>
|
||||
values === undefined ||
|
||||
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
) &&
|
||||
Array.isArray(values) &&
|
||||
@@ -793,9 +828,9 @@ export function restoreBusinessPlanSnapshot(
|
||||
values.every((value) => typeof value === 'string'));
|
||||
return (
|
||||
(schedule !== undefined &&
|
||||
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
(![
|
||||
9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22,
|
||||
].includes(Number(decoded.version)) ||
|
||||
!Array.isArray(schedule) ||
|
||||
schedule.length < Number(plan.periods) ||
|
||||
schedule.length > 60 ||
|
||||
@@ -832,7 +867,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
entry.paymentLagMonths < 0 ||
|
||||
entry.paymentLagMonths > 12)) ||
|
||||
(entry.paymentInstallments !== undefined &&
|
||||
(![16, 17, 20, 21].includes(
|
||||
(![16, 17, 20, 21, 22].includes(
|
||||
Number(decoded.version),
|
||||
) ||
|
||||
!Array.isArray(
|
||||
@@ -1489,6 +1524,27 @@ type ActiveDayTerms = ReturnType<typeof buildDayTermSchedule> & {
|
||||
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
const config = input.dayTerms;
|
||||
const advances = input.supplierAdvances;
|
||||
if (
|
||||
input.accountingRegime !== undefined &&
|
||||
!['PGC-PE', 'PGC-NIRF'].includes(input.accountingRegime)
|
||||
)
|
||||
throw Error('Seleccione PGC-PE ou PGC-NIRF no plano.');
|
||||
if (
|
||||
advances?.regime === 'PGC-NIRF' &&
|
||||
input.accountingRegime !== 'PGC-NIRF'
|
||||
)
|
||||
throw Error(
|
||||
'Adiantamentos PGC-NIRF exigem identificação explícita do regime no plano.',
|
||||
);
|
||||
if (
|
||||
input.accountingRegime &&
|
||||
advances?.regime &&
|
||||
input.accountingRegime !== advances.regime
|
||||
)
|
||||
throw Error(
|
||||
'O regime do plano diverge da agenda de adiantamentos. Confirme a mudança de regime antes de recalcular.',
|
||||
);
|
||||
|
||||
if (config !== undefined && !isDayTerms(config))
|
||||
throw new Error('Prazos em dias: estrutura inválida.');
|
||||
if (advances !== undefined && !isSupplierAdvances(advances))
|
||||
@@ -3710,11 +3766,19 @@ export function exportBusinessPlanCsv(
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (input.accountingRegime)
|
||||
rows.push(
|
||||
[],
|
||||
[
|
||||
'Regime contabilístico declarado no plano',
|
||||
input.accountingRegime,
|
||||
],
|
||||
);
|
||||
if (result.supplierAdvanceLedger) {
|
||||
rows.push(
|
||||
[],
|
||||
[
|
||||
'Adiantamentos por operação — PGC-PE; projecções sem IVA, câmbio, perdas ou penalizações',
|
||||
`Adiantamentos por operação — ${result.supplierAdvanceLedger.regime}; projecções sem IVA, câmbio, perdas ou penalizações`,
|
||||
],
|
||||
[
|
||||
'Operação',
|
||||
@@ -3760,6 +3824,34 @@ export function exportBusinessPlanCsv(
|
||||
]),
|
||||
),
|
||||
);
|
||||
if (result.supplierAdvanceLedger.regime === 'PGC-NIRF')
|
||||
rows.push(
|
||||
[],
|
||||
[
|
||||
'Operação',
|
||||
'Parcela',
|
||||
'Acordo formal',
|
||||
'Data do acordo',
|
||||
'Aplicação',
|
||||
'Fundamento',
|
||||
'Referência',
|
||||
],
|
||||
...result.supplierAdvanceLedger.operations.flatMap((o) =>
|
||||
o.events
|
||||
.filter((e) => e.kind === 'apply')
|
||||
.map((e) => [
|
||||
o.originId,
|
||||
o.parcelId,
|
||||
o.formalAgreement?.reference ?? '',
|
||||
o.formalAgreement?.date ?? '',
|
||||
e.date,
|
||||
e.applicationBasis?.kind === 'formal_agreement'
|
||||
? 'Acordo formal'
|
||||
: 'Factura',
|
||||
e.applicationBasis?.reference ?? '',
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
return `\uFEFF${rows
|
||||
.map((row) => row.map(csvCell).join(','))
|
||||
|
||||
@@ -4,7 +4,10 @@ import {
|
||||
type BusinessFinancialPlanInput,
|
||||
} from './business-financial-plan.ts';
|
||||
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
|
||||
import { advanceEventLabels } from './supplier-advances.ts';
|
||||
import {
|
||||
advanceEventLabels,
|
||||
advanceDocumentLabel,
|
||||
} from './supplier-advances.ts';
|
||||
|
||||
export type InvestmentReportTable = {
|
||||
id: string;
|
||||
@@ -712,6 +715,10 @@ export function buildIntegralFinancialTables(
|
||||
label,
|
||||
ledger.map((row) => row[key]),
|
||||
);
|
||||
if (plan.accountingRegime)
|
||||
table('balance').notes.push(
|
||||
`Regime contabilístico declarado no plano: ${plan.accountingRegime}. Tratamentos limitados ao âmbito implementado; não equivale a certificação integral do regime.`,
|
||||
);
|
||||
if (result.supplierAdvanceLedger) {
|
||||
stocks(
|
||||
'balance',
|
||||
@@ -739,16 +746,34 @@ export function buildIntegralFinancialTables(
|
||||
),
|
||||
);
|
||||
table('balance').notes.push(
|
||||
'PGC-PE: adiantamentos identificados apresentados no activo, separados das obrigações brutas. Líquido por liquidar é calculado por operação/parcela, sem compensação entre operações. Devoluções não são receita; aplicações não movimentam caixa.',
|
||||
`${result.supplierAdvanceLedger.regime}: adiantamentos identificados apresentados no activo, separados das obrigações brutas. Líquido por liquidar é calculado por operação/parcela, sem compensação entre operações. Devoluções não são receita; aplicações não movimentam caixa.`,
|
||||
);
|
||||
table('cashflow').notes.push(
|
||||
'Adiantamentos, aplicações, devoluções e remanescentes são projecções discriminadas, já incluídas nos totais de caixa quando aplicável; não somar novamente. Sem automatização de IVA, câmbio, perdas, penalizações ou contratos especiais.',
|
||||
...result.supplierAdvanceLedger.operations.map(
|
||||
(o) =>
|
||||
`${o.originId}/${o.parcelId} — ${o.supplier}: reconhecimento ${o.recognitionDate || 'por confirmar'}; factura ${o.invoiceDate || 'por confirmar'}. ${o.events.map((e) => `${advanceEventLabels[e.kind]}: ${e.date}, ${e.amount} ${plan.currency}${e.outsideHorizon ? ' (fora do horizonte)' : ''}`).join('; ')}.`,
|
||||
`${o.originId}/${o.parcelId} — ${o.supplier}: reconhecimento ${o.recognitionDate || 'por confirmar'}; factura ${o.invoiceDate || 'por confirmar'}. ${o.formalAgreement ? `Acordo formal ${o.formalAgreement.reference}, ${o.formalAgreement.date}. ` : ''}${o.events.map((e) => `${advanceEventLabels[e.kind]}: ${e.date}, ${e.amount} ${plan.currency}${e.outsideHorizon ? ' (fora do horizonte)' : ''}`).join('; ')}.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (result.supplierAdvanceLedger?.regime === 'PGC-NIRF')
|
||||
table('balance').notes.push(
|
||||
...result.supplierAdvanceLedger.operations.map(
|
||||
(o) =>
|
||||
`${o.originId}/${o.parcelId}: ${o.monthly.map((m) => `mês ${m.month}, ${advanceDocumentLabel(m.documentaryStatus ?? '')}`).join('; ')}.`,
|
||||
),
|
||||
);
|
||||
if (result.supplierAdvanceLedger?.regime === 'PGC-NIRF')
|
||||
table('cashflow').notes.push(
|
||||
...result.supplierAdvanceLedger.operations.flatMap((o) =>
|
||||
o.events
|
||||
.filter((e) => e.applicationBasis)
|
||||
.map(
|
||||
(e) =>
|
||||
`${o.originId}/${o.parcelId}: aplicação ${e.date}, fundamento ${e.applicationBasis!.kind === 'formal_agreement' ? 'acordo formal' : 'factura'}, referência ${e.applicationBasis!.reference}, data ${e.applicationBasis!.date}.`,
|
||||
),
|
||||
),
|
||||
);
|
||||
table('balance').rows.push([
|
||||
'Existências',
|
||||
...ledger.map((row) =>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export type AdvanceKind = 'purchases' | 'services';
|
||||
export type AdvanceEventKind = 'advance' | 'apply' | 'refund' | 'settle';
|
||||
export type AccountingRegime = 'PGC-PE' | 'PGC-NIRF';
|
||||
export type SupplierAdvanceOperation = {
|
||||
originId: string;
|
||||
parcelId: string;
|
||||
@@ -8,6 +9,7 @@ export type SupplierAdvanceOperation = {
|
||||
amount: string;
|
||||
recognitionDate: string;
|
||||
invoiceDate: string;
|
||||
formalAgreement?: { date: string; reference: string };
|
||||
ordinaryContract: boolean;
|
||||
events: {
|
||||
id: string;
|
||||
@@ -17,7 +19,7 @@ export type SupplierAdvanceOperation = {
|
||||
}[];
|
||||
};
|
||||
export type SupplierAdvances = {
|
||||
regime: '' | 'PGC-PE';
|
||||
regime: '' | AccountingRegime;
|
||||
purchases: boolean;
|
||||
services: boolean;
|
||||
operations: SupplierAdvanceOperation[];
|
||||
@@ -32,12 +34,22 @@ export const advanceEventLabels = {
|
||||
refund: 'Devolução do adiantamento',
|
||||
settle: 'Pagamento do remanescente',
|
||||
};
|
||||
export function advanceDocumentLabel(status: string) {
|
||||
const labels: Record<string, string> = {
|
||||
not_recognized: 'Ainda não reconhecido',
|
||||
invoice: 'Fornecimento facturado',
|
||||
formal_agreement: 'Fornecimento formalmente acordado',
|
||||
pending_documentation:
|
||||
'Fornecimento reconhecido, documentação por confirmar',
|
||||
};
|
||||
return labels[status] ?? 'Por confirmar';
|
||||
}
|
||||
const text = (v: unknown) => typeof v === 'string' && v.length <= 160;
|
||||
export function isSupplierAdvances(v: unknown): v is SupplierAdvances {
|
||||
if (!v || typeof v !== 'object') return false;
|
||||
const c = v as SupplierAdvances;
|
||||
return (
|
||||
['', 'PGC-PE'].includes(c.regime) &&
|
||||
['', 'PGC-PE', 'PGC-NIRF'].includes(c.regime) &&
|
||||
typeof c.purchases === 'boolean' &&
|
||||
typeof c.services === 'boolean' &&
|
||||
Array.isArray(c.operations) &&
|
||||
@@ -47,6 +59,10 @@ export function isSupplierAdvances(v: unknown): v is SupplierAdvances {
|
||||
o &&
|
||||
['purchases', 'services'].includes(o.kind) &&
|
||||
typeof o.ordinaryContract === 'boolean' &&
|
||||
(o.formalAgreement === undefined ||
|
||||
(o.formalAgreement &&
|
||||
text(o.formalAgreement.date) &&
|
||||
text(o.formalAgreement.reference))) &&
|
||||
[
|
||||
'originId',
|
||||
'parcelId',
|
||||
@@ -89,9 +105,9 @@ export function buildSupplierAdvances(
|
||||
) {
|
||||
if (!isSupplierAdvances(config))
|
||||
throw Error('Adiantamentos: estrutura inválida.');
|
||||
if (config.regime !== 'PGC-PE')
|
||||
if (!['PGC-PE', 'PGC-NIRF'].includes(config.regime))
|
||||
throw Error(
|
||||
'Adiantamentos: seleccione explicitamente PGC-PE. Outros regimes não estão automatizados.',
|
||||
'Adiantamentos: seleccione explicitamente PGC-PE ou PGC-NIRF.',
|
||||
);
|
||||
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
|
||||
throw Error(
|
||||
@@ -145,6 +161,12 @@ export function buildSupplierAdvances(
|
||||
o.supplier.trim(),
|
||||
o.recognitionDate,
|
||||
o.invoiceDate,
|
||||
...(config.regime === 'PGC-NIRF'
|
||||
? [
|
||||
o.formalAgreement?.date ?? '',
|
||||
o.formalAgreement?.reference.trim() ?? '',
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
if (origins.has(originKey) && origins.get(originKey) !== identity)
|
||||
fail(
|
||||
@@ -158,6 +180,18 @@ export function buildSupplierAdvances(
|
||||
? date(o.recognitionDate)
|
||||
: null;
|
||||
const invoice = o.invoiceDate ? date(o.invoiceDate) : null;
|
||||
const agreement =
|
||||
config.regime === 'PGC-NIRF' && o.formalAgreement
|
||||
? date(o.formalAgreement.date)
|
||||
: null;
|
||||
if (
|
||||
config.regime === 'PGC-NIRF' &&
|
||||
o.formalAgreement &&
|
||||
(!agreement || !o.formalAgreement.reference.trim())
|
||||
)
|
||||
fail(
|
||||
'acordo formal exige data válida e referência identificada da mesma operação; não basta orçamento ou encomenda.',
|
||||
);
|
||||
if (o.recognitionDate && !recognition)
|
||||
fail('data de reconhecimento inválida.');
|
||||
if (o.invoiceDate && !invoice) fail('data de factura inválida.');
|
||||
@@ -204,6 +238,11 @@ export function buildSupplierAdvances(
|
||||
advance: string;
|
||||
obligation: string;
|
||||
netDue: string;
|
||||
applicationBasis?: {
|
||||
kind: 'invoice' | 'formal_agreement';
|
||||
date: string;
|
||||
reference: string;
|
||||
};
|
||||
}[] = [];
|
||||
const process = (e: (typeof events)[number]) => {
|
||||
if (!isRecognized && recognition && recognition <= e.when) {
|
||||
@@ -212,6 +251,13 @@ export function buildSupplierAdvances(
|
||||
}
|
||||
const m = index(e.when);
|
||||
const inside = m >= 0 && m < periods;
|
||||
let applicationBasis:
|
||||
| {
|
||||
kind: 'invoice' | 'formal_agreement';
|
||||
date: string;
|
||||
reference: string;
|
||||
}
|
||||
| undefined;
|
||||
if (e.kind === 'advance') {
|
||||
if (isRecognized)
|
||||
fail(
|
||||
@@ -223,10 +269,26 @@ export function buildSupplierAdvances(
|
||||
paid[m] += e.value;
|
||||
}
|
||||
} else if (e.kind === 'apply') {
|
||||
if (!isRecognized || !invoice || invoice > e.when)
|
||||
const hasInvoice = !!invoice && invoice <= e.when;
|
||||
const hasAgreement = !!agreement && agreement <= e.when;
|
||||
if (!isRecognized || (!hasInvoice && !hasAgreement))
|
||||
fail(
|
||||
'aplicação exige reconhecimento e factura correspondente, sem antecipar datas.',
|
||||
config.regime === 'PGC-NIRF'
|
||||
? 'aplicação exige reconhecimento e factura ou acordo formal correspondente já datado e identificado, sem antecipar datas.'
|
||||
: 'aplicação exige reconhecimento e factura correspondente, sem antecipar datas.',
|
||||
);
|
||||
if (config.regime === 'PGC-NIRF')
|
||||
applicationBasis = hasInvoice
|
||||
? {
|
||||
kind: 'invoice',
|
||||
date: o.invoiceDate,
|
||||
reference: o.originId + '/' + o.parcelId,
|
||||
}
|
||||
: {
|
||||
kind: 'formal_agreement',
|
||||
date: o.formalAgreement!.date,
|
||||
reference: o.formalAgreement!.reference,
|
||||
};
|
||||
if (e.value > advance || e.value > obligation)
|
||||
fail(
|
||||
'aplicação excede o saldo da mesma parcela ou a obrigação reconhecida.',
|
||||
@@ -269,6 +331,7 @@ export function buildSupplierAdvances(
|
||||
netDue: money(
|
||||
obligation > advance ? obligation - advance : 0n,
|
||||
),
|
||||
...(applicationBasis ? { applicationBasis } : {}),
|
||||
});
|
||||
};
|
||||
const monthly = [];
|
||||
@@ -293,6 +356,17 @@ export function buildSupplierAdvances(
|
||||
obligation: money(obligation),
|
||||
netDue: money(netDue),
|
||||
recognized: isRecognized,
|
||||
...(config.regime === 'PGC-NIRF'
|
||||
? {
|
||||
documentaryStatus: !isRecognized
|
||||
? 'not_recognized'
|
||||
: invoice && invoice < boundary
|
||||
? 'invoice'
|
||||
: agreement && agreement < boundary
|
||||
? 'formal_agreement'
|
||||
: 'pending_documentation',
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
// Validate future events as well; they never leak into the last month of cash.
|
||||
@@ -305,6 +379,9 @@ export function buildSupplierAdvances(
|
||||
amount: money(amount),
|
||||
recognitionDate: o.recognitionDate,
|
||||
invoiceDate: o.invoiceDate,
|
||||
...(config.regime === 'PGC-NIRF' && o.formalAgreement
|
||||
? { formalAgreement: o.formalAgreement }
|
||||
: {}),
|
||||
recognitionOutsideHorizon: !recognition || recognition >= end,
|
||||
monthly,
|
||||
events: audit,
|
||||
|
||||
Reference in New Issue
Block a user