fix: retain editable investment plans and record partial QA continuity evidence
This commit is contained in:
@@ -10353,3 +10353,11 @@ QA: seis testes novos (instruções fiscais/financeiras, tipos, percursos adapta
|
||||
Complemento do mesmo lote: ensaio com Dialog real confirmou a necessidade de manter a ajuda dentro do foco da janela. O painel usa portal React no próprio dialog, conserva os campos montados e volta à página quando a janela fecha. Verificados abrir, fechar/reabrir a ajuda, fechar a janela e regressar ao campo da página, sem submissões. Diálogos nativos abertos também fazem parte do grupo visível. Teste de integração/privacidade acrescentado.
|
||||
|
||||
Cobertura das três páginas técnicas fora do cliente React: editorial-mfa, editorial-installation e sector-reconciliation recebem orientação visível e Ajuda neste passo nativa em details, sem Javascript, mudança de estilos gerais ou alteração dos formulários, CSRF, campos ocultos, confirmações, endpoints e guardas. Textos limitados ao preenchimento/confirmacão da prévia existente. Sem executar qualquer operação dessas páginas.
|
||||
|
||||
## 20/11/2026 — Continuidade do investimento: candidata parcial, sem instalação
|
||||
|
||||
Candidata isolada `qa/continuidade-investimento-20261120`, base servida `bae996e1`. Corrigida a perda de valores do plano por recuperação de percentagens vazias; rascunhos incompletos conservam os valores e percentagens inválidas permanecem editáveis. Cálculo estrito e avanço financeiro validado; mensagens por campo monetário/unidades base. Estados de preparação traduzidos no produtor comum, comparação jurídica organizada por tema e acção explícita para pesquisar instituição noutra província sem alterar a localização do investimento. Nenhuma instalação ou alteração de dados/permissões do activo.
|
||||
|
||||
Verificações: 1 990 frontend, com 1 989 aprovados na ronda geral e o teste de manifesto aprovado depois com o caminho QA correcto; HTTP financeiro/planos/tesouraria 7/155 e comparação jurídica 10/193 na base nova `continuity_20261120_test:55441`; tipos/lint/Pint/build aprovados. Acesso visual bloqueado pelo conector e alternativa nativa; não declarar demonstração integral Hotel/Agronegócio. Novo relatório de onze tabelas, avisos, exemplo e CAE até nível 5 permanecem pendentes; três divergências concretas do anexo aguardam resposta.
|
||||
|
||||
Incidente aberto: uma suite com RefreshDatabase reinicializou indevidamente a base sintética anterior `investor_intent_20261115_test`; zero utilizadores encontrados depois. Activo e ficheiros de provas anteriores preservados. Restauro exacto não demonstrado; não confundir scripts/JSON de fixtures com recuperação do histórico completo. A equipa foi informada e os testes seguintes passaram para a base nova. Detalhes, causas, saldo 4.1–4.9, oito prioridades do segundo anexo e limites em `../v2/auditoria-portal/apresentacao-contexto-qa-20261115.md`, aditamento 20/11. Matriz existente actualizada sem encerrar requisitos globais ou revogar provas anteriores.
|
||||
@@ -359,3 +359,59 @@ Delta verificado: 3 testes HTTP/49 asserções e 1 teste/12 asserções para o e
|
||||
Utilização: no próprio dossier aberto, «Actividades existentes na localização» → pesquisar a actividade pelos primeiros três caracteres ou código → «Consultar e guardar análise agregada». A análise, classificação e histórico são privados e recuperáveis. A escolha não substitui a actividade do investimento. Sem correspondência previamente demonstrada, pede-se a escolha da classificação em vez de presumir equivalência entre taxonomias. Grupos pequenos, conflitos e falta de identidade/classificação conservam a explicação de cobertura insuficiente, nunca «não existem empresas».
|
||||
|
||||
Estado desta passagem: candidato verificado, instalação já autorizada e ainda não executada neste registo. Prosseguir pelo executor Git com capacidade, backup/restauro frescos, pin da revisão, activação apenas de `INVESTOR_PROTECTED_SUPPLY_ENABLED` e conferência do delta. Sem migrações, novos papéis, exposição individual ou produção. Ofertas, dashboard, correcção financeira e d3067050 preservados. Tradução permanece separada.
|
||||
|
||||
## 20/11/2026 — continuidade e anexos de correcção: delta parcial em QA
|
||||
|
||||
Pedido actual: anexos recebidos em 20/11 e instrução de intervenção transversal. Respostas do proprietário no primeiro anexo são decisões vigentes, sem nova confirmação. O segundo anexo detalha o relatório com tabelas financeiras; esta indicação posterior substitui a exclusão genérica de tabelas apenas no âmbito desse relatório. Não autoriza instalação.
|
||||
|
||||
Base confrontada com `/build/revision.json`: `bae996e10d0473805c51be30422da3b415f40853`, servida na homologação em 20/11. Candidata isolada em `C:/laragon/www/portal-investidor-continuity-qa-20261120`, ramo `qa/continuidade-investimento-20261120`. As diferenças locais da pasta principal foram conservadas. Não houve push, instalação, alterações no activo, permissões, dados públicos ou regras fiscais.
|
||||
|
||||
### Resultado efectivamente implementado
|
||||
|
||||
- Causa do bloqueio de valores delimitada: o plano inicial tem percentagens vazias; a recuperação interpretava-as como plano inválido e descartava todas as edições após cada eco do estado. Recuperação agora conserva vazios e, no editor, percentagens inválidas para correcção. Nenhuma percentagem é substituída no plano devolvido; o cálculo permanece estrito. Unidades, preços, custos e despesas mantêm-se após edição e recuperação.
|
||||
- Campos monetários e unidades base mostram os erros de preenchimento junto do campo, com associação acessível. Um plano existente inválido bloqueia o avanço financeiro, mostra a explicação e conserva o rascunho. Este recorte não implementa ainda todas as validações, ligações por campo ou avisos do segundo anexo.
|
||||
- Preparação e relatórios consumidores de `getProjectReadiness` apresentam Sim/Não/Parcialmente/Por confirmar/Em curso, conservando os códigos guardados e a lógica anterior.
|
||||
- Comparação jurídica mantém o circuito privado já existente; perguntas por tema e frase expressamente pedida. Gravação, recuperação, replay, conflito, histórico e isolamento conferidos por HTTP. Não foi criada outra comparação paralela.
|
||||
- Sem correspondências físicas na pesquisa aplicada por província, acção explícita para procurar noutra província: limpa apenas a localização da consulta e o selector visível; conserva categoria, tipo, necessidade, contexto e oportunidade. Não modifica a localização do investimento. Palavras-chave identificadas como refinamento opcional.
|
||||
|
||||
### Saldo do primeiro anexo, sem apagar provas anteriores
|
||||
|
||||
| Secção | Estado desta intervenção | Critério que permanece por demonstrar |
|
||||
| --- | --- | --- |
|
||||
| 4.1 Demografia | Provas e incorporação anteriores conservadas; sem nova alteração neste delta | Turismo, apresentação inteira de todas as dimensões, referência documental, diferenças e continuidade sectorial na revisão actual |
|
||||
| 4.2 Financiamento | Acção noutra província e ajuda de palavra-chave implementadas/testadas; cinco testes HTTP aprovados | Conferência visual; mínimo de critérios, incompatibilidades proactivas e ligação completa instituição → dossier do exemplo |
|
||||
| 4.3 Carteira | Sem nova alteração | Oportunidades, filtro provincial, deduplicação e referências internas nos exemplos actuais |
|
||||
| 4.4 Zonas | Decisão sobre mesmo contexto preservada | Grupo, regresso, limpeza entre contextos diferentes e limites sem repetição |
|
||||
| 4.5 Negócios | Sem nova alteração | Oportunidades na própria consulta e opções agrupadas em todos os consumidores |
|
||||
| 4.6 Educação | Fontes e provas anteriores preservadas | Confronto dos requisitos e indisponibilidades na revisão actual |
|
||||
| 4.7 Preparação | Gravação/recuperação e isolamento dos planos reconferidos; sem escolha automática nova de dossier/sector | Percurso integral Hotel e Agronegócio, ida/volta, menus, entidade, localização e financiamento no navegador |
|
||||
| 4.8 Formulários fiscais | Nenhum cálculo ou formulário fiscal alterado | Remoção transversal da informação interna nos exemplos actuais |
|
||||
| 4.9 Idioma/apresentação | Estados de preparação traduzidos no produtor partilhado | Textos das fontes e cartões, campos Não documentado e investigação factual, grafia e referências internas restantes |
|
||||
|
||||
### Saldo do segundo anexo
|
||||
|
||||
1. Estado do simulador: causa dos valores resolvida em código e testes; percurso completo no navegador pendente.
|
||||
2. Validação: mensagens dos controlos monetários/unidades base e bloqueio financeiro implementados; restantes validações individuais e sumário de campos em falta pendentes.
|
||||
3. Relatório essencial com onze tabelas: não implementado neste delta. Relatórios e cálculos anteriores mantidos; não declarar cumprimento do novo exemplo.
|
||||
4. Avisos dispensáveis/configuráveis: novo conjunto ainda não implementado.
|
||||
5. Cenário de exemplo: não carregado automaticamente, não gravado em dossier e não usado para activar taxas fiscais. Divergências concretas abaixo aguardam resposta.
|
||||
6. Formas jurídicas: organização por tema implementada; circuito de persistência existente reconferido por dez testes/193 asserções. Conferência visual pendente.
|
||||
7. Hotel/CAE nível 5: sem nova associação automática. Reutilizar apenas correspondências documentadas; não inferir um subtipo quando houver alternativas. Critério pendente.
|
||||
8. Novo modelo integral de plano de negócio: pendente, reutilizando os componentes existentes; não substituir o modelo por valores inventados.
|
||||
|
||||
Decisões solicitadas ao proprietário: (a) falta de financiamento é erro no plano, mas o exemplo com zero financiado deve não gerar erros; (b) crescimento superior a 100% é simultaneamente erro de intervalo e aviso; (c) linhas mensais de Janeiro somam 510 em vendas e 431 em custos, mas os totais indicam 680 e 586; também as linhas anuais visíveis não reconciliam todos os totais. Foram apresentadas opções concretas em três perguntas; ausência de resposta não equivale a decisão. Os cálculos independentes destes pontos prosseguiram.
|
||||
|
||||
### Verificações e limites
|
||||
|
||||
- Frontend: 1 990 testes executados; 1 989 passaram na ronda geral. O único erro foi o teste do manifesto que procurava `public/build/manifest.json`, ausente num build QA. Repetido esse teste com `EDITORIAL_BUILD_MANIFEST` apontado ao manifesto QA real: aprovado, sem alterar o teste nem fabricar um manifesto. Log: `outputs/continuity-20261120/frontend-all.log`.
|
||||
- HTTP: sete testes/155 asserções para pesquisa financeira, planos de dois dossiers, recuperação numa nova sessão, conta alheia e tesouraria na base nova `continuity_20261120_test:55441`; dez testes/193 asserções da comparação jurídica na mesma base. Logs `draft-funding-tests.log` e `company-tests.log`.
|
||||
- Tipos, lint focado, Pint e compilação QA aprovados; avisos existentes de tamanho de chunks e fonte opcional conservados. `git diff --check` aprovado. Não equivale a CI remoto ou conferência visual.
|
||||
- Navegador: conector devolveu `The browser access host is unavailable`. Alternativa nativa Edge: primeiro timeout em `get_window_state`; após recuperar a janela, `Accessibility state unavailable for window 133188`. Frente visual parada após duas tentativas sem observação utilizável. Não há captura ou demonstração visual nova. A aplicação QA respondeu HTTP 200.
|
||||
|
||||
### Incidente de preservação do QA — aberto
|
||||
|
||||
Uma execução incluiu indevidamente `CompanyComparisonTest`, com `RefreshDatabase`, na base sintética existente `investor_intent_20261115_test`. A suite reinicializou essa base antes da interrupção; a consulta posterior encontrou zero utilizadores. Não foi a base activa: ligação explícita loopback/55441 e nome `_test`. O código e os recibos históricos em ficheiros foram preservados, mas isso não recupera os dados da antiga base QA.
|
||||
|
||||
Não foi localizado um backup exacto nas localizações consultadas. Não se declara restauro nem se recriam histórias como se fossem originais. A recuperação exacta permanece por resolver; as fixtures antigas em JSON/scripts não bastam para certificar o histórico completo. A equipa foi informada. Testes posteriores passaram a usar exclusivamente a base nova `continuity_20261120_test`; o router QA foi vinculado a essa identidade. Bootstrap explícito garante que a junction de vendor partilha dependências, sem carregar classes App/Tests da pasta principal. A primeira ronda que carregou classes antigas por essa junction foi invalidada, diagnosticada e repetida com as fontes correctas.
|
||||
|
||||
**Estado final deste recorte:** parcialmente implementado e testado em QA, sem instalação. Matriz existente actualizada nas linhas pertinentes. Pendentes: recuperação exacta do QA anterior, três decisões concretas, implementação dos restantes requisitos e conferência integral dos percursos antes de qualquer autorização de entrega.
|
||||
File diff suppressed because one or more lines are too long
@@ -1,7 +1,8 @@
|
||||
import CurrencySelect from '@/components/currency-select';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import {
|
||||
compareBusinessScenarios,
|
||||
businessPlanNumberError,
|
||||
exportBusinessPlanCsv,
|
||||
forecastBusinessPlan,
|
||||
MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH,
|
||||
@@ -74,23 +75,45 @@ function MoneyInput({
|
||||
value,
|
||||
onChange,
|
||||
allowNegative = false,
|
||||
step = '0.01',
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
allowNegative?: boolean;
|
||||
step?: string;
|
||||
}) {
|
||||
const errorId = useId();
|
||||
const [touched, setTouched] = useState(false);
|
||||
const error = touched
|
||||
? businessPlanNumberError(value, { allowNegative })
|
||||
: '';
|
||||
return (
|
||||
<label className="block text-sm font-medium">
|
||||
{label}
|
||||
<input
|
||||
type="number"
|
||||
min={allowNegative ? undefined : '0'}
|
||||
step="0.01"
|
||||
step={step}
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
onChange={(event) => {
|
||||
setTouched(true);
|
||||
onChange(event.target.value);
|
||||
}}
|
||||
onBlur={() => setTouched(true)}
|
||||
aria-invalid={!!error}
|
||||
aria-describedby={error ? errorId : undefined}
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
/>
|
||||
{error && (
|
||||
<span
|
||||
id={errorId}
|
||||
role="alert"
|
||||
className="mt-1 block text-sm text-red-800"
|
||||
>
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -252,7 +275,7 @@ export function SimulationBusinessPlan({
|
||||
unitVariableCostByPeriod: 'unitVariableCost',
|
||||
};
|
||||
const plan = workingPlan ??
|
||||
restoreBusinessPlanSnapshot(snapshot) ?? {
|
||||
restoreBusinessPlanSnapshot(snapshot, { editable: true }) ?? {
|
||||
...emptyPlan,
|
||||
currency: projectCurrency,
|
||||
};
|
||||
@@ -857,7 +880,11 @@ export function SimulationBusinessPlan({
|
||||
const fiscalBridge = result ? buildFinancialFiscalBridge(result) : null;
|
||||
|
||||
return (
|
||||
<details className="rounded-lg border border-slate-300 p-4" open>
|
||||
<details
|
||||
id="business-financial-plan"
|
||||
className="rounded-lg border border-slate-300 p-4"
|
||||
open
|
||||
>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Plano financeiro empresarial (pressupostos editáveis)
|
||||
</summary>
|
||||
@@ -1092,25 +1119,18 @@ export function SimulationBusinessPlan({
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
{product.monthlyUnitsByPeriod
|
||||
? 'Unidades mensais base'
|
||||
: 'Unidades por mes'}
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.001"
|
||||
value={product.monthlyUnits}
|
||||
onChange={(event) =>
|
||||
updateProduct(
|
||||
index,
|
||||
'monthlyUnits',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
/>
|
||||
</label>
|
||||
<MoneyInput
|
||||
label={
|
||||
product.monthlyUnitsByPeriod
|
||||
? 'Unidades mensais base'
|
||||
: 'Unidades por mes'
|
||||
}
|
||||
step="0.001"
|
||||
value={product.monthlyUnits}
|
||||
onChange={(value) =>
|
||||
updateProduct(index, 'monthlyUnits', value)
|
||||
}
|
||||
/>
|
||||
<MoneyInput
|
||||
label="Preço por unidade"
|
||||
value={product.unitPrice}
|
||||
|
||||
@@ -3298,6 +3298,21 @@ export function SimulationForm() {
|
||||
>
|
||||
{current.title}
|
||||
</h3>
|
||||
{errors.business_plan_snapshot && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded border border-red-400 bg-red-50 p-3 text-red-900"
|
||||
>
|
||||
<a
|
||||
className="underline"
|
||||
href="#business-financial-plan"
|
||||
>
|
||||
{errors.business_plan_snapshot}
|
||||
</a>{' '}
|
||||
Os dados permanecem no rascunho; corrija o plano
|
||||
financeiro para continuar.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
data-form-help-open
|
||||
|
||||
@@ -13,6 +13,29 @@ type ProductLine = {
|
||||
productInventoryPurchasesByPeriod?: InventoryPurchasePeriod[] | null;
|
||||
};
|
||||
export const MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH = 60_000;
|
||||
|
||||
export function businessPlanNumberError(
|
||||
value: string,
|
||||
options: {
|
||||
allowNegative?: boolean;
|
||||
integer?: boolean;
|
||||
percent?: boolean;
|
||||
} = {},
|
||||
): string {
|
||||
if (value.trim() === '') return 'Preencha este campo para continuar.';
|
||||
if (
|
||||
!/^-?\d+(?:\.\d+)?$/.test(value.trim()) ||
|
||||
!Number.isFinite(Number(value))
|
||||
)
|
||||
return 'Introduza apenas números (ex.: 25.000).';
|
||||
if (!options.allowNegative && Number(value) < 0)
|
||||
return 'Este valor não pode ser negativo.';
|
||||
if (options.integer && !Number.isSafeInteger(Number(value)))
|
||||
return 'Introduza um número inteiro de pessoas.';
|
||||
if (options.percent && (Number(value) < 0 || Number(value) > 100))
|
||||
return 'Introduza uma percentagem entre 0% e 100%.';
|
||||
return '';
|
||||
}
|
||||
export type ScenarioAdjustment = {
|
||||
unitVolumePercent: string;
|
||||
unitPricePercent: string;
|
||||
@@ -179,6 +202,7 @@ export function serializeBusinessPlanSnapshot(
|
||||
|
||||
export function restoreBusinessPlanSnapshot(
|
||||
snapshot: string | undefined,
|
||||
options: { editable?: boolean } = {},
|
||||
): BusinessFinancialPlanInput | null {
|
||||
if (!snapshot || snapshot.length > MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH)
|
||||
return null;
|
||||
@@ -210,6 +234,15 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
const plan = decoded.plan as Record<string, unknown>;
|
||||
// A blank percentage is an unfinished draft, not a zero assumption.
|
||||
// Editable recovery also retains invalid percentages for correction.
|
||||
// The zero below is only an upper-bound validation accumulator, never
|
||||
// a replacement in the returned plan. Calculation remains strict.
|
||||
const snapshotPercentage = (value: string, label: string): bigint =>
|
||||
options.editable || value.trim() === ''
|
||||
? 0n
|
||||
: percentMicro(value, label);
|
||||
|
||||
const textFields = [
|
||||
'currency',
|
||||
'openingCash',
|
||||
@@ -336,7 +369,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
const collectionPercent = String(plan.salesCollectionPercent ?? '100');
|
||||
const collectionRate = percentMicro(
|
||||
const collectionRate = snapshotPercentage(
|
||||
collectionPercent,
|
||||
'Percentagem de cobrança',
|
||||
);
|
||||
@@ -360,7 +393,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
!Object.hasOwn(plan, 'openingReceivablesCollectionPercent'))
|
||||
)
|
||||
return null;
|
||||
const openingCollectionRate = percentMicro(
|
||||
const openingCollectionRate = snapshotPercentage(
|
||||
String(plan.openingReceivablesCollectionPercent ?? '100'),
|
||||
'Percentagem de cobrança dos valores a receber de abertura',
|
||||
);
|
||||
@@ -391,7 +424,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
typeof entry.percent !== 'string'
|
||||
)
|
||||
return null;
|
||||
const rate = percentMicro(
|
||||
const rate = snapshotPercentage(
|
||||
entry.percent,
|
||||
'Percentagem da parcela de recebíveis',
|
||||
);
|
||||
@@ -419,11 +452,11 @@ export function restoreBusinessPlanSnapshot(
|
||||
entry.month < 1 ||
|
||||
entry.month > 60 ||
|
||||
typeof entry.percent !== 'string' ||
|
||||
percentMicro(
|
||||
snapshotPercentage(
|
||||
entry.percent,
|
||||
'Percentagem da liquidação de valores a pagar',
|
||||
) < 0n ||
|
||||
percentMicro(
|
||||
snapshotPercentage(
|
||||
entry.percent,
|
||||
'Percentagem da liquidação de valores a pagar',
|
||||
) > 100_000_000n,
|
||||
@@ -431,7 +464,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
plan.openingPayablesInstallments.reduce(
|
||||
(sum, entry) =>
|
||||
sum +
|
||||
percentMicro(
|
||||
snapshotPercentage(
|
||||
entry.percent,
|
||||
'Percentagem da liquidação de valores a pagar',
|
||||
),
|
||||
@@ -462,7 +495,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
)
|
||||
return null;
|
||||
months.add(entry.month);
|
||||
const rate = percentMicro(
|
||||
const rate = snapshotPercentage(
|
||||
entry.percent,
|
||||
'Percentagem de recuperação de vendas',
|
||||
);
|
||||
@@ -634,11 +667,11 @@ export function restoreBusinessPlanSnapshot(
|
||||
part.lagMonths > 12 ||
|
||||
typeof part.percent !==
|
||||
'string' ||
|
||||
percentMicro(
|
||||
snapshotPercentage(
|
||||
part.percent,
|
||||
'Percentagem da parcela',
|
||||
) < 0n ||
|
||||
percentMicro(
|
||||
snapshotPercentage(
|
||||
part.percent,
|
||||
'Percentagem da parcela',
|
||||
) > 100_000_000n,
|
||||
@@ -646,7 +679,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
entry.paymentInstallments.reduce(
|
||||
(sum: bigint, part: any) =>
|
||||
sum +
|
||||
percentMicro(
|
||||
snapshotPercentage(
|
||||
part.percent,
|
||||
'Percentagem da parcela',
|
||||
),
|
||||
|
||||
@@ -26,6 +26,20 @@ function value(draft: ReadinessDraft, key: string): string {
|
||||
return typeof current === 'string' ? current.trim() : '';
|
||||
}
|
||||
|
||||
function statusLabel(status: string): string {
|
||||
const labels: Record<string, string> = {
|
||||
yes: 'Sim',
|
||||
no: 'Não',
|
||||
partial: 'Parcialmente',
|
||||
unknown: 'Por confirmar',
|
||||
not_applicable: 'Não aplicável',
|
||||
in_process: 'Em curso',
|
||||
not_started: 'Por iniciar',
|
||||
confirmed: 'Confirmado',
|
||||
};
|
||||
return labels[status] ?? 'Não indicado';
|
||||
}
|
||||
|
||||
function rows(
|
||||
draft: ReadinessDraft,
|
||||
key: string,
|
||||
@@ -80,7 +94,7 @@ export function getProjectReadiness(
|
||||
kind: 'missing',
|
||||
title: 'Clientes ainda pouco definidos',
|
||||
origin: customerStatus
|
||||
? `Estado declarado: ${customerStatus}. Não foi indicada uma descrição de clientes ou beneficiários.`
|
||||
? `Estado declarado: ${statusLabel(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:
|
||||
@@ -98,7 +112,7 @@ export function getProjectReadiness(
|
||||
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}` : ''}.`,
|
||||
origin: `Foi registada informação de mercado sem origem/data confirmada${customerStatus ? `; estado declarado da conversa com clientes: ${statusLabel(customerStatus)}` : ''}.`,
|
||||
affected: 'Procura, preço e projecções de vendas.',
|
||||
consequence:
|
||||
'A hipótese pode não representar informação actual ou verificável.',
|
||||
@@ -117,7 +131,7 @@ export function getProjectReadiness(
|
||||
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.'}`
|
||||
? `Estado declarado: ${statusLabel(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.',
|
||||
@@ -141,7 +155,7 @@ export function getProjectReadiness(
|
||||
: 'missing',
|
||||
title: 'Prazo de recebimentos por esclarecer',
|
||||
origin: collectionStatus
|
||||
? `Estado declarado sobre o prazo de recebimento: ${collectionStatus}.`
|
||||
? `Estado declarado sobre o prazo de recebimento: ${statusLabel(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:
|
||||
@@ -162,7 +176,7 @@ export function getProjectReadiness(
|
||||
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.'}`,
|
||||
origin: `Estado declarado: ${statusLabel(locationStatus)}. ${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:
|
||||
@@ -205,7 +219,7 @@ export function getProjectReadiness(
|
||||
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.`,
|
||||
: `Estado do financiamento declarado: ${statusLabel(fundingStatus)}; 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.',
|
||||
|
||||
@@ -3,6 +3,10 @@ import { landStatusVisible } from './investment-land-preparation.ts';
|
||||
import { csvCell } from './csv.js';
|
||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from './business-financial-plan.ts';
|
||||
|
||||
export type SimulationDraft = Record<string, string | string[]>;
|
||||
export const projectQuestionnaireVersion =
|
||||
@@ -1801,6 +1805,26 @@ export function validateSimulationDraft(
|
||||
errors.total_investment =
|
||||
'A soma do capital, dívida e subvenções deve corresponder ao investimento total.';
|
||||
}
|
||||
if (
|
||||
sectionId === 'financial' &&
|
||||
typeof draft.business_plan_snapshot === 'string' &&
|
||||
draft.business_plan_snapshot
|
||||
) {
|
||||
const plan = restoreBusinessPlanSnapshot(draft.business_plan_snapshot);
|
||||
if (!plan)
|
||||
errors.business_plan_snapshot =
|
||||
'Não foi possível recuperar o plano financeiro. Reveja os dados guardados.';
|
||||
else {
|
||||
try {
|
||||
forecastBusinessPlan(plan);
|
||||
} catch (cause) {
|
||||
errors.business_plan_snapshot =
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Reveja os dados do plano financeiro antes de continuar.';
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import { InstitutionView, type InstitutionDetails } from "@/components/funding-institution";
|
||||
import { financialCategories, financialTypes } from "@/components/funding-classification";
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { Frame, card, button } from "@/pages/investment/shared";
|
||||
import { type Programme, windowLabels } from "./shared";
|
||||
import { useRef, useState } from "react";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import {
|
||||
InstitutionView,
|
||||
type InstitutionDetails,
|
||||
} from '@/components/funding-institution';
|
||||
import {
|
||||
financialCategories,
|
||||
financialTypes,
|
||||
} from '@/components/funding-classification';
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { type Programme, windowLabels } from './shared';
|
||||
import { useRef, useState } from 'react';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
|
||||
export default function FundingIndex(props: Parameters<typeof Index>[0]) {
|
||||
return <Index key={JSON.stringify(props.filters)} {...props} />;
|
||||
@@ -54,35 +63,38 @@ function Index({
|
||||
territorySelection?: TerritoryOption[];
|
||||
criteriaErrors?: Record<string, string[]>;
|
||||
}) {
|
||||
const [notice, setNotice] = useState("");
|
||||
const [notice, setNotice] = useState('');
|
||||
const [searchTerritory, setSearchTerritory] = useState(territorySelection);
|
||||
const form = useForm({
|
||||
category: filters.category ?? "",
|
||||
institution_type: filters.institution_type ?? "",
|
||||
location_mode: filters.location_mode ?? "coverage",
|
||||
include_historical: filters.include_historical ?? "0",
|
||||
context: filters.context ?? "",
|
||||
opportunity: filters.opportunity ?? "",
|
||||
need: filters.need ?? "",
|
||||
q: filters.q ?? "",
|
||||
kind: filters.kind ?? "",
|
||||
sector: filters.sector ?? "",
|
||||
territory: filters.territory ?? "",
|
||||
province_id: filters.province_id ?? "",
|
||||
district_id: filters.district_id ?? "",
|
||||
admin_post_id: filters.admin_post_id ?? "",
|
||||
locality_id: filters.locality_id ?? "",
|
||||
category: filters.category ?? '',
|
||||
institution_type: filters.institution_type ?? '',
|
||||
location_mode: filters.location_mode ?? 'coverage',
|
||||
include_historical: filters.include_historical ?? '0',
|
||||
context: filters.context ?? '',
|
||||
opportunity: filters.opportunity ?? '',
|
||||
need: filters.need ?? '',
|
||||
q: filters.q ?? '',
|
||||
kind: filters.kind ?? '',
|
||||
sector: filters.sector ?? '',
|
||||
territory: filters.territory ?? '',
|
||||
province_id: filters.province_id ?? '',
|
||||
district_id: filters.district_id ?? '',
|
||||
admin_post_id: filters.admin_post_id ?? '',
|
||||
locality_id: filters.locality_id ?? '',
|
||||
certainty:
|
||||
filters.certainty ??
|
||||
(filters.location_mode === "physical" ? "documented" : "include_unknown"),
|
||||
state: filters.state ?? "",
|
||||
(filters.location_mode === 'physical'
|
||||
? 'documented'
|
||||
: 'include_unknown'),
|
||||
state: filters.state ?? '',
|
||||
});
|
||||
const applied = useRef(JSON.stringify(form.data));
|
||||
const criteriaChanged = JSON.stringify(form.data) !== applied.current;
|
||||
const typeAllowed = (category: string, type: string) =>
|
||||
!category ||
|
||||
category === "other" ||
|
||||
category === 'other' ||
|
||||
!type ||
|
||||
type === "other" ||
|
||||
type === 'other' ||
|
||||
(categoryTypes[category] ?? []).includes(type);
|
||||
return (
|
||||
<Frame title="Instituições financeiras, fundos e programas de apoio">
|
||||
@@ -95,25 +107,33 @@ function Index({
|
||||
A minha selecção
|
||||
</Link>
|
||||
<p>
|
||||
Encontre bancos, seguradoras, fundos e outros parceiros financeiros. Explore as
|
||||
soluções e os contactos adequados ao seu investimento.
|
||||
Encontre bancos, seguradoras, fundos e outros parceiros
|
||||
financeiros. Explore as soluções e os contactos adequados ao seu
|
||||
investimento.
|
||||
</p>
|
||||
<form
|
||||
className={`${card} flex flex-wrap gap-4 [&_select]:w-full [&_select]:max-w-full [&_select]:min-w-0 [&>label]:w-full [&>label]:max-w-full [&>label]:min-w-0 sm:[&>label]:w-auto`}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.get("/fundos");
|
||||
form.get('/fundos');
|
||||
}}
|
||||
>
|
||||
{Object.keys(criteriaErrors).length > 0 && (
|
||||
<aside className="basis-full rounded border border-amber-600 p-3" role="alert">
|
||||
<h2 className="font-semibold">Reveja esta combinação de critérios</h2>
|
||||
{Object.entries(criteriaErrors).map(([key, messages]) => (
|
||||
<p key={key}>{messages.join(" ")}</p>
|
||||
))}
|
||||
<aside
|
||||
className="basis-full rounded border border-amber-600 p-3"
|
||||
role="alert"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
Reveja esta combinação de critérios
|
||||
</h2>
|
||||
{Object.entries(criteriaErrors).map(
|
||||
([key, messages]) => (
|
||||
<p key={key}>{messages.join(' ')}</p>
|
||||
),
|
||||
)}
|
||||
<p>
|
||||
A pesquisa não foi executada. Corrija os critérios indicados e volte a
|
||||
pesquisar.
|
||||
A pesquisa não foi executada. Corrija os critérios
|
||||
indicados e volte a pesquisar.
|
||||
</p>
|
||||
</aside>
|
||||
)}
|
||||
@@ -128,15 +148,16 @@ function Index({
|
||||
</p>
|
||||
))}
|
||||
{form.data.kind &&
|
||||
form.data.kind !== "institution" &&
|
||||
form.data.kind !== 'institution' &&
|
||||
(form.data.category ||
|
||||
form.data.institution_type ||
|
||||
form.data.location_mode === "physical") && (
|
||||
form.data.location_mode === 'physical') && (
|
||||
<aside className="basis-full rounded border p-3">
|
||||
<p>
|
||||
Categoria, tipo de instituição e presença física não identificam um
|
||||
fundo ou programa. Reveja o tipo de registo ou retire apenas estes
|
||||
critérios incompatíveis.
|
||||
Categoria, tipo de instituição e presença física
|
||||
não identificam um fundo ou programa. Reveja o
|
||||
tipo de registo ou retire apenas estes critérios
|
||||
incompatíveis.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
@@ -144,16 +165,17 @@ function Index({
|
||||
onClick={() => {
|
||||
form.setData({
|
||||
...form.data,
|
||||
category: "",
|
||||
institution_type: "",
|
||||
location_mode: "coverage",
|
||||
category: '',
|
||||
institution_type: '',
|
||||
location_mode: 'coverage',
|
||||
});
|
||||
setNotice(
|
||||
"Critérios de instituição retirados por sua escolha. Local, sector, necessidade e janela foram preservados.",
|
||||
'Critérios de instituição retirados por sua escolha. Local, sector, necessidade e janela foram preservados.',
|
||||
);
|
||||
}}
|
||||
>
|
||||
Manter o fundo/programa e rever os critérios de instituição
|
||||
Manter o fundo/programa e rever os critérios de
|
||||
instituição
|
||||
</button>
|
||||
</aside>
|
||||
)}
|
||||
@@ -164,24 +186,31 @@ function Index({
|
||||
value={form.data.category}
|
||||
onChange={(e) => {
|
||||
const category = e.target.value;
|
||||
const valid = typeAllowed(category, form.data.institution_type);
|
||||
const valid = typeAllowed(
|
||||
category,
|
||||
form.data.institution_type,
|
||||
);
|
||||
if (!valid)
|
||||
setNotice(
|
||||
"O tipo anterior não pertence à nova categoria e foi retirado. Escolha um dos tipos aplicáveis.",
|
||||
'O tipo anterior não pertence à nova categoria e foi retirado. Escolha um dos tipos aplicáveis.',
|
||||
);
|
||||
form.setData({
|
||||
...form.data,
|
||||
category,
|
||||
institution_type: valid ? form.data.institution_type : "",
|
||||
institution_type: valid
|
||||
? form.data.institution_type
|
||||
: '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="">Todas</option>
|
||||
{Object.entries(financialCategories).map(([id, label]) => (
|
||||
<option key={id} value={id}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
{Object.entries(financialCategories).map(
|
||||
([id, label]) => (
|
||||
<option key={id} value={id}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
@@ -189,7 +218,9 @@ function Index({
|
||||
<select
|
||||
className="block rounded border p-2"
|
||||
value={form.data.institution_type}
|
||||
onChange={(e) => form.setData("institution_type", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('institution_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{Object.entries(financialTypes)
|
||||
@@ -202,7 +233,7 @@ function Index({
|
||||
<option key={id} value={id}>
|
||||
{typeAllowed(form.data.category, id)
|
||||
? label
|
||||
: "Incompatível: " + label}
|
||||
: 'Incompatível: ' + label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -210,19 +241,23 @@ function Index({
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.include_historical === "1"}
|
||||
checked={form.data.include_historical === '1'}
|
||||
onChange={(e) =>
|
||||
form.setData("include_historical", e.target.checked ? "1" : "0")
|
||||
form.setData(
|
||||
'include_historical',
|
||||
e.target.checked ? '1' : '0',
|
||||
)
|
||||
}
|
||||
/>
|
||||
Incluir instituições históricas/fundidas, identificadas como tal
|
||||
Incluir instituições históricas/fundidas, identificadas como
|
||||
tal
|
||||
</label>
|
||||
<label>
|
||||
Necessidade do processo
|
||||
<select
|
||||
className="block rounded border p-2"
|
||||
value={form.data.need}
|
||||
onChange={(e) => form.setData("need", e.target.value)}
|
||||
onChange={(e) => form.setData('need', e.target.value)}
|
||||
>
|
||||
<option value="">Todas / por identificar</option>
|
||||
{Object.entries(needs).map(([id, label]) => (
|
||||
@@ -233,20 +268,24 @@ function Index({
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Palavras-chave
|
||||
Palavras-chave (opcional)
|
||||
<input
|
||||
className="block rounded border p-2"
|
||||
value={form.data.q}
|
||||
maxLength={150}
|
||||
onChange={(e) => form.setData("q", e.target.value)}
|
||||
onChange={(e) => form.setData('q', e.target.value)}
|
||||
/>
|
||||
<span className="block text-sm">
|
||||
Refine pelo nome ou descrição; este campo não substitui
|
||||
a localização, categoria ou finalidade.
|
||||
</span>
|
||||
</label>
|
||||
<label>
|
||||
Tipo de registo a consultar
|
||||
<select
|
||||
className="block rounded border p-2"
|
||||
value={form.data.kind}
|
||||
onChange={(e) => form.setData("kind", e.target.value)}
|
||||
onChange={(e) => form.setData('kind', e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{Object.entries(kinds).map(([key, name]) => (
|
||||
@@ -261,7 +300,7 @@ function Index({
|
||||
<select
|
||||
className="block rounded border p-2"
|
||||
value={form.data.sector}
|
||||
onChange={(e) => form.setData("sector", e.target.value)}
|
||||
onChange={(e) => form.setData('sector', e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{options.sectors.map((item) => (
|
||||
@@ -272,7 +311,9 @@ function Index({
|
||||
</select>
|
||||
</label>
|
||||
<fieldset className="min-w-0 basis-full">
|
||||
<legend>Local de interesse — seleccione até ao nível conhecido</legend>
|
||||
<legend>
|
||||
Local de interesse — seleccione até ao nível conhecido
|
||||
</legend>
|
||||
<label>
|
||||
Localização a pesquisar
|
||||
<select
|
||||
@@ -283,40 +324,52 @@ function Index({
|
||||
...form.data,
|
||||
location_mode: e.target.value,
|
||||
certainty:
|
||||
e.target.value === "physical"
|
||||
? "documented"
|
||||
e.target.value === 'physical'
|
||||
? 'documented'
|
||||
: form.data.certainty,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="physical">Sede, balcão ou presença física</option>
|
||||
<option value="coverage">Cobertura do financiamento/produto</option>
|
||||
<option value="physical">
|
||||
Sede, balcão ou presença física
|
||||
</option>
|
||||
<option value="coverage">
|
||||
Cobertura do financiamento/produto
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p className="mb-3 text-sm">
|
||||
Escolha a província e, se necessário, o distrito. Sede e balcões identificam
|
||||
onde pode contactar a instituição; a cobertura indica onde o financiamento
|
||||
se aplica.
|
||||
Escolha a província e, se necessário, o distrito. Sede e
|
||||
balcões identificam onde pode contactar a instituição; a
|
||||
cobertura indica onde o financiamento se aplica.
|
||||
</p>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
initial={searchTerritory}
|
||||
showMap={false}
|
||||
onChange={(path) =>
|
||||
form.setData({
|
||||
...form.data,
|
||||
territory: path.at(-1)?.id ?? "",
|
||||
territory: path.at(-1)?.id ?? '',
|
||||
province_id:
|
||||
path.find((node) => node.location_type === "province")?.id ??
|
||||
"",
|
||||
path.find(
|
||||
(node) =>
|
||||
node.location_type === 'province',
|
||||
)?.id ?? '',
|
||||
district_id:
|
||||
path.find((node) => node.location_type === "district")?.id ??
|
||||
"",
|
||||
path.find(
|
||||
(node) =>
|
||||
node.location_type === 'district',
|
||||
)?.id ?? '',
|
||||
admin_post_id:
|
||||
path.find((node) => node.location_type === "admin_post")?.id ??
|
||||
"",
|
||||
path.find(
|
||||
(node) =>
|
||||
node.location_type === 'admin_post',
|
||||
)?.id ?? '',
|
||||
locality_id:
|
||||
path.find((node) => node.location_type === "locality")?.id ??
|
||||
"",
|
||||
path.find(
|
||||
(node) =>
|
||||
node.location_type === 'locality',
|
||||
)?.id ?? '',
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -326,9 +379,13 @@ function Index({
|
||||
<select
|
||||
className="block rounded border p-2"
|
||||
value={form.data.certainty}
|
||||
onChange={(e) => form.setData("certainty", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('certainty', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="include_unknown">Incluir e assinalar</option>
|
||||
<option value="include_unknown">
|
||||
Incluir e assinalar
|
||||
</option>
|
||||
<option value="documented">
|
||||
Apenas âmbito documentado para os filtros escolhidos
|
||||
</option>
|
||||
@@ -339,7 +396,7 @@ function Index({
|
||||
<select
|
||||
className="block rounded border p-2"
|
||||
value={form.data.state}
|
||||
onChange={(e) => form.setData("state", e.target.value)}
|
||||
onChange={(e) => form.setData('state', e.target.value)}
|
||||
>
|
||||
<option value="">Qualquer estado</option>
|
||||
{Object.entries(windowLabels).map(([key, label]) => (
|
||||
@@ -355,46 +412,77 @@ function Index({
|
||||
</form>
|
||||
{criteriaChanged && (
|
||||
<p role="status">
|
||||
Alterou os critérios. Clique em Pesquisar para os aplicar. Os resultados
|
||||
anteriores ficam separados abaixo.
|
||||
Alterou os critérios. Clique em Pesquisar para os aplicar.
|
||||
Os resultados anteriores ficam separados abaixo.
|
||||
</p>
|
||||
)}
|
||||
<details
|
||||
open={!criteriaChanged && Object.keys(criteriaErrors).length === 0}
|
||||
open={
|
||||
!criteriaChanged && Object.keys(criteriaErrors).length === 0
|
||||
}
|
||||
className="space-y-3"
|
||||
>
|
||||
<summary>
|
||||
{Object.keys(criteriaErrors).length
|
||||
? "Pesquisa não executada — critérios inválidos"
|
||||
? 'Pesquisa não executada — critérios inválidos'
|
||||
: criteriaChanged
|
||||
? "Resultados da pesquisa anterior — não correspondem aos critérios por aplicar"
|
||||
: "Resultados correspondentes à pesquisa"}
|
||||
? 'Resultados da pesquisa anterior — não correspondem aos critérios por aplicar'
|
||||
: 'Resultados correspondentes à pesquisa'}
|
||||
</summary>
|
||||
<p className="text-sm">
|
||||
Explore as instituições e soluções adequadas ao seu investimento. Use os filtros
|
||||
para encontrar a informação de que precisa.
|
||||
Explore as instituições e soluções adequadas ao seu
|
||||
investimento. Use os filtros para encontrar a informação de
|
||||
que precisa.
|
||||
</p>
|
||||
{items.data.length === 0 && Object.keys(criteriaErrors).length === 0 && (
|
||||
<p>
|
||||
Não foram encontradas instituições, fundos ou programas publicados que
|
||||
correspondam a todos os critérios desta pesquisa.
|
||||
</p>
|
||||
)}
|
||||
{items.data.length === 0 &&
|
||||
Object.keys(criteriaErrors).length === 0 && (
|
||||
<div className="grid gap-3">
|
||||
<p>
|
||||
Não foram encontradas instituições, fundos ou
|
||||
programas publicados que correspondam a todos os
|
||||
critérios desta pesquisa.
|
||||
</p>
|
||||
{!criteriaChanged &&
|
||||
filters.location_mode === 'physical' &&
|
||||
filters.province_id && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
form.setData({
|
||||
...form.data,
|
||||
territory: '',
|
||||
province_id: '',
|
||||
district_id: '',
|
||||
admin_post_id: '',
|
||||
locality_id: '',
|
||||
});
|
||||
setSearchTerritory([]);
|
||||
setNotice(
|
||||
'Escolha outra província no local a pesquisar. Categoria, tipo e finalidade foram conservados; a localização do investimento no dossier mantém-se.',
|
||||
);
|
||||
}}
|
||||
>
|
||||
Procurar instituição noutra província
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{items.data.map((item) => (
|
||||
<article className={card} key={item.id}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/fundos/${item.id}?${new URLSearchParams(Object.entries(filters).filter((entry): entry is [string, string] => typeof entry[1] === "string"))}`}
|
||||
href={`/fundos/${item.id}?${new URLSearchParams(Object.entries(filters).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))}`}
|
||||
>
|
||||
{item.payload.title}
|
||||
</Link>
|
||||
</h2>
|
||||
{item.payload.kind === "institution" ? (
|
||||
{item.payload.kind === 'institution' ? (
|
||||
<InstitutionView
|
||||
compact
|
||||
physicalTerritory={
|
||||
filters.location_mode === "physical"
|
||||
filters.location_mode === 'physical'
|
||||
? filters.territory
|
||||
: undefined
|
||||
}
|
||||
@@ -408,25 +496,30 @@ function Index({
|
||||
) : (
|
||||
<>
|
||||
<p>{item.payload.summary}</p>
|
||||
<p>Entidade gestora: {item.payload.manager_name}</p>
|
||||
{Object.entries(item.filter_explanation ?? {}).map(
|
||||
([key, message]) => (
|
||||
<p key={key}>{message}</p>
|
||||
),
|
||||
)}
|
||||
<p>
|
||||
Entidade gestora:{' '}
|
||||
{item.payload.manager_name}
|
||||
</p>
|
||||
{Object.entries(
|
||||
item.filter_explanation ?? {},
|
||||
).map(([key, message]) => (
|
||||
<p key={key}>{message}</p>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
{item.payload.kind === "institution" &&
|
||||
item.payload.windows.length === 0 ? null : item.payload.windows.length ===
|
||||
0 ? (
|
||||
{item.payload.kind === 'institution' &&
|
||||
item.payload.windows.length === 0 ? null : item.payload
|
||||
.windows.length === 0 ? (
|
||||
<p>
|
||||
Não existe uma janela de candidatura confirmada para este programa.
|
||||
Não existe uma janela de candidatura confirmada
|
||||
para este programa.
|
||||
</p>
|
||||
) : (
|
||||
<ul>
|
||||
{item.payload.windows.map((window) => (
|
||||
<li key={window.code}>
|
||||
{window.title}: {windowLabels[window.state]}
|
||||
{window.title}:{' '}
|
||||
{windowLabels[window.state]}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -439,10 +532,12 @@ function Index({
|
||||
<Link
|
||||
key={index}
|
||||
href={link.url}
|
||||
aria-current={link.active ? "page" : undefined}
|
||||
aria-current={link.active ? 'page' : undefined}
|
||||
className="underline"
|
||||
>
|
||||
{link.label.replace(/«/g, "«").replace(/»/g, "»")}
|
||||
{link.label
|
||||
.replace(/«/g, '«')
|
||||
.replace(/»/g, '»')}
|
||||
</Link>
|
||||
) : null,
|
||||
)}
|
||||
|
||||
@@ -9,6 +9,17 @@ import {
|
||||
} from '@/lib/company-comparison';
|
||||
|
||||
type Question = { label: string; options: Record<string, string> };
|
||||
const questionThemes: Record<string, string> = {
|
||||
purpose: 'Organização do pedido',
|
||||
participants: 'Titulares, sócios e accionistas',
|
||||
participation: 'Participações',
|
||||
capital: 'Capital e contribuições',
|
||||
management: 'Gestão',
|
||||
responsibility: 'Responsabilidade limitada',
|
||||
listing: 'Negociação em Bolsa',
|
||||
regulated: 'Regras profissionais ou sectoriais',
|
||||
preferred: 'Alternativa a aprofundar',
|
||||
};
|
||||
type Result = {
|
||||
engine_version: string;
|
||||
source: {
|
||||
@@ -135,8 +146,8 @@ function Comparator(props: Props) {
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Compare a estrutura pretendida e os pontos a esclarecer antes de
|
||||
preparar o acto constitutivo.
|
||||
Compare alternativas para discutir a constituição; não existe
|
||||
uma forma universalmente preferível.
|
||||
</p>
|
||||
{saved && (
|
||||
<p>
|
||||
@@ -178,32 +189,46 @@ function Comparator(props: Props) {
|
||||
{Object.entries(definition.questions).map(
|
||||
([key, question]) =>
|
||||
active.includes(key) ? (
|
||||
<label key={key} className="grid gap-1">
|
||||
{question.label}
|
||||
<select
|
||||
className={input}
|
||||
name={`answers[${key}]`}
|
||||
value={answers[key] ?? 'unknown'}
|
||||
disabled={busy}
|
||||
onChange={(e) => {
|
||||
setAnswers({
|
||||
...answers,
|
||||
[key]: e.target.value,
|
||||
});
|
||||
setDirty(true);
|
||||
operation.current =
|
||||
createOperationKey();
|
||||
}}
|
||||
>
|
||||
{Object.entries(
|
||||
question.options,
|
||||
).map(([code, label]) => (
|
||||
<option key={code} value={code}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<fieldset
|
||||
key={key}
|
||||
className="min-w-0 rounded border p-3"
|
||||
>
|
||||
<legend className="px-1 font-semibold">
|
||||
{questionThemes[key] ??
|
||||
question.label}
|
||||
</legend>
|
||||
<label className="grid gap-1">
|
||||
{question.label}
|
||||
<select
|
||||
className={input}
|
||||
name={`answers[${key}]`}
|
||||
value={
|
||||
answers[key] ?? 'unknown'
|
||||
}
|
||||
disabled={busy}
|
||||
onChange={(e) => {
|
||||
setAnswers({
|
||||
...answers,
|
||||
[key]: e.target.value,
|
||||
});
|
||||
setDirty(true);
|
||||
operation.current =
|
||||
createOperationKey();
|
||||
}}
|
||||
>
|
||||
{Object.entries(
|
||||
question.options,
|
||||
).map(([code, label]) => (
|
||||
<option
|
||||
key={code}
|
||||
value={code}
|
||||
>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</fieldset>
|
||||
) : (
|
||||
<input
|
||||
key={key}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class BusinessPlanDraftContinuityTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
public function test_incomplete_plans_keep_exact_values_in_their_own_dossier_after_a_new_session(): void
|
||||
{
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
$this->assertSame('continuity_20261120_test', $identity->name);
|
||||
$this->assertSame(55441, (int) $identity->port);
|
||||
config(['investor-path.enabled' => true]);
|
||||
$owner = User::factory()->create();
|
||||
$cases = [];
|
||||
foreach (['Hotel sintético QA' => '250.50', 'Agronegócio sintético QA' => '375.25'] as $title => $price) {
|
||||
$case = app(VirtualDesk::class)->createCase($owner, ['title' => $title, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true]);
|
||||
$snapshot = json_encode(['version' => 17, 'plan' => ['currency' => 'MZN', 'products' => [['label' => $title, 'monthlyUnits' => '25', 'unitPrice' => $price, 'unitVariableCost' => '100.50']], 'monthlyOperatingExpenses' => '500.25', 'salesCollectionPercent' => '', 'openingReceivablesCollectionPercent' => '']], JSON_THROW_ON_ERROR);
|
||||
$this->actingAs($owner)->postJson('/api/v1/simulation-drafts', ['context' => $case->id, 'personal_snapshot' => [], 'economic_snapshot' => ['purpose' => 'simulate_only', 'journey_type' => 'small_business', 'business_plan_snapshot' => $snapshot]], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated();
|
||||
$cases[] = [$case->id, $snapshot];
|
||||
}
|
||||
$this->flushSession();
|
||||
foreach ($cases as [$caseId, $snapshot]) {
|
||||
$this->actingAs(User::findOrFail($owner->id))->getJson('/api/v1/simulation-drafts/current?context='.$caseId)->assertOk()->assertJsonPath('data.economic_snapshot.business_plan_snapshot', $snapshot);
|
||||
}
|
||||
$this->actingAs(User::factory()->create())->getJson('/api/v1/simulation-drafts/current?context='.$cases[0][0])->assertForbidden();
|
||||
}
|
||||
}
|
||||
@@ -14,21 +14,31 @@ use Tests\TestCase;
|
||||
final class FundingCriteriaCoherenceTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
private User $editor;
|
||||
|
||||
private array $geo = [];
|
||||
|
||||
private int $sector;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp(); $this->withoutVite();
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$db = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
$this->assertSame('investor_intent_20261115_test', $db->name); $this->assertSame(55441, (int) $db->port);
|
||||
$this->editor = User::factory()->create(); config(['portal.managers' => [$this->editor->email]]);
|
||||
$this->assertContains($db->name, ['investor_intent_20261115_test', 'continuity_20261120_test']);
|
||||
$this->assertSame(55441, (int) $db->port);
|
||||
// Counts below concern this test's fixtures. Existing browser fixtures
|
||||
// remain unchanged after DatabaseTransactions rolls the test back.
|
||||
DB::table('funding_programmes')->update(['published_version_id' => null]);
|
||||
$this->editor = User::factory()->create();
|
||||
config(['portal.managers' => [$this->editor->email]]);
|
||||
$parent = null;
|
||||
foreach (['country', 'province', 'district'] as $type) {
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$type, 'code' => $id, 'location_type' => $type, 'source_system' => 'cartografia-workbook', 'data_classification' => 'public', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
|
||||
$this->geo[$type] = $id; $parent = $id;
|
||||
$this->geo[$type] = $id;
|
||||
$parent = $id;
|
||||
}
|
||||
$this->sector = Sector::create(['slug' => 'synthetic-funding-qa', 'name' => 'SYNTHETIC sector', 'is_active' => true, 'published_at' => now()])->id;
|
||||
}
|
||||
@@ -37,13 +47,16 @@ final class FundingCriteriaCoherenceTest extends TestCase
|
||||
{
|
||||
$source = ['source_url' => 'https://example.invalid/synthetic-qa', 'source_reference' => 'SYNTHETIC QA ONLY', 'checked_on' => today()->toDateString()];
|
||||
$draft = ['title' => 'SYNTHETIC '.$code, 'kind' => $kind, 'manager_name' => 'SYNTHETIC manager', 'summary' => 'Synthetic isolated record, not real content.', 'source_url' => $source['source_url'], 'source_reference' => $source['source_reference'], 'source_checked_on' => $source['checked_on'], 'source_status' => 'identified', 'coverage' => 'national', 'sectors_scope' => 'all', 'funding_needs' => ['investment'], 'windows' => []];
|
||||
if ($kind === 'institution') $draft += ['institution_key' => $code, 'institution_nature' => 'bank', 'institution_categories' => ['banking'], 'institution_types' => ['commercial_bank'], 'institution_status' => 'reported',
|
||||
'locations' => [['role' => 'headquarters', 'label' => 'Synthetic headquarters', 'territory_id' => $this->geo['district'], 'evidence_status' => 'reported', ...$source]],
|
||||
'products' => [['code' => 'investment', 'title' => 'Synthetic investment product', 'needs' => ['investment'], 'coverage' => 'national', 'availability' => 'documented', ...$source]]];
|
||||
if ($kind === 'institution') {
|
||||
$draft += ['institution_key' => $code, 'institution_nature' => 'bank', 'institution_categories' => ['banking'], 'institution_types' => ['commercial_bank'], 'institution_status' => 'reported',
|
||||
'locations' => [['role' => 'headquarters', 'label' => 'Synthetic headquarters', 'territory_id' => $this->geo['district'], 'evidence_status' => 'reported', ...$source]],
|
||||
'products' => [['code' => 'investment', 'title' => 'Synthetic investment product', 'needs' => ['investment'], 'coverage' => 'national', 'availability' => 'documented', ...$source]]];
|
||||
}
|
||||
$service = app(FundingProgrammes::class);
|
||||
$id = $service->save($this->editor, null, ['version' => 0, 'code' => $code, 'reason' => 'Synthetic QA fixture', 'draft' => array_replace($draft, $overrides)]);
|
||||
$plan = $service->preview($this->editor, $id);
|
||||
$service->publish($this->editor, $id, ['version' => $plan['version'], 'hash' => $plan['hash'], 'confirm' => true, 'reason' => 'Synthetic QA only, rolled back']);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
@@ -62,7 +75,9 @@ final class FundingCriteriaCoherenceTest extends TestCase
|
||||
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $bank)->where('territorySelection.0.id', $this->geo['province'])->where('territorySelection.1.id', $this->geo['district']));
|
||||
$returnFilters = [...$filters, 'q' => 'qa', 'state' => 'closed', 'kind' => 'institution', 'include_historical' => '0', 'province_id' => $this->geo['province'], 'district_id' => $this->geo['district'], 'page' => '2'];
|
||||
$this->get('/fundos/'.$bank.'?'.http_build_query($returnFilters))->assertOk()->assertInertia(function ($page) use ($returnFilters) {
|
||||
foreach ($returnFilters as $key => $value) $page->where('selection.'.$key, (string) $value);
|
||||
foreach ($returnFilters as $key => $value) {
|
||||
$page->where('selection.'.$key, (string) $value);
|
||||
}
|
||||
});
|
||||
$this->getJson('/api/v1/investment/territory-options?type=district')->assertOk()->assertJsonCount(0, 'data');
|
||||
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$this->geo['province'])->assertOk()->assertJsonCount(1, 'data');
|
||||
@@ -82,8 +97,12 @@ final class FundingCriteriaCoherenceTest extends TestCase
|
||||
public function test_contradictory_type_or_record_kind_and_incomplete_hierarchy_are_rejected(): void
|
||||
{
|
||||
foreach ([['category' => 'banking', 'institution_type' => 'broker'], ['category' => 'banking', 'institution_type' => 'commercial_bank', 'kind' => 'fund', 'location_mode' => 'physical'], ['district_id' => $this->geo['district']]] as $filters) {
|
||||
try { app(FundingProgrammes::class)->catalogueQuery($filters)->count(); $this->fail('Contradictory criteria must not silently broaden a query.'); }
|
||||
catch (ValidationException $error) { $this->assertNotEmpty($error->errors()); }
|
||||
try {
|
||||
app(FundingProgrammes::class)->catalogueQuery($filters)->count();
|
||||
$this->fail('Contradictory criteria must not silently broaden a query.');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertNotEmpty($error->errors());
|
||||
}
|
||||
$this->getJson('/fundos?'.http_build_query($filters))->assertUnprocessable();
|
||||
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page->has('criteriaErrors')->has('items.data', 0));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import * as business from '../../resources/js/lib/business-financial-plan.ts';
|
||||
import * as contract from '../../resources/js/lib/simulation-contract.ts';
|
||||
import * as bridge from '../../resources/js/lib/financial-fiscal-bridge.ts';
|
||||
import { validateSimulationDraft } from '../../resources/js/lib/simulation-form.ts';
|
||||
|
||||
// Exercise the real input callbacks and the parent's snapshot echo, including
|
||||
// effects. No server, database or fiscal rates are used by this regression.
|
||||
function editor(initialSnapshot) {
|
||||
const values = [],
|
||||
dependencies = [];
|
||||
let cursor = 0,
|
||||
pending = [],
|
||||
changed = false,
|
||||
snapshot = initialSnapshot;
|
||||
const hooks = {
|
||||
...React,
|
||||
useState(initial) {
|
||||
const index = cursor++;
|
||||
if (!(index in values)) values[index] = initial;
|
||||
return [
|
||||
values[index],
|
||||
(next) => {
|
||||
const value =
|
||||
typeof next === 'function' ? next(values[index]) : next;
|
||||
if (!Object.is(value, values[index])) changed = true;
|
||||
values[index] = value;
|
||||
},
|
||||
];
|
||||
},
|
||||
useEffect(callback, deps) {
|
||||
const index = cursor++;
|
||||
if (
|
||||
!dependencies[index] ||
|
||||
deps.some(
|
||||
(value, i) => !Object.is(value, dependencies[index][i]),
|
||||
)
|
||||
) {
|
||||
dependencies[index] = deps;
|
||||
pending.push(callback);
|
||||
}
|
||||
},
|
||||
};
|
||||
const require = createRequire(import.meta.url),
|
||||
module = { exports: {} };
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/simulation-business-plan.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(name) =>
|
||||
({
|
||||
react: hooks,
|
||||
'@/components/currency-select': { CurrencySelect: () => null },
|
||||
'@/lib/business-financial-plan': business,
|
||||
'@/lib/simulation-contract': contract,
|
||||
'@/lib/financial-fiscal-bridge': bridge,
|
||||
})[name] ?? require(name),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
let tree;
|
||||
function render() {
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
changed = false;
|
||||
cursor = 0;
|
||||
pending = [];
|
||||
tree = module.exports.SimulationBusinessPlan({
|
||||
currency: 'MZN',
|
||||
snapshot,
|
||||
onCurrencyChange() {},
|
||||
onSnapshotChange(value) {
|
||||
snapshot = value;
|
||||
changed = true;
|
||||
},
|
||||
});
|
||||
pending.forEach((callback) => callback());
|
||||
if (!changed) return;
|
||||
}
|
||||
throw new Error('Editor did not settle');
|
||||
}
|
||||
function walk(node, predicate) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (predicate(node)) return node;
|
||||
for (const child of React.Children.toArray(node.props?.children)) {
|
||||
const found = walk(child, predicate);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
function field(label) {
|
||||
const money = walk(
|
||||
tree,
|
||||
(node) =>
|
||||
node.props?.label === label &&
|
||||
typeof node.props.onChange === 'function',
|
||||
);
|
||||
if (money) return money.props;
|
||||
const container = walk(
|
||||
tree,
|
||||
(node) =>
|
||||
node.type === 'label' &&
|
||||
React.Children.toArray(node.props.children).some(
|
||||
(child) => typeof child === 'string' && child === label,
|
||||
),
|
||||
);
|
||||
const input = walk(container, (node) => node.type === 'input');
|
||||
assert.ok(input, `Missing field: ${label}`);
|
||||
return {
|
||||
value: input.props.value,
|
||||
onChange: (value) => input.props.onChange({ target: { value } }),
|
||||
};
|
||||
}
|
||||
render();
|
||||
return {
|
||||
field,
|
||||
edit(label, value) {
|
||||
field(label).onChange(value);
|
||||
render();
|
||||
},
|
||||
snapshot: () => snapshot,
|
||||
};
|
||||
}
|
||||
|
||||
void test('monthly units, unit price, variable cost and operating expenses remain editable after snapshot echo', () => {
|
||||
const form = editor();
|
||||
for (const label of [
|
||||
'Unidades por mes',
|
||||
'Preço por unidade',
|
||||
'Custo variável por unidade',
|
||||
'Despesas operacionais reconhecidas',
|
||||
]) {
|
||||
for (const value of ['', '2', '25', '250.50']) {
|
||||
form.edit(label, value);
|
||||
assert.equal(
|
||||
form.field(label).value,
|
||||
value,
|
||||
`${label}: ${value}; saved=${form.snapshot()}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const restored = business.restoreBusinessPlanSnapshot(form.snapshot());
|
||||
assert.ok(restored, 'The edited plan must remain recoverable');
|
||||
assert.equal(restored.products[0].monthlyUnits, '250.50');
|
||||
assert.equal(restored.monthlyOperatingExpenses, '250.50');
|
||||
assert.equal(restored.salesCollectionPercent, '');
|
||||
assert.equal(restored.openingReceivablesCollectionPercent, '');
|
||||
const recovered = editor(form.snapshot());
|
||||
assert.equal(recovered.field('Preço por unidade').value, '250.50');
|
||||
recovered.edit('Despesas operacionais reconhecidas', '500');
|
||||
assert.equal(recovered.field('Preço por unidade').value, '250.50');
|
||||
assert.equal(
|
||||
recovered.field('Despesas operacionais reconhecidas').value,
|
||||
'500',
|
||||
);
|
||||
assert.throws(() => business.forecastBusinessPlan(restored));
|
||||
assert.ok(
|
||||
validateSimulationDraft(
|
||||
{ business_plan_snapshot: form.snapshot() },
|
||||
'financial',
|
||||
).business_plan_snapshot,
|
||||
);
|
||||
assert.equal(
|
||||
validateSimulationDraft({}, 'financial').business_plan_snapshot,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
void test('numeric entry messages distinguish missing, invalid, negative, fractional people and percentages', () => {
|
||||
assert.equal(
|
||||
business.businessPlanNumberError(''),
|
||||
'Preencha este campo para continuar.',
|
||||
);
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('abc'),
|
||||
'Introduza apenas números (ex.: 25.000).',
|
||||
);
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('-1'),
|
||||
'Este valor não pode ser negativo.',
|
||||
);
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('1.5', { integer: true }),
|
||||
'Introduza um número inteiro de pessoas.',
|
||||
);
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('101', { percent: true }),
|
||||
'Introduza uma percentagem entre 0% e 100%.',
|
||||
);
|
||||
assert.equal(business.businessPlanNumberError('0'), '');
|
||||
assert.equal(business.businessPlanNumberError('25.50'), '');
|
||||
assert.equal(
|
||||
business.businessPlanNumberError('-25.50', { allowNegative: true }),
|
||||
'',
|
||||
);
|
||||
});
|
||||
|
||||
void test('invalid percentages remain editable after recovery without becoming valid calculation inputs', () => {
|
||||
const form = editor();
|
||||
form.edit('Preço por unidade', '250.50');
|
||||
const decoded = JSON.parse(form.snapshot());
|
||||
decoded.plan.salesCollectionPercent = '101';
|
||||
const snapshot = JSON.stringify(decoded);
|
||||
assert.equal(business.restoreBusinessPlanSnapshot(snapshot), null);
|
||||
const editable = business.restoreBusinessPlanSnapshot(snapshot, {
|
||||
editable: true,
|
||||
});
|
||||
assert.equal(editable.salesCollectionPercent, '101');
|
||||
assert.equal(editor(snapshot).field('Preço por unidade').value, '250.50');
|
||||
assert.ok(
|
||||
validateSimulationDraft(
|
||||
{ business_plan_snapshot: snapshot },
|
||||
'financial',
|
||||
).business_plan_snapshot,
|
||||
);
|
||||
});
|
||||
@@ -1,26 +1,26 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { compileFunction } from "node:vm";
|
||||
import React from "react";
|
||||
import ts from "typescript";
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const nodes = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.flatMap(nodes)
|
||||
: tree && typeof tree === "object"
|
||||
: tree && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
const text = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.map(text).join("")
|
||||
? tree.map(text).join('')
|
||||
: tree?.props
|
||||
? text(tree.props.children)
|
||||
: typeof tree === "string"
|
||||
: typeof tree === 'string'
|
||||
? tree
|
||||
: "";
|
||||
: '';
|
||||
|
||||
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
|
||||
function harness(filters, errors = {}) {
|
||||
@@ -32,7 +32,8 @@ function harness(filters, errors = {}) {
|
||||
return [
|
||||
memory[id],
|
||||
(next) => {
|
||||
memory[id] = typeof next === "function" ? next(memory[id]) : next;
|
||||
memory[id] =
|
||||
typeof next === 'function' ? next(memory[id]) : next;
|
||||
},
|
||||
];
|
||||
};
|
||||
@@ -40,7 +41,10 @@ function harness(filters, errors = {}) {
|
||||
let form;
|
||||
const TerritoryFields = () => null;
|
||||
const module = { exports: {} };
|
||||
const source = fs.readFileSync("resources/js/pages/funding/index.tsx", "utf8");
|
||||
const source = fs.readFileSync(
|
||||
'resources/js/pages/funding/index.tsx',
|
||||
'utf8',
|
||||
);
|
||||
compileFunction(
|
||||
ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
@@ -48,10 +52,10 @@ function harness(filters, errors = {}) {
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText,
|
||||
["require", "module", "exports"],
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(id) => {
|
||||
if (id === "react")
|
||||
if (id === 'react')
|
||||
return {
|
||||
...React,
|
||||
useState: state,
|
||||
@@ -60,9 +64,9 @@ function harness(filters, errors = {}) {
|
||||
return value;
|
||||
},
|
||||
};
|
||||
if (id === "@inertiajs/react")
|
||||
if (id === '@inertiajs/react')
|
||||
return {
|
||||
Link: "a",
|
||||
Link: 'a',
|
||||
useForm(initial) {
|
||||
const [data, set] = state(initial);
|
||||
form = {
|
||||
@@ -70,7 +74,11 @@ function harness(filters, errors = {}) {
|
||||
errors: {},
|
||||
processing: false,
|
||||
setData(key, value) {
|
||||
set(typeof key === "string" ? { ...data, [key]: value } : key);
|
||||
set(
|
||||
typeof key === 'string'
|
||||
? { ...data, [key]: value }
|
||||
: key,
|
||||
);
|
||||
},
|
||||
get(url) {
|
||||
submitted = { url, data };
|
||||
@@ -79,22 +87,25 @@ function harness(filters, errors = {}) {
|
||||
return form;
|
||||
},
|
||||
};
|
||||
if (id === "@/pages/investment/shared") return { Frame: "main", card: "", button: "" };
|
||||
if (id === "@/components/funding-classification")
|
||||
if (id === '@/pages/investment/shared')
|
||||
return { Frame: 'main', card: '', button: '' };
|
||||
if (id === '@/components/funding-classification')
|
||||
return {
|
||||
financialCategories: {
|
||||
banking: "Banca",
|
||||
insurance_intermediation: "Mediação de seguros",
|
||||
banking: 'Banca',
|
||||
insurance_intermediation: 'Mediação de seguros',
|
||||
},
|
||||
financialTypes: {
|
||||
commercial_bank: "Banco comercial",
|
||||
broker: "Corretora",
|
||||
other: "Outro",
|
||||
commercial_bank: 'Banco comercial',
|
||||
broker: 'Corretora',
|
||||
other: 'Outro',
|
||||
},
|
||||
};
|
||||
if (id === "@/components/investment-territory") return { TerritoryFields };
|
||||
if (id === "@/components/funding-institution") return { InstitutionView: "article" };
|
||||
if (id === "./shared") return { windowLabels: {} };
|
||||
if (id === '@/components/investment-territory')
|
||||
return { TerritoryFields };
|
||||
if (id === '@/components/funding-institution')
|
||||
return { InstitutionView: 'article' };
|
||||
if (id === './shared') return { windowLabels: {} };
|
||||
return require(id);
|
||||
},
|
||||
module,
|
||||
@@ -105,11 +116,11 @@ function harness(filters, errors = {}) {
|
||||
criteriaErrors: errors,
|
||||
items: { data: [], links: [] },
|
||||
options: { sectors: [], territories: [] },
|
||||
kinds: { institution: "Instituição", fund: "Fundo" },
|
||||
kinds: { institution: 'Instituição', fund: 'Fundo' },
|
||||
management: false,
|
||||
categoryTypes: {
|
||||
banking: ["commercial_bank"],
|
||||
insurance_intermediation: ["broker"],
|
||||
banking: ['commercial_bank'],
|
||||
insurance_intermediation: ['broker'],
|
||||
},
|
||||
};
|
||||
let tree;
|
||||
@@ -120,9 +131,11 @@ function harness(filters, errors = {}) {
|
||||
return tree;
|
||||
}
|
||||
const select = (label) =>
|
||||
nodes(nodes(tree).find((n) => n.type === "label" && text(n).startsWith(label))).find(
|
||||
(n) => n.type === "select",
|
||||
);
|
||||
nodes(
|
||||
nodes(tree).find(
|
||||
(n) => n.type === 'label' && text(n).startsWith(label),
|
||||
),
|
||||
).find((n) => n.type === 'select');
|
||||
render();
|
||||
return {
|
||||
render,
|
||||
@@ -134,92 +147,150 @@ function harness(filters, errors = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
test("institution category restricts types and removes only an incompatible dependent choice", () => {
|
||||
void test('searching another province resets only the search location and preserves the investment scope', () => {
|
||||
const filters = {
|
||||
category: 'banking',
|
||||
institution_type: 'commercial_bank',
|
||||
need: 'investment',
|
||||
context: 'case-qa',
|
||||
opportunity: 'opportunity-qa',
|
||||
province_id: 'province-qa',
|
||||
district_id: 'district-qa',
|
||||
territory: 'district-qa',
|
||||
location_mode: 'physical',
|
||||
certainty: 'documented',
|
||||
};
|
||||
const h = harness(filters);
|
||||
const action = nodes(h.tree()).find(
|
||||
(n) =>
|
||||
n.type === 'button' &&
|
||||
text(n) === 'Procurar instituição noutra província',
|
||||
);
|
||||
assert.ok(action);
|
||||
action.props.onClick();
|
||||
h.render();
|
||||
for (const key of [
|
||||
'territory',
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
])
|
||||
assert.equal(h.form().data[key], '');
|
||||
for (const key of [
|
||||
'category',
|
||||
'institution_type',
|
||||
'need',
|
||||
'context',
|
||||
'opportunity',
|
||||
'location_mode',
|
||||
'certainty',
|
||||
])
|
||||
assert.equal(h.form().data[key], filters[key]);
|
||||
assert.deepEqual(h.territory().props.initial, []);
|
||||
assert.equal(h.submitted(), undefined);
|
||||
assert.match(
|
||||
text(h.tree()),
|
||||
/a localização do investimento no dossier mantém-se/,
|
||||
);
|
||||
});
|
||||
|
||||
void test('institution category restricts types and removes only an incompatible dependent choice', () => {
|
||||
const h = harness({
|
||||
category: "insurance_intermediation",
|
||||
institution_type: "broker",
|
||||
sector: "7",
|
||||
need: "investment",
|
||||
territory: "district-qa",
|
||||
category: 'insurance_intermediation',
|
||||
institution_type: 'broker',
|
||||
sector: '7',
|
||||
need: 'investment',
|
||||
territory: 'district-qa',
|
||||
});
|
||||
h.select("Categoria da instituição").props.onChange({
|
||||
target: { value: "banking" },
|
||||
h.select('Categoria da instituição').props.onChange({
|
||||
target: { value: 'banking' },
|
||||
});
|
||||
h.render();
|
||||
assert.equal(h.form().data.institution_type, "");
|
||||
assert.equal(h.form().data.institution_type, '');
|
||||
for (const [key, value] of Object.entries({
|
||||
sector: "7",
|
||||
need: "investment",
|
||||
territory: "district-qa",
|
||||
sector: '7',
|
||||
need: 'investment',
|
||||
territory: 'district-qa',
|
||||
}))
|
||||
assert.equal(h.form().data[key], value);
|
||||
assert.deepEqual(
|
||||
nodes(h.select("Tipo de instituição"))
|
||||
.filter((n) => n.type === "option")
|
||||
nodes(h.select('Tipo de instituição'))
|
||||
.filter((n) => n.type === 'option')
|
||||
.map((n) => n.props.value),
|
||||
["", "commercial_bank", "other"],
|
||||
['', 'commercial_bank', 'other'],
|
||||
);
|
||||
assert.match(text(h.tree()), /tipo anterior não pertence/);
|
||||
const results = nodes(h.tree()).find((n) => n.type === "details");
|
||||
const results = nodes(h.tree()).find((n) => n.type === 'details');
|
||||
assert.equal(results.props.open, false);
|
||||
assert.match(text(results), /pesquisa anterior/);
|
||||
});
|
||||
|
||||
test("contradictory record criteria remain explicit until the user chooses a correction", () => {
|
||||
void test('contradictory record criteria remain explicit until the user chooses a correction', () => {
|
||||
const h = harness(
|
||||
{
|
||||
kind: "fund",
|
||||
category: "banking",
|
||||
institution_type: "commercial_bank",
|
||||
location_mode: "physical",
|
||||
province_id: "province-qa",
|
||||
sector: "8",
|
||||
state: "closed",
|
||||
certainty: "documented",
|
||||
kind: 'fund',
|
||||
category: 'banking',
|
||||
institution_type: 'commercial_bank',
|
||||
location_mode: 'physical',
|
||||
province_id: 'province-qa',
|
||||
sector: '8',
|
||||
state: 'closed',
|
||||
certainty: 'documented',
|
||||
},
|
||||
{ kind: ["Combinação incompatível."] },
|
||||
{ kind: ['Combinação incompatível.'] },
|
||||
);
|
||||
assert.match(text(h.tree()), /A pesquisa não foi executada/);
|
||||
assert.equal(h.form().data.kind, "fund");
|
||||
assert.equal(h.form().data.kind, 'fund');
|
||||
const action = nodes(h.tree()).find(
|
||||
(n) => n.type === "button" && /Manter o fundo/.test(text(n)),
|
||||
(n) => n.type === 'button' && /Manter o fundo/.test(text(n)),
|
||||
);
|
||||
action.props.onClick();
|
||||
h.render();
|
||||
assert.equal(h.form().data.category, "");
|
||||
assert.equal(h.form().data.institution_type, "");
|
||||
assert.equal(h.form().data.location_mode, "coverage");
|
||||
assert.equal(h.form().data.category, '');
|
||||
assert.equal(h.form().data.institution_type, '');
|
||||
assert.equal(h.form().data.location_mode, 'coverage');
|
||||
for (const [key, value] of Object.entries({
|
||||
kind: "fund",
|
||||
province_id: "province-qa",
|
||||
sector: "8",
|
||||
state: "closed",
|
||||
certainty: "documented",
|
||||
kind: 'fund',
|
||||
province_id: 'province-qa',
|
||||
sector: '8',
|
||||
state: 'closed',
|
||||
certainty: 'documented',
|
||||
}))
|
||||
assert.equal(h.form().data[key], value);
|
||||
nodes(h.tree())
|
||||
.find((n) => n.type === "form")
|
||||
.find((n) => n.type === 'form')
|
||||
.props.onSubmit({ preventDefault() {} });
|
||||
assert.equal(h.submitted().url, "/fundos");
|
||||
assert.equal(h.submitted().data.province_id, "province-qa");
|
||||
assert.ok(h.territory(), "the catalogue consumes the common hierarchical location control");
|
||||
assert.equal(h.submitted().url, '/fundos');
|
||||
assert.equal(h.submitted().data.province_id, 'province-qa');
|
||||
assert.ok(
|
||||
h.territory(),
|
||||
'the catalogue consumes the common hierarchical location control',
|
||||
);
|
||||
});
|
||||
|
||||
test("local search defaults to documented presence and keeps the explicit unknown option and chosen territory", () => {
|
||||
const h = harness({ territory: "district-qa", sector: "7" });
|
||||
h.select("Localização a pesquisar").props.onChange({ target: { value: "physical" } });
|
||||
h.render();
|
||||
assert.equal(h.form().data.certainty, "documented");
|
||||
assert.equal(h.form().data.territory, "district-qa");
|
||||
assert.equal(h.form().data.sector, "7");
|
||||
h.select("Informação por confirmar").props.onChange({ target: { value: "include_unknown" } });
|
||||
h.render();
|
||||
assert.equal(h.form().data.certainty, "include_unknown");
|
||||
const resumed = harness({
|
||||
location_mode: "physical",
|
||||
territory: "district-qa",
|
||||
certainty: "include_unknown",
|
||||
void test('local search defaults to documented presence and keeps the explicit unknown option and chosen territory', () => {
|
||||
const h = harness({ territory: 'district-qa', sector: '7' });
|
||||
h.select('Localização a pesquisar').props.onChange({
|
||||
target: { value: 'physical' },
|
||||
});
|
||||
assert.equal(resumed.form().data.certainty, "include_unknown");
|
||||
assert.equal(harness({ location_mode: "physical" }).form().data.certainty, "documented");
|
||||
h.render();
|
||||
assert.equal(h.form().data.certainty, 'documented');
|
||||
assert.equal(h.form().data.territory, 'district-qa');
|
||||
assert.equal(h.form().data.sector, '7');
|
||||
h.select('Informação por confirmar').props.onChange({
|
||||
target: { value: 'include_unknown' },
|
||||
});
|
||||
h.render();
|
||||
assert.equal(h.form().data.certainty, 'include_unknown');
|
||||
const resumed = harness({
|
||||
location_mode: 'physical',
|
||||
territory: 'district-qa',
|
||||
certainty: 'include_unknown',
|
||||
});
|
||||
assert.equal(resumed.form().data.certainty, 'include_unknown');
|
||||
assert.equal(
|
||||
harness({ location_mode: 'physical' }).form().data.certainty,
|
||||
'documented',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -8,6 +8,32 @@ import {
|
||||
import { getSimulationSections } from '../../resources/js/lib/simulation-form.ts';
|
||||
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
void test('readiness explains stored answer codes in Portuguese without changing the draft', () => {
|
||||
const draft = {
|
||||
target_customers: 'Clientes sintéticos',
|
||||
market_assumption: 'Hipótese por testar',
|
||||
customer_validation_status: 'partial',
|
||||
cost_estimate_status: 'unknown',
|
||||
location_assessment_status: 'no',
|
||||
funding_status: 'in_process',
|
||||
receivables_timing_status: 'not_started',
|
||||
annual_revenue: '12000',
|
||||
};
|
||||
const before = JSON.stringify(draft);
|
||||
const origins = getProjectReadiness(draft)
|
||||
.map((item) => item.origin)
|
||||
.join('\n');
|
||||
assert.match(origins, /Parcialmente/);
|
||||
assert.match(origins, /Por confirmar/);
|
||||
assert.match(origins, /Estado declarado: Não/);
|
||||
assert.match(origins, /Em curso/);
|
||||
assert.doesNotMatch(
|
||||
origins,
|
||||
/\b(?:partial|unknown|in_process|not_started)\b/,
|
||||
);
|
||||
assert.equal(JSON.stringify(draft), before);
|
||||
});
|
||||
|
||||
void test('idea journey reuses one dossier and exposes the six requested stages', () => {
|
||||
const sections = getSimulationSections({
|
||||
purpose: 'simulate_only',
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
// Isolated worktrees share only vendor dependencies, never application sources.
|
||||
$qaRoot = dirname(__DIR__);
|
||||
putenv('APP_BASE_PATH='.$qaRoot);
|
||||
$_ENV['APP_BASE_PATH'] = $_SERVER['APP_BASE_PATH'] = $qaRoot;
|
||||
$loader = require $qaRoot.'/vendor/autoload.php';
|
||||
foreach ($loader->getPrefixesPsr4() as $prefix => $paths) {
|
||||
if (in_array($prefix, ['App\\', 'Tests\\', 'Database\\Factories\\', 'Database\\Seeders\\'], true)) {
|
||||
$directories = ['App\\' => 'app', 'Tests\\' => 'tests', 'Database\\Factories\\' => 'database/factories', 'Database\\Seeders\\' => 'database/seeders'];
|
||||
$loader->setPsr4($prefix, $qaRoot.'/'.$directories[$prefix]);
|
||||
}
|
||||
}
|
||||
$overrides = [];
|
||||
foreach ($loader->getClassMap() as $class => $path) {
|
||||
foreach (['App\\' => 'app', 'Tests\\' => 'tests', 'Database\\Factories\\' => 'database/factories', 'Database\\Seeders\\' => 'database/seeders'] as $prefix => $directory) {
|
||||
if (str_starts_with($class, $prefix)) {
|
||||
$candidate = $qaRoot.'/'.$directory.'/'.str_replace('\\', '/', substr($class, strlen($prefix))).'.php';
|
||||
if (is_file($candidate)) {
|
||||
$overrides[$class] = $candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$loader->addClassMap($overrides);
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Foundation\Vite;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require __DIR__.'/continuity-qa-bootstrap.php';
|
||||
$qaRoot = dirname(__DIR__);
|
||||
$public = $qaRoot.'/public';
|
||||
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
||||
if ($path !== '/' && is_file($public.$path)) {
|
||||
return false;
|
||||
}
|
||||
$app = require $qaRoot.'/bootstrap/app.php';
|
||||
$app->booted(function () {
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
if (! IsolatedQaDatabase::allowsSchemaChanges() || $identity->name !== 'continuity_20261120_test' || (int) $identity->port !== 55441) {
|
||||
abort(503);
|
||||
}
|
||||
app(Vite::class)->useBuildDirectory('build-qa-opportunities');
|
||||
});
|
||||
$app->handleRequest(Request::capture());
|
||||
Reference in New Issue
Block a user