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.
|
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.
|
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».
|
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.
|
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 CurrencySelect from '@/components/currency-select';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useId, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
compareBusinessScenarios,
|
compareBusinessScenarios,
|
||||||
|
businessPlanNumberError,
|
||||||
exportBusinessPlanCsv,
|
exportBusinessPlanCsv,
|
||||||
forecastBusinessPlan,
|
forecastBusinessPlan,
|
||||||
MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH,
|
MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH,
|
||||||
@@ -74,23 +75,45 @@ function MoneyInput({
|
|||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
allowNegative = false,
|
allowNegative = false,
|
||||||
|
step = '0.01',
|
||||||
}: {
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
value: string;
|
value: string;
|
||||||
onChange: (value: string) => void;
|
onChange: (value: string) => void;
|
||||||
allowNegative?: boolean;
|
allowNegative?: boolean;
|
||||||
|
step?: string;
|
||||||
}) {
|
}) {
|
||||||
|
const errorId = useId();
|
||||||
|
const [touched, setTouched] = useState(false);
|
||||||
|
const error = touched
|
||||||
|
? businessPlanNumberError(value, { allowNegative })
|
||||||
|
: '';
|
||||||
return (
|
return (
|
||||||
<label className="block text-sm font-medium">
|
<label className="block text-sm font-medium">
|
||||||
{label}
|
{label}
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={allowNegative ? undefined : '0'}
|
min={allowNegative ? undefined : '0'}
|
||||||
step="0.01"
|
step={step}
|
||||||
value={value}
|
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"
|
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>
|
</label>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -252,7 +275,7 @@ export function SimulationBusinessPlan({
|
|||||||
unitVariableCostByPeriod: 'unitVariableCost',
|
unitVariableCostByPeriod: 'unitVariableCost',
|
||||||
};
|
};
|
||||||
const plan = workingPlan ??
|
const plan = workingPlan ??
|
||||||
restoreBusinessPlanSnapshot(snapshot) ?? {
|
restoreBusinessPlanSnapshot(snapshot, { editable: true }) ?? {
|
||||||
...emptyPlan,
|
...emptyPlan,
|
||||||
currency: projectCurrency,
|
currency: projectCurrency,
|
||||||
};
|
};
|
||||||
@@ -857,7 +880,11 @@ export function SimulationBusinessPlan({
|
|||||||
const fiscalBridge = result ? buildFinancialFiscalBridge(result) : null;
|
const fiscalBridge = result ? buildFinancialFiscalBridge(result) : null;
|
||||||
|
|
||||||
return (
|
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">
|
<summary className="cursor-pointer text-lg font-semibold">
|
||||||
Plano financeiro empresarial (pressupostos editáveis)
|
Plano financeiro empresarial (pressupostos editáveis)
|
||||||
</summary>
|
</summary>
|
||||||
@@ -1092,25 +1119,18 @@ export function SimulationBusinessPlan({
|
|||||||
className="mt-1 w-full rounded border p-2"
|
className="mt-1 w-full rounded border p-2"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="block text-sm">
|
<MoneyInput
|
||||||
{product.monthlyUnitsByPeriod
|
label={
|
||||||
? 'Unidades mensais base'
|
product.monthlyUnitsByPeriod
|
||||||
: 'Unidades por mes'}
|
? 'Unidades mensais base'
|
||||||
<input
|
: 'Unidades por mes'
|
||||||
type="number"
|
}
|
||||||
min="0"
|
step="0.001"
|
||||||
step="0.001"
|
value={product.monthlyUnits}
|
||||||
value={product.monthlyUnits}
|
onChange={(value) =>
|
||||||
onChange={(event) =>
|
updateProduct(index, 'monthlyUnits', value)
|
||||||
updateProduct(
|
}
|
||||||
index,
|
/>
|
||||||
'monthlyUnits',
|
|
||||||
event.target.value,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
className="mt-1 w-full rounded border p-2"
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
<MoneyInput
|
<MoneyInput
|
||||||
label="Preço por unidade"
|
label="Preço por unidade"
|
||||||
value={product.unitPrice}
|
value={product.unitPrice}
|
||||||
|
|||||||
@@ -3298,6 +3298,21 @@ export function SimulationForm() {
|
|||||||
>
|
>
|
||||||
{current.title}
|
{current.title}
|
||||||
</h3>
|
</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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-form-help-open
|
data-form-help-open
|
||||||
|
|||||||
@@ -13,6 +13,29 @@ type ProductLine = {
|
|||||||
productInventoryPurchasesByPeriod?: InventoryPurchasePeriod[] | null;
|
productInventoryPurchasesByPeriod?: InventoryPurchasePeriod[] | null;
|
||||||
};
|
};
|
||||||
export const MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH = 60_000;
|
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 = {
|
export type ScenarioAdjustment = {
|
||||||
unitVolumePercent: string;
|
unitVolumePercent: string;
|
||||||
unitPricePercent: string;
|
unitPricePercent: string;
|
||||||
@@ -179,6 +202,7 @@ export function serializeBusinessPlanSnapshot(
|
|||||||
|
|
||||||
export function restoreBusinessPlanSnapshot(
|
export function restoreBusinessPlanSnapshot(
|
||||||
snapshot: string | undefined,
|
snapshot: string | undefined,
|
||||||
|
options: { editable?: boolean } = {},
|
||||||
): BusinessFinancialPlanInput | null {
|
): BusinessFinancialPlanInput | null {
|
||||||
if (!snapshot || snapshot.length > MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH)
|
if (!snapshot || snapshot.length > MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH)
|
||||||
return null;
|
return null;
|
||||||
@@ -210,6 +234,15 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
const plan = decoded.plan as Record<string, unknown>;
|
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 = [
|
const textFields = [
|
||||||
'currency',
|
'currency',
|
||||||
'openingCash',
|
'openingCash',
|
||||||
@@ -336,7 +369,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
const collectionPercent = String(plan.salesCollectionPercent ?? '100');
|
const collectionPercent = String(plan.salesCollectionPercent ?? '100');
|
||||||
const collectionRate = percentMicro(
|
const collectionRate = snapshotPercentage(
|
||||||
collectionPercent,
|
collectionPercent,
|
||||||
'Percentagem de cobrança',
|
'Percentagem de cobrança',
|
||||||
);
|
);
|
||||||
@@ -360,7 +393,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
!Object.hasOwn(plan, 'openingReceivablesCollectionPercent'))
|
!Object.hasOwn(plan, 'openingReceivablesCollectionPercent'))
|
||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
const openingCollectionRate = percentMicro(
|
const openingCollectionRate = snapshotPercentage(
|
||||||
String(plan.openingReceivablesCollectionPercent ?? '100'),
|
String(plan.openingReceivablesCollectionPercent ?? '100'),
|
||||||
'Percentagem de cobrança dos valores a receber de abertura',
|
'Percentagem de cobrança dos valores a receber de abertura',
|
||||||
);
|
);
|
||||||
@@ -391,7 +424,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
typeof entry.percent !== 'string'
|
typeof entry.percent !== 'string'
|
||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
const rate = percentMicro(
|
const rate = snapshotPercentage(
|
||||||
entry.percent,
|
entry.percent,
|
||||||
'Percentagem da parcela de recebíveis',
|
'Percentagem da parcela de recebíveis',
|
||||||
);
|
);
|
||||||
@@ -419,11 +452,11 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
entry.month < 1 ||
|
entry.month < 1 ||
|
||||||
entry.month > 60 ||
|
entry.month > 60 ||
|
||||||
typeof entry.percent !== 'string' ||
|
typeof entry.percent !== 'string' ||
|
||||||
percentMicro(
|
snapshotPercentage(
|
||||||
entry.percent,
|
entry.percent,
|
||||||
'Percentagem da liquidação de valores a pagar',
|
'Percentagem da liquidação de valores a pagar',
|
||||||
) < 0n ||
|
) < 0n ||
|
||||||
percentMicro(
|
snapshotPercentage(
|
||||||
entry.percent,
|
entry.percent,
|
||||||
'Percentagem da liquidação de valores a pagar',
|
'Percentagem da liquidação de valores a pagar',
|
||||||
) > 100_000_000n,
|
) > 100_000_000n,
|
||||||
@@ -431,7 +464,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
plan.openingPayablesInstallments.reduce(
|
plan.openingPayablesInstallments.reduce(
|
||||||
(sum, entry) =>
|
(sum, entry) =>
|
||||||
sum +
|
sum +
|
||||||
percentMicro(
|
snapshotPercentage(
|
||||||
entry.percent,
|
entry.percent,
|
||||||
'Percentagem da liquidação de valores a pagar',
|
'Percentagem da liquidação de valores a pagar',
|
||||||
),
|
),
|
||||||
@@ -462,7 +495,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
months.add(entry.month);
|
months.add(entry.month);
|
||||||
const rate = percentMicro(
|
const rate = snapshotPercentage(
|
||||||
entry.percent,
|
entry.percent,
|
||||||
'Percentagem de recuperação de vendas',
|
'Percentagem de recuperação de vendas',
|
||||||
);
|
);
|
||||||
@@ -634,11 +667,11 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
part.lagMonths > 12 ||
|
part.lagMonths > 12 ||
|
||||||
typeof part.percent !==
|
typeof part.percent !==
|
||||||
'string' ||
|
'string' ||
|
||||||
percentMicro(
|
snapshotPercentage(
|
||||||
part.percent,
|
part.percent,
|
||||||
'Percentagem da parcela',
|
'Percentagem da parcela',
|
||||||
) < 0n ||
|
) < 0n ||
|
||||||
percentMicro(
|
snapshotPercentage(
|
||||||
part.percent,
|
part.percent,
|
||||||
'Percentagem da parcela',
|
'Percentagem da parcela',
|
||||||
) > 100_000_000n,
|
) > 100_000_000n,
|
||||||
@@ -646,7 +679,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
entry.paymentInstallments.reduce(
|
entry.paymentInstallments.reduce(
|
||||||
(sum: bigint, part: any) =>
|
(sum: bigint, part: any) =>
|
||||||
sum +
|
sum +
|
||||||
percentMicro(
|
snapshotPercentage(
|
||||||
part.percent,
|
part.percent,
|
||||||
'Percentagem da parcela',
|
'Percentagem da parcela',
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -26,6 +26,20 @@ function value(draft: ReadinessDraft, key: string): string {
|
|||||||
return typeof current === 'string' ? current.trim() : '';
|
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(
|
function rows(
|
||||||
draft: ReadinessDraft,
|
draft: ReadinessDraft,
|
||||||
key: string,
|
key: string,
|
||||||
@@ -80,7 +94,7 @@ export function getProjectReadiness(
|
|||||||
kind: 'missing',
|
kind: 'missing',
|
||||||
title: 'Clientes ainda pouco definidos',
|
title: 'Clientes ainda pouco definidos',
|
||||||
origin: customerStatus
|
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.',
|
: 'Não foi indicada uma descrição de clientes ou beneficiários.',
|
||||||
affected: 'Procura e receitas previstas.',
|
affected: 'Procura e receitas previstas.',
|
||||||
consequence:
|
consequence:
|
||||||
@@ -98,7 +112,7 @@ export function getProjectReadiness(
|
|||||||
id: 'market-source',
|
id: 'market-source',
|
||||||
kind: 'unverified',
|
kind: 'unverified',
|
||||||
title: 'Hipótese de mercado sem fonte ou data',
|
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.',
|
affected: 'Procura, preço e projecções de vendas.',
|
||||||
consequence:
|
consequence:
|
||||||
'A hipótese pode não representar informação actual ou verificável.',
|
'A hipótese pode não representar informação actual ou verificável.',
|
||||||
@@ -117,7 +131,7 @@ export function getProjectReadiness(
|
|||||||
kind: 'missing',
|
kind: 'missing',
|
||||||
title: 'Custos do projecto por detalhar',
|
title: 'Custos do projecto por detalhar',
|
||||||
origin: costStatus
|
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.',
|
: 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.',
|
||||||
affected: 'Investimento necessário, margem e tesouraria.',
|
affected: 'Investimento necessário, margem e tesouraria.',
|
||||||
consequence: 'O capital necessário pode estar subestimado.',
|
consequence: 'O capital necessário pode estar subestimado.',
|
||||||
@@ -141,7 +155,7 @@ export function getProjectReadiness(
|
|||||||
: 'missing',
|
: 'missing',
|
||||||
title: 'Prazo de recebimentos por esclarecer',
|
title: 'Prazo de recebimentos por esclarecer',
|
||||||
origin: collectionStatus
|
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.',
|
: '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.',
|
affected: 'Fluxo de caixa e capital de giro.',
|
||||||
consequence:
|
consequence:
|
||||||
@@ -162,7 +176,7 @@ export function getProjectReadiness(
|
|||||||
id: 'location',
|
id: 'location',
|
||||||
kind: territory && locationReason ? 'unverified' : 'missing',
|
kind: territory && locationReason ? 'unverified' : 'missing',
|
||||||
title: 'Adequação da localização por esclarecer',
|
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:
|
affected:
|
||||||
'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
|
'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
|
||||||
consequence:
|
consequence:
|
||||||
@@ -205,7 +219,7 @@ export function getProjectReadiness(
|
|||||||
origin:
|
origin:
|
||||||
sought > secured
|
sought > secured
|
||||||
? 'O montante indicado como necessário excede os recursos declarados como mobilizados.'
|
? '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.',
|
affected: 'Calendário de investimento e implementação.',
|
||||||
consequence:
|
consequence:
|
||||||
'Os recursos podem não estar disponíveis quando forem necessários.',
|
'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 { csvCell } from './csv.js';
|
||||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||||
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
|
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
|
||||||
|
import {
|
||||||
|
forecastBusinessPlan,
|
||||||
|
restoreBusinessPlanSnapshot,
|
||||||
|
} from './business-financial-plan.ts';
|
||||||
|
|
||||||
export type SimulationDraft = Record<string, string | string[]>;
|
export type SimulationDraft = Record<string, string | string[]>;
|
||||||
export const projectQuestionnaireVersion =
|
export const projectQuestionnaireVersion =
|
||||||
@@ -1801,6 +1805,26 @@ export function validateSimulationDraft(
|
|||||||
errors.total_investment =
|
errors.total_investment =
|
||||||
'A soma do capital, dívida e subvenções deve corresponder ao investimento total.';
|
'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;
|
return errors;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,19 @@
|
|||||||
import { InstitutionView, type InstitutionDetails } from "@/components/funding-institution";
|
import {
|
||||||
import { financialCategories, financialTypes } from "@/components/funding-classification";
|
InstitutionView,
|
||||||
import { Link, useForm } from "@inertiajs/react";
|
type InstitutionDetails,
|
||||||
import { Frame, card, button } from "@/pages/investment/shared";
|
} from '@/components/funding-institution';
|
||||||
import { type Programme, windowLabels } from "./shared";
|
import {
|
||||||
import { useRef, useState } from "react";
|
financialCategories,
|
||||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
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]) {
|
export default function FundingIndex(props: Parameters<typeof Index>[0]) {
|
||||||
return <Index key={JSON.stringify(props.filters)} {...props} />;
|
return <Index key={JSON.stringify(props.filters)} {...props} />;
|
||||||
@@ -54,35 +63,38 @@ function Index({
|
|||||||
territorySelection?: TerritoryOption[];
|
territorySelection?: TerritoryOption[];
|
||||||
criteriaErrors?: Record<string, string[]>;
|
criteriaErrors?: Record<string, string[]>;
|
||||||
}) {
|
}) {
|
||||||
const [notice, setNotice] = useState("");
|
const [notice, setNotice] = useState('');
|
||||||
|
const [searchTerritory, setSearchTerritory] = useState(territorySelection);
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
category: filters.category ?? "",
|
category: filters.category ?? '',
|
||||||
institution_type: filters.institution_type ?? "",
|
institution_type: filters.institution_type ?? '',
|
||||||
location_mode: filters.location_mode ?? "coverage",
|
location_mode: filters.location_mode ?? 'coverage',
|
||||||
include_historical: filters.include_historical ?? "0",
|
include_historical: filters.include_historical ?? '0',
|
||||||
context: filters.context ?? "",
|
context: filters.context ?? '',
|
||||||
opportunity: filters.opportunity ?? "",
|
opportunity: filters.opportunity ?? '',
|
||||||
need: filters.need ?? "",
|
need: filters.need ?? '',
|
||||||
q: filters.q ?? "",
|
q: filters.q ?? '',
|
||||||
kind: filters.kind ?? "",
|
kind: filters.kind ?? '',
|
||||||
sector: filters.sector ?? "",
|
sector: filters.sector ?? '',
|
||||||
territory: filters.territory ?? "",
|
territory: filters.territory ?? '',
|
||||||
province_id: filters.province_id ?? "",
|
province_id: filters.province_id ?? '',
|
||||||
district_id: filters.district_id ?? "",
|
district_id: filters.district_id ?? '',
|
||||||
admin_post_id: filters.admin_post_id ?? "",
|
admin_post_id: filters.admin_post_id ?? '',
|
||||||
locality_id: filters.locality_id ?? "",
|
locality_id: filters.locality_id ?? '',
|
||||||
certainty:
|
certainty:
|
||||||
filters.certainty ??
|
filters.certainty ??
|
||||||
(filters.location_mode === "physical" ? "documented" : "include_unknown"),
|
(filters.location_mode === 'physical'
|
||||||
state: filters.state ?? "",
|
? 'documented'
|
||||||
|
: 'include_unknown'),
|
||||||
|
state: filters.state ?? '',
|
||||||
});
|
});
|
||||||
const applied = useRef(JSON.stringify(form.data));
|
const applied = useRef(JSON.stringify(form.data));
|
||||||
const criteriaChanged = JSON.stringify(form.data) !== applied.current;
|
const criteriaChanged = JSON.stringify(form.data) !== applied.current;
|
||||||
const typeAllowed = (category: string, type: string) =>
|
const typeAllowed = (category: string, type: string) =>
|
||||||
!category ||
|
!category ||
|
||||||
category === "other" ||
|
category === 'other' ||
|
||||||
!type ||
|
!type ||
|
||||||
type === "other" ||
|
type === 'other' ||
|
||||||
(categoryTypes[category] ?? []).includes(type);
|
(categoryTypes[category] ?? []).includes(type);
|
||||||
return (
|
return (
|
||||||
<Frame title="Instituições financeiras, fundos e programas de apoio">
|
<Frame title="Instituições financeiras, fundos e programas de apoio">
|
||||||
@@ -95,25 +107,33 @@ function Index({
|
|||||||
A minha selecção
|
A minha selecção
|
||||||
</Link>
|
</Link>
|
||||||
<p>
|
<p>
|
||||||
Encontre bancos, seguradoras, fundos e outros parceiros financeiros. Explore as
|
Encontre bancos, seguradoras, fundos e outros parceiros
|
||||||
soluções e os contactos adequados ao seu investimento.
|
financeiros. Explore as soluções e os contactos adequados ao seu
|
||||||
|
investimento.
|
||||||
</p>
|
</p>
|
||||||
<form
|
<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`}
|
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) => {
|
onSubmit={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
form.get("/fundos");
|
form.get('/fundos');
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{Object.keys(criteriaErrors).length > 0 && (
|
{Object.keys(criteriaErrors).length > 0 && (
|
||||||
<aside className="basis-full rounded border border-amber-600 p-3" role="alert">
|
<aside
|
||||||
<h2 className="font-semibold">Reveja esta combinação de critérios</h2>
|
className="basis-full rounded border border-amber-600 p-3"
|
||||||
{Object.entries(criteriaErrors).map(([key, messages]) => (
|
role="alert"
|
||||||
<p key={key}>{messages.join(" ")}</p>
|
>
|
||||||
))}
|
<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>
|
<p>
|
||||||
A pesquisa não foi executada. Corrija os critérios indicados e volte a
|
A pesquisa não foi executada. Corrija os critérios
|
||||||
pesquisar.
|
indicados e volte a pesquisar.
|
||||||
</p>
|
</p>
|
||||||
</aside>
|
</aside>
|
||||||
)}
|
)}
|
||||||
@@ -128,15 +148,16 @@ function Index({
|
|||||||
</p>
|
</p>
|
||||||
))}
|
))}
|
||||||
{form.data.kind &&
|
{form.data.kind &&
|
||||||
form.data.kind !== "institution" &&
|
form.data.kind !== 'institution' &&
|
||||||
(form.data.category ||
|
(form.data.category ||
|
||||||
form.data.institution_type ||
|
form.data.institution_type ||
|
||||||
form.data.location_mode === "physical") && (
|
form.data.location_mode === 'physical') && (
|
||||||
<aside className="basis-full rounded border p-3">
|
<aside className="basis-full rounded border p-3">
|
||||||
<p>
|
<p>
|
||||||
Categoria, tipo de instituição e presença física não identificam um
|
Categoria, tipo de instituição e presença física
|
||||||
fundo ou programa. Reveja o tipo de registo ou retire apenas estes
|
não identificam um fundo ou programa. Reveja o
|
||||||
critérios incompatíveis.
|
tipo de registo ou retire apenas estes critérios
|
||||||
|
incompatíveis.
|
||||||
</p>
|
</p>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -144,16 +165,17 @@ function Index({
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
form.setData({
|
form.setData({
|
||||||
...form.data,
|
...form.data,
|
||||||
category: "",
|
category: '',
|
||||||
institution_type: "",
|
institution_type: '',
|
||||||
location_mode: "coverage",
|
location_mode: 'coverage',
|
||||||
});
|
});
|
||||||
setNotice(
|
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>
|
</button>
|
||||||
</aside>
|
</aside>
|
||||||
)}
|
)}
|
||||||
@@ -164,24 +186,31 @@ function Index({
|
|||||||
value={form.data.category}
|
value={form.data.category}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const category = e.target.value;
|
const category = e.target.value;
|
||||||
const valid = typeAllowed(category, form.data.institution_type);
|
const valid = typeAllowed(
|
||||||
|
category,
|
||||||
|
form.data.institution_type,
|
||||||
|
);
|
||||||
if (!valid)
|
if (!valid)
|
||||||
setNotice(
|
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.setData({
|
||||||
...form.data,
|
...form.data,
|
||||||
category,
|
category,
|
||||||
institution_type: valid ? form.data.institution_type : "",
|
institution_type: valid
|
||||||
|
? form.data.institution_type
|
||||||
|
: '',
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<option value="">Todas</option>
|
<option value="">Todas</option>
|
||||||
{Object.entries(financialCategories).map(([id, label]) => (
|
{Object.entries(financialCategories).map(
|
||||||
<option key={id} value={id}>
|
([id, label]) => (
|
||||||
{label}
|
<option key={id} value={id}>
|
||||||
</option>
|
{label}
|
||||||
))}
|
</option>
|
||||||
|
),
|
||||||
|
)}
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
@@ -189,7 +218,9 @@ function Index({
|
|||||||
<select
|
<select
|
||||||
className="block rounded border p-2"
|
className="block rounded border p-2"
|
||||||
value={form.data.institution_type}
|
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>
|
<option value="">Todos</option>
|
||||||
{Object.entries(financialTypes)
|
{Object.entries(financialTypes)
|
||||||
@@ -202,7 +233,7 @@ function Index({
|
|||||||
<option key={id} value={id}>
|
<option key={id} value={id}>
|
||||||
{typeAllowed(form.data.category, id)
|
{typeAllowed(form.data.category, id)
|
||||||
? label
|
? label
|
||||||
: "Incompatível: " + label}
|
: 'Incompatível: ' + label}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
@@ -210,19 +241,23 @@ function Index({
|
|||||||
<label>
|
<label>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
checked={form.data.include_historical === "1"}
|
checked={form.data.include_historical === '1'}
|
||||||
onChange={(e) =>
|
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>
|
||||||
<label>
|
<label>
|
||||||
Necessidade do processo
|
Necessidade do processo
|
||||||
<select
|
<select
|
||||||
className="block rounded border p-2"
|
className="block rounded border p-2"
|
||||||
value={form.data.need}
|
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>
|
<option value="">Todas / por identificar</option>
|
||||||
{Object.entries(needs).map(([id, label]) => (
|
{Object.entries(needs).map(([id, label]) => (
|
||||||
@@ -233,20 +268,24 @@ function Index({
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
Palavras-chave
|
Palavras-chave (opcional)
|
||||||
<input
|
<input
|
||||||
className="block rounded border p-2"
|
className="block rounded border p-2"
|
||||||
value={form.data.q}
|
value={form.data.q}
|
||||||
maxLength={150}
|
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>
|
||||||
<label>
|
<label>
|
||||||
Tipo de registo a consultar
|
Tipo de registo a consultar
|
||||||
<select
|
<select
|
||||||
className="block rounded border p-2"
|
className="block rounded border p-2"
|
||||||
value={form.data.kind}
|
value={form.data.kind}
|
||||||
onChange={(e) => form.setData("kind", e.target.value)}
|
onChange={(e) => form.setData('kind', e.target.value)}
|
||||||
>
|
>
|
||||||
<option value="">Todos</option>
|
<option value="">Todos</option>
|
||||||
{Object.entries(kinds).map(([key, name]) => (
|
{Object.entries(kinds).map(([key, name]) => (
|
||||||
@@ -261,7 +300,7 @@ function Index({
|
|||||||
<select
|
<select
|
||||||
className="block rounded border p-2"
|
className="block rounded border p-2"
|
||||||
value={form.data.sector}
|
value={form.data.sector}
|
||||||
onChange={(e) => form.setData("sector", e.target.value)}
|
onChange={(e) => form.setData('sector', e.target.value)}
|
||||||
>
|
>
|
||||||
<option value="">Todos</option>
|
<option value="">Todos</option>
|
||||||
{options.sectors.map((item) => (
|
{options.sectors.map((item) => (
|
||||||
@@ -272,7 +311,9 @@ function Index({
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<fieldset className="min-w-0 basis-full">
|
<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>
|
<label>
|
||||||
Localização a pesquisar
|
Localização a pesquisar
|
||||||
<select
|
<select
|
||||||
@@ -283,40 +324,52 @@ function Index({
|
|||||||
...form.data,
|
...form.data,
|
||||||
location_mode: e.target.value,
|
location_mode: e.target.value,
|
||||||
certainty:
|
certainty:
|
||||||
e.target.value === "physical"
|
e.target.value === 'physical'
|
||||||
? "documented"
|
? 'documented'
|
||||||
: form.data.certainty,
|
: form.data.certainty,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<option value="physical">Sede, balcão ou presença física</option>
|
<option value="physical">
|
||||||
<option value="coverage">Cobertura do financiamento/produto</option>
|
Sede, balcão ou presença física
|
||||||
|
</option>
|
||||||
|
<option value="coverage">
|
||||||
|
Cobertura do financiamento/produto
|
||||||
|
</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<p className="mb-3 text-sm">
|
<p className="mb-3 text-sm">
|
||||||
Escolha a província e, se necessário, o distrito. Sede e balcões identificam
|
Escolha a província e, se necessário, o distrito. Sede e
|
||||||
onde pode contactar a instituição; a cobertura indica onde o financiamento
|
balcões identificam onde pode contactar a instituição; a
|
||||||
se aplica.
|
cobertura indica onde o financiamento se aplica.
|
||||||
</p>
|
</p>
|
||||||
<TerritoryFields
|
<TerritoryFields
|
||||||
initial={territorySelection}
|
initial={searchTerritory}
|
||||||
showMap={false}
|
showMap={false}
|
||||||
onChange={(path) =>
|
onChange={(path) =>
|
||||||
form.setData({
|
form.setData({
|
||||||
...form.data,
|
...form.data,
|
||||||
territory: path.at(-1)?.id ?? "",
|
territory: path.at(-1)?.id ?? '',
|
||||||
province_id:
|
province_id:
|
||||||
path.find((node) => node.location_type === "province")?.id ??
|
path.find(
|
||||||
"",
|
(node) =>
|
||||||
|
node.location_type === 'province',
|
||||||
|
)?.id ?? '',
|
||||||
district_id:
|
district_id:
|
||||||
path.find((node) => node.location_type === "district")?.id ??
|
path.find(
|
||||||
"",
|
(node) =>
|
||||||
|
node.location_type === 'district',
|
||||||
|
)?.id ?? '',
|
||||||
admin_post_id:
|
admin_post_id:
|
||||||
path.find((node) => node.location_type === "admin_post")?.id ??
|
path.find(
|
||||||
"",
|
(node) =>
|
||||||
|
node.location_type === 'admin_post',
|
||||||
|
)?.id ?? '',
|
||||||
locality_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
|
<select
|
||||||
className="block rounded border p-2"
|
className="block rounded border p-2"
|
||||||
value={form.data.certainty}
|
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">
|
<option value="documented">
|
||||||
Apenas âmbito documentado para os filtros escolhidos
|
Apenas âmbito documentado para os filtros escolhidos
|
||||||
</option>
|
</option>
|
||||||
@@ -339,7 +396,7 @@ function Index({
|
|||||||
<select
|
<select
|
||||||
className="block rounded border p-2"
|
className="block rounded border p-2"
|
||||||
value={form.data.state}
|
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>
|
<option value="">Qualquer estado</option>
|
||||||
{Object.entries(windowLabels).map(([key, label]) => (
|
{Object.entries(windowLabels).map(([key, label]) => (
|
||||||
@@ -355,46 +412,77 @@ function Index({
|
|||||||
</form>
|
</form>
|
||||||
{criteriaChanged && (
|
{criteriaChanged && (
|
||||||
<p role="status">
|
<p role="status">
|
||||||
Alterou os critérios. Clique em Pesquisar para os aplicar. Os resultados
|
Alterou os critérios. Clique em Pesquisar para os aplicar.
|
||||||
anteriores ficam separados abaixo.
|
Os resultados anteriores ficam separados abaixo.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<details
|
<details
|
||||||
open={!criteriaChanged && Object.keys(criteriaErrors).length === 0}
|
open={
|
||||||
|
!criteriaChanged && Object.keys(criteriaErrors).length === 0
|
||||||
|
}
|
||||||
className="space-y-3"
|
className="space-y-3"
|
||||||
>
|
>
|
||||||
<summary>
|
<summary>
|
||||||
{Object.keys(criteriaErrors).length
|
{Object.keys(criteriaErrors).length
|
||||||
? "Pesquisa não executada — critérios inválidos"
|
? 'Pesquisa não executada — critérios inválidos'
|
||||||
: criteriaChanged
|
: criteriaChanged
|
||||||
? "Resultados da pesquisa anterior — não correspondem aos critérios por aplicar"
|
? 'Resultados da pesquisa anterior — não correspondem aos critérios por aplicar'
|
||||||
: "Resultados correspondentes à pesquisa"}
|
: 'Resultados correspondentes à pesquisa'}
|
||||||
</summary>
|
</summary>
|
||||||
<p className="text-sm">
|
<p className="text-sm">
|
||||||
Explore as instituições e soluções adequadas ao seu investimento. Use os filtros
|
Explore as instituições e soluções adequadas ao seu
|
||||||
para encontrar a informação de que precisa.
|
investimento. Use os filtros para encontrar a informação de
|
||||||
|
que precisa.
|
||||||
</p>
|
</p>
|
||||||
{items.data.length === 0 && Object.keys(criteriaErrors).length === 0 && (
|
{items.data.length === 0 &&
|
||||||
<p>
|
Object.keys(criteriaErrors).length === 0 && (
|
||||||
Não foram encontradas instituições, fundos ou programas publicados que
|
<div className="grid gap-3">
|
||||||
correspondam a todos os critérios desta pesquisa.
|
<p>
|
||||||
</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) => (
|
{items.data.map((item) => (
|
||||||
<article className={card} key={item.id}>
|
<article className={card} key={item.id}>
|
||||||
<h2 className="text-xl font-semibold">
|
<h2 className="text-xl font-semibold">
|
||||||
<Link
|
<Link
|
||||||
className="underline"
|
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}
|
{item.payload.title}
|
||||||
</Link>
|
</Link>
|
||||||
</h2>
|
</h2>
|
||||||
{item.payload.kind === "institution" ? (
|
{item.payload.kind === 'institution' ? (
|
||||||
<InstitutionView
|
<InstitutionView
|
||||||
compact
|
compact
|
||||||
physicalTerritory={
|
physicalTerritory={
|
||||||
filters.location_mode === "physical"
|
filters.location_mode === 'physical'
|
||||||
? filters.territory
|
? filters.territory
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
@@ -408,25 +496,30 @@ function Index({
|
|||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<p>{item.payload.summary}</p>
|
<p>{item.payload.summary}</p>
|
||||||
<p>Entidade gestora: {item.payload.manager_name}</p>
|
<p>
|
||||||
{Object.entries(item.filter_explanation ?? {}).map(
|
Entidade gestora:{' '}
|
||||||
([key, message]) => (
|
{item.payload.manager_name}
|
||||||
<p key={key}>{message}</p>
|
</p>
|
||||||
),
|
{Object.entries(
|
||||||
)}
|
item.filter_explanation ?? {},
|
||||||
|
).map(([key, message]) => (
|
||||||
|
<p key={key}>{message}</p>
|
||||||
|
))}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{item.payload.kind === "institution" &&
|
{item.payload.kind === 'institution' &&
|
||||||
item.payload.windows.length === 0 ? null : item.payload.windows.length ===
|
item.payload.windows.length === 0 ? null : item.payload
|
||||||
0 ? (
|
.windows.length === 0 ? (
|
||||||
<p>
|
<p>
|
||||||
Não existe uma janela de candidatura confirmada para este programa.
|
Não existe uma janela de candidatura confirmada
|
||||||
|
para este programa.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<ul>
|
<ul>
|
||||||
{item.payload.windows.map((window) => (
|
{item.payload.windows.map((window) => (
|
||||||
<li key={window.code}>
|
<li key={window.code}>
|
||||||
{window.title}: {windowLabels[window.state]}
|
{window.title}:{' '}
|
||||||
|
{windowLabels[window.state]}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
@@ -439,10 +532,12 @@ function Index({
|
|||||||
<Link
|
<Link
|
||||||
key={index}
|
key={index}
|
||||||
href={link.url}
|
href={link.url}
|
||||||
aria-current={link.active ? "page" : undefined}
|
aria-current={link.active ? 'page' : undefined}
|
||||||
className="underline"
|
className="underline"
|
||||||
>
|
>
|
||||||
{link.label.replace(/«/g, "«").replace(/»/g, "»")}
|
{link.label
|
||||||
|
.replace(/«/g, '«')
|
||||||
|
.replace(/»/g, '»')}
|
||||||
</Link>
|
</Link>
|
||||||
) : null,
|
) : null,
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -9,6 +9,17 @@ import {
|
|||||||
} from '@/lib/company-comparison';
|
} from '@/lib/company-comparison';
|
||||||
|
|
||||||
type Question = { label: string; options: Record<string, string> };
|
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 = {
|
type Result = {
|
||||||
engine_version: string;
|
engine_version: string;
|
||||||
source: {
|
source: {
|
||||||
@@ -135,8 +146,8 @@ function Comparator(props: Props) {
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<p>
|
<p>
|
||||||
Compare a estrutura pretendida e os pontos a esclarecer antes de
|
Compare alternativas para discutir a constituição; não existe
|
||||||
preparar o acto constitutivo.
|
uma forma universalmente preferível.
|
||||||
</p>
|
</p>
|
||||||
{saved && (
|
{saved && (
|
||||||
<p>
|
<p>
|
||||||
@@ -178,32 +189,46 @@ function Comparator(props: Props) {
|
|||||||
{Object.entries(definition.questions).map(
|
{Object.entries(definition.questions).map(
|
||||||
([key, question]) =>
|
([key, question]) =>
|
||||||
active.includes(key) ? (
|
active.includes(key) ? (
|
||||||
<label key={key} className="grid gap-1">
|
<fieldset
|
||||||
{question.label}
|
key={key}
|
||||||
<select
|
className="min-w-0 rounded border p-3"
|
||||||
className={input}
|
>
|
||||||
name={`answers[${key}]`}
|
<legend className="px-1 font-semibold">
|
||||||
value={answers[key] ?? 'unknown'}
|
{questionThemes[key] ??
|
||||||
disabled={busy}
|
question.label}
|
||||||
onChange={(e) => {
|
</legend>
|
||||||
setAnswers({
|
<label className="grid gap-1">
|
||||||
...answers,
|
{question.label}
|
||||||
[key]: e.target.value,
|
<select
|
||||||
});
|
className={input}
|
||||||
setDirty(true);
|
name={`answers[${key}]`}
|
||||||
operation.current =
|
value={
|
||||||
createOperationKey();
|
answers[key] ?? 'unknown'
|
||||||
}}
|
}
|
||||||
>
|
disabled={busy}
|
||||||
{Object.entries(
|
onChange={(e) => {
|
||||||
question.options,
|
setAnswers({
|
||||||
).map(([code, label]) => (
|
...answers,
|
||||||
<option key={code} value={code}>
|
[key]: e.target.value,
|
||||||
{label}
|
});
|
||||||
</option>
|
setDirty(true);
|
||||||
))}
|
operation.current =
|
||||||
</select>
|
createOperationKey();
|
||||||
</label>
|
}}
|
||||||
|
>
|
||||||
|
{Object.entries(
|
||||||
|
question.options,
|
||||||
|
).map(([code, label]) => (
|
||||||
|
<option
|
||||||
|
key={code}
|
||||||
|
value={code}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
) : (
|
) : (
|
||||||
<input
|
<input
|
||||||
key={key}
|
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
|
final class FundingCriteriaCoherenceTest extends TestCase
|
||||||
{
|
{
|
||||||
use DatabaseTransactions;
|
use DatabaseTransactions;
|
||||||
|
|
||||||
private User $editor;
|
private User $editor;
|
||||||
|
|
||||||
private array $geo = [];
|
private array $geo = [];
|
||||||
|
|
||||||
private int $sector;
|
private int $sector;
|
||||||
|
|
||||||
protected function setUp(): void
|
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');
|
$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->assertContains($db->name, ['investor_intent_20261115_test', 'continuity_20261120_test']);
|
||||||
$this->editor = User::factory()->create(); config(['portal.managers' => [$this->editor->email]]);
|
$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;
|
$parent = null;
|
||||||
foreach (['country', 'province', 'district'] as $type) {
|
foreach (['country', 'province', 'district'] as $type) {
|
||||||
$id = (string) Str::uuid();
|
$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]);
|
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;
|
$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()];
|
$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' => []];
|
$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',
|
if ($kind === 'institution') {
|
||||||
'locations' => [['role' => 'headquarters', 'label' => 'Synthetic headquarters', 'territory_id' => $this->geo['district'], 'evidence_status' => 'reported', ...$source]],
|
$draft += ['institution_key' => $code, 'institution_nature' => 'bank', 'institution_categories' => ['banking'], 'institution_types' => ['commercial_bank'], 'institution_status' => 'reported',
|
||||||
'products' => [['code' => 'investment', 'title' => 'Synthetic investment product', 'needs' => ['investment'], 'coverage' => 'national', 'availability' => 'documented', ...$source]]];
|
'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);
|
$service = app(FundingProgrammes::class);
|
||||||
$id = $service->save($this->editor, null, ['version' => 0, 'code' => $code, 'reason' => 'Synthetic QA fixture', 'draft' => array_replace($draft, $overrides)]);
|
$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);
|
$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']);
|
$service->publish($this->editor, $id, ['version' => $plan['version'], 'hash' => $plan['hash'], 'confirm' => true, 'reason' => 'Synthetic QA only, rolled back']);
|
||||||
|
|
||||||
return $id;
|
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']));
|
$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'];
|
$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) {
|
$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')->assertOk()->assertJsonCount(0, 'data');
|
||||||
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$this->geo['province'])->assertOk()->assertJsonCount(1, '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
|
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) {
|
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.'); }
|
try {
|
||||||
catch (ValidationException $error) { $this->assertNotEmpty($error->errors()); }
|
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->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));
|
$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 test from 'node:test';
|
||||||
import assert from "node:assert/strict";
|
import assert from 'node:assert/strict';
|
||||||
import fs from "node:fs";
|
import fs from 'node:fs';
|
||||||
import { createRequire } from "node:module";
|
import { createRequire } from 'node:module';
|
||||||
import { compileFunction } from "node:vm";
|
import { compileFunction } from 'node:vm';
|
||||||
import React from "react";
|
import React from 'react';
|
||||||
import ts from "typescript";
|
import ts from 'typescript';
|
||||||
|
|
||||||
const require = createRequire(import.meta.url);
|
const require = createRequire(import.meta.url);
|
||||||
const nodes = (tree) =>
|
const nodes = (tree) =>
|
||||||
Array.isArray(tree)
|
Array.isArray(tree)
|
||||||
? tree.flatMap(nodes)
|
? tree.flatMap(nodes)
|
||||||
: tree && typeof tree === "object"
|
: tree && typeof tree === 'object'
|
||||||
? [tree, ...nodes(tree.props?.children)]
|
? [tree, ...nodes(tree.props?.children)]
|
||||||
: [];
|
: [];
|
||||||
const text = (tree) =>
|
const text = (tree) =>
|
||||||
Array.isArray(tree)
|
Array.isArray(tree)
|
||||||
? tree.map(text).join("")
|
? tree.map(text).join('')
|
||||||
: tree?.props
|
: tree?.props
|
||||||
? text(tree.props.children)
|
? text(tree.props.children)
|
||||||
: typeof tree === "string"
|
: typeof tree === 'string'
|
||||||
? tree
|
? tree
|
||||||
: "";
|
: '';
|
||||||
|
|
||||||
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
|
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
|
||||||
function harness(filters, errors = {}) {
|
function harness(filters, errors = {}) {
|
||||||
@@ -32,7 +32,8 @@ function harness(filters, errors = {}) {
|
|||||||
return [
|
return [
|
||||||
memory[id],
|
memory[id],
|
||||||
(next) => {
|
(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;
|
let form;
|
||||||
const TerritoryFields = () => null;
|
const TerritoryFields = () => null;
|
||||||
const module = { exports: {} };
|
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(
|
compileFunction(
|
||||||
ts.transpileModule(source, {
|
ts.transpileModule(source, {
|
||||||
compilerOptions: {
|
compilerOptions: {
|
||||||
@@ -48,10 +52,10 @@ function harness(filters, errors = {}) {
|
|||||||
jsx: ts.JsxEmit.ReactJSX,
|
jsx: ts.JsxEmit.ReactJSX,
|
||||||
},
|
},
|
||||||
}).outputText,
|
}).outputText,
|
||||||
["require", "module", "exports"],
|
['require', 'module', 'exports'],
|
||||||
)(
|
)(
|
||||||
(id) => {
|
(id) => {
|
||||||
if (id === "react")
|
if (id === 'react')
|
||||||
return {
|
return {
|
||||||
...React,
|
...React,
|
||||||
useState: state,
|
useState: state,
|
||||||
@@ -60,9 +64,9 @@ function harness(filters, errors = {}) {
|
|||||||
return value;
|
return value;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
if (id === "@inertiajs/react")
|
if (id === '@inertiajs/react')
|
||||||
return {
|
return {
|
||||||
Link: "a",
|
Link: 'a',
|
||||||
useForm(initial) {
|
useForm(initial) {
|
||||||
const [data, set] = state(initial);
|
const [data, set] = state(initial);
|
||||||
form = {
|
form = {
|
||||||
@@ -70,7 +74,11 @@ function harness(filters, errors = {}) {
|
|||||||
errors: {},
|
errors: {},
|
||||||
processing: false,
|
processing: false,
|
||||||
setData(key, value) {
|
setData(key, value) {
|
||||||
set(typeof key === "string" ? { ...data, [key]: value } : key);
|
set(
|
||||||
|
typeof key === 'string'
|
||||||
|
? { ...data, [key]: value }
|
||||||
|
: key,
|
||||||
|
);
|
||||||
},
|
},
|
||||||
get(url) {
|
get(url) {
|
||||||
submitted = { url, data };
|
submitted = { url, data };
|
||||||
@@ -79,22 +87,25 @@ function harness(filters, errors = {}) {
|
|||||||
return form;
|
return form;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
if (id === "@/pages/investment/shared") return { Frame: "main", card: "", button: "" };
|
if (id === '@/pages/investment/shared')
|
||||||
if (id === "@/components/funding-classification")
|
return { Frame: 'main', card: '', button: '' };
|
||||||
|
if (id === '@/components/funding-classification')
|
||||||
return {
|
return {
|
||||||
financialCategories: {
|
financialCategories: {
|
||||||
banking: "Banca",
|
banking: 'Banca',
|
||||||
insurance_intermediation: "Mediação de seguros",
|
insurance_intermediation: 'Mediação de seguros',
|
||||||
},
|
},
|
||||||
financialTypes: {
|
financialTypes: {
|
||||||
commercial_bank: "Banco comercial",
|
commercial_bank: 'Banco comercial',
|
||||||
broker: "Corretora",
|
broker: 'Corretora',
|
||||||
other: "Outro",
|
other: 'Outro',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
if (id === "@/components/investment-territory") return { TerritoryFields };
|
if (id === '@/components/investment-territory')
|
||||||
if (id === "@/components/funding-institution") return { InstitutionView: "article" };
|
return { TerritoryFields };
|
||||||
if (id === "./shared") return { windowLabels: {} };
|
if (id === '@/components/funding-institution')
|
||||||
|
return { InstitutionView: 'article' };
|
||||||
|
if (id === './shared') return { windowLabels: {} };
|
||||||
return require(id);
|
return require(id);
|
||||||
},
|
},
|
||||||
module,
|
module,
|
||||||
@@ -105,11 +116,11 @@ function harness(filters, errors = {}) {
|
|||||||
criteriaErrors: errors,
|
criteriaErrors: errors,
|
||||||
items: { data: [], links: [] },
|
items: { data: [], links: [] },
|
||||||
options: { sectors: [], territories: [] },
|
options: { sectors: [], territories: [] },
|
||||||
kinds: { institution: "Instituição", fund: "Fundo" },
|
kinds: { institution: 'Instituição', fund: 'Fundo' },
|
||||||
management: false,
|
management: false,
|
||||||
categoryTypes: {
|
categoryTypes: {
|
||||||
banking: ["commercial_bank"],
|
banking: ['commercial_bank'],
|
||||||
insurance_intermediation: ["broker"],
|
insurance_intermediation: ['broker'],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let tree;
|
let tree;
|
||||||
@@ -120,9 +131,11 @@ function harness(filters, errors = {}) {
|
|||||||
return tree;
|
return tree;
|
||||||
}
|
}
|
||||||
const select = (label) =>
|
const select = (label) =>
|
||||||
nodes(nodes(tree).find((n) => n.type === "label" && text(n).startsWith(label))).find(
|
nodes(
|
||||||
(n) => n.type === "select",
|
nodes(tree).find(
|
||||||
);
|
(n) => n.type === 'label' && text(n).startsWith(label),
|
||||||
|
),
|
||||||
|
).find((n) => n.type === 'select');
|
||||||
render();
|
render();
|
||||||
return {
|
return {
|
||||||
render,
|
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({
|
const h = harness({
|
||||||
category: "insurance_intermediation",
|
category: 'insurance_intermediation',
|
||||||
institution_type: "broker",
|
institution_type: 'broker',
|
||||||
sector: "7",
|
sector: '7',
|
||||||
need: "investment",
|
need: 'investment',
|
||||||
territory: "district-qa",
|
territory: 'district-qa',
|
||||||
});
|
});
|
||||||
h.select("Categoria da instituição").props.onChange({
|
h.select('Categoria da instituição').props.onChange({
|
||||||
target: { value: "banking" },
|
target: { value: 'banking' },
|
||||||
});
|
});
|
||||||
h.render();
|
h.render();
|
||||||
assert.equal(h.form().data.institution_type, "");
|
assert.equal(h.form().data.institution_type, '');
|
||||||
for (const [key, value] of Object.entries({
|
for (const [key, value] of Object.entries({
|
||||||
sector: "7",
|
sector: '7',
|
||||||
need: "investment",
|
need: 'investment',
|
||||||
territory: "district-qa",
|
territory: 'district-qa',
|
||||||
}))
|
}))
|
||||||
assert.equal(h.form().data[key], value);
|
assert.equal(h.form().data[key], value);
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
nodes(h.select("Tipo de instituição"))
|
nodes(h.select('Tipo de instituição'))
|
||||||
.filter((n) => n.type === "option")
|
.filter((n) => n.type === 'option')
|
||||||
.map((n) => n.props.value),
|
.map((n) => n.props.value),
|
||||||
["", "commercial_bank", "other"],
|
['', 'commercial_bank', 'other'],
|
||||||
);
|
);
|
||||||
assert.match(text(h.tree()), /tipo anterior não pertence/);
|
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.equal(results.props.open, false);
|
||||||
assert.match(text(results), /pesquisa anterior/);
|
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(
|
const h = harness(
|
||||||
{
|
{
|
||||||
kind: "fund",
|
kind: 'fund',
|
||||||
category: "banking",
|
category: 'banking',
|
||||||
institution_type: "commercial_bank",
|
institution_type: 'commercial_bank',
|
||||||
location_mode: "physical",
|
location_mode: 'physical',
|
||||||
province_id: "province-qa",
|
province_id: 'province-qa',
|
||||||
sector: "8",
|
sector: '8',
|
||||||
state: "closed",
|
state: 'closed',
|
||||||
certainty: "documented",
|
certainty: 'documented',
|
||||||
},
|
},
|
||||||
{ kind: ["Combinação incompatível."] },
|
{ kind: ['Combinação incompatível.'] },
|
||||||
);
|
);
|
||||||
assert.match(text(h.tree()), /A pesquisa não foi executada/);
|
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(
|
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();
|
action.props.onClick();
|
||||||
h.render();
|
h.render();
|
||||||
assert.equal(h.form().data.category, "");
|
assert.equal(h.form().data.category, '');
|
||||||
assert.equal(h.form().data.institution_type, "");
|
assert.equal(h.form().data.institution_type, '');
|
||||||
assert.equal(h.form().data.location_mode, "coverage");
|
assert.equal(h.form().data.location_mode, 'coverage');
|
||||||
for (const [key, value] of Object.entries({
|
for (const [key, value] of Object.entries({
|
||||||
kind: "fund",
|
kind: 'fund',
|
||||||
province_id: "province-qa",
|
province_id: 'province-qa',
|
||||||
sector: "8",
|
sector: '8',
|
||||||
state: "closed",
|
state: 'closed',
|
||||||
certainty: "documented",
|
certainty: 'documented',
|
||||||
}))
|
}))
|
||||||
assert.equal(h.form().data[key], value);
|
assert.equal(h.form().data[key], value);
|
||||||
nodes(h.tree())
|
nodes(h.tree())
|
||||||
.find((n) => n.type === "form")
|
.find((n) => n.type === 'form')
|
||||||
.props.onSubmit({ preventDefault() {} });
|
.props.onSubmit({ preventDefault() {} });
|
||||||
assert.equal(h.submitted().url, "/fundos");
|
assert.equal(h.submitted().url, '/fundos');
|
||||||
assert.equal(h.submitted().data.province_id, "province-qa");
|
assert.equal(h.submitted().data.province_id, 'province-qa');
|
||||||
assert.ok(h.territory(), "the catalogue consumes the common hierarchical location control");
|
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", () => {
|
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" });
|
const h = harness({ territory: 'district-qa', sector: '7' });
|
||||||
h.select("Localização a pesquisar").props.onChange({ target: { value: "physical" } });
|
h.select('Localização a pesquisar').props.onChange({
|
||||||
h.render();
|
target: { value: 'physical' },
|
||||||
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");
|
h.render();
|
||||||
assert.equal(harness({ location_mode: "physical" }).form().data.certainty, "documented");
|
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 { getSimulationSections } from '../../resources/js/lib/simulation-form.ts';
|
||||||
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.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', () => {
|
void test('idea journey reuses one dossier and exposes the six requested stages', () => {
|
||||||
const sections = getSimulationSections({
|
const sections = getSimulationSections({
|
||||||
purpose: 'simulate_only',
|
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