fix: complete InvesteMoz validation and error corrections
This commit is contained in:
@@ -1,13 +1,13 @@
|
||||
import {annualReportRows} from './irpc-annual-settlement.ts';
|
||||
import {proactiveInvestmentRows} from './proactive-investment-report.ts';
|
||||
import {normalReportRows} from './irpc-normal.ts';
|
||||
import {irpcReportRows} from './irpc-withholdings.ts';
|
||||
import {ispcResidualReportRows} from './ispc-residuals.ts';
|
||||
import {ispcWithholdingReportRows} from './ispc-withholding.ts';
|
||||
import {ispcQuarterReportRows} from './ispc-quarter.ts';
|
||||
import {ispcEligibilityReportRows} from './ispc-eligibility.ts';
|
||||
import {fiscalCalculationGapReportRows} from './iva-calculation-gaps.ts';
|
||||
import {l3FormPreparationReportRows} from './l3-form-preparation.ts';
|
||||
import { annualReportRows } from './irpc-annual-settlement.ts';
|
||||
import { proactiveInvestmentRows } from './proactive-investment-report.ts';
|
||||
import { normalReportRows } from './irpc-normal.ts';
|
||||
import { irpcReportRows } from './irpc-withholdings.ts';
|
||||
import { ispcResidualReportRows } from './ispc-residuals.ts';
|
||||
import { ispcWithholdingReportRows } from './ispc-withholding.ts';
|
||||
import { ispcQuarterReportRows } from './ispc-quarter.ts';
|
||||
import { ispcEligibilityReportRows } from './ispc-eligibility.ts';
|
||||
import { fiscalCalculationGapReportRows } from './iva-calculation-gaps.ts';
|
||||
import { l3FormPreparationReportRows } from './l3-form-preparation.ts';
|
||||
import { remissionReportRows } from './iva-remission-imports.ts';
|
||||
import { digitalReportRows } from './iva-digital.ts';
|
||||
import { objectiveImportReportRows } from './iva-objective-imports.ts';
|
||||
@@ -22,13 +22,18 @@ import { goodsPresumptionReportRows } from './iva-goods-presumptions.ts';
|
||||
import { displayValue } from './display-value.ts';
|
||||
import { investmentFieldOrigin } from './context-inheritance.ts';
|
||||
import { investmentLandPreparation } from './investment-land-preparation.ts';
|
||||
import { monthlyIvaInput, monthlyIvaKey, readMonthlyIvaRecord, readMonthlyIvaSettings } from './monthly-iva.ts';
|
||||
import {
|
||||
monthlyIvaInput,
|
||||
monthlyIvaKey,
|
||||
readMonthlyIvaRecord,
|
||||
readMonthlyIvaSettings,
|
||||
} from './monthly-iva.ts';
|
||||
import { modeloAPurchaseReferences } from './iva-modelo-a.ts';
|
||||
import { acquisitionReportRows } from './iva-acquisitions.ts';
|
||||
import {closureReportRows} from './iva-closure.ts';
|
||||
import {substitutionReportRows} from './iva-substitution.ts';
|
||||
import {refundReportRows} from './iva-refund.ts';
|
||||
import {beverageRestitutionReportRows} from './iva-beverage-restitution.ts';
|
||||
import { closureReportRows } from './iva-closure.ts';
|
||||
import { substitutionReportRows } from './iva-substitution.ts';
|
||||
import { refundReportRows } from './iva-refund.ts';
|
||||
import { beverageRestitutionReportRows } from './iva-beverage-restitution.ts';
|
||||
import { importExemptionReportRows } from './iva-import-exemptions.ts';
|
||||
import { publicBaseReportRows } from './iva-public-authority-base.ts';
|
||||
import { commissionBaseReportRows } from './iva-commission-base.ts';
|
||||
@@ -707,14 +712,64 @@ export function buildProjectDossierRows(
|
||||
if (draft.monthly_iva_snapshot) {
|
||||
const saved = readMonthlyIvaRecord(String(draft.monthly_iva_snapshot));
|
||||
let current = false;
|
||||
try { current = !!saved && monthlyIvaKey(monthlyIvaInput(draft, readMonthlyIvaSettings(String(draft.monthly_iva_settings ?? '')))) === monthlyIvaKey(saved.input); } catch { /* An old fiscal version is never silently made current. */ }
|
||||
rows.push(['IVA mensal', 'Estado da versão', current ? 'Entradas correspondentes à projecção guardada' : 'Histórico desactualizado face às vendas ou pressupostos actuais; não aplicar como resultado actual', 'Execução versionada no servidor; sem apuramento final']);
|
||||
if (saved?.execution.result_snapshot) for (const [label,value] of fiscalQaRows(saved.execution.result_snapshot)) rows.push(['IVA mensal', operationRows.length ? `Execução geral separada — ${label}` : label, value, operationRows.length ? 'Snapshot geral conservado como execução separada; não somar nem substituir a classificação por operação L1. Sem recálculo na exportação.' : 'Snapshot fiscal preservado; sem recálculo na exportação']);
|
||||
else rows.push(['IVA mensal', 'Resultado', 'Indeterminado ou execução ainda não concluída', 'Sem substituição por zero']);
|
||||
try {
|
||||
for (const purchase of modeloAPurchaseReferences(draft)) rows.push(['IVA mensal', `Compras/encomendas — mês ${purchase.month}`, purchase.declared ?? 'Sem informação', 'Pressuposto actual do plano, não resultado fiscal histórico; base/IVA incluído por classificar; IVA suportado e dedutível indeterminados; não é data de factura ou pagamento']);
|
||||
current =
|
||||
!!saved &&
|
||||
monthlyIvaKey(
|
||||
monthlyIvaInput(
|
||||
draft,
|
||||
readMonthlyIvaSettings(
|
||||
String(draft.monthly_iva_settings ?? ''),
|
||||
),
|
||||
),
|
||||
) === monthlyIvaKey(saved.input);
|
||||
} catch {
|
||||
rows.push(['IVA mensal','Aquisições projectadas','Não foi possível recuperar; sem substituição por zero','Pressupostos guardados preservados; não calcula deduções']);
|
||||
/* An old fiscal version is never silently made current. */
|
||||
}
|
||||
rows.push([
|
||||
'IVA mensal',
|
||||
'Estado da versão',
|
||||
current
|
||||
? 'Entradas correspondentes à projecção guardada'
|
||||
: 'Histórico desactualizado face às vendas ou pressupostos actuais; não aplicar como resultado actual',
|
||||
'Execução versionada no servidor; sem apuramento final',
|
||||
]);
|
||||
if (saved?.execution.result_snapshot)
|
||||
for (const [label, value] of fiscalQaRows(
|
||||
saved.execution.result_snapshot,
|
||||
))
|
||||
rows.push([
|
||||
'IVA mensal',
|
||||
operationRows.length
|
||||
? `Execução geral separada — ${label}`
|
||||
: label,
|
||||
value,
|
||||
operationRows.length
|
||||
? 'Snapshot geral conservado como execução separada; não somar nem substituir a classificação por operação L1. Sem recálculo na exportação.'
|
||||
: 'Snapshot fiscal preservado; sem recálculo na exportação',
|
||||
]);
|
||||
else
|
||||
rows.push([
|
||||
'IVA mensal',
|
||||
'Resultado',
|
||||
'Indeterminado ou execução ainda não concluída',
|
||||
'Sem substituição por zero',
|
||||
]);
|
||||
try {
|
||||
for (const purchase of modeloAPurchaseReferences(draft))
|
||||
rows.push([
|
||||
'IVA mensal',
|
||||
`Compras/encomendas — mês ${purchase.month}`,
|
||||
purchase.declared ?? 'Sem informação',
|
||||
'Pressuposto actual do plano, não resultado fiscal histórico; base/IVA incluído por classificar; IVA suportado e dedutível indeterminados; não é data de factura ou pagamento',
|
||||
]);
|
||||
} catch {
|
||||
rows.push([
|
||||
'IVA mensal',
|
||||
'Aquisições projectadas',
|
||||
'Não foi possível recuperar; sem substituição por zero',
|
||||
'Pressupostos guardados preservados; não calcula deduções',
|
||||
]);
|
||||
}
|
||||
}
|
||||
if (draft.cashflow_snapshot) {
|
||||
@@ -728,9 +783,18 @@ export function buildProjectDossierRows(
|
||||
throw new Error(
|
||||
'Pressupostos de tesouraria não recuperáveis; não foram substituídos por valores alternativos.',
|
||||
);
|
||||
const originCurrency = cashflowCurrency(saved, 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 (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.',
|
||||
@@ -783,33 +847,139 @@ export function buildProjectDossierRows(
|
||||
}
|
||||
if (draft.context_applicability_snapshot) {
|
||||
try {
|
||||
const context = JSON.parse(String(draft.context_applicability_snapshot));
|
||||
if (context.version === 1 && Array.isArray(context.complements)) for (const item of context.complements) {
|
||||
if (typeof item?.title !== 'string' || typeof item?.origin?.title !== 'string') continue;
|
||||
rows.push(['Localização', 'Complemento escolhido', item.title, `Origem: ${item.origin.title}; ${item.kind === 'need' ? 'necessidade complementar em preparação' : item.kind === 'service' ? 'serviço/instrumento' : 'oportunidade cadastrada'}`]);
|
||||
if (typeof item.target?.title === 'string') rows.push(['Localização', 'Ficha complementar', item.target.title, item.target.href ?? 'Referência guardada']);
|
||||
}
|
||||
if (context.version === 1 && Array.isArray(context.opportunity_choices)) for (const choice of context.opportunity_choices) {
|
||||
if (typeof choice?.opportunity?.title !== 'string') continue;
|
||||
rows.push(['Localização', 'Oportunidade escolhida', choice.opportunity.title, 'Referência escolhida no mesmo dossier']);
|
||||
rows.push(['Localização', 'Localização da oportunidade', typeof choice.territory?.title === 'string' ? choice.territory.title : 'Por definir', choice.opportunity.title]);
|
||||
rows.push(['Localização', 'Zona/parque da oportunidade', typeof choice.park?.title === 'string' ? choice.park.title : 'Sem selecção', choice.opportunity.title+'; '+choice.opportunity.key]);
|
||||
if (Array.isArray(choice.portfolio_origins)) for (const origin of choice.portfolio_origins) {
|
||||
if (typeof origin?.title !== 'string') continue;
|
||||
rows.push(['Localização', 'Associação escolhida na carteira', origin.title, choice.opportunity.title+'; referência documental consultada, sem inferir implantação ou benefícios']);
|
||||
const context = JSON.parse(
|
||||
String(draft.context_applicability_snapshot),
|
||||
);
|
||||
if (context.version === 1 && Array.isArray(context.complements))
|
||||
for (const item of context.complements) {
|
||||
if (
|
||||
typeof item?.title !== 'string' ||
|
||||
typeof item?.origin?.title !== 'string'
|
||||
)
|
||||
continue;
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Complemento escolhido',
|
||||
item.title,
|
||||
`Origem: ${item.origin.title}; ${item.kind === 'need' ? 'necessidade complementar em preparação' : item.kind === 'service' ? 'serviço/instrumento' : 'oportunidade cadastrada'}`,
|
||||
]);
|
||||
if (typeof item.target?.title === 'string')
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Ficha complementar',
|
||||
item.target.title,
|
||||
item.target.href ?? 'Referência guardada',
|
||||
]);
|
||||
}
|
||||
}
|
||||
} catch { /* An unreadable context remains indeterminate; do not reconstruct associations. */ }
|
||||
const land = investmentLandPreparation(draft.context_applicability_snapshot);
|
||||
rows.push(['Localização', 'Necessidade de terra', land.need === 'no' ? 'Não' : land.need === 'yes' ? 'Sim' : 'Por definir', land.reason || 'Decisão de preparação do dossier; não comprova direitos sobre a terra']);
|
||||
if (land.need === 'yes') rows.push(['Localização', 'Situação do terreno', String(draft.land_status_label ?? ({ owned: 'Próprio', duat: 'DUAT', leased: 'Arrendado', requested: 'Pedido em curso', unknown: 'Por determinar' } as Record<string, string>)[String(draft.land_status)] ?? 'Informação em falta'), 'Informação declarada; não comprova título ou disponibilidade']);
|
||||
else rows.push(['Localização', 'Preparação do terreno', land.need === 'no' ? 'Situação do terreno não aplicável à preparação actual; valores anteriores conservados.' : 'Definir se precisa de terra; pode continuar a preparar o investimento.', 'Sem inferência de dispensa legal']);
|
||||
if (
|
||||
context.version === 1 &&
|
||||
Array.isArray(context.opportunity_choices)
|
||||
)
|
||||
for (const choice of context.opportunity_choices) {
|
||||
if (typeof choice?.opportunity?.title !== 'string')
|
||||
continue;
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Oportunidade escolhida',
|
||||
choice.opportunity.title,
|
||||
'Referência escolhida no mesmo dossier',
|
||||
]);
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Localização da oportunidade',
|
||||
typeof choice.territory?.title === 'string'
|
||||
? choice.territory.title
|
||||
: 'Por definir',
|
||||
choice.opportunity.title,
|
||||
]);
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Zona/parque da oportunidade',
|
||||
typeof choice.park?.title === 'string'
|
||||
? choice.park.title
|
||||
: 'Sem selecção',
|
||||
choice.opportunity.title +
|
||||
'; ' +
|
||||
choice.opportunity.key,
|
||||
]);
|
||||
if (Array.isArray(choice.portfolio_origins))
|
||||
for (const origin of choice.portfolio_origins) {
|
||||
if (typeof origin?.title !== 'string') continue;
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Associação escolhida na carteira',
|
||||
origin.title,
|
||||
choice.opportunity.title +
|
||||
'; referência documental consultada, sem inferir implantação ou benefícios',
|
||||
]);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* An unreadable context remains indeterminate; do not reconstruct associations. */
|
||||
}
|
||||
const land = investmentLandPreparation(
|
||||
draft.context_applicability_snapshot,
|
||||
);
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Necessidade de terra',
|
||||
land.need === 'no'
|
||||
? 'Não'
|
||||
: land.need === 'yes'
|
||||
? 'Sim'
|
||||
: 'Por definir',
|
||||
land.reason ||
|
||||
'Decisão de preparação do dossier; não comprova direitos sobre a terra',
|
||||
]);
|
||||
if (land.need === 'yes')
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Situação do terreno',
|
||||
String(
|
||||
draft.land_status_label ??
|
||||
(
|
||||
{
|
||||
owned: 'Próprio',
|
||||
duat: 'DUAT',
|
||||
leased: 'Arrendado',
|
||||
requested: 'Pedido em curso',
|
||||
unknown: 'Por determinar',
|
||||
} as Record<string, string>
|
||||
)[String(draft.land_status)] ??
|
||||
'Informação em falta',
|
||||
),
|
||||
'Informação declarada; não comprova título ou disponibilidade',
|
||||
]);
|
||||
else
|
||||
rows.push([
|
||||
'Localização',
|
||||
'Preparação do terreno',
|
||||
land.need === 'no'
|
||||
? 'Situação do terreno não aplicável à preparação actual; valores anteriores conservados.'
|
||||
: 'Definir se precisa de terra; pode continuar a preparar o investimento.',
|
||||
'Sem inferência de dispensa legal',
|
||||
]);
|
||||
}
|
||||
rows.push(...proactiveInvestmentRows(draft));
|
||||
const lineageFields: Record<string, string> = {'Título':'project_title','Resumo':'project_summary','Sector':'sector_id','Província':'province_id','Distrito':'district_id','Posto administrativo':'admin_post_id','Localidade':'locality_id'};
|
||||
return rows.map(row => {
|
||||
const lineageFields: Record<string, string> = {
|
||||
Título: 'project_title',
|
||||
Resumo: 'project_summary',
|
||||
Sector: 'sector_id',
|
||||
Província: 'province_id',
|
||||
Distrito: 'district_id',
|
||||
'Posto administrativo': 'admin_post_id',
|
||||
Localidade: 'locality_id',
|
||||
};
|
||||
return rows.map((row) => {
|
||||
const key = lineageFields[row[1]];
|
||||
return key && row[2] ? [row[0], row[1], row[2], investmentFieldOrigin(draft, key, row[3])] : row;
|
||||
return key && row[2]
|
||||
? [
|
||||
row[0],
|
||||
row[1],
|
||||
row[2],
|
||||
investmentFieldOrigin(draft, key, row[3]),
|
||||
]
|
||||
: row;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user