This commit is contained in:
@@ -10320,3 +10320,16 @@ Delta verificado: 3 testes HTTP/49 asserções e 1 teste/12 asserções para o e
|
||||
Utilização: no próprio dossier aberto, «Actividades existentes na localização» → pesquisar a actividade pelos primeiros três caracteres ou código → «Consultar e guardar análise agregada». A análise, classificação e histórico são privados e recuperáveis. A escolha não substitui a actividade do investimento. Sem correspondência previamente demonstrada, pede-se a escolha da classificação em vez de presumir equivalência entre taxonomias. Grupos pequenos, conflitos e falta de identidade/classificação conservam a explicação de cobertura insuficiente, nunca «não existem empresas».
|
||||
|
||||
Estado desta passagem: candidato verificado, instalação já autorizada e ainda não executada neste registo. Prosseguir pelo executor Git com capacidade, backup/restauro frescos, pin da revisão, activação apenas de `INVESTOR_PROTECTED_SUPPLY_ENABLED` e conferência do delta. Sem migrações, novos papéis, exposição individual ou produção. Ofertas, dashboard, correcção financeira e d3067050 preservados. Tradução permanece separada.
|
||||
|
||||
|
||||
## 17/11/2026 — GUIA-PASSO-20261117: preparação da instalação autorizada
|
||||
|
||||
Pedido expresso nesta conversa: disponibilizar o guia no Investemoz online. Candidato preparado sobre b60c231d, conservando as evoluções já instaladas de promotor, orçamento, demografia, análises sectoriais e agregados protegidos; não copiar as versões antigas das páginas locais. Introduz ajuda nas 19 etapas adaptativas permitidas e nas escolhas, declarações e revisão dos dados. Instrução, exemplo e finalidade específicos; abertura automática, Seguinte/Voltar/Concluir, fecho/reabertura, Escape e foco recuperado. A sequência segue a aplicabilidade existente. Preferência facultativa por utilizador/percurso no navegador, sem guardar dados de formulários. Não altera estados, cálculos, permissões, submissões ou dados.
|
||||
|
||||
Verificações locais do candidato actualizado: 32 testes focados aprovados; tipos e lint focado aprovados. Reutiliza o ensaio sintético do componente real de GUIA-PASSO-20261117: avanço/regresso, conservação de campos, fecho, reabertura, preferência após recarregar, Escape e orientação ao abrir etapa. Não repete provas aceites não afectadas. Cobertura parcial de MASTER-e1169a77-0101 e MASTER-6e51cfcd-0023, sem encerrar os restantes critérios.
|
||||
|
||||
Destino confirmado pelo executor existente: https://teste-investidor.tempo.co.mz, main, revisão b60c231ddcddb77514491a4ac185b37eab98f6f5. Instalação via Git, com CI normal, backup/restauro fresco e reversão de release preservando dados posteriores. Sem migrations, importações, alterações ao executor ou à configuração. O resultado da instalação deve ser confirmado em /build/revision.json e registado em recibo posterior; este registo não declara instalação concluída.
|
||||
|
||||
Pré-instalação: backup fresco em /var/backups/investmoz-guide-20261117/backup, restauro isolado integral de 195 tabelas e 417 ficheiros conferido; fontes do executor e configuração preservadas. Verificação global npm run check detecta formatação em 65 ficheiros anteriores não alterados por este lote; lint focado e tipos aprovados. Não foram reformulados ficheiros não relacionados para corrigir essa dívida. O executor mantém os seus testes normais sem dispensa.
|
||||
|
||||
Regressão final do candidato: 1 977 testes frontend aprovados após compilação QA; tipos e lint dos ficheiros afectados aprovados. Actualizados exclusivamente os mocks de importação/autenticação dos ensaios existentes para manter as verificações anteriores com o novo componente. O registo demográfico anterior conserva a referência e4735424 e um manifesto que já não coincide com b60c231d; é uma condição anterior a este incremento, preservada sem activação/revalidação por este lote.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,292 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { CircleHelp } from 'lucide-react';
|
||||
import {
|
||||
helpPreferenceKey,
|
||||
readHelpPreference,
|
||||
type InvestmentHelp,
|
||||
} from '@/lib/investment-step-help';
|
||||
|
||||
type GuideState = {
|
||||
steps: InvestmentHelp[];
|
||||
active: string | null;
|
||||
automatic: boolean;
|
||||
choose: (code: string | null, reveal?: boolean) => void;
|
||||
};
|
||||
const GuideContext = createContext<GuideState | null>(null);
|
||||
const helpButton =
|
||||
'inline-flex min-h-11 items-center justify-center gap-2 rounded-lg border px-3 py-2 text-sm font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700';
|
||||
|
||||
export function InvestmentHelpGuide({
|
||||
steps,
|
||||
user,
|
||||
flow,
|
||||
initialCode,
|
||||
children,
|
||||
}: {
|
||||
steps: InvestmentHelp[];
|
||||
user: string | number;
|
||||
flow: string;
|
||||
initialCode?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const [active, setActive] = useState<string | null>(null);
|
||||
const [automatic, setAutomatic] = useState(true);
|
||||
const paused = useRef(false);
|
||||
const key = helpPreferenceKey(user, flow);
|
||||
const firstCode = steps.some((step) => step.code === initialCode)
|
||||
? initialCode
|
||||
: steps[0]?.code;
|
||||
|
||||
useEffect(() => {
|
||||
let preference = readHelpPreference(null);
|
||||
try {
|
||||
preference = readHelpPreference(window.localStorage.getItem(key));
|
||||
} catch {
|
||||
/* Help also works without browser storage. */
|
||||
}
|
||||
setAutomatic(preference.automatic);
|
||||
setActive(
|
||||
preference.automatic && !preference.seen
|
||||
? (firstCode ?? null)
|
||||
: null,
|
||||
);
|
||||
paused.current = false;
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
key,
|
||||
JSON.stringify({ ...preference, seen: true }),
|
||||
);
|
||||
} catch {
|
||||
/* Optional preference only. */
|
||||
}
|
||||
}, [key]); // A new applicable step does not restart a dismissed guide.
|
||||
|
||||
const visibleActive = steps.some((step) => step.code === active)
|
||||
? active
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (!visibleActive || !root.current) return;
|
||||
const target = Array.from(
|
||||
root.current.querySelectorAll<HTMLElement>(
|
||||
'[data-investment-step]',
|
||||
),
|
||||
).find((node) => node.dataset.investmentStep === visibleActive);
|
||||
let ancestor: HTMLElement | null = target ?? null;
|
||||
while (ancestor && ancestor !== root.current) {
|
||||
if (ancestor.tagName === 'DETAILS')
|
||||
(ancestor as HTMLDetailsElement).open = true;
|
||||
ancestor = ancestor.parentElement;
|
||||
}
|
||||
}, [visibleActive]);
|
||||
|
||||
function choose(code: string | null, reveal = false) {
|
||||
paused.current = code === null;
|
||||
if (code === null && visibleActive) {
|
||||
const panel = Array.from(
|
||||
root.current?.querySelectorAll<HTMLElement>(
|
||||
'[data-help-panel]',
|
||||
) ?? [],
|
||||
).find((node) => node.dataset.helpPanel === visibleActive);
|
||||
panel?.parentElement
|
||||
?.querySelector<HTMLButtonElement>('button')
|
||||
?.focus({ preventScroll: true });
|
||||
}
|
||||
setActive(code);
|
||||
if (code && reveal) {
|
||||
// Wait for the selected inline explanation to render before focusing it.
|
||||
requestAnimationFrame(() => {
|
||||
const target = Array.from(
|
||||
root.current?.querySelectorAll<HTMLElement>(
|
||||
'[data-help-panel]',
|
||||
) ?? [],
|
||||
).find((node) => node.dataset.helpPanel === code);
|
||||
target?.scrollIntoView({ block: 'nearest' });
|
||||
target?.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function orient(target: EventTarget) {
|
||||
if (
|
||||
!automatic ||
|
||||
paused.current ||
|
||||
!(target instanceof Element) ||
|
||||
target.closest('[data-help-controls]')
|
||||
)
|
||||
return;
|
||||
const code = target.closest<HTMLElement>('[data-investment-step]')
|
||||
?.dataset.investmentStep;
|
||||
if (code && steps.some((step) => step.code === code)) setActive(code);
|
||||
}
|
||||
|
||||
return (
|
||||
<GuideContext.Provider
|
||||
value={{ steps, active: visibleActive, automatic, choose }}
|
||||
>
|
||||
<div
|
||||
ref={root}
|
||||
className="space-y-5"
|
||||
onFocusCapture={(event) => orient(event.target)}
|
||||
onClickCapture={(event) => orient(event.target)}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key === 'Escape' &&
|
||||
visibleActive &&
|
||||
(event.target as Element).closest('[data-help-panel]')
|
||||
) {
|
||||
event.preventDefault();
|
||||
choose(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<section
|
||||
aria-label="Guia de ajuda do Investemoz"
|
||||
data-help-controls
|
||||
className="flex flex-wrap items-center gap-3 rounded-xl border border-emerald-700/30 bg-emerald-50 p-4 text-slate-900 dark:bg-emerald-950 dark:text-slate-100"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-semibold">Guia do Investemoz</p>
|
||||
<p className="text-sm">
|
||||
Consulte o que fazer, veja um exemplo e avance ao
|
||||
seu ritmo.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
disabled={!steps.length}
|
||||
onClick={() =>
|
||||
choose(visibleActive ?? firstCode ?? null, true)
|
||||
}
|
||||
>
|
||||
Ver guia passo a passo
|
||||
</button>
|
||||
<label className="flex min-h-11 cursor-pointer items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={automatic}
|
||||
onChange={(event) => {
|
||||
const enabled = event.target.checked;
|
||||
setAutomatic(enabled);
|
||||
paused.current = !enabled;
|
||||
setActive(enabled ? (firstCode ?? null) : null);
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
key,
|
||||
JSON.stringify({
|
||||
automatic: enabled,
|
||||
seen: true,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
/* Optional preference only. */
|
||||
}
|
||||
}}
|
||||
/>
|
||||
Orientações automáticas
|
||||
</label>
|
||||
</section>
|
||||
{children}
|
||||
</div>
|
||||
</GuideContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function HelpAtStep({ code }: { code: string }) {
|
||||
const guide = useContext(GuideContext);
|
||||
const id = useId();
|
||||
const index = guide?.steps.findIndex((step) => step.code === code) ?? -1;
|
||||
if (!guide || index < 0) return null;
|
||||
const step = guide.steps[index];
|
||||
const open = guide.active === code;
|
||||
return (
|
||||
<div data-help-controls className="my-3">
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
aria-expanded={open}
|
||||
aria-controls={id}
|
||||
aria-label={`Ajuda neste passo: ${step.title}`}
|
||||
onClick={() => guide.choose(open ? null : code)}
|
||||
>
|
||||
<CircleHelp className="size-4 shrink-0" aria-hidden="true" />{' '}
|
||||
Ajuda neste passo
|
||||
</button>
|
||||
{open && (
|
||||
<section
|
||||
id={id}
|
||||
data-help-panel={code}
|
||||
tabIndex={-1}
|
||||
aria-labelledby={`${id}-title`}
|
||||
className="mt-3 space-y-3 rounded-xl border-2 border-emerald-700 bg-emerald-50 p-4 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 dark:bg-emerald-950 dark:text-slate-100"
|
||||
>
|
||||
<p className="text-sm" role="status">
|
||||
Ajuda · Passo {index + 1} de {guide.steps.length}
|
||||
</p>
|
||||
<h3 id={`${id}-title`} className="font-semibold">
|
||||
{step.title}
|
||||
</h3>
|
||||
<p>
|
||||
<strong>O que fazer:</strong> {step.instruction}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Exemplo:</strong> {step.example}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Para que serve:</strong> {step.purpose}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
disabled={index === 0}
|
||||
onClick={() =>
|
||||
guide.choose(guide.steps[index - 1].code, true)
|
||||
}
|
||||
>
|
||||
Voltar
|
||||
</button>
|
||||
{index < guide.steps.length - 1 ? (
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
onClick={() =>
|
||||
guide.choose(
|
||||
guide.steps[index + 1].code,
|
||||
true,
|
||||
)
|
||||
}
|
||||
>
|
||||
Seguinte
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
onClick={() => guide.choose(null)}
|
||||
>
|
||||
Concluir guia
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={helpButton}
|
||||
onClick={() => guide.choose(null)}
|
||||
>
|
||||
Fechar guia
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
export type InvestmentHelp = {
|
||||
code: string;
|
||||
title: string;
|
||||
instruction: string;
|
||||
example: string;
|
||||
purpose: string;
|
||||
};
|
||||
|
||||
// Orientation only: the existing path continues to determine applicability and permissions.
|
||||
const stageHelp: Record<string, [string, string, string]> = {
|
||||
S01: [
|
||||
'Descreva a ideia, o produto ou serviço e os clientes que pretende servir.',
|
||||
'Produzir hortícolas para fornecer mercados locais.',
|
||||
'Definir o investimento que irá preparar nas etapas seguintes.',
|
||||
],
|
||||
S02: [
|
||||
'Reúna informação sobre o mercado, os recursos necessários e os principais riscos. Consulte as ferramentas disponíveis no dossier.',
|
||||
'Compare procura, fornecedores, localização e custos previstos.',
|
||||
'Identificar o que já sabe e a informação que ainda precisa de obter.',
|
||||
],
|
||||
S03: [
|
||||
'Compare as receitas e os custos estimados e registe a sua conclusão sobre a viabilidade.',
|
||||
'Teste como uma redução das vendas afecta o resultado estimado.',
|
||||
'Apoiar a sua decisão com pressupostos explícitos. Uma simulação é uma estimativa.',
|
||||
],
|
||||
S04: [
|
||||
'Organize os recursos, os participantes e o plano de realização do investimento.',
|
||||
'Indique quem fará o quê e quais os recursos a mobilizar.',
|
||||
'Transformar a ideia num plano de preparação e execução.',
|
||||
],
|
||||
S05: [
|
||||
'Confira a situação da entidade e os elementos de constituição e registo aplicáveis. Reutilize os dados já disponíveis.',
|
||||
'Se a empresa já existe, confira os seus dados antes de os voltar a preencher.',
|
||||
'Preparar a identificação da entidade que realizará o investimento.',
|
||||
],
|
||||
S06: [
|
||||
'Reúna os dados e associe os documentos indicados para este investimento. Reveja o que ainda falta.',
|
||||
'Associe um documento já disponível no dossier ao requisito correspondente.',
|
||||
'Organizar o dossier antes de preparar uma entrega.',
|
||||
],
|
||||
S07: [
|
||||
'Confira o destinatário e os requisitos da entrega aplicável. Se já entregou, registe a referência e a evidência disponível.',
|
||||
'Registe a data e o protocolo de uma entrega efectivamente realizada.',
|
||||
'Acompanhar a entrega sem confundir preparação com submissão.',
|
||||
],
|
||||
S08: [
|
||||
'Consulte as licenças indicadas para a actividade e localização. Prepare os elementos em falta e registe os actos já documentados.',
|
||||
'Identifique a entidade competente e associe a licença recebida, quando disponível.',
|
||||
'Acompanhar o licenciamento aplicável ao seu projecto.',
|
||||
],
|
||||
S09: [
|
||||
'Indique se o investimento necessita de terra e explique a situação conhecida.',
|
||||
'Indique se utilizará instalações existentes ou se precisa de uma nova área.',
|
||||
'Adaptar a preparação da terra às necessidades do investimento.',
|
||||
],
|
||||
S10: [
|
||||
'Reúna a informação da localização e os documentos relativos à regularização da terra indicados no percurso.',
|
||||
'Associe o documento disponível e identifique a área a que se refere.',
|
||||
'Organizar a preparação da terra sem presumir direitos ainda não documentados.',
|
||||
],
|
||||
S11: [
|
||||
'Confira a regularização aplicável e registe o resultado com o respectivo fundamento.',
|
||||
'Registe a referência e a data do documento que comprova a situação declarada.',
|
||||
'Distinguir a preparação da confirmação documental da regularização.',
|
||||
],
|
||||
S12: [
|
||||
'Compare os recursos próprios com o investimento previsto e indique se necessita de financiamento externo.',
|
||||
'Separe o capital disponível do montante que ainda precisa de mobilizar.',
|
||||
'Dimensionar a necessidade de financiamento do projecto.',
|
||||
],
|
||||
S13: [
|
||||
'Prepare a informação pedida pelo potencial financiador e registe os pontos de negociação.',
|
||||
'Organize projecções, documentos solicitados e condições em discussão.',
|
||||
'Acompanhar a análise e a negociação do financiamento.',
|
||||
],
|
||||
S14: [
|
||||
'Registe a decisão recebida do financiador e associe a evidência disponível.',
|
||||
'Indique a referência da comunicação recebida e as condições nela apresentadas.',
|
||||
'Conservar a decisão real, sem tratar uma candidatura como aprovação.',
|
||||
],
|
||||
S15: [
|
||||
'Confira as condições de fecho e acompanhe os desembolsos efectivamente documentados.',
|
||||
'Registe a referência e a data de uma disponibilização de fundos confirmada.',
|
||||
'Acompanhar a concretização do financiamento e as condições pendentes.',
|
||||
],
|
||||
S16: [
|
||||
'Organize as actividades de implementação e acompanhe os recursos e os prazos.',
|
||||
'Crie uma tarefa para instalar equipamento com responsável e data prevista.',
|
||||
'Acompanhar a execução do investimento.',
|
||||
],
|
||||
S17: [
|
||||
'Prepare as inspecções e os testes aplicáveis e reúna os documentos para a operação.',
|
||||
'Associe um relatório de inspecção ou a licença recebida à etapa correspondente.',
|
||||
'Identificar o que falta antes do início de operação.',
|
||||
],
|
||||
S18: [
|
||||
'Confira as condições indicadas no percurso e registe o início de operação quando estiver documentado.',
|
||||
'Indique a data efectiva de início e a respectiva referência documental.',
|
||||
'Distinguir a previsão de arranque do início efectivo da actividade.',
|
||||
],
|
||||
S19: [
|
||||
'Actualize o acompanhamento do projecto e reveja as tarefas e os documentos que necessitam de atenção.',
|
||||
'Registe uma tarefa de acompanhamento com responsável e prazo.',
|
||||
'Manter o dossier útil ao longo da operação.',
|
||||
],
|
||||
};
|
||||
|
||||
export function investmentStageHelp(
|
||||
code: string,
|
||||
title: string,
|
||||
): InvestmentHelp {
|
||||
const [instruction, example, purpose] = stageHelp[code] ?? [
|
||||
'Consulte as indicações desta etapa, confira os dados disponíveis e complete o que estiver em falta.',
|
||||
'Registe uma referência documental que sustente a informação preenchida.',
|
||||
'Acompanhar a preparação desta etapa no seu dossier.',
|
||||
];
|
||||
return { code, title, instruction, example, purpose };
|
||||
}
|
||||
|
||||
export const preparationHelp: InvestmentHelp[] = [
|
||||
{
|
||||
code: 'help-choices',
|
||||
title: 'Escolhas e dados do investimento',
|
||||
instruction:
|
||||
'Escolha a oportunidade, o sector e a localização que correspondem ao seu investimento. Confira os dados já recuperados.',
|
||||
example:
|
||||
'Seleccione uma oportunidade existente ou indique o sector e a localização da sua ideia.',
|
||||
purpose: 'Adaptar o percurso ao investimento que pretende realizar.',
|
||||
},
|
||||
{
|
||||
code: 'help-declarations',
|
||||
title: 'Declarações deste investimento',
|
||||
instruction:
|
||||
'Complete apenas as declarações conhecidas e confira os documentos associados. Use as opções apresentadas conforme a sua situação.',
|
||||
example:
|
||||
'Indique a moeda do projecto e confira a situação da entidade.',
|
||||
purpose:
|
||||
'Preparar os dados do processo e identificar o que ainda precisa de esclarecimento.',
|
||||
},
|
||||
{
|
||||
code: 'help-review',
|
||||
title: 'Revisão e confirmação',
|
||||
instruction:
|
||||
'Clique em “Rever dados antes de guardar”. Compare as alterações apresentadas e confirme apenas quando corresponderem ao que pretende.',
|
||||
example:
|
||||
'Ao mudar a localização, confira os dados alterados e as etapas que precisam de revisão.',
|
||||
purpose: 'Permitir que avalie o impacto antes de guardar as escolhas.',
|
||||
},
|
||||
];
|
||||
|
||||
export function helpPreferenceKey(user: string | number, flow: string): string {
|
||||
return `investemoz:step-help:v1:${encodeURIComponent(String(user))}:${encodeURIComponent(flow)}`;
|
||||
}
|
||||
|
||||
export function readHelpPreference(value: string | null): {
|
||||
automatic: boolean;
|
||||
seen: boolean;
|
||||
} {
|
||||
try {
|
||||
const parsed = JSON.parse(value ?? 'null');
|
||||
return {
|
||||
automatic: parsed?.automatic !== false,
|
||||
seen: parsed?.seen === true,
|
||||
};
|
||||
} catch {
|
||||
return { automatic: true, seen: false };
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,88 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import {
|
||||
investmentStageHelp,
|
||||
preparationHelp,
|
||||
helpPreferenceKey,
|
||||
readHelpPreference,
|
||||
} from '../../resources/js/lib/investment-step-help.ts';
|
||||
|
||||
test('each of the 19 existing stages has specific orientation, an example and a purpose', () => {
|
||||
const instructions = new Set();
|
||||
for (let i = 1; i <= 19; i++) {
|
||||
const code = `S${String(i).padStart(2, '0')}`;
|
||||
const help = investmentStageHelp(code, `Título ${i}`);
|
||||
assert.equal(help.code, code);
|
||||
assert.equal(help.title, `Título ${i}`);
|
||||
assert.ok(help.instruction.length > 30);
|
||||
assert.ok(help.example.length > 25);
|
||||
assert.ok(help.purpose.length > 25);
|
||||
instructions.add(help.instruction);
|
||||
}
|
||||
assert.equal(instructions.size, 19);
|
||||
assert.equal(
|
||||
investmentStageHelp('future-stage', 'Nova etapa').title,
|
||||
'Nova etapa',
|
||||
);
|
||||
});
|
||||
|
||||
test('preparation guidance preserves the review before confirmation sequence', () => {
|
||||
assert.deepEqual(
|
||||
preparationHelp.map((step) => step.code),
|
||||
['help-choices', 'help-declarations', 'help-review'],
|
||||
);
|
||||
assert.match(preparationHelp[2].instruction, /Compare.*confirme/);
|
||||
});
|
||||
|
||||
test('preferences default safely, survive malformed storage and remain separate per user and flow', () => {
|
||||
assert.deepEqual(readHelpPreference(null), {
|
||||
automatic: true,
|
||||
seen: false,
|
||||
});
|
||||
assert.deepEqual(readHelpPreference('{bad'), {
|
||||
automatic: true,
|
||||
seen: false,
|
||||
});
|
||||
assert.deepEqual(readHelpPreference('{"automatic":false,"seen":true}'), {
|
||||
automatic: false,
|
||||
seen: true,
|
||||
});
|
||||
assert.deepEqual(readHelpPreference('{"automatic":true,"seen":true}'), {
|
||||
automatic: true,
|
||||
seen: true,
|
||||
});
|
||||
assert.notEqual(helpPreferenceKey(1, 'path'), helpPreferenceKey(2, 'path'));
|
||||
assert.notEqual(
|
||||
helpPreferenceKey(1, 'path'),
|
||||
helpPreferenceKey(1, 'preparation'),
|
||||
);
|
||||
assert.notEqual(
|
||||
helpPreferenceKey('a:b', 'c'),
|
||||
helpPreferenceKey('a', 'b:c'),
|
||||
);
|
||||
});
|
||||
|
||||
test('dossier help follows only the steps already permitted by the adaptive path', () => {
|
||||
const page = readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/pages/investor-path/show.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(
|
||||
page,
|
||||
/steps=\{path\.steps\s*\.filter\(\(step\) => step\.preparation_allowed\)/,
|
||||
);
|
||||
assert.match(page, /<HelpAtStep code=\{step.code\}/);
|
||||
const component = readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/investment-step-help.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
assert.doesNotMatch(component, /router\.|fetch\(|\.submit\(|\.post\(/);
|
||||
assert.doesNotMatch(component, /location\.(assign|reload)|window\.history/);
|
||||
});
|
||||
@@ -23,7 +23,9 @@ function load(path, mocks = {}, exportName = 'default', extra = '') {
|
||||
compileFunction(output + extra, ['require', 'module', 'exports'])(
|
||||
(name) =>
|
||||
mocks[name] ??
|
||||
(name.startsWith('@/') ? { default: () => null } : require(name)),
|
||||
(name === '@/components/investment-step-help'
|
||||
? { HelpAtStep: () => null, InvestmentHelpGuide: ({ children }) => children }
|
||||
: name.startsWith('@/') ? { default: () => null } : require(name)),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
@@ -508,7 +510,7 @@ function contextPreviewHarness(overrides = {}) {
|
||||
const pending = [];
|
||||
const Editor = load('../../resources/js/pages/investor-path/context.tsx', {
|
||||
react: hooks,
|
||||
'@inertiajs/react': { Link: () => null, router: {} },
|
||||
'@inertiajs/react': { usePage: () => ({ props: { auth: { user: { id: 1 } } } }), Link: () => null, router: {} },
|
||||
'@/components/navigation-context': {
|
||||
useNavigationContext: () => ({ refresh() {} }),
|
||||
},
|
||||
|
||||
@@ -1,31 +1,35 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import { compileFunction } from "node:vm";
|
||||
import { createRequire } from "node:module";
|
||||
import ts from "typescript";
|
||||
import React from "react";
|
||||
import { revealPathStage } from "../../resources/js/lib/investor-path-stage.ts";
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import { revealPathStage } from '../../resources/js/lib/investor-path-stage.ts';
|
||||
import { investmentStageHelp } from '../../resources/js/lib/investment-step-help.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const flatten = (node) =>
|
||||
Array.isArray(node)
|
||||
? node.flatMap(flatten)
|
||||
: node && typeof node === "object"
|
||||
: node && typeof node === 'object'
|
||||
? [node, ...flatten(node.props?.children)]
|
||||
: [];
|
||||
const text = (node) =>
|
||||
Array.isArray(node)
|
||||
? node.map(text).join("")
|
||||
: node && typeof node === "object"
|
||||
? node.map(text).join('')
|
||||
: node && typeof node === 'object'
|
||||
? text(node.props?.children)
|
||||
: String(node ?? "");
|
||||
: String(node ?? '');
|
||||
function harness(overrides = {}, react = React) {
|
||||
const requests = [];
|
||||
let form;
|
||||
const module = { exports: {} };
|
||||
const source = fs.readFileSync(
|
||||
new URL("../../resources/js/pages/investor-path/show.tsx", import.meta.url),
|
||||
"utf8",
|
||||
new URL(
|
||||
'../../resources/js/pages/investor-path/show.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
@@ -33,13 +37,19 @@ function harness(overrides = {}, react = React) {
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
compileFunction(code + "\nmodule.exports.Stage = Stage;", ["require", "module", "exports"])(
|
||||
compileFunction(code + '\nmodule.exports.Stage = Stage;', [
|
||||
'require',
|
||||
'module',
|
||||
'exports',
|
||||
])(
|
||||
(name) =>
|
||||
name === "react"
|
||||
name === 'react'
|
||||
? react
|
||||
: name === "@inertiajs/react"
|
||||
: name === '@inertiajs/react'
|
||||
? {
|
||||
usePage: () => ({ props: { auth: { user: { id: 1 } }, flash: {} } }),
|
||||
usePage: () => ({
|
||||
props: { auth: { user: { id: 1 } }, flash: {} },
|
||||
}),
|
||||
useForm(initial) {
|
||||
form ??= {
|
||||
data: initial,
|
||||
@@ -52,115 +62,145 @@ function harness(overrides = {}, react = React) {
|
||||
this.convert = fn;
|
||||
},
|
||||
post(url, options) {
|
||||
requests.push({ url, options, data: this.convert(this.data) });
|
||||
requests.push({
|
||||
url,
|
||||
options,
|
||||
data: this.convert(this.data),
|
||||
});
|
||||
},
|
||||
};
|
||||
return form;
|
||||
},
|
||||
}
|
||||
: name === "@/lib/investor-path"
|
||||
? { pathStates: { preparing: "Em preparação" } }
|
||||
: name === "@/lib/operation-key" ? { createOperationKey: () => 'qa-key' }
|
||||
: name === "@/lib/investor-path-stage" ? { revealPathStage }
|
||||
: name === "@/components/proactive-investment" ? { proactiveView: () => null }
|
||||
: name.startsWith("@/")
|
||||
? {}
|
||||
: require(name),
|
||||
: name === '@/lib/investor-path'
|
||||
? { pathStates: { preparing: 'Em preparação' } }
|
||||
: name === '@/lib/operation-key'
|
||||
? { createOperationKey: () => 'qa-key' }
|
||||
: name === '@/lib/investor-path-stage'
|
||||
? { revealPathStage }
|
||||
: name === '@/lib/investment-step-help'
|
||||
? { investmentStageHelp }
|
||||
: name === '@/components/proactive-investment'
|
||||
? { proactiveView: () => null }
|
||||
: name.startsWith('@/')
|
||||
? {}
|
||||
: require(name),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const path = {
|
||||
case: { id: "dossier-qa", version: 7 },
|
||||
context_opportunity: "opportunity:42",
|
||||
case: { id: 'dossier-qa', version: 7 },
|
||||
context_opportunity: 'opportunity:42',
|
||||
investment_context: { revision: 3 },
|
||||
canWrite: true,
|
||||
canReview: false,
|
||||
steps: [],
|
||||
next: { code: "S02" },
|
||||
documents: [{ document_id: "doc-qa", file_name: "Prova QA", malware_scan_status: "clean" }],
|
||||
next: { code: 'S02' },
|
||||
documents: [
|
||||
{
|
||||
document_id: 'doc-qa',
|
||||
file_name: 'Prova QA',
|
||||
malware_scan_status: 'clean',
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
const step = {
|
||||
code: "S08",
|
||||
title: "Licenciamento prévio",
|
||||
state: "preparing",
|
||||
code: 'S08',
|
||||
title: 'Licenciamento prévio',
|
||||
state: 'preparing',
|
||||
preparation_allowed: true,
|
||||
action_gaps: {},
|
||||
detail: {},
|
||||
source_paragraph: 8,
|
||||
};
|
||||
return {
|
||||
render: (changes = {}) => module.exports.Stage({ step: { ...step, ...changes }, path }),
|
||||
render: (changes = {}) =>
|
||||
module.exports.Stage({ step: { ...step, ...changes }, path }),
|
||||
renderPage: () => module.exports.default(path),
|
||||
requests,
|
||||
form: () => form,
|
||||
path,
|
||||
};
|
||||
}
|
||||
test("S08 has one current state, a visible primary save action and no nested disclosure", () => {
|
||||
test('S08 has one current state, a visible primary save action and no nested disclosure', () => {
|
||||
const h = harness();
|
||||
const tree = h.render();
|
||||
const nodes = flatten(tree);
|
||||
assert.equal(tree.type, "section");
|
||||
assert.equal(nodes.filter((n) => n.type === "details").length, 0);
|
||||
assert.equal(tree.type, 'section');
|
||||
assert.equal(nodes.filter((n) => n.type === 'details').length, 0);
|
||||
assert.equal(
|
||||
nodes.filter((n) => ["h3", "p"].includes(n.type) && text(n).includes("Em preparação"))
|
||||
.length,
|
||||
nodes.filter(
|
||||
(n) =>
|
||||
['h3', 'p'].includes(n.type) &&
|
||||
text(n).includes('Em preparação'),
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
assert.equal(nodes.find((n) => n.type === "button").props.disabled, false);
|
||||
assert.match(nodes.find((n) => n.type === "button").props.className, /bg-emerald/);
|
||||
assert.equal(nodes.filter((n) => n.type === "form").length, 1);
|
||||
assert.equal(nodes.find((n) => n.type === 'button').props.disabled, false);
|
||||
assert.match(
|
||||
nodes.find((n) => n.type === 'button').props.className,
|
||||
/bg-emerald/,
|
||||
);
|
||||
assert.equal(nodes.filter((n) => n.type === 'form').length, 1);
|
||||
assert.equal(tree.props.tabIndex, -1);
|
||||
});
|
||||
test("editing and saving retain context, current version, fields and existing endpoint", () => {
|
||||
test('editing and saving retain context, current version, fields and existing endpoint', () => {
|
||||
const h = harness({ canReview: true });
|
||||
let tree = h.render();
|
||||
const form = h.form();
|
||||
Object.assign(form.data, {
|
||||
reason: "Fundamento deliberado",
|
||||
reference: "REF-QA",
|
||||
authority: "Entidade QA",
|
||||
document_id: "doc-qa",
|
||||
decision_date: "2026-11-10",
|
||||
reason: 'Fundamento deliberado',
|
||||
reference: 'REF-QA',
|
||||
authority: 'Entidade QA',
|
||||
document_id: 'doc-qa',
|
||||
decision_date: '2026-11-10',
|
||||
context_reviewed: true,
|
||||
});
|
||||
h.path.case.version = 8;
|
||||
tree = h.render();
|
||||
assert.equal(form.data.reason, "Fundamento deliberado");
|
||||
assert.equal(flatten(tree).filter((n) => n.type === "input").length, 3);
|
||||
assert.equal(form.data.reason, 'Fundamento deliberado');
|
||||
assert.equal(flatten(tree).filter((n) => n.type === 'input').length, 3);
|
||||
flatten(tree)
|
||||
.find((n) => n.type === "form")
|
||||
.find((n) => n.type === 'form')
|
||||
.props.onSubmit({ preventDefault() {} });
|
||||
assert.deepEqual(h.requests, [
|
||||
{
|
||||
url: "/investimentos/dossier-qa/etapas/S08",
|
||||
url: '/investimentos/dossier-qa/etapas/S08',
|
||||
options: { preserveScroll: true },
|
||||
data: { ...form.data, version: 8 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
test("read-only and inapplicable stages do not acquire write controls; errors and processing remain visible", () => {
|
||||
test('read-only and inapplicable stages do not acquire write controls; errors and processing remain visible', () => {
|
||||
const read = harness({ canWrite: false, canReview: false });
|
||||
assert.equal(flatten(read.render()).filter((n) => n.type === "form").length, 0);
|
||||
assert.equal(
|
||||
flatten(read.render()).filter((n) => n.type === 'form').length,
|
||||
0,
|
||||
);
|
||||
const h = harness();
|
||||
h.render();
|
||||
assert.equal(
|
||||
flatten(h.render({ preparation_allowed: false })).filter((n) => n.type === "form").length,
|
||||
flatten(h.render({ preparation_allowed: false })).filter(
|
||||
(n) => n.type === 'form',
|
||||
).length,
|
||||
0,
|
||||
);
|
||||
h.form().processing = true;
|
||||
h.form().errors = { reason: "Conflito de versão" };
|
||||
h.form().errors = { reason: 'Conflito de versão' };
|
||||
const nodes = flatten(h.render());
|
||||
assert.equal(nodes.find((n) => n.type === "button").props.disabled, true);
|
||||
assert.equal(text(nodes.find((n) => n.props.role === "alert")), "Conflito de versão");
|
||||
assert.equal(nodes.find((n) => n.type === 'button').props.disabled, true);
|
||||
assert.equal(
|
||||
text(nodes.find((n) => n.props.role === 'alert')),
|
||||
'Conflito de versão',
|
||||
);
|
||||
});
|
||||
test("other stages keep their existing disclosure and reviewer fields/action choices", () => {
|
||||
test('other stages keep their existing disclosure and reviewer fields/action choices', () => {
|
||||
const h = harness({ canWrite: false, canReview: true });
|
||||
const tree = h.render({ code: "S07" });
|
||||
assert.equal(tree.type, "details");
|
||||
assert.equal(flatten(tree).filter((n) => n.type === "details").length, 3);
|
||||
assert.equal(h.form().data.action, "review");
|
||||
const tree = h.render({ code: 'S07' });
|
||||
assert.equal(tree.type, 'details');
|
||||
assert.equal(flatten(tree).filter((n) => n.type === 'details').length, 3);
|
||||
assert.equal(h.form().data.action, 'review');
|
||||
assert.match(text(tree), /Registar acto externo/);
|
||||
assert.match(text(tree), /Documento de suporte/);
|
||||
});
|
||||
@@ -168,46 +208,48 @@ function targetFixture() {
|
||||
const calls = [];
|
||||
const root = {
|
||||
contains: (node) => node === target,
|
||||
ownerDocument: { getElementById: (id) => (id === "S08" ? target : null) },
|
||||
ownerDocument: {
|
||||
getElementById: (id) => (id === 'S08' ? target : null),
|
||||
},
|
||||
};
|
||||
const phase = { tagName: "DETAILS", open: false, parentElement: root };
|
||||
const phase = { tagName: 'DETAILS', open: false, parentElement: root };
|
||||
const target = {
|
||||
tagName: "SECTION",
|
||||
tagName: 'SECTION',
|
||||
parentElement: phase,
|
||||
scrollIntoView: (options) => calls.push(["scroll", options]),
|
||||
focus: (options) => calls.push(["focus", options]),
|
||||
scrollIntoView: (options) => calls.push(['scroll', options]),
|
||||
focus: (options) => calls.push(['focus', options]),
|
||||
};
|
||||
return { root, phase, target, calls };
|
||||
}
|
||||
test("deep-link opens the containing phase and focuses S08 without navigation or changing fields", () => {
|
||||
test('deep-link opens the containing phase and focuses S08 without navigation or changing fields', () => {
|
||||
const f = targetFixture();
|
||||
assert.equal(revealPathStage(f.root, "#S08", ["S02", "S08"]), true);
|
||||
assert.equal(revealPathStage(f.root, '#S08', ['S02', 'S08']), true);
|
||||
assert.equal(f.phase.open, true);
|
||||
assert.deepEqual(f.calls, [
|
||||
["scroll", { block: "start" }],
|
||||
["focus", { preventScroll: true }],
|
||||
['scroll', { block: 'start' }],
|
||||
['focus', { preventScroll: true }],
|
||||
]);
|
||||
f.phase.open = false;
|
||||
assert.equal(revealPathStage(f.root, "#S08", ["S08"]), true);
|
||||
assert.equal(revealPathStage(f.root, '#S08', ['S08']), true);
|
||||
assert.equal(f.phase.open, true);
|
||||
});
|
||||
test("unknown, absent or out-of-scope hash targets have no effect", () => {
|
||||
test('unknown, absent or out-of-scope hash targets have no effect', () => {
|
||||
const f = targetFixture();
|
||||
for (const hash of ["", "#unknown", "#S08%22", "#S07"])
|
||||
assert.equal(revealPathStage(f.root, hash, ["S08"]), false);
|
||||
for (const hash of ['', '#unknown', '#S08%22', '#S07'])
|
||||
assert.equal(revealPathStage(f.root, hash, ['S08']), false);
|
||||
f.root.contains = () => false;
|
||||
assert.equal(revealPathStage(f.root, "#S08", ["S08"]), false);
|
||||
assert.equal(revealPathStage(f.root, '#S08', ['S08']), false);
|
||||
assert.equal(f.phase.open, false);
|
||||
assert.deepEqual(f.calls, []);
|
||||
});
|
||||
test("page reveals the initial hash and server next-stage updates, listens for hash changes and cleans up", () => {
|
||||
test('page reveals the initial hash and server next-stage updates, listens for hash changes and cleans up', () => {
|
||||
const f = targetFixture(),
|
||||
effects = [],
|
||||
listeners = new Map();
|
||||
const previousWindow = globalThis.window;
|
||||
let previousDependencies;
|
||||
globalThis.window = {
|
||||
location: { hash: "#S08" },
|
||||
location: { hash: '#S08' },
|
||||
addEventListener: (type, fn) => listeners.set(type, fn),
|
||||
removeEventListener: (type, fn) => {
|
||||
assert.equal(listeners.get(type), fn);
|
||||
@@ -229,19 +271,24 @@ test("page reveals the initial hash and server next-stage updates, listens for h
|
||||
tools: {},
|
||||
content_sources: [],
|
||||
services: [],
|
||||
steps: [{ code: "S08", preparation_allowed: true }],
|
||||
steps: [{ code: 'S08', preparation_allowed: true }],
|
||||
},
|
||||
{
|
||||
...React,
|
||||
useRef: () => ({ current: f.root }),
|
||||
useEffect: (effect, dependencies) => {
|
||||
if (!previousDependencies || dependencies.some((value, i) => value !== previousDependencies[i])) {
|
||||
if (
|
||||
!previousDependencies ||
|
||||
dependencies.some(
|
||||
(value, i) => value !== previousDependencies[i],
|
||||
)
|
||||
) {
|
||||
effects.push(effect);
|
||||
}
|
||||
previousDependencies = dependencies;
|
||||
},
|
||||
useState: (initial) => [
|
||||
typeof initial === "function" ? initial() : initial,
|
||||
typeof initial === 'function' ? initial() : initial,
|
||||
() => {},
|
||||
],
|
||||
},
|
||||
@@ -251,14 +298,14 @@ test("page reveals the initial hash and server next-stage updates, listens for h
|
||||
const cleanup = effects[0]();
|
||||
assert.equal(f.phase.open, true);
|
||||
f.phase.open = false;
|
||||
listeners.get("hashchange")();
|
||||
listeners.get('hashchange')();
|
||||
assert.equal(f.phase.open, true);
|
||||
cleanup();
|
||||
assert.equal(listeners.size, 0);
|
||||
h.renderPage();
|
||||
assert.equal(effects.length, 1);
|
||||
// A saved transition changes the controlled phase's `open` prop.
|
||||
h.path.next = { code: "S09" };
|
||||
h.path.next = { code: 'S09' };
|
||||
f.phase.open = false;
|
||||
h.renderPage();
|
||||
assert.equal(effects.length, 2);
|
||||
|
||||
@@ -27,7 +27,7 @@ function load(file, mocks = {}) {
|
||||
return {
|
||||
Link: ({ children, ...props }) =>
|
||||
React.createElement('a', props, children),
|
||||
usePage: () => ({ url: '/sectores/test' }),
|
||||
usePage: () => ({ url: '/sectores/test', props: { auth: { user: { id: 1 } } } }),
|
||||
};
|
||||
if (id.startsWith('.') || id.startsWith('@/')) {
|
||||
const base = id.startsWith('@/')
|
||||
@@ -111,6 +111,7 @@ test('demographic comparison retains four saved places and requires a province b
|
||||
test('the real preparation editor opens an own idea with its budget and no mandatory advert or duplicate reference selector', () => {
|
||||
const Empty = () => null;
|
||||
const Editor = load('pages/investor-path/context.tsx', {
|
||||
'@/components/investment-step-help': { HelpAtStep: Empty, InvestmentHelpGuide: ({ children }) => children },
|
||||
'@/pages/investment/shared': {
|
||||
Frame: ({ children }) =>
|
||||
React.createElement('main', null, children),
|
||||
|
||||
Reference in New Issue
Block a user