fix: preserve cashflow currency and recover admitted monthly IVA executions in QA
This commit is contained in:
@@ -17,7 +17,9 @@ export function defaultCashflowDraftInputs() {
|
||||
}
|
||||
|
||||
export type CashflowDraftSnapshot = {
|
||||
version: 1;
|
||||
version: 1 | 2;
|
||||
/** Missing in legacy v1: never infer it from the current project. */
|
||||
currency?: string | null;
|
||||
taxMode: 'fixed' | 'schedule';
|
||||
inputs: ReturnType<typeof defaultCashflowDraftInputs>;
|
||||
};
|
||||
@@ -31,7 +33,8 @@ export function restoreCashflowDraftSnapshot(
|
||||
const parsed = JSON.parse(snapshot);
|
||||
if (
|
||||
!parsed ||
|
||||
parsed.version !== 1 ||
|
||||
![1, 2].includes(parsed.version) ||
|
||||
(parsed.version === 2 && parsed.currency !== null && (typeof parsed.currency !== 'string' || !/^[A-Z]{3}$/.test(parsed.currency))) ||
|
||||
!['fixed', 'schedule'].includes(parsed.taxMode) ||
|
||||
!parsed.inputs ||
|
||||
typeof parsed.inputs !== 'object' ||
|
||||
@@ -55,7 +58,7 @@ export function restoreCashflowDraftSnapshot(
|
||||
} else if (typeof value !== 'string' || value.length > 160)
|
||||
return null;
|
||||
}
|
||||
return { version: 1, taxMode: parsed.taxMode, inputs: parsed.inputs };
|
||||
return { version: parsed.version, ...(parsed.version === 2 ? {currency: parsed.currency} : {}), taxMode: parsed.taxMode, inputs: parsed.inputs };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -64,8 +67,16 @@ export function restoreCashflowDraftSnapshot(
|
||||
export function serializeCashflowDraftSnapshot(
|
||||
taxMode: CashflowDraftSnapshot['taxMode'],
|
||||
inputs: CashflowDraftSnapshot['inputs'],
|
||||
currency?: string | null,
|
||||
): string {
|
||||
return JSON.stringify({ version: 1, taxMode, inputs });
|
||||
return JSON.stringify({ version: currency === undefined ? 1 : 2, ...(currency !== undefined ? {currency} : {}), taxMode, inputs });
|
||||
}
|
||||
|
||||
export function cashflowCurrency(saved: CashflowDraftSnapshot, projectCurrency: string): {currency: string; matchesProject: boolean; notice: string} {
|
||||
const currency = saved.version === 2 ? saved.currency : null;
|
||||
if (!currency) throw new Error('A moeda de origem da tesouraria guardada está por confirmar. Os montantes foram preservados; confirme a moeda na ferramenta de tesouraria antes de calcular ou reutilizar as vendas.');
|
||||
const matchesProject = currency === projectCurrency;
|
||||
return {currency, matchesProject, notice: matchesProject ? '' : `A tesouraria foi guardada em ${currency}, mas o projecto está em ${projectCurrency || 'moeda por indicar'}. Os montantes continuam em ${currency}; não foram convertidos nem reinterpretados. Para os reutilizar no projecto, restaure explicitamente a moeda de origem. Uma projecção noutra moeda exige pressupostos próprios.`};
|
||||
}
|
||||
|
||||
export type MonthlyCashflowInput = {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { monthlyProjectedSales, restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
|
||||
import { restoreCashflowDraftSnapshot } from './monthly-cashflow.ts';
|
||||
import { cashflowCurrency, restoreCashflowDraftSnapshot } from './monthly-cashflow.ts';
|
||||
import { isApiSimulationReadResponseV1, type ApiSimulationExecutionV1 } from './simulation-contract.ts';
|
||||
|
||||
export type MonthlyIvaInput = {
|
||||
@@ -27,6 +27,8 @@ export function monthlySalesFromDraft(draft: Record<string, unknown>): { amounts
|
||||
if (draft.cashflow_snapshot) {
|
||||
const saved = restoreCashflowDraftSnapshot(String(draft.cashflow_snapshot));
|
||||
if (!saved) throw new Error('Não foi possível recuperar a receita projectada.');
|
||||
const origin = cashflowCurrency(saved, String(draft.currency ?? ''));
|
||||
if (!origin.matchesProject) throw new Error(origin.notice);
|
||||
return {amounts: Array.from({length: 12}, () => saved.inputs.monthlyRevenue.trim() === '' ? null : saved.inputs.monthlyRevenue), source: 'Receita mensal constante já declarada na projecção de tesouraria; confirme que corresponde a vendas tributáveis.'};
|
||||
}
|
||||
return {amounts: Array.from({length: 12}, () => null), source: 'Sem projecção de vendas guardada. Prepare as vendas no plano empresarial; não é necessário voltar a introduzi-las aqui.'};
|
||||
@@ -48,4 +50,11 @@ export function readMonthlyIvaRecord(raw?: string): MonthlyIvaRecord | null {
|
||||
} catch { /* Keep the stored value intact; no fallback fiscal result. */ }
|
||||
return null;
|
||||
}
|
||||
/** Read an admitted execution through the existing ownership-protected endpoint; never create one. */
|
||||
export async function recoverMonthlyIvaRecord(record: MonthlyIvaRecord, request: typeof fetch = fetch): Promise<MonthlyIvaRecord> {
|
||||
const response = await request(`/api/v1/simulations/${encodeURIComponent(record.execution.id)}`, {credentials:'same-origin', headers:{Accept:'application/json'}});
|
||||
const value: unknown = await response.json();
|
||||
if (!response.ok || !isApiSimulationReadResponseV1(value) || value.data.id !== record.execution.id) throw new Error('Não foi possível recuperar a execução mensal guardada. Os dados foram preservados e não foi criada uma execução alternativa.');
|
||||
return {input: record.input, execution: value.data};
|
||||
}
|
||||
export const monthlyIvaCashTreatment = 'IVA apresentado separadamente: não é somado novamente aos recebimentos declarados nem deduzido como custo ou imposto final a pagar. A tesouraria conserva os recebimentos e pagamentos introduzidos, antes de uma liquidação fiscal não apurada; não se presume cobrança integral das vendas no mesmo mês.';
|
||||
|
||||
@@ -7,6 +7,7 @@ import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
import { csvCellWithDelimiter } from './csv.js';
|
||||
import {
|
||||
restoreCashflowDraftSnapshot,
|
||||
cashflowCurrency,
|
||||
projectMonthlyCashflow,
|
||||
} from './monthly-cashflow.ts';
|
||||
import {
|
||||
@@ -637,7 +638,9 @@ export function buildProjectDossierRows(
|
||||
throw new Error(
|
||||
'Pressupostos de tesouraria não recuperáveis; não foram substituídos por valores alternativos.',
|
||||
);
|
||||
const currency = String(draft.currency ?? '');
|
||||
const originCurrency = cashflowCurrency(saved, String(draft.currency ?? ''));
|
||||
const currency = originCurrency.currency;
|
||||
if (originCurrency.notice) rows.push(['Tesouraria', 'Divergência de moeda', originCurrency.notice, 'Moeda original preservada; sem conversão']);
|
||||
if (!currency)
|
||||
throw new Error(
|
||||
'Indique uma moeda para interpretar os montantes de tesouraria.',
|
||||
|
||||
Reference in New Issue
Block a user