@@ -1349,9 +1349,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
|
||||
const presentationCurrency = input.presentationCurrency || input.currency;
|
||||
if (!validCurrency(presentationCurrency))
|
||||
throw new Error(
|
||||
'Seleccione uma moeda de apresentação ISO suportada.',
|
||||
);
|
||||
throw new Error('Seleccione uma moeda de apresentação ISO suportada.');
|
||||
let fxRate: bigint | null = null;
|
||||
if (presentationCurrency !== input.currency) {
|
||||
if (!input.fxRate || !input.fxDate || !input.fxSource?.trim())
|
||||
@@ -1417,7 +1415,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
product.unitVariableCost,
|
||||
`Custo variável do produto ${index + 1}`,
|
||||
);
|
||||
const productInventoryOpening = useProductInventorySchedule
|
||||
const _productInventoryOpening = useProductInventorySchedule
|
||||
? cents(
|
||||
product.productInventoryOpening ?? '',
|
||||
`Opening inventory for ${product.label}`,
|
||||
@@ -1458,7 +1456,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
),
|
||||
};
|
||||
});
|
||||
const productStockInputs = input.products.map((product, index) => {
|
||||
const productStockInputs = input.products.map((product, _index) => {
|
||||
if (!useProductInventorySchedule)
|
||||
return { opening: null, orders: null };
|
||||
const opening = cents(
|
||||
@@ -1863,7 +1861,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
const periodPayrollPayment = payrollPaymentsByPeriod[month - 1];
|
||||
const revenue = revenueByPeriod[month - 1];
|
||||
const costOfSales = costOfSalesByPeriod[month - 1];
|
||||
const opening = cash;
|
||||
const _opening = cash;
|
||||
const openingInventory = inventoryBalance;
|
||||
let inventoryShortfall: bigint | null = null;
|
||||
let closingInventory: bigint | null = null;
|
||||
@@ -3087,8 +3085,7 @@ export function exportBusinessPlanCsv(
|
||||
row.openingReceivablesBalance ?? '',
|
||||
row.openingPayablesPayments ?? '',
|
||||
row.openingPayablesBalance ?? '',
|
||||
row.otherCollections ??
|
||||
'incluídas nas cobranças manuais',
|
||||
row.otherCollections ?? 'incluídas nas cobranças manuais',
|
||||
row.profitBeforeTax ?? '',
|
||||
row.netCashFlow ?? '',
|
||||
row.closingCash ?? '',
|
||||
|
||||
@@ -12,20 +12,29 @@ export const emptyBusinessLocation = (): BusinessLocationPath => ({
|
||||
locality_id: '',
|
||||
});
|
||||
|
||||
export function decodeBusinessLocations(value?: string): BusinessLocationPath[] {
|
||||
export function decodeBusinessLocations(
|
||||
value?: string,
|
||||
): BusinessLocationPath[] {
|
||||
if (!value) return [];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.slice(0, 20).map((entry) => {
|
||||
const row = entry && typeof entry === 'object'
|
||||
? (entry as Record<string, unknown>)
|
||||
: {};
|
||||
const row =
|
||||
entry && typeof entry === 'object'
|
||||
? (entry as Record<string, unknown>)
|
||||
: {};
|
||||
return {
|
||||
province_id: typeof row.province_id === 'string' ? row.province_id : '',
|
||||
district_id: typeof row.district_id === 'string' ? row.district_id : '',
|
||||
admin_post_id: typeof row.admin_post_id === 'string' ? row.admin_post_id : '',
|
||||
locality_id: typeof row.locality_id === 'string' ? row.locality_id : '',
|
||||
province_id:
|
||||
typeof row.province_id === 'string' ? row.province_id : '',
|
||||
district_id:
|
||||
typeof row.district_id === 'string' ? row.district_id : '',
|
||||
admin_post_id:
|
||||
typeof row.admin_post_id === 'string'
|
||||
? row.admin_post_id
|
||||
: '',
|
||||
locality_id:
|
||||
typeof row.locality_id === 'string' ? row.locality_id : '',
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
@@ -46,7 +55,9 @@ export function updateBusinessLocation(
|
||||
if (!rows[index]) return rows;
|
||||
const next = rows.map((row) => ({ ...row }));
|
||||
next[index][key] = value;
|
||||
const children: Partial<Record<keyof BusinessLocationPath, (keyof BusinessLocationPath)[]>> = {
|
||||
const children: Partial<
|
||||
Record<keyof BusinessLocationPath, (keyof BusinessLocationPath)[]>
|
||||
> = {
|
||||
province_id: ['district_id', 'admin_post_id', 'locality_id'],
|
||||
district_id: ['admin_post_id', 'locality_id'],
|
||||
admin_post_id: ['locality_id'],
|
||||
@@ -55,18 +66,28 @@ export function updateBusinessLocation(
|
||||
return next;
|
||||
}
|
||||
|
||||
export function hasDuplicateBusinessLocationPath(rows: BusinessLocationPath[]): boolean {
|
||||
const paths = rows.map((row) => [
|
||||
row.province_id,
|
||||
row.district_id,
|
||||
row.admin_post_id,
|
||||
row.locality_id,
|
||||
].filter(Boolean));
|
||||
return paths.some((path, index) => path.length > 0 && paths.slice(index + 1).some((other) => {
|
||||
if (other.length === 0) return false;
|
||||
const common = Math.min(path.length, other.length);
|
||||
return path.slice(0, common).every((id, part) => id === other[part]);
|
||||
}));
|
||||
export function hasDuplicateBusinessLocationPath(
|
||||
rows: BusinessLocationPath[],
|
||||
): boolean {
|
||||
const paths = rows.map((row) =>
|
||||
[
|
||||
row.province_id,
|
||||
row.district_id,
|
||||
row.admin_post_id,
|
||||
row.locality_id,
|
||||
].filter(Boolean),
|
||||
);
|
||||
return paths.some(
|
||||
(path, index) =>
|
||||
path.length > 0 &&
|
||||
paths.slice(index + 1).some((other) => {
|
||||
if (other.length === 0) return false;
|
||||
const common = Math.min(path.length, other.length);
|
||||
return path
|
||||
.slice(0, common)
|
||||
.every((id, part) => id === other[part]);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function locationPathFromPayload(
|
||||
|
||||
Vendored
+4
-1
@@ -1,2 +1,5 @@
|
||||
export declare function csvCell(value: unknown): string;
|
||||
export declare function csvCellWithDelimiter(value: unknown, delimiter: string): string;
|
||||
export declare function csvCellWithDelimiter(
|
||||
value: unknown,
|
||||
delimiter: string,
|
||||
): string;
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
function serializeCell(value, delimiter) {
|
||||
const raw = String(value ?? '');
|
||||
const formulaLike = /^[\u0000-\u0020\uFEFF]*[=+\-@]/.test(raw);
|
||||
let prefix = 0;
|
||||
while (
|
||||
prefix < raw.length &&
|
||||
(raw.charCodeAt(prefix) <= 32 || raw.charCodeAt(prefix) === 0xfeff)
|
||||
)
|
||||
prefix++;
|
||||
const formulaLike = /^[=+\-@]/.test(raw.slice(prefix));
|
||||
const numeric = /^-?\d+(?:\.\d+)?$/.test(raw);
|
||||
const text = formulaLike && !numeric ? `'${raw}` : raw;
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Display only scalar values; an object is not a verified textual value. */
|
||||
export function displayValue(value: unknown, fallback = ''): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (typeof value === 'number' && Number.isFinite(value))
|
||||
return String(value);
|
||||
if (typeof value === 'boolean') return String(value);
|
||||
return fallback;
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
/** Estados de preparação usados pelo cadastro de oportunidades (níveis 1–6). */
|
||||
export const MATURITY_LEVELS = [
|
||||
"Ideia identificada",
|
||||
"Pré-estudo disponível",
|
||||
"Estudo de viabilidade em curso",
|
||||
"Projecto estruturado",
|
||||
"Pronto para investimento",
|
||||
"Em negociação ou implementação",
|
||||
'Ideia identificada',
|
||||
'Pré-estudo disponível',
|
||||
'Estudo de viabilidade em curso',
|
||||
'Projecto estruturado',
|
||||
'Pronto para investimento',
|
||||
'Em negociação ou implementação',
|
||||
] as const;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,53 +9,182 @@ export type RoadmapPhase = {
|
||||
|
||||
export const roadmapPhases: RoadmapPhase[] = [
|
||||
{
|
||||
id: 'concepcao', title: 'Concepção',
|
||||
summary: 'Transformar a ideia numa proposta de valor e identificar o enquadramento da actividade.',
|
||||
id: 'concepcao',
|
||||
title: 'Concepção',
|
||||
summary:
|
||||
'Transformar a ideia numa proposta de valor e identificar o enquadramento da actividade.',
|
||||
steps: [
|
||||
{ title: 'Definir a ideia e a oportunidade', description: 'Identificar o problema, a necessidade do mercado e o objectivo do investimento.', result: 'Conceito definido.' },
|
||||
{ title: 'Estruturar a proposta de valor', description: 'Especificar produto ou serviço, público-alvo, benefícios e diferenciais.', result: 'Proposta de valor definida.' },
|
||||
{
|
||||
title: 'Definir a ideia e a oportunidade',
|
||||
description:
|
||||
'Identificar o problema, a necessidade do mercado e o objectivo do investimento.',
|
||||
result: 'Conceito definido.',
|
||||
},
|
||||
{
|
||||
title: 'Estruturar a proposta de valor',
|
||||
description:
|
||||
'Especificar produto ou serviço, público-alvo, benefícios e diferenciais.',
|
||||
result: 'Proposta de valor definida.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{
|
||||
label: 'Desenvolver a ideia no dossier',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{ label: 'Explorar sectores económicos', href: '/sectores' },
|
||||
{ label: 'Encontrar oportunidades', href: '/oportunidades' },
|
||||
],
|
||||
links: [{ label: 'Desenvolver a ideia no dossier', href: '/simulador-fiscal' }, { label: 'Explorar sectores económicos', href: '/sectores' }, { label: 'Encontrar oportunidades', href: '/oportunidades' }],
|
||||
},
|
||||
{
|
||||
id: 'analise', title: 'Análise',
|
||||
summary: 'Estudar mercado, requisitos, localização e viabilidade com pressupostos explícitos.',
|
||||
id: 'analise',
|
||||
title: 'Análise',
|
||||
summary:
|
||||
'Estudar mercado, requisitos, localização e viabilidade com pressupostos explícitos.',
|
||||
steps: [
|
||||
{ title: 'Mapear os requisitos', description: 'Identificar exigências legais, fiscais, técnicas, ambientais, de segurança, infra-estrutura e operação aplicáveis ao projecto.', result: 'Matriz de requisitos a confirmar.' },
|
||||
{ title: 'Realizar o estudo de mercado', description: 'Analisar procura, clientes, concorrência, preços, canais e tendências; registar fontes e datas.', result: 'Estudo de mercado.' },
|
||||
{ title: 'Seleccionar a localização', description: 'Comparar custos, clientes, logística, água, energia, mão de obra, incentivos potenciais e riscos nas alternativas de localização.', result: 'Matriz multicritério de localização.' },
|
||||
{ title: 'Avaliar a viabilidade', description: 'Testar viabilidade comercial, técnica, financeira, ambiental e social. Rever proposta, mercado, localização ou modelo quando necessário.', result: 'Estudo de viabilidade e cenários.' },
|
||||
{
|
||||
title: 'Mapear os requisitos',
|
||||
description:
|
||||
'Identificar exigências legais, fiscais, técnicas, ambientais, de segurança, infra-estrutura e operação aplicáveis ao projecto.',
|
||||
result: 'Matriz de requisitos a confirmar.',
|
||||
},
|
||||
{
|
||||
title: 'Realizar o estudo de mercado',
|
||||
description:
|
||||
'Analisar procura, clientes, concorrência, preços, canais e tendências; registar fontes e datas.',
|
||||
result: 'Estudo de mercado.',
|
||||
},
|
||||
{
|
||||
title: 'Seleccionar a localização',
|
||||
description:
|
||||
'Comparar custos, clientes, logística, água, energia, mão de obra, incentivos potenciais e riscos nas alternativas de localização.',
|
||||
result: 'Matriz multicritério de localização.',
|
||||
},
|
||||
{
|
||||
title: 'Avaliar a viabilidade',
|
||||
description:
|
||||
'Testar viabilidade comercial, técnica, financeira, ambiental e social. Rever proposta, mercado, localização ou modelo quando necessário.',
|
||||
result: 'Estudo de viabilidade e cenários.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{ label: 'Explorar locais de investimento', href: '/zonas' },
|
||||
{
|
||||
label: 'Consultar clusters e cadeias de valor',
|
||||
href: '/clusters',
|
||||
},
|
||||
{
|
||||
label: 'Comparar finanças e efeito fiscal',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{ label: 'Consultar terra e DUAT', href: '/terra-duat' },
|
||||
{ label: 'Consultar fontes legais', href: '/legislacao' },
|
||||
],
|
||||
links: [{ label: 'Explorar locais de investimento', href: '/zonas' }, { label: 'Consultar clusters e cadeias de valor', href: '/clusters' }, { label: 'Comparar finanças e efeito fiscal', href: '/simulador-fiscal' }, { label: 'Consultar terra e DUAT', href: '/terra-duat' }, { label: 'Consultar fontes legais', href: '/legislacao' }],
|
||||
},
|
||||
{
|
||||
id: 'planeamento', title: 'Planeamento e Formalização',
|
||||
summary: 'Consolidar o plano, mobilizar recursos e preparar registos, licenças e autorizações aplicáveis.',
|
||||
id: 'planeamento',
|
||||
title: 'Planeamento e Formalização',
|
||||
summary:
|
||||
'Consolidar o plano, mobilizar recursos e preparar registos, licenças e autorizações aplicáveis.',
|
||||
steps: [
|
||||
{ title: 'Elaborar o modelo e o plano de negócios', description: 'Consolidar estratégia, operação, marketing, projecções financeiras, metas e indicadores.', result: 'Plano de negócios para decisão do promotor.' },
|
||||
{ title: 'Mobilizar recursos', description: 'Definir financiamento, recursos materiais, tecnológicos e humanos; identificar lacunas e alternativas.', result: 'Recursos e financiamento planeados ou assegurados, conforme evidência.' },
|
||||
{ title: 'Constituir e registar a empresa', description: 'Preparar forma jurídica, registo, NUIT e obrigações laborais e fiscais conforme a actividade e a fase de execução.', result: 'Formalização e pendências documentadas.' },
|
||||
{ title: 'Obter licenças, autorizações e incentivos', description: 'Confirmar licenciamento económico, sectorial, ambiental e uso do espaço; verificar condições dos benefícios pretendidos.', result: 'Licenças e autorizações aplicáveis identificadas e acompanhadas.' },
|
||||
{
|
||||
title: 'Elaborar o modelo e o plano de negócios',
|
||||
description:
|
||||
'Consolidar estratégia, operação, marketing, projecções financeiras, metas e indicadores.',
|
||||
result: 'Plano de negócios para decisão do promotor.',
|
||||
},
|
||||
{
|
||||
title: 'Mobilizar recursos',
|
||||
description:
|
||||
'Definir financiamento, recursos materiais, tecnológicos e humanos; identificar lacunas e alternativas.',
|
||||
result: 'Recursos e financiamento planeados ou assegurados, conforme evidência.',
|
||||
},
|
||||
{
|
||||
title: 'Constituir e registar a empresa',
|
||||
description:
|
||||
'Preparar forma jurídica, registo, NUIT e obrigações laborais e fiscais conforme a actividade e a fase de execução.',
|
||||
result: 'Formalização e pendências documentadas.',
|
||||
},
|
||||
{
|
||||
title: 'Obter licenças, autorizações e incentivos',
|
||||
description:
|
||||
'Confirmar licenciamento económico, sectorial, ambiental e uso do espaço; verificar condições dos benefícios pretendidos.',
|
||||
result: 'Licenças e autorizações aplicáveis identificadas e acompanhadas.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{
|
||||
label: 'Continuar o plano financeiro e dossier',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{ label: 'Explorar parcerias', href: '/parcerias' },
|
||||
{
|
||||
label: 'Consultar documentos e formulários',
|
||||
href: '/documentos',
|
||||
},
|
||||
{ label: 'Pedir apoio ao investimento', href: '/apoio' },
|
||||
],
|
||||
links: [{ label: 'Continuar o plano financeiro e dossier', href: '/simulador-fiscal' }, { label: 'Explorar parcerias', href: '/parcerias' }, { label: 'Consultar documentos e formulários', href: '/documentos' }, { label: 'Pedir apoio ao investimento', href: '/apoio' }],
|
||||
},
|
||||
{
|
||||
id: 'preparacao', title: 'Preparação e Teste',
|
||||
summary: 'Preparar equipa, instalações e processos; testar em escala controlada e corrigir resultados.',
|
||||
id: 'preparacao',
|
||||
title: 'Preparação e Teste',
|
||||
summary:
|
||||
'Preparar equipa, instalações e processos; testar em escala controlada e corrigir resultados.',
|
||||
steps: [
|
||||
{ title: 'Preparar a operação', description: 'Contratar e formar a equipa, seleccionar fornecedores, instalar equipamentos e sistemas e estabelecer procedimentos e controlos.', result: 'Plano de prontidão operacional.' },
|
||||
{ title: 'Executar o piloto', description: 'Testar produto ou serviço, processos, capacidade, custos e experiência do cliente. Corrigir oferta, equipa, processos e custos e repetir o teste quando necessário.', result: 'Piloto e evidências de aceitação.' },
|
||||
{
|
||||
title: 'Preparar a operação',
|
||||
description:
|
||||
'Contratar e formar a equipa, seleccionar fornecedores, instalar equipamentos e sistemas e estabelecer procedimentos e controlos.',
|
||||
result: 'Plano de prontidão operacional.',
|
||||
},
|
||||
{
|
||||
title: 'Executar o piloto',
|
||||
description:
|
||||
'Testar produto ou serviço, processos, capacidade, custos e experiência do cliente. Corrigir oferta, equipa, processos e custos e repetir o teste quando necessário.',
|
||||
result: 'Piloto e evidências de aceitação.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{
|
||||
label: 'Registar equipa, riscos e marcos no dossier',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{ label: 'Encontrar parceiros e negócios', href: '/negocios' },
|
||||
{ label: 'Consultar requisitos documentais', href: '/documentos' },
|
||||
{ label: 'Pedir apoio à preparação', href: '/apoio' },
|
||||
],
|
||||
links: [{ label: 'Registar equipa, riscos e marcos no dossier', href: '/simulador-fiscal' }, { label: 'Encontrar parceiros e negócios', href: '/negocios' }, { label: 'Consultar requisitos documentais', href: '/documentos' }, { label: 'Pedir apoio à preparação', href: '/apoio' }],
|
||||
},
|
||||
{
|
||||
id: 'execucao', title: 'Execução e Controlo',
|
||||
summary: 'Lançar a actividade, acompanhar indicadores e manter um plano de melhoria e conformidade.',
|
||||
id: 'execucao',
|
||||
title: 'Execução e Controlo',
|
||||
summary:
|
||||
'Lançar a actividade, acompanhar indicadores e manter um plano de melhoria e conformidade.',
|
||||
steps: [
|
||||
{ title: 'Lançar a operação', description: 'Iniciar a actividade, activar canais comerciais, acompanhar clientes e estabilizar a produção ou prestação do serviço.', result: 'Operação iniciada e acompanhada.' },
|
||||
{ title: 'Monitorizar e melhorar', description: 'Acompanhar indicadores financeiros, operacionais, comerciais, sociais e ambientais; controlar riscos, validades e acções correctivas.', result: 'Desempenho e continuidade acompanhados.' },
|
||||
{
|
||||
title: 'Lançar a operação',
|
||||
description:
|
||||
'Iniciar a actividade, activar canais comerciais, acompanhar clientes e estabilizar a produção ou prestação do serviço.',
|
||||
result: 'Operação iniciada e acompanhada.',
|
||||
},
|
||||
{
|
||||
title: 'Monitorizar e melhorar',
|
||||
description:
|
||||
'Acompanhar indicadores financeiros, operacionais, comerciais, sociais e ambientais; controlar riscos, validades e acções correctivas.',
|
||||
result: 'Desempenho e continuidade acompanhados.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{
|
||||
label: 'Rever cenários e plano financeiro',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{
|
||||
label: 'Consultar o espaço privado do investidor',
|
||||
href: '/investidor',
|
||||
},
|
||||
{ label: 'Consultar legislação e documentos', href: '/legislacao' },
|
||||
{ label: 'Solicitar apoio', href: '/apoio' },
|
||||
],
|
||||
links: [{ label: 'Rever cenários e plano financeiro', href: '/simulador-fiscal' }, { label: 'Consultar o espaço privado do investidor', href: '/investidor' }, { label: 'Consultar legislação e documentos', href: '/legislacao' }, { label: 'Solicitar apoio', href: '/apoio' }],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -67,7 +196,14 @@ export const investmentLocations: RoadmapLink[] = [
|
||||
{ label: 'Outras localizações e dossiers territoriais', href: '/carteira' },
|
||||
];
|
||||
|
||||
export const correctiveStates = ['Por iniciar', 'Em execução', 'Bloqueada', 'Pendente de evidência', 'Em validação', 'Encerrada'];
|
||||
export const correctiveStates = [
|
||||
'Por iniciar',
|
||||
'Em execução',
|
||||
'Bloqueada',
|
||||
'Pendente de evidência',
|
||||
'Em validação',
|
||||
'Encerrada',
|
||||
];
|
||||
|
||||
/** Bookmarks select a phase without imposing completion or approval requirements. */
|
||||
export function roadmapPhaseIndex(hash: string): number {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
restoreBusinessPlanSnapshot,
|
||||
compareBusinessScenarios,
|
||||
} from './business-financial-plan.ts';
|
||||
import { buildProjectDossierRows } from './project-dossier.ts';
|
||||
import { restoreFinancialToolsSnapshot } from './financial-calculators.ts';
|
||||
|
||||
/** Reuses the dossier's existing report for loan, budget, funding and break-even. */
|
||||
export function guidanceFinancialTools(draft: Record<string, unknown> | null) {
|
||||
const snapshot =
|
||||
typeof draft?.financial_tools_snapshot === 'string'
|
||||
? draft.financial_tools_snapshot
|
||||
: '';
|
||||
const assumptions = restoreFinancialToolsSnapshot(snapshot);
|
||||
if (!assumptions) return null;
|
||||
const input = {
|
||||
financial_tools_snapshot: snapshot,
|
||||
currency: typeof draft?.currency === 'string' ? draft.currency : '',
|
||||
};
|
||||
return {
|
||||
calculator: 'financial-calculators/project-dossier',
|
||||
snapshotVersion: 1,
|
||||
assumptions,
|
||||
rows: buildProjectDossierRows(input).filter(
|
||||
(row) => row[0] === 'Plano financeiro',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** The assistant only presents outputs of the existing calculator. */
|
||||
export function guidanceFinance(draft: Record<string, unknown> | null) {
|
||||
const snapshot =
|
||||
typeof draft?.business_plan_snapshot === 'string'
|
||||
? draft.business_plan_snapshot
|
||||
: '';
|
||||
const plan = restoreBusinessPlanSnapshot(snapshot);
|
||||
if (!plan)
|
||||
return {
|
||||
status: 'indeterminate' as const,
|
||||
reason: 'Sem snapshot financeiro compatível.',
|
||||
result: null,
|
||||
scenarios: null,
|
||||
};
|
||||
try {
|
||||
const result = forecastBusinessPlan(plan);
|
||||
let scenarios: ReturnType<typeof compareBusinessScenarios> | null =
|
||||
null;
|
||||
try {
|
||||
scenarios = compareBusinessScenarios(plan);
|
||||
} catch {
|
||||
/* Missing scenario inputs remain indeterminate. */
|
||||
}
|
||||
return {
|
||||
status: 'calculated' as const,
|
||||
reason: 'Estimativa determinística; pressupostos declarados, sem validação de procura ou financiamento.',
|
||||
result,
|
||||
scenarios,
|
||||
snapshotVersion: (JSON.parse(snapshot) as { version: number })
|
||||
.version,
|
||||
assumptions: plan,
|
||||
calculator: 'business-financial-plan',
|
||||
tax: 'indeterminate' as const,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
status: 'indeterminate' as const,
|
||||
reason:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Pressupostos incompatíveis.',
|
||||
result: null,
|
||||
scenarios: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -93,24 +93,27 @@ export class PortalApiError extends Error {
|
||||
constructor(status: number, errors: Record<string, string[]> = {}) {
|
||||
super(
|
||||
status === 429
|
||||
? "Foram enviados demasiados pedidos. Aguarde um minuto e tente novamente."
|
||||
? 'Foram enviados demasiados pedidos. Aguarde um minuto e tente novamente.'
|
||||
: status === 404
|
||||
? "O registo solicitado já não está disponível."
|
||||
? 'O registo solicitado já não está disponível.'
|
||||
: status === 422
|
||||
? "Verifique os campos assinalados."
|
||||
: "Não foi possível comunicar com o portal. Tente novamente.",
|
||||
? 'Verifique os campos assinalados.'
|
||||
: 'Não foi possível comunicar com o portal. Tente novamente.',
|
||||
);
|
||||
this.status = status;
|
||||
this.errors = errors;
|
||||
}
|
||||
}
|
||||
|
||||
export async function portalRequest<T>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
export async function portalRequest<T>(
|
||||
url: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const headers = new Headers(options.headers);
|
||||
headers.set("Accept", "application/json");
|
||||
headers.set('Accept', 'application/json');
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
credentials: "same-origin",
|
||||
credentials: 'same-origin',
|
||||
headers,
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
@@ -128,7 +131,7 @@ export function toOpportunity(record: OpportunityRecord): Opportunity {
|
||||
slug: record.slug,
|
||||
reference: record.reference,
|
||||
title: record.title,
|
||||
sectorName: record.sector?.name ?? "Sector não indicado",
|
||||
sectorName: record.sector?.name ?? 'Sector não indicado',
|
||||
province: record.province,
|
||||
maturity: record.maturity_label,
|
||||
amount: record.estimated_investment_amount,
|
||||
@@ -142,13 +145,13 @@ export function toOpportunity(record: OpportunityRecord): Opportunity {
|
||||
}
|
||||
|
||||
export function toFeaturedOpportunity(
|
||||
record: HomeResponse["data"]["featuredOpportunities"][number],
|
||||
record: HomeResponse['data']['featuredOpportunities'][number],
|
||||
): Opportunity {
|
||||
return {
|
||||
slug: record.url.split("/").filter(Boolean).at(-1) ?? "",
|
||||
slug: record.url.split('/').filter(Boolean).at(-1) ?? '',
|
||||
reference: record.reference,
|
||||
title: record.title,
|
||||
sectorName: record.sector ?? "Sector não indicado",
|
||||
sectorName: record.sector ?? 'Sector não indicado',
|
||||
province: record.province,
|
||||
maturity: record.maturity,
|
||||
amount: record.estimatedInvestment.amount,
|
||||
@@ -162,14 +165,14 @@ export function toFeaturedOpportunity(
|
||||
}
|
||||
|
||||
export function searchUrl(filters: Filters, page: number): string {
|
||||
const params = new URLSearchParams({ page: String(page), per_page: "12" });
|
||||
if (filters.query.trim()) params.set("q", filters.query.trim());
|
||||
if (filters.sector) params.set("sector", filters.sector);
|
||||
if (filters.province) params.set("province", filters.province);
|
||||
if (filters.maturity) params.set("maturity_level", filters.maturity);
|
||||
if (filters.minAmount) params.set("min_amount", filters.minAmount);
|
||||
if (filters.maxAmount) params.set("max_amount", filters.maxAmount);
|
||||
if (filters.currency) params.set("currency", filters.currency);
|
||||
const params = new URLSearchParams({ page: String(page), per_page: '12' });
|
||||
if (filters.query.trim()) params.set('q', filters.query.trim());
|
||||
if (filters.sector) params.set('sector', filters.sector);
|
||||
if (filters.province) params.set('province', filters.province);
|
||||
if (filters.maturity) params.set('maturity_level', filters.maturity);
|
||||
if (filters.minAmount) params.set('min_amount', filters.minAmount);
|
||||
if (filters.maxAmount) params.set('max_amount', filters.maxAmount);
|
||||
if (filters.currency) params.set('currency', filters.currency);
|
||||
return `/api/v1/opportunities/search?${params.toString()}`;
|
||||
}
|
||||
|
||||
@@ -183,27 +186,29 @@ export function newSubmissionKey(): string {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
const hex = Array.from(bytes, (byte) =>
|
||||
byte.toString(16).padStart(2, '0'),
|
||||
).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
export function fieldErrors(error: PortalApiError): FormErrors {
|
||||
const result: FormErrors = {};
|
||||
const fields: (keyof InterestFormData)[] = [
|
||||
"name",
|
||||
"email",
|
||||
"phone",
|
||||
"investorType",
|
||||
"country",
|
||||
"sectorInterest",
|
||||
"opportunityReference",
|
||||
"investmentRange",
|
||||
"message",
|
||||
"privacyConsent",
|
||||
'name',
|
||||
'email',
|
||||
'phone',
|
||||
'investorType',
|
||||
'country',
|
||||
'sectorInterest',
|
||||
'opportunityReference',
|
||||
'investmentRange',
|
||||
'message',
|
||||
'privacyConsent',
|
||||
];
|
||||
for (const field of fields) {
|
||||
const messages = error.errors[field === "name" ? "fullName" : field];
|
||||
if (Array.isArray(messages) && typeof messages[0] === "string") {
|
||||
const messages = error.errors[field === 'name' ? 'fullName' : field];
|
||||
if (Array.isArray(messages) && typeof messages[0] === 'string') {
|
||||
result[field] = messages[0];
|
||||
}
|
||||
}
|
||||
@@ -211,11 +216,12 @@ export function fieldErrors(error: PortalApiError): FormErrors {
|
||||
}
|
||||
|
||||
export function money(amount: string | null, currency: string): string {
|
||||
if (amount === null || !/^-?\d+(\.\d+)?$/.test(amount)) return "Por indicar";
|
||||
if (amount === null || !/^-?\d+(\.\d+)?$/.test(amount))
|
||||
return 'Por indicar';
|
||||
try {
|
||||
// Intl accepts decimal strings without converting them to a lossy Number.
|
||||
const formatter = new Intl.NumberFormat("pt-MZ", {
|
||||
style: "currency",
|
||||
const formatter = new Intl.NumberFormat('pt-MZ', {
|
||||
style: 'currency',
|
||||
currency,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
export type PortalNavItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
href?: string;
|
||||
children?: PortalNavItem[];
|
||||
};
|
||||
export type PortalNavAccess = {
|
||||
authenticated: boolean;
|
||||
manager: boolean;
|
||||
businesses?: boolean;
|
||||
education?: boolean;
|
||||
ai?: boolean;
|
||||
};
|
||||
const link = (id: string, label: string, href: string): PortalNavItem => ({
|
||||
id,
|
||||
label,
|
||||
href,
|
||||
});
|
||||
|
||||
/** One route catalogue for the public shell and authenticated pages. */
|
||||
export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
const groups: PortalNavItem[] = [
|
||||
{
|
||||
id: 'explore',
|
||||
label: 'Explorar investimentos',
|
||||
children: [
|
||||
link('opportunities', 'Oportunidades', '/oportunidades'),
|
||||
link('sectors', 'Sectores', '/sectores'),
|
||||
{
|
||||
id: 'structures',
|
||||
label: 'Carteira e estruturas',
|
||||
children: [
|
||||
link(
|
||||
'portfolio',
|
||||
'Carteira de investimento',
|
||||
'/carteira',
|
||||
),
|
||||
link(
|
||||
'projects',
|
||||
'Projectos âncora',
|
||||
'/carteira?kind=project',
|
||||
),
|
||||
link('clusters', 'Clusters', '/carteira?kind=cluster'),
|
||||
link(
|
||||
'corridors',
|
||||
'Corredores',
|
||||
'/carteira?kind=corridor',
|
||||
),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'zones',
|
||||
label: 'Zonas e parques',
|
||||
children: [
|
||||
link('all-zones', 'Todas as zonas', '/zonas'),
|
||||
link('zee', 'ZEE', '/zonas?category=zee'),
|
||||
link('zfi', 'ZFI', '/zonas?category=zfi'),
|
||||
link(
|
||||
'parks',
|
||||
'Parques industriais',
|
||||
'/zonas?physical_category=industrial_park',
|
||||
),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'prepare',
|
||||
label: 'Preparar o projecto',
|
||||
children: [
|
||||
link('roadmap', 'Como investir', '/como-investir'),
|
||||
link('dossier', 'Preparar dossier', '/simulador-fiscal'),
|
||||
link('simulator', 'Simulador', '/simulador-fiscal'),
|
||||
link('land', 'Terra e DUAT', '/terra-duat'),
|
||||
...(access.education
|
||||
? [
|
||||
link(
|
||||
'education',
|
||||
'Educação e competências',
|
||||
'/educacao',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'support',
|
||||
label: 'Serviços e apoio',
|
||||
children: [
|
||||
link('desk', 'Balcão Virtual', '/balcao-virtual'),
|
||||
link('help', 'Apoio ao investidor', '/apoio'),
|
||||
link('documents', 'Documentos e formulários', '/documentos'),
|
||||
link('law', 'Legislação', '/legislacao'),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'partnerships',
|
||||
label: 'Parcerias',
|
||||
children: [
|
||||
link('exchange', 'Bolsa de Parcerias', '/parcerias'),
|
||||
link('businesses', 'Negócios e participações', '/negocios'),
|
||||
...(access.authenticated
|
||||
? [
|
||||
link(
|
||||
'my-partnerships',
|
||||
'As minhas parcerias',
|
||||
'/parcerias/painel',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...(access.authenticated && access.businesses
|
||||
? [
|
||||
link(
|
||||
'my-businesses',
|
||||
'Os meus negócios',
|
||||
'/investidor/negocios',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'account',
|
||||
label: 'A minha área',
|
||||
children: access.authenticated
|
||||
? [
|
||||
link('dashboard', 'Painel', '/investidor'),
|
||||
link(
|
||||
'profile',
|
||||
'Perfil e empresas',
|
||||
'/investidor/profile',
|
||||
),
|
||||
link('dossiers', 'Dossiers e percursos', '/investidor'),
|
||||
link(
|
||||
'requests',
|
||||
'Pedidos e tarefas de acompanhamento',
|
||||
'/balcao-virtual',
|
||||
),
|
||||
link(
|
||||
'interests',
|
||||
'Manifestações e favoritos',
|
||||
'/investidor/manifestacoes',
|
||||
),
|
||||
link(
|
||||
'notifications',
|
||||
'Notificações',
|
||||
'/investidor/notifications',
|
||||
),
|
||||
]
|
||||
: [
|
||||
link('login', 'Entrar', '/login'),
|
||||
link('register', 'Criar conta', '/register'),
|
||||
],
|
||||
},
|
||||
];
|
||||
if (access.manager)
|
||||
groups.push({
|
||||
id: 'management',
|
||||
label: 'Gestão',
|
||||
children: [
|
||||
link(
|
||||
'manage-interests',
|
||||
'Pedidos de interesse',
|
||||
'/management/interests',
|
||||
),
|
||||
link('crm', 'CRM interno', '/management/crm/leads'),
|
||||
{
|
||||
id: 'manage-catalogue',
|
||||
label: 'Catálogo de investimento',
|
||||
children: [
|
||||
link(
|
||||
'manage-sectors',
|
||||
'Sectores',
|
||||
'/management/sectors',
|
||||
),
|
||||
link(
|
||||
'manage-opportunities',
|
||||
'Oportunidades',
|
||||
'/management/opportunities',
|
||||
),
|
||||
link(
|
||||
'manage-projects',
|
||||
'Projectos',
|
||||
'/management/projects',
|
||||
),
|
||||
link(
|
||||
'manage-clusters',
|
||||
'Clusters',
|
||||
'/management/clusters',
|
||||
),
|
||||
],
|
||||
},
|
||||
link(
|
||||
'manage-portfolio',
|
||||
'Carteira e estruturas',
|
||||
'/management/portfolio',
|
||||
),
|
||||
link(
|
||||
'manage-documents',
|
||||
'Acervo documental',
|
||||
'/management/portal-services',
|
||||
),
|
||||
link(
|
||||
'manage-zones',
|
||||
'Zonas e parques',
|
||||
'/management/investment/zones',
|
||||
),
|
||||
link(
|
||||
'manage-territory',
|
||||
'Associações territoriais',
|
||||
'/management/territory-associations',
|
||||
),
|
||||
link(
|
||||
'manage-references',
|
||||
'Referências e formulários',
|
||||
'/management/investment/references',
|
||||
),
|
||||
link(
|
||||
'desk-installation',
|
||||
'Estado do Balcão e orientação',
|
||||
'/management/balcao-install',
|
||||
),
|
||||
link(
|
||||
'exchange-installation',
|
||||
'Estado da Bolsa de Parcerias',
|
||||
'/management/partnerships-install',
|
||||
),
|
||||
...(access.ai
|
||||
? [
|
||||
link(
|
||||
'manage-ai',
|
||||
'Assistência interna',
|
||||
'/management/ai',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...(access.education
|
||||
? [
|
||||
link(
|
||||
'manage-education',
|
||||
'Educação e competências',
|
||||
'/management/education',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function currentNavigationGroup(
|
||||
groups: PortalNavItem[],
|
||||
url: string,
|
||||
): string | null {
|
||||
const current = new URL(url, 'https://portal.invalid');
|
||||
let match: { group: string; score: number } | null = null;
|
||||
const visit = (items: PortalNavItem[], group: string) =>
|
||||
items.forEach((item) => {
|
||||
if (item.children) visit(item.children, group);
|
||||
if (!item.href) return;
|
||||
const target = new URL(item.href, current.origin);
|
||||
if (
|
||||
current.pathname !== target.pathname &&
|
||||
!current.pathname.startsWith(target.pathname + '/')
|
||||
)
|
||||
return;
|
||||
for (const [key, value] of target.searchParams)
|
||||
if (current.searchParams.get(key) !== value) return;
|
||||
const score =
|
||||
target.pathname.length + target.searchParams.size * 100;
|
||||
if (!match || score > match.score) match = { group, score };
|
||||
});
|
||||
for (const group of groups) visit(group.children ?? [], group.id);
|
||||
return (match as { group: string; score: number } | null)?.group ?? null;
|
||||
}
|
||||
|
||||
/** Select one destination, preferring a matching catalogue filter. */
|
||||
export function currentNavigationItem(
|
||||
groups: PortalNavItem[],
|
||||
url: string,
|
||||
): string | null {
|
||||
const current = new URL(url, 'https://portal.invalid');
|
||||
const best = { id: null as string | null, score: -1 };
|
||||
const visit = (items: PortalNavItem[]) => {
|
||||
for (const item of items) {
|
||||
if (item.children) visit(item.children);
|
||||
if (!item.href) continue;
|
||||
const target = new URL(item.href, current.origin);
|
||||
if (current.pathname !== target.pathname) continue;
|
||||
if (
|
||||
[...target.searchParams].some(
|
||||
([key, value]) => current.searchParams.get(key) !== value,
|
||||
)
|
||||
)
|
||||
continue;
|
||||
const score = target.searchParams.size;
|
||||
if (score > best.score) {
|
||||
best.id = item.id;
|
||||
best.score = score;
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const group of groups) visit(group.children ?? []);
|
||||
return best.id;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,4 @@
|
||||
import { displayValue } from './display-value.ts';
|
||||
import { csvCellWithDelimiter } from './csv.js';
|
||||
import {
|
||||
calculateFinancialTools,
|
||||
@@ -7,7 +8,10 @@ import {
|
||||
forecastBusinessPlan,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from './business-financial-plan.ts';
|
||||
import { getProjectReadiness, readPlannedRiskResponses } from './project-readiness.ts';
|
||||
import {
|
||||
getProjectReadiness,
|
||||
readPlannedRiskResponses,
|
||||
} from './project-readiness.ts';
|
||||
|
||||
export type TeamNeed = {
|
||||
competency: string;
|
||||
@@ -30,60 +34,259 @@ export function readRows<T>(value: string, allowed: readonly string[]): T[] {
|
||||
const parsed: unknown = JSON.parse(value || '[]');
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((row): row is T =>
|
||||
Boolean(row && typeof row === 'object' && !Array.isArray(row) &&
|
||||
allowed.every((key) => typeof (row as Record<string, unknown>)[key] === 'string')),
|
||||
Boolean(
|
||||
row &&
|
||||
typeof row === 'object' &&
|
||||
!Array.isArray(row) &&
|
||||
allowed.every(
|
||||
(key) =>
|
||||
typeof (row as Record<string, unknown>)[key] ===
|
||||
'string',
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export type ProjectDossierRow = [section: string, field: string, value: string, origin: string];
|
||||
export type ProjectDossierRow = [
|
||||
section: string,
|
||||
field: string,
|
||||
value: string,
|
||||
origin: string,
|
||||
];
|
||||
|
||||
export function buildProjectDossierRows(draft: Record<string, string | string[]>): ProjectDossierRow[] {
|
||||
export function buildProjectDossierRows(
|
||||
draft: Record<string, string | string[]>,
|
||||
): ProjectDossierRow[] {
|
||||
const rows: ProjectDossierRow[] = [
|
||||
['Secção', 'Campo', 'Valor', 'Origem / estado'],
|
||||
['Projecto', 'Título', String(draft.project_title ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Versão do questionário', String(draft.project_questionnaire_version ?? 'legacy-unversioned'), 'Metadado do questionário; não altera resultados guardados'],
|
||||
['Projecto', 'Resumo', String(draft.project_summary ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Problema', String(draft.project_problem ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Clientes/beneficiários', String(draft.target_customers ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Proposta de valor', String(draft.value_proposition ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Tipo de projecto', String(draft.project_type_label ?? draft.project_type ?? ''), 'Declarado/seleccionado pelo utilizador'],
|
||||
['Projecto', 'Sector', String(draft.sector_id_label ?? draft.sector_id ?? ''), 'Selecção declarada pelo utilizador'],
|
||||
['Projecto', 'Actividade económica', String(draft.activity_id_label ?? draft.activity_id ?? ''), 'Selecção declarada pelo utilizador'],
|
||||
['Projecto', 'Produtos e serviços', String(draft.products_services ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Fase de maturidade', String(draft.maturity_stage_label ?? draft.maturity_stage ?? ''), 'Declarada pelo utilizador'],
|
||||
['Projecto', 'Data prevista de início', String(draft.expected_start_date ?? ''), 'Declarada pelo utilizador; data não verificada'],
|
||||
['Projecto', 'Duração prevista', draft.project_duration_years ? `${draft.project_duration_years} anos` : '', 'Declarada pelo utilizador'],
|
||||
['Mercado', 'Hipótese', String(draft.market_assumption ?? ''), 'Informação declarada, não verificada'],
|
||||
['Mercado', 'Fonte e data', String(draft.market_source ?? ''), 'Opcional; não verificada'],
|
||||
['Mercado', 'Concorrência e alternativas', String(draft.competitor_assumption ?? ''), 'Hipótese declarada; não verificada'],
|
||||
['Mercado', 'Canal de venda', String(draft.sales_channel_assumption ?? ''), 'Planeamento declarado; não confirmado'],
|
||||
['Mercado', 'Acções de divulgação', String(draft.marketing_approach ?? ''), 'Planeamento declarado; não confirmado'],
|
||||
['Localização', 'Província', String(draft.province_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Distrito', String(draft.district_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Posto administrativo', String(draft.admin_post_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Localidade', String(draft.locality_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Critérios e pontos a confirmar', String(draft.location_rationale ?? ''), 'Declaração do utilizador; não confirma disponibilidade'],
|
||||
['Plano financeiro', 'Estado do plano detalhado', draft.business_plan_snapshot ? 'Snapshot versionado disponível; usar também a exportação do plano financeiro' : 'Sem plano empresarial detalhado preenchido', 'Pressupostos declarados; não é demonstração contabilística'],
|
||||
['Equipa', 'Nota anterior sobre competências', String(draft.skills_needed ?? ''), 'Texto declarado existente'],
|
||||
['Execução', 'Nota anterior sobre marcos', String(draft.project_milestones ?? ''), 'Texto declarado existente'],
|
||||
['Financiamento', 'Estado de pré-elegibilidade', 'Informação insuficiente', 'Sem catálogo documentado de produtos e critérios'],
|
||||
['Necessidade de negócio', 'Descrição', String(draft.opportunity_description ?? ''), 'Declarado pelo utilizador'],
|
||||
['Necessidade de negócio', 'Infra-estrutura necessária', (Array.isArray(draft.infrastructure_needs) ? draft.infrastructure_needs : []).join(', '), 'Declarado/seleccionado pelo utilizador'],
|
||||
['Financiamento', 'Montante pretendido', String(draft.opportunity_value ?? ''), 'Declarado pelo utilizador; ver moeda separada'],
|
||||
['Financiamento', 'Moeda do montante', String(draft.opportunity_currency_label ?? draft.opportunity_currency ?? ''), 'Declarada/seleccionada; sem avaliação de produto'],
|
||||
[
|
||||
'Projecto',
|
||||
'Título',
|
||||
String(draft.project_title ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Versão do questionário',
|
||||
String(draft.project_questionnaire_version ?? 'legacy-unversioned'),
|
||||
'Metadado do questionário; não altera resultados guardados',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Resumo',
|
||||
String(draft.project_summary ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Problema',
|
||||
String(draft.project_problem ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Clientes/beneficiários',
|
||||
String(draft.target_customers ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Proposta de valor',
|
||||
String(draft.value_proposition ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Tipo de projecto',
|
||||
String(draft.project_type_label ?? draft.project_type ?? ''),
|
||||
'Declarado/seleccionado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Sector',
|
||||
String(draft.sector_id_label ?? draft.sector_id ?? ''),
|
||||
'Selecção declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Actividade económica',
|
||||
String(draft.activity_id_label ?? draft.activity_id ?? ''),
|
||||
'Selecção declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Produtos e serviços',
|
||||
String(draft.products_services ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Fase de maturidade',
|
||||
String(draft.maturity_stage_label ?? draft.maturity_stage ?? ''),
|
||||
'Declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Data prevista de início',
|
||||
String(draft.expected_start_date ?? ''),
|
||||
'Declarada pelo utilizador; data não verificada',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Duração prevista',
|
||||
draft.project_duration_years
|
||||
? `${displayValue(draft.project_duration_years)} anos`
|
||||
: '',
|
||||
'Declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Hipótese',
|
||||
String(draft.market_assumption ?? ''),
|
||||
'Informação declarada, não verificada',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Fonte e data',
|
||||
String(draft.market_source ?? ''),
|
||||
'Opcional; não verificada',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Concorrência e alternativas',
|
||||
String(draft.competitor_assumption ?? ''),
|
||||
'Hipótese declarada; não verificada',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Canal de venda',
|
||||
String(draft.sales_channel_assumption ?? ''),
|
||||
'Planeamento declarado; não confirmado',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Acções de divulgação',
|
||||
String(draft.marketing_approach ?? ''),
|
||||
'Planeamento declarado; não confirmado',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Província',
|
||||
String(draft.province_id_label ?? ''),
|
||||
'Selecção de catálogo territorial',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Distrito',
|
||||
String(draft.district_id_label ?? ''),
|
||||
'Selecção de catálogo territorial',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Posto administrativo',
|
||||
String(draft.admin_post_id_label ?? ''),
|
||||
'Selecção de catálogo territorial',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Localidade',
|
||||
String(draft.locality_id_label ?? ''),
|
||||
'Selecção de catálogo territorial',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Critérios e pontos a confirmar',
|
||||
String(draft.location_rationale ?? ''),
|
||||
'Declaração do utilizador; não confirma disponibilidade',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Estado do plano detalhado',
|
||||
draft.business_plan_snapshot
|
||||
? 'Snapshot versionado disponível; usar também a exportação do plano financeiro'
|
||||
: 'Sem plano empresarial detalhado preenchido',
|
||||
'Pressupostos declarados; não é demonstração contabilística',
|
||||
],
|
||||
[
|
||||
'Equipa',
|
||||
'Nota anterior sobre competências',
|
||||
String(draft.skills_needed ?? ''),
|
||||
'Texto declarado existente',
|
||||
],
|
||||
[
|
||||
'Execução',
|
||||
'Nota anterior sobre marcos',
|
||||
String(draft.project_milestones ?? ''),
|
||||
'Texto declarado existente',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Estado de pré-elegibilidade',
|
||||
'Informação insuficiente',
|
||||
'Sem catálogo documentado de produtos e critérios',
|
||||
],
|
||||
[
|
||||
'Necessidade de negócio',
|
||||
'Descrição',
|
||||
String(draft.opportunity_description ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Necessidade de negócio',
|
||||
'Infra-estrutura necessária',
|
||||
(Array.isArray(draft.infrastructure_needs)
|
||||
? draft.infrastructure_needs
|
||||
: []
|
||||
).join(', '),
|
||||
'Declarado/seleccionado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Montante pretendido',
|
||||
String(draft.opportunity_value ?? ''),
|
||||
'Declarado pelo utilizador; ver moeda separada',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Moeda do montante',
|
||||
String(
|
||||
draft.opportunity_currency_label ??
|
||||
draft.opportunity_currency ??
|
||||
'',
|
||||
),
|
||||
'Declarada/seleccionada; sem avaliação de produto',
|
||||
],
|
||||
];
|
||||
const plannedResponses = readPlannedRiskResponses(draft);
|
||||
for (const item of getProjectReadiness(draft)) {
|
||||
const response = plannedResponses.find((entry) => entry.risk_id === item.id);
|
||||
const response = plannedResponses.find(
|
||||
(entry) => entry.risk_id === item.id,
|
||||
);
|
||||
const responseText = response
|
||||
? [response.action, response.owner ? `Responsável: ${response.owner}` : '', response.estimated_cost ? `Custo previsto: ${response.estimated_cost} ${String(draft.currency ?? '')}` : '', response.due_date ? `Prazo: ${response.due_date}` : ''].filter(Boolean).join(' · ')
|
||||
? [
|
||||
response.action,
|
||||
response.owner ? `Responsável: ${response.owner}` : '',
|
||||
response.estimated_cost
|
||||
? `Custo previsto: ${response.estimated_cost} ${String(draft.currency ?? '')}`
|
||||
: '',
|
||||
response.due_date ? `Prazo: ${response.due_date}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
: 'Resposta ainda não registada';
|
||||
rows.push(['Risco', item.title, `${item.origin} ${item.affected} Consequência possível: ${item.consequence} Acção: ${item.nextAction} Resposta planeada: ${responseText}`, 'Derivado das respostas e campos em falta; estimativa qualitativa, sem probabilidade ou gravidade atribuída']);
|
||||
rows.push([
|
||||
'Risco',
|
||||
item.title,
|
||||
`${item.origin} ${item.affected} Consequência possível: ${item.consequence} Acção: ${item.nextAction} Resposta planeada: ${responseText}`,
|
||||
'Derivado das respostas e campos em falta; estimativa qualitativa, sem probabilidade ou gravidade atribuída',
|
||||
]);
|
||||
}
|
||||
const finance = restoreFinancialToolsSnapshot(String(draft.financial_tools_snapshot ?? ''));
|
||||
const finance = restoreFinancialToolsSnapshot(
|
||||
String(draft.financial_tools_snapshot ?? ''),
|
||||
);
|
||||
if (finance) {
|
||||
const calculation = calculateFinancialTools({
|
||||
loan: {
|
||||
@@ -109,70 +312,304 @@ export function buildProjectDossierRows(draft: Record<string, string | string[]>
|
||||
expenses: finance.expenses.map((row) => row.amount),
|
||||
});
|
||||
const currency = String(draft.currency ?? '') || 'moeda não indicada';
|
||||
const source = 'Estimativa matemática baseada em pressupostos declarados; não é oferta de crédito nem resultado oficial';
|
||||
const source =
|
||||
'Estimativa matemática baseada em pressupostos declarados; não é oferta de crédito nem resultado oficial';
|
||||
rows.push(
|
||||
['Plano financeiro', 'Periodicidade do orçamento', finance.budgetPeriod, 'Declarada pelo utilizador'],
|
||||
['Empréstimo educativo', 'Capital pressuposto', `${finance.loan.principal} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Empréstimo educativo', 'Taxa anual pressuposta', `${finance.loan.rate}% (${finance.loan.rateType})`, 'Declarada pelo utilizador; não é taxa de produto'],
|
||||
['Empréstimo educativo', 'Prazo pressuposto', `${finance.loan.months} meses`, 'Declarado pelo utilizador'],
|
||||
['Empréstimo educativo', 'Método e pressupostos substituídos', `Saldo decrescente; capital ${finance.loan.principal}; taxa ${finance.loan.rate}% ${finance.loan.rateType}; ${finance.loan.months} meses; período ${finance.loan.periodMonths} meses; carência ${finance.loan.gracePeriods}; comissão inicial ${finance.loan.upfrontFee}; comissão periódica ${finance.loan.recurringFee}`, 'Cronograma do simulador; taxa declarada, sem correspondência a produto'],
|
||||
['Empréstimo educativo', 'Prestação do primeiro período', calculation.loan.value?.schedule[0]?.totalPayment ? `${calculation.loan.value.schedule[0].totalPayment} ${currency}` : 'Indeterminado', source],
|
||||
['Empréstimo educativo', 'Juros totais estimados', calculation.loan.value?.totalInterest ? `${calculation.loan.value.totalInterest} ${currency}` : 'Indeterminado', source],
|
||||
['Empréstimo educativo', 'Estado/erro do cálculo', calculation.loan.error ?? (calculation.loan.value ? 'Calculado pelo cronograma do simulador' : 'Indeterminado'), source],
|
||||
['Ponto de equilíbrio', 'Fórmula e valores substituídos', `${finance.breakEven.fixed} / (${finance.breakEven.price} − ${finance.breakEven.variable}); unidades arredondadas para cima`, 'Custos fixos ÷ margem de contribuição unitária; pressupostos declarados'],
|
||||
['Ponto de equilíbrio', 'Unidades estimadas', calculation.breakEven.value?.breakEvenUnits ?? 'Indeterminado', source],
|
||||
['Ponto de equilíbrio', 'Vendas correspondentes', calculation.breakEven.value?.breakEvenRevenue ? `${calculation.breakEven.value.breakEvenRevenue} ${currency}` : 'Indeterminado', source],
|
||||
['Ponto de equilíbrio', 'Estado/erro do cálculo', calculation.breakEven.error ?? (calculation.breakEven.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
['Financiamento', 'Investimento total pressuposto', `${finance.funding.total} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Financiamento', 'Montante já mobilizado pressuposto', `${finance.funding.secured} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Financiamento', 'Fórmula e valores substituídos', `${finance.funding.total} − ${finance.funding.secured}`, 'Investimento total declarado − financiamento mobilizado declarado'],
|
||||
['Financiamento', 'Diferença por financiar', calculation.funding.value?.gap ? `${calculation.funding.value.gap} ${currency}` : calculation.funding.value?.gap === '0.00' ? `0.00 ${currency}` : 'Indeterminado', source],
|
||||
['Financiamento', 'Estado/erro do cálculo', calculation.funding.error ?? (calculation.funding.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
['Orçamento', 'Fórmula e valores substituídos', `${calculation.budget.value?.incomeTotal ?? 'Não informado'} − ${calculation.budget.value?.expenseTotal ?? 'Não informado'}`, 'Receitas declaradas − despesas declaradas; valores ausentes não são zero'],
|
||||
['Orçamento', 'Receitas declaradas', calculation.budget.value?.incomeTotal ? `${calculation.budget.value.incomeTotal} ${currency}` : 'Indeterminado', 'Declarado pelo utilizador'],
|
||||
['Orçamento', 'Despesas declaradas', calculation.budget.value?.expenseTotal ? `${calculation.budget.value.expenseTotal} ${currency}` : 'Indeterminado', 'Declarado pelo utilizador'],
|
||||
['Orçamento', 'Saldo operacional estimado', calculation.budget.value?.operatingBalance ? `${calculation.budget.value.operatingBalance} ${currency}` : 'Indeterminado', source],
|
||||
['Orçamento', 'Estado/erro do cálculo', calculation.budget.error ?? (calculation.budget.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Periodicidade do orçamento',
|
||||
finance.budgetPeriod,
|
||||
'Declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Capital pressuposto',
|
||||
`${finance.loan.principal} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Taxa anual pressuposta',
|
||||
`${finance.loan.rate}% (${finance.loan.rateType})`,
|
||||
'Declarada pelo utilizador; não é taxa de produto',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Prazo pressuposto',
|
||||
`${finance.loan.months} meses`,
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Método e pressupostos substituídos',
|
||||
`Saldo decrescente; capital ${finance.loan.principal}; taxa ${finance.loan.rate}% ${finance.loan.rateType}; ${finance.loan.months} meses; período ${finance.loan.periodMonths} meses; carência ${finance.loan.gracePeriods}; comissão inicial ${finance.loan.upfrontFee}; comissão periódica ${finance.loan.recurringFee}`,
|
||||
'Cronograma do simulador; taxa declarada, sem correspondência a produto',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Prestação do primeiro período',
|
||||
calculation.loan.value?.schedule[0]?.totalPayment
|
||||
? `${calculation.loan.value.schedule[0].totalPayment} ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Juros totais estimados',
|
||||
calculation.loan.value?.totalInterest
|
||||
? `${calculation.loan.value.totalInterest} ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Estado/erro do cálculo',
|
||||
calculation.loan.error ??
|
||||
(calculation.loan.value
|
||||
? 'Calculado pelo cronograma do simulador'
|
||||
: 'Indeterminado'),
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Ponto de equilíbrio',
|
||||
'Fórmula e valores substituídos',
|
||||
`${finance.breakEven.fixed} / (${finance.breakEven.price} − ${finance.breakEven.variable}); unidades arredondadas para cima`,
|
||||
'Custos fixos ÷ margem de contribuição unitária; pressupostos declarados',
|
||||
],
|
||||
[
|
||||
'Ponto de equilíbrio',
|
||||
'Unidades estimadas',
|
||||
calculation.breakEven.value?.breakEvenUnits ?? 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Ponto de equilíbrio',
|
||||
'Vendas correspondentes',
|
||||
calculation.breakEven.value?.breakEvenRevenue
|
||||
? `${calculation.breakEven.value.breakEvenRevenue} ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Ponto de equilíbrio',
|
||||
'Estado/erro do cálculo',
|
||||
calculation.breakEven.error ??
|
||||
(calculation.breakEven.value
|
||||
? 'Calculado pelo simulador'
|
||||
: 'Indeterminado'),
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Investimento total pressuposto',
|
||||
`${finance.funding.total} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Montante já mobilizado pressuposto',
|
||||
`${finance.funding.secured} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Fórmula e valores substituídos',
|
||||
`${finance.funding.total} − ${finance.funding.secured}`,
|
||||
'Investimento total declarado − financiamento mobilizado declarado',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Diferença por financiar',
|
||||
calculation.funding.value?.gap
|
||||
? `${calculation.funding.value.gap} ${currency}`
|
||||
: calculation.funding.value?.gap === '0.00'
|
||||
? `0.00 ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Estado/erro do cálculo',
|
||||
calculation.funding.error ??
|
||||
(calculation.funding.value
|
||||
? 'Calculado pelo simulador'
|
||||
: 'Indeterminado'),
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Fórmula e valores substituídos',
|
||||
`${calculation.budget.value?.incomeTotal ?? 'Não informado'} − ${calculation.budget.value?.expenseTotal ?? 'Não informado'}`,
|
||||
'Receitas declaradas − despesas declaradas; valores ausentes não são zero',
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Receitas declaradas',
|
||||
calculation.budget.value?.incomeTotal
|
||||
? `${calculation.budget.value.incomeTotal} ${currency}`
|
||||
: 'Indeterminado',
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Despesas declaradas',
|
||||
calculation.budget.value?.expenseTotal
|
||||
? `${calculation.budget.value.expenseTotal} ${currency}`
|
||||
: 'Indeterminado',
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Saldo operacional estimado',
|
||||
calculation.budget.value?.operatingBalance
|
||||
? `${calculation.budget.value.operatingBalance} ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Estado/erro do cálculo',
|
||||
calculation.budget.error ??
|
||||
(calculation.budget.value
|
||||
? 'Calculado pelo simulador'
|
||||
: 'Indeterminado'),
|
||||
source,
|
||||
],
|
||||
);
|
||||
for (const income of finance.incomes) {
|
||||
rows.push(['Orçamento', `Receita declarada: ${income.label}`, `${income.amount} ${currency}`, 'Declarado pelo utilizador']);
|
||||
rows.push([
|
||||
'Orçamento',
|
||||
`Receita declarada: ${income.label}`,
|
||||
`${income.amount} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
]);
|
||||
}
|
||||
for (const expense of finance.expenses) {
|
||||
rows.push(['Orçamento', `Despesa declarada: ${expense.label}`, `${expense.amount} ${currency}`, 'Declarado pelo utilizador']);
|
||||
rows.push([
|
||||
'Orçamento',
|
||||
`Despesa declarada: ${expense.label}`,
|
||||
`${expense.amount} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
]);
|
||||
}
|
||||
}
|
||||
const businessPlan = restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot ?? ''));
|
||||
const businessPlan = restoreBusinessPlanSnapshot(
|
||||
String(draft.business_plan_snapshot ?? ''),
|
||||
);
|
||||
if (businessPlan) {
|
||||
try {
|
||||
const forecast = forecastBusinessPlan(businessPlan);
|
||||
const source = 'Estimativa calculada pelo plano financeiro a partir de pressupostos declarados; não é demonstração contabilística nem resultado confirmado';
|
||||
const source =
|
||||
'Estimativa calculada pelo plano financeiro a partir de pressupostos declarados; não é demonstração contabilística nem resultado confirmado';
|
||||
rows.push(
|
||||
['Plano financeiro', 'Moeda do plano', businessPlan.currency, 'Declarada pelo utilizador'],
|
||||
['Plano financeiro', 'Horizonte', `${businessPlan.periods ?? 12} meses`, 'Pressuposto declarado'],
|
||||
['Plano financeiro', 'Facturação no horizonte', `${forecast.totalRevenue} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Fórmula e valores substituídos', `Facturação: quantidade mensal × preço unitário por produto; caixa final: saldo de abertura + cobranças e fontes − pagamentos. Horizonte: ${businessPlan.periods ?? 12} meses; moeda: ${businessPlan.currency}.`, 'Métodos do plano financeiro; agendas e pressupostos declarados no snapshot'],
|
||||
['Plano financeiro', 'Cobranças no horizonte', `${forecast.totalCashCollections} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Pagamentos no horizonte', `${forecast.totalPayments} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Resultado antes de impostos', `${forecast.totalProfitBeforeTax} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Caixa final projectada', `${forecast.endingCash} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Reconciliação do financiamento', forecast.fundingStatus, 'Comparação calculada entre usos e fontes declarados'],
|
||||
['Plano financeiro', 'Diferença entre usos e fontes', `${forecast.fundingGap} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Taxa de câmbio de apresentação', businessPlan.fxRate ? `${businessPlan.fxRate}; ${businessPlan.fxDate ?? 'data não informada'}; ${businessPlan.fxSource ?? 'fonte não informada'}` : 'Não utilizada', businessPlan.fxRate ? 'Pressuposto de planeamento declarado pelo utilizador; não verificado' : 'Sem conversão'],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Moeda do plano',
|
||||
businessPlan.currency,
|
||||
'Declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Horizonte',
|
||||
`${businessPlan.periods ?? 12} meses`,
|
||||
'Pressuposto declarado',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Facturação no horizonte',
|
||||
`${forecast.totalRevenue} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Fórmula e valores substituídos',
|
||||
`Facturação: quantidade mensal × preço unitário por produto; caixa final: saldo de abertura + cobranças e fontes − pagamentos. Horizonte: ${businessPlan.periods ?? 12} meses; moeda: ${businessPlan.currency}.`,
|
||||
'Métodos do plano financeiro; agendas e pressupostos declarados no snapshot',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Cobranças no horizonte',
|
||||
`${forecast.totalCashCollections} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Pagamentos no horizonte',
|
||||
`${forecast.totalPayments} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Resultado antes de impostos',
|
||||
`${forecast.totalProfitBeforeTax} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Caixa final projectada',
|
||||
`${forecast.endingCash} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Reconciliação do financiamento',
|
||||
forecast.fundingStatus,
|
||||
'Comparação calculada entre usos e fontes declarados',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Diferença entre usos e fontes',
|
||||
`${forecast.fundingGap} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Taxa de câmbio de apresentação',
|
||||
businessPlan.fxRate
|
||||
? `${businessPlan.fxRate}; ${businessPlan.fxDate ?? 'data não informada'}; ${businessPlan.fxSource ?? 'fonte não informada'}`
|
||||
: 'Não utilizada',
|
||||
businessPlan.fxRate
|
||||
? 'Pressuposto de planeamento declarado pelo utilizador; não verificado'
|
||||
: 'Sem conversão',
|
||||
],
|
||||
);
|
||||
} catch {
|
||||
rows.push(['Plano financeiro', 'Estado do cálculo', 'Indeterminado', 'Snapshot inválido ou pressupostos incompatíveis; reveja o plano antes de exportar']);
|
||||
rows.push([
|
||||
'Plano financeiro',
|
||||
'Estado do cálculo',
|
||||
'Indeterminado',
|
||||
'Snapshot inválido ou pressupostos incompatíveis; reveja o plano antes de exportar',
|
||||
]);
|
||||
}
|
||||
}
|
||||
for (const [index, need] of readRows<TeamNeed>(String(draft.project_team_snapshot ?? ''), ['competency', 'state', 'action', 'estimated_cost', 'due_date']).entries()) {
|
||||
rows.push(['Equipa', `Necessidade ${index + 1}`, `${need.competency}; ${need.state}; resposta: ${need.action}; custo: ${need.estimated_cost}; prazo: ${need.due_date}`, 'Declarado pelo utilizador; sem certificação ou correspondência']);
|
||||
for (const [index, need] of readRows<TeamNeed>(
|
||||
String(draft.project_team_snapshot ?? ''),
|
||||
['competency', 'state', 'action', 'estimated_cost', 'due_date'],
|
||||
).entries()) {
|
||||
rows.push([
|
||||
'Equipa',
|
||||
`Necessidade ${index + 1}`,
|
||||
`${need.competency}; ${need.state}; resposta: ${need.action}; custo: ${need.estimated_cost}; prazo: ${need.due_date}`,
|
||||
'Declarado pelo utilizador; sem certificação ou correspondência',
|
||||
]);
|
||||
}
|
||||
for (const [index, milestone] of readRows<ProjectMilestone>(String(draft.project_execution_snapshot ?? ''), ['title', 'due_date', 'status', 'planned_amount', 'actual_amount']).entries()) {
|
||||
rows.push(['Execução', `Marco ${index + 1}`, `${milestone.title}; ${milestone.status}; prazo: ${milestone.due_date}; planeado: ${milestone.planned_amount}; realizado: ${milestone.actual_amount}`, 'Planeado/realizado declarado pelo utilizador']);
|
||||
for (const [index, milestone] of readRows<ProjectMilestone>(
|
||||
String(draft.project_execution_snapshot ?? ''),
|
||||
['title', 'due_date', 'status', 'planned_amount', 'actual_amount'],
|
||||
).entries()) {
|
||||
rows.push([
|
||||
'Execução',
|
||||
`Marco ${index + 1}`,
|
||||
`${milestone.title}; ${milestone.status}; prazo: ${milestone.due_date}; planeado: ${milestone.planned_amount}; realizado: ${milestone.actual_amount}`,
|
||||
'Planeado/realizado declarado pelo utilizador',
|
||||
]);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function exportProjectDossierCsv(draft: Record<string, string | string[]>): string {
|
||||
export function exportProjectDossierCsv(
|
||||
draft: Record<string, string | string[]>,
|
||||
): string {
|
||||
const rows = buildProjectDossierRows(draft);
|
||||
// Semicolon is the active list separator in the target Excel locale (pt-MZ).
|
||||
return `\uFEFF${rows.map((row) => row.map((value) => csvCellWithDelimiter(value, ';')).join(';')).join('\r\n')}`;
|
||||
|
||||
@@ -26,12 +26,17 @@ function value(draft: ReadinessDraft, key: string): string {
|
||||
return typeof current === 'string' ? current.trim() : '';
|
||||
}
|
||||
|
||||
function rows(draft: ReadinessDraft, key: string): Array<Record<string, string>> {
|
||||
function rows(
|
||||
draft: ReadinessDraft,
|
||||
key: string,
|
||||
): Array<Record<string, string>> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value(draft, key) || '[]');
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((item): item is Record<string, string> =>
|
||||
Boolean(item && typeof item === 'object' && !Array.isArray(item)),
|
||||
Boolean(
|
||||
item && typeof item === 'object' && !Array.isArray(item),
|
||||
),
|
||||
)
|
||||
: [];
|
||||
} catch {
|
||||
@@ -46,15 +51,22 @@ export function getProjectReadiness(
|
||||
const customers = value(draft, 'target_customers');
|
||||
const market = value(draft, 'market_assumption');
|
||||
const marketSource = value(draft, 'market_source');
|
||||
const costs = value(draft, 'business_plan_snapshot') ||
|
||||
const costs =
|
||||
value(draft, 'business_plan_snapshot') ||
|
||||
value(draft, 'financial_tools_snapshot') ||
|
||||
value(draft, 'annual_operating_costs');
|
||||
const territory = ['province_id', 'district_id', 'locality_id'].some((key) => value(draft, key));
|
||||
const territory = ['province_id', 'district_id', 'locality_id'].some(
|
||||
(key) => value(draft, key),
|
||||
);
|
||||
const locationReason = value(draft, 'location_rationale');
|
||||
const team = rows(draft, 'project_team_snapshot');
|
||||
const identifiedGap = team.some((item) => item.state === 'gap');
|
||||
const sought = Number(value(draft, 'sought_amount') || value(draft, 'opportunity_value') || 0);
|
||||
const secured = Number(value(draft, 'secured_amount') || value(draft, 'own_capital') || 0);
|
||||
const sought = Number(
|
||||
value(draft, 'sought_amount') || value(draft, 'opportunity_value') || 0,
|
||||
);
|
||||
const secured = Number(
|
||||
value(draft, 'secured_amount') || value(draft, 'own_capital') || 0,
|
||||
);
|
||||
const benefits = value(draft, 'claimed_benefits');
|
||||
const customerStatus = value(draft, 'customer_validation_status');
|
||||
const costStatus = value(draft, 'cost_estimate_status');
|
||||
@@ -64,89 +76,156 @@ export function getProjectReadiness(
|
||||
|
||||
if (!customers && customerStatus !== 'not_applicable') {
|
||||
items.push({
|
||||
id: 'customers', kind: 'missing', title: 'Clientes ainda pouco definidos',
|
||||
origin: customerStatus ? `Estado declarado: ${customerStatus}. Não foi indicada uma descrição de clientes ou beneficiários.` : 'Não foi indicada uma descrição de clientes ou beneficiários.',
|
||||
id: 'customers',
|
||||
kind: 'missing',
|
||||
title: 'Clientes ainda pouco definidos',
|
||||
origin: customerStatus
|
||||
? `Estado declarado: ${customerStatus}. Não foi indicada uma descrição de clientes ou beneficiários.`
|
||||
: 'Não foi indicada uma descrição de clientes ou beneficiários.',
|
||||
affected: 'Procura e receitas previstas.',
|
||||
consequence: 'As vendas planeadas podem não corresponder à procura real.',
|
||||
nextAction: 'Indique quem poderá comprar, onde está e que necessidade procura resolver.',
|
||||
consequence:
|
||||
'As vendas planeadas podem não corresponder à procura real.',
|
||||
nextAction:
|
||||
'Indique quem poderá comprar, onde está e que necessidade procura resolver.',
|
||||
fieldKey: 'target_customers',
|
||||
});
|
||||
} else if (customers && ((!marketSource && market) || ['no', 'partial', 'unknown'].includes(customerStatus))) {
|
||||
} else if (
|
||||
customers &&
|
||||
((!marketSource && market) ||
|
||||
['no', 'partial', 'unknown'].includes(customerStatus))
|
||||
) {
|
||||
items.push({
|
||||
id: 'market-source', kind: 'unverified', title: 'Hipótese de mercado sem fonte ou data',
|
||||
id: 'market-source',
|
||||
kind: 'unverified',
|
||||
title: 'Hipótese de mercado sem fonte ou data',
|
||||
origin: `Foi registada informação de mercado sem origem/data confirmada${customerStatus ? `; estado declarado da conversa com clientes: ${customerStatus}` : ''}.`,
|
||||
affected: 'Procura, preço e projecções de vendas.',
|
||||
consequence: 'A hipótese pode não representar informação actual ou verificável.',
|
||||
nextAction: 'Registe a origem e a data, ou marque-a como uma hipótese ainda por testar.',
|
||||
consequence:
|
||||
'A hipótese pode não representar informação actual ou verificável.',
|
||||
nextAction:
|
||||
'Registe a origem e a data, ou marque-a como uma hipótese ainda por testar.',
|
||||
fieldKey: 'market_source',
|
||||
});
|
||||
}
|
||||
|
||||
if ((!costs || ['no', 'partial', 'unknown'].includes(costStatus)) && costStatus !== 'not_applicable') {
|
||||
if (
|
||||
(!costs || ['no', 'partial', 'unknown'].includes(costStatus)) &&
|
||||
costStatus !== 'not_applicable'
|
||||
) {
|
||||
items.push({
|
||||
id: 'costs', kind: 'missing', title: 'Custos do projecto por detalhar',
|
||||
origin: costStatus ? `Estado declarado: ${costStatus}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}` : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.',
|
||||
id: 'costs',
|
||||
kind: 'missing',
|
||||
title: 'Custos do projecto por detalhar',
|
||||
origin: costStatus
|
||||
? `Estado declarado: ${costStatus}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}`
|
||||
: 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.',
|
||||
affected: 'Investimento necessário, margem e tesouraria.',
|
||||
consequence: 'O capital necessário pode estar subestimado.',
|
||||
nextAction: 'Registe os principais custos, moeda e periodicidade no plano financeiro.',
|
||||
nextAction:
|
||||
'Registe os principais custos, moeda e periodicidade no plano financeiro.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if ((value(draft, 'business_plan_snapshot') || value(draft, 'annual_revenue'))
|
||||
&& ['no', 'partial', 'unknown', ''].includes(collectionStatus)
|
||||
&& collectionStatus !== 'not_applicable') {
|
||||
if (
|
||||
(value(draft, 'business_plan_snapshot') ||
|
||||
value(draft, 'annual_revenue')) &&
|
||||
['no', 'partial', 'unknown', ''].includes(collectionStatus) &&
|
||||
collectionStatus !== 'not_applicable'
|
||||
) {
|
||||
items.push({
|
||||
id: 'receivables', kind: collectionStatus === 'no' || collectionStatus === 'partial' ? 'risk' : 'missing',
|
||||
id: 'receivables',
|
||||
kind:
|
||||
collectionStatus === 'no' || collectionStatus === 'partial'
|
||||
? 'risk'
|
||||
: 'missing',
|
||||
title: 'Prazo de recebimentos por esclarecer',
|
||||
origin: collectionStatus ? `Estado declarado sobre o prazo de recebimento: ${collectionStatus}.` : 'Existe um plano/valor de vendas, mas não foi indicado se o prazo de recebimento é conhecido.',
|
||||
origin: collectionStatus
|
||||
? `Estado declarado sobre o prazo de recebimento: ${collectionStatus}.`
|
||||
: 'Existe um plano/valor de vendas, mas não foi indicado se o prazo de recebimento é conhecido.',
|
||||
affected: 'Fluxo de caixa e capital de giro.',
|
||||
consequence: 'A tesouraria pode ficar abaixo do necessário mesmo quando há vendas previstas.',
|
||||
nextAction: 'Registe os prazos previstos de cobrança no plano de fluxo de caixa e confirme-os com os clientes.',
|
||||
consequence:
|
||||
'A tesouraria pode ficar abaixo do necessário mesmo quando há vendas previstas.',
|
||||
nextAction:
|
||||
'Registe os prazos previstos de cobrança no plano de fluxo de caixa e confirme-os com os clientes.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if ((!territory || !locationReason || ['no', 'partial', 'unknown'].includes(locationStatus)) && locationStatus !== 'not_applicable') {
|
||||
if (
|
||||
(!territory ||
|
||||
!locationReason ||
|
||||
['no', 'partial', 'unknown'].includes(locationStatus)) &&
|
||||
locationStatus !== 'not_applicable'
|
||||
) {
|
||||
items.push({
|
||||
id: 'location', kind: territory && locationReason ? 'unverified' : 'missing', title: 'Adequação da localização por esclarecer',
|
||||
id: 'location',
|
||||
kind: territory && locationReason ? 'unverified' : 'missing',
|
||||
title: 'Adequação da localização por esclarecer',
|
||||
origin: `Estado declarado: ${locationStatus || 'não indicado'}. ${territory ? 'Há uma localização seleccionada.' : 'Não foi seleccionada uma localização territorial.'} ${locationReason ? '' : 'Falta explicar os critérios considerados.'}`,
|
||||
affected: 'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
|
||||
consequence: 'Podem existir limitações logísticas ou custos locais ainda não considerados.',
|
||||
nextAction: 'Registe por que escolheu o local e quais recursos precisam de confirmação.',
|
||||
affected:
|
||||
'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
|
||||
consequence:
|
||||
'Podem existir limitações logísticas ou custos locais ainda não considerados.',
|
||||
nextAction:
|
||||
'Registe por que escolheu o local e quais recursos precisam de confirmação.',
|
||||
fieldKey: 'location_rationale',
|
||||
});
|
||||
}
|
||||
|
||||
if (identifiedGap || team.length === 0) {
|
||||
items.push({
|
||||
id: 'team', kind: identifiedGap ? 'risk' : 'missing', title: identifiedGap ? 'Competência em falta identificada' : 'Equipa e competências por detalhar',
|
||||
origin: identifiedGap ? 'O plano de equipa assinala pelo menos uma competência como lacuna.' : 'Ainda não há necessidades de equipa registadas.',
|
||||
id: 'team',
|
||||
kind: identifiedGap ? 'risk' : 'missing',
|
||||
title: identifiedGap
|
||||
? 'Competência em falta identificada'
|
||||
: 'Equipa e competências por detalhar',
|
||||
origin: identifiedGap
|
||||
? 'O plano de equipa assinala pelo menos uma competência como lacuna.'
|
||||
: 'Ainda não há necessidades de equipa registadas.',
|
||||
affected: 'Preparação e execução das actividades.',
|
||||
consequence: 'A execução pode atrasar ou exigir apoio e custos adicionais.',
|
||||
nextAction: 'Registe a competência, a resposta planeada, o responsável e o prazo.',
|
||||
consequence:
|
||||
'A execução pode atrasar ou exigir apoio e custos adicionais.',
|
||||
nextAction:
|
||||
'Registe a competência, a resposta planeada, o responsável e o prazo.',
|
||||
fieldKey: 'team',
|
||||
});
|
||||
}
|
||||
|
||||
if ((sought > secured || ['in_process', 'not_started', 'unknown'].includes(fundingStatus) || (fundingStatus === 'confirmed' && sought === 0 && secured === 0)) && fundingStatus !== 'not_applicable') {
|
||||
if (
|
||||
(sought > secured ||
|
||||
['in_process', 'not_started', 'unknown'].includes(fundingStatus) ||
|
||||
(fundingStatus === 'confirmed' && sought === 0 && secured === 0)) &&
|
||||
fundingStatus !== 'not_applicable'
|
||||
) {
|
||||
items.push({
|
||||
id: 'funding', kind: 'risk', title: 'Financiamento ainda não confirmado',
|
||||
origin: sought > secured ? 'O montante indicado como necessário excede os recursos declarados como mobilizados.' : `Estado do financiamento declarado: ${fundingStatus || 'não indicado'}; os montantes e condições não permitem confirmar recursos disponíveis.`,
|
||||
id: 'funding',
|
||||
kind: 'risk',
|
||||
title: 'Financiamento ainda não confirmado',
|
||||
origin:
|
||||
sought > secured
|
||||
? 'O montante indicado como necessário excede os recursos declarados como mobilizados.'
|
||||
: `Estado do financiamento declarado: ${fundingStatus || 'não indicado'}; os montantes e condições não permitem confirmar recursos disponíveis.`,
|
||||
affected: 'Calendário de investimento e implementação.',
|
||||
consequence: 'Os recursos podem não estar disponíveis quando forem necessários.',
|
||||
nextAction: 'Identifique a fonte, o estado, as condições e uma alternativa de financiamento.',
|
||||
consequence:
|
||||
'Os recursos podem não estar disponíveis quando forem necessários.',
|
||||
nextAction:
|
||||
'Identifique a fonte, o estado, as condições e uma alternativa de financiamento.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if (benefits) {
|
||||
items.push({
|
||||
id: 'benefits', kind: 'unverified', title: 'Benefício fiscal carece de validação',
|
||||
id: 'benefits',
|
||||
kind: 'unverified',
|
||||
title: 'Benefício fiscal carece de validação',
|
||||
origin: 'Foram indicados benefícios para validação no dossier.',
|
||||
affected: 'Impostos e retorno financeiro estimado.',
|
||||
consequence: 'O retorno pode estar sobrestimado se as condições não forem satisfeitas.',
|
||||
nextAction: 'Confirme a regra, vigência, regime e documentação numa fonte oficial; mantenha o benefício fora do cenário base até confirmação.',
|
||||
consequence:
|
||||
'O retorno pode estar sobrestimado se as condições não forem satisfeitas.',
|
||||
nextAction:
|
||||
'Confirme a regra, vigência, regime e documentação numa fonte oficial; mantenha o benefício fora do cenário base até confirmação.',
|
||||
fieldKey: 'tax',
|
||||
});
|
||||
}
|
||||
@@ -154,21 +233,33 @@ export function getProjectReadiness(
|
||||
return items;
|
||||
}
|
||||
|
||||
export function readPlannedRiskResponses(draft: ReadinessDraft): PlannedRiskResponse[] {
|
||||
export function readPlannedRiskResponses(
|
||||
draft: ReadinessDraft,
|
||||
): PlannedRiskResponse[] {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value(draft, 'project_risk_responses_snapshot') || '[]');
|
||||
const parsed: unknown = JSON.parse(
|
||||
value(draft, 'project_risk_responses_snapshot') || '[]',
|
||||
);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((item): item is PlannedRiskResponse => Boolean(
|
||||
item && typeof item === 'object' && !Array.isArray(item) &&
|
||||
typeof item.risk_id === 'string' && typeof item.action === 'string' &&
|
||||
typeof item.owner === 'string' && typeof item.estimated_cost === 'string' &&
|
||||
typeof item.due_date === 'string',
|
||||
));
|
||||
return parsed.filter((item): item is PlannedRiskResponse =>
|
||||
Boolean(
|
||||
item &&
|
||||
typeof item === 'object' &&
|
||||
!Array.isArray(item) &&
|
||||
typeof item.risk_id === 'string' &&
|
||||
typeof item.action === 'string' &&
|
||||
typeof item.owner === 'string' &&
|
||||
typeof item.estimated_cost === 'string' &&
|
||||
typeof item.due_date === 'string',
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function serializePlannedRiskResponses(responses: PlannedRiskResponse[]): string {
|
||||
export function serializePlannedRiskResponses(
|
||||
responses: PlannedRiskResponse[],
|
||||
): string {
|
||||
return JSON.stringify(responses.slice(0, 30));
|
||||
}
|
||||
|
||||
@@ -541,24 +541,44 @@ function isApiSimulationDraftV1(value: unknown): value is ApiSimulationDraftV1 {
|
||||
Array.isArray(value.simulation_sources) &&
|
||||
value.simulation_sources.every(isApiSimulationSourceV1) &&
|
||||
(value.updated_at === null || isIsoDateTime(value.updated_at)) &&
|
||||
(value.expires_at === undefined || value.expires_at === null || isIsoDateTime(value.expires_at))
|
||||
(value.expires_at === undefined ||
|
||||
value.expires_at === null ||
|
||||
isIsoDateTime(value.expires_at))
|
||||
);
|
||||
}
|
||||
|
||||
function isApiSimulationDraftSummaryV1(value: unknown): value is ApiSimulationDraftSummaryV1 {
|
||||
return isPlainObject(value) && typeof value.id === 'string' && uuidPattern.test(value.id) &&
|
||||
function isApiSimulationDraftSummaryV1(
|
||||
value: unknown,
|
||||
): value is ApiSimulationDraftSummaryV1 {
|
||||
return (
|
||||
isPlainObject(value) &&
|
||||
typeof value.id === 'string' &&
|
||||
uuidPattern.test(value.id) &&
|
||||
typeof value.title === 'string' &&
|
||||
(value.updated_at === null || isIsoDateTime(value.updated_at)) &&
|
||||
(value.expires_at === null || isIsoDateTime(value.expires_at)) &&
|
||||
Number.isSafeInteger(value.version_no) && Number(value.version_no) > 0;
|
||||
Number.isSafeInteger(value.version_no) &&
|
||||
Number(value.version_no) > 0
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftListResponseV1(value: unknown): value is { data: ApiSimulationDraftSummaryV1[] } {
|
||||
return isPlainObject(value) && Array.isArray(value.data) && value.data.every(isApiSimulationDraftSummaryV1);
|
||||
export function isApiSimulationDraftListResponseV1(
|
||||
value: unknown,
|
||||
): value is { data: ApiSimulationDraftSummaryV1[] } {
|
||||
return (
|
||||
isPlainObject(value) &&
|
||||
Array.isArray(value.data) &&
|
||||
value.data.every(isApiSimulationDraftSummaryV1)
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftClaimPreviewV1(value: unknown): value is { data: ApiSimulationDraftSummaryV1 | null } {
|
||||
return isPlainObject(value) && (value.data === null || isApiSimulationDraftSummaryV1(value.data));
|
||||
export function isApiSimulationDraftClaimPreviewV1(
|
||||
value: unknown,
|
||||
): value is { data: ApiSimulationDraftSummaryV1 | null } {
|
||||
return (
|
||||
isPlainObject(value) &&
|
||||
(value.data === null || isApiSimulationDraftSummaryV1(value.data))
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftReadResponseV1(
|
||||
@@ -579,7 +599,9 @@ export function isApiSimulationDraftWriteResponseV1(value: unknown): value is {
|
||||
uuidPattern.test(data.id) &&
|
||||
Number.isSafeInteger(data.version_no) &&
|
||||
Number(data.version_no) > 0 &&
|
||||
(value.expires_at === undefined || value.expires_at === null || isIsoDateTime(value.expires_at)) &&
|
||||
(value.expires_at === undefined ||
|
||||
value.expires_at === null ||
|
||||
isIsoDateTime(value.expires_at)) &&
|
||||
(data.replayed === undefined || typeof data.replayed === 'boolean')
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@ import { csvCell } from './csv.js';
|
||||
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
|
||||
|
||||
export type SimulationDraft = Record<string, string | string[]>;
|
||||
export const projectQuestionnaireVersion = 'investmoz-project-dossier-2026-10-05.1';
|
||||
export const projectQuestionnaireVersion =
|
||||
'investmoz-project-dossier-2026-10-05.1';
|
||||
|
||||
function isProjectGuidedJourney(draft: SimulationDraft): boolean {
|
||||
return (
|
||||
@@ -12,7 +13,9 @@ function isProjectGuidedJourney(draft: SimulationDraft): boolean {
|
||||
}
|
||||
|
||||
function isInvestorProjectJourney(draft: SimulationDraft): boolean {
|
||||
return draft.purpose === 'simulate_only' && draft.journey_type === 'investor';
|
||||
return (
|
||||
draft.purpose === 'simulate_only' && draft.journey_type === 'investor'
|
||||
);
|
||||
}
|
||||
|
||||
export function getFiscalPeriodRange(
|
||||
@@ -87,7 +90,13 @@ export function getSimulationSections(draft: SimulationDraft) {
|
||||
if (draft.journey_type === 'investor') {
|
||||
return [
|
||||
...simulationSections.filter((section) =>
|
||||
['purpose', 'project', 'location', 'financial', 'tax'].includes(section.id),
|
||||
[
|
||||
'purpose',
|
||||
'project',
|
||||
'location',
|
||||
'financial',
|
||||
'tax',
|
||||
].includes(section.id),
|
||||
),
|
||||
{ id: 'scenarios', title: 'Cenários e retorno indicativo' },
|
||||
{ id: 'procedures', title: 'Procedimentos e documentos' },
|
||||
@@ -254,7 +263,13 @@ export const simulationOptions: Record<string, string[]> = {
|
||||
'unknown',
|
||||
],
|
||||
preparedness_status: ['yes', 'no', 'partial', 'unknown', 'not_applicable'],
|
||||
funding_status: ['confirmed', 'in_process', 'not_started', 'unknown', 'not_applicable'],
|
||||
funding_status: [
|
||||
'confirmed',
|
||||
'in_process',
|
||||
'not_started',
|
||||
'unknown',
|
||||
'not_applicable',
|
||||
],
|
||||
fiscal_month: Array.from({ length: 12 }, (_, index) =>
|
||||
String(index + 1).padStart(2, '0'),
|
||||
),
|
||||
@@ -501,19 +516,25 @@ export const simulationFieldGroups: Record<
|
||||
key: 'target_customers',
|
||||
label: 'Quem são os clientes ou beneficiários?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'value_proposition',
|
||||
label: 'Que solução ou proposta de valor oferece?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'market_assumption',
|
||||
label: 'Hipótese sobre mercado, concorrência ou procura',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'market_source',
|
||||
@@ -600,42 +621,56 @@ export const simulationFieldGroups: Record<
|
||||
key: 'customer_validation_status',
|
||||
label: 'Já conversou com potenciais clientes sobre esta necessidade?',
|
||||
options: 'preparedness_status',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'target_customers',
|
||||
label: 'Quem são os clientes ou beneficiários? Onde estão e que necessidade têm?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'market_assumption',
|
||||
label: 'O que sabe ou está a assumir sobre procura, preço e concorrência?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'market_source',
|
||||
label: 'Qual é a origem e a data dessa informação, se as conhecer?',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'competitor_assumption',
|
||||
label: 'Que alternativas ou concorrentes os clientes usam actualmente?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'sales_channel_assumption',
|
||||
label: 'Como pretende chegar aos clientes e receber encomendas?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'marketing_approach',
|
||||
label: 'Que acções de divulgação pretende experimentar?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
],
|
||||
location: [
|
||||
@@ -643,7 +678,8 @@ export const simulationFieldGroups: Record<
|
||||
key: 'location_assessment_status',
|
||||
label: 'Já avaliou a adequação desta localização?',
|
||||
options: 'preparedness_status',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'province_id',
|
||||
@@ -684,31 +720,36 @@ export const simulationFieldGroups: Record<
|
||||
label: 'Local conhecido?',
|
||||
options: 'yes_no',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'location_rationale',
|
||||
label: 'Porque considera esta localização e o que ainda precisa de confirmar?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'land_status',
|
||||
label: 'Situação do terreno',
|
||||
options: 'land_status',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'area_required',
|
||||
label: 'Área necessária',
|
||||
type: 'number',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'area_unit',
|
||||
label: 'Unidade da área',
|
||||
options: 'area_unit',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'latitude',
|
||||
@@ -725,14 +766,16 @@ export const simulationFieldGroups: Record<
|
||||
{
|
||||
key: 'special_zone_id',
|
||||
label: 'Zona especial ZEE/ZFI',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'infrastructure_needs',
|
||||
label: 'Necessidades de infra-estrutura',
|
||||
options: 'infrastructure',
|
||||
multiple: true,
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
],
|
||||
financial: [
|
||||
@@ -740,86 +783,99 @@ export const simulationFieldGroups: Record<
|
||||
key: 'cost_estimate_status',
|
||||
label: 'Já identificou os principais custos e respectiva periodicidade?',
|
||||
options: 'preparedness_status',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'receivables_timing_status',
|
||||
label: 'Já sabe quando as vendas serão recebidas?',
|
||||
options: 'preparedness_status',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'funding_status',
|
||||
label: 'Qual é o estado dos recursos de financiamento de que precisa?',
|
||||
options: 'funding_status',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'currency',
|
||||
label: 'Moeda',
|
||||
options: 'currency',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'total_investment',
|
||||
label: 'Investimento total',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'own_capital',
|
||||
label: 'Capital próprio',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'domestic_debt',
|
||||
label: 'Financiamento interno',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'foreign_debt',
|
||||
label: 'Financiamento externo',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'grants',
|
||||
label: 'Subvenções',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'secured_amount',
|
||||
label: 'Montante mobilizado',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'sought_amount',
|
||||
label: 'Montante procurado',
|
||||
type: 'number',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'annual_revenue',
|
||||
label: 'Receitas anuais estimadas',
|
||||
type: 'number',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'annual_operating_costs',
|
||||
label: 'Custos operacionais anuais',
|
||||
type: 'number',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'expected_profit',
|
||||
@@ -1232,7 +1288,8 @@ export const simulationFieldGroups: Record<
|
||||
label: 'Documentos de suporte que já possui ou pretende preparar',
|
||||
options: 'document_types',
|
||||
multiple: true,
|
||||
showWhen: (d) => d.journey_type === 'investor' && d.purpose === 'simulate_only',
|
||||
showWhen: (d) =>
|
||||
d.journey_type === 'investor' && d.purpose === 'simulate_only',
|
||||
},
|
||||
],
|
||||
review: [
|
||||
|
||||
Reference in New Issue
Block a user