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 };
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,12 @@ import InvestmentComplements, {
|
||||
type Complement,
|
||||
type ComplementOption,
|
||||
} from '@/components/investment-complements';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import {
|
||||
HelpAtStep,
|
||||
InvestmentHelpGuide,
|
||||
} from '@/components/investment-step-help';
|
||||
import { preparationHelp } from '@/lib/investment-step-help';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Frame, button, card, input } from '@/pages/investment/shared';
|
||||
import {
|
||||
@@ -89,6 +94,7 @@ function ScopedContextEditor({
|
||||
} | null;
|
||||
}) {
|
||||
const navigation = useNavigationContext();
|
||||
const { auth } = usePage<{ auth: { user: { id: number } } }>().props;
|
||||
const [complements, setComplements] =
|
||||
useState<Complement[]>(entryComplements);
|
||||
const [complementOptions, setComplementOptions] = useState<
|
||||
@@ -567,6 +573,11 @@ function ScopedContextEditor({
|
||||
}
|
||||
return (
|
||||
<Frame title="Preparar investimento">
|
||||
<InvestmentHelpGuide
|
||||
user={auth.user.id}
|
||||
flow="investment-preparation"
|
||||
steps={preparationHelp}
|
||||
>
|
||||
<div className="space-y-5 [overflow-wrap:anywhere]">
|
||||
<Link
|
||||
className="underline"
|
||||
@@ -586,7 +597,9 @@ function ScopedContextEditor({
|
||||
? undefined
|
||||
: (key) => {
|
||||
setComplements((items) =>
|
||||
items.filter((item) => item.key !== key),
|
||||
items.filter(
|
||||
(item) => item.key !== key,
|
||||
),
|
||||
);
|
||||
setPlan(null);
|
||||
}
|
||||
@@ -613,7 +626,8 @@ function ScopedContextEditor({
|
||||
'/contexto/rascunho',
|
||||
{
|
||||
...JSON.parse(latestDraft.current),
|
||||
draft_sequence: ++sequence.current.value,
|
||||
draft_sequence: ++sequence.current
|
||||
.value,
|
||||
},
|
||||
'POST',
|
||||
);
|
||||
@@ -638,8 +652,8 @@ function ScopedContextEditor({
|
||||
<p key={row.title}>
|
||||
{row.title}: a localização recebida (
|
||||
{row.requested}) não substituiu a escolha
|
||||
guardada ({row.saved}). Pode rever a localização
|
||||
abaixo antes de confirmar.
|
||||
guardada ({row.saved}). Pode rever a
|
||||
localização abaixo antes de confirmar.
|
||||
</p>
|
||||
))}
|
||||
</aside>
|
||||
@@ -667,13 +681,19 @@ function ScopedContextEditor({
|
||||
</div>
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
<section className={card + ' space-y-4'}>
|
||||
<section
|
||||
className={card + ' space-y-4'}
|
||||
data-investment-step="help-choices"
|
||||
>
|
||||
<HelpAtStep code="help-choices" />
|
||||
{corridorError && (
|
||||
<p role="alert">
|
||||
{corridorError}{' '}
|
||||
<button
|
||||
className="underline"
|
||||
onClick={() => setCorridorRetry((v) => v + 1)}
|
||||
onClick={() =>
|
||||
setCorridorRetry((v) => v + 1)
|
||||
}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
@@ -724,16 +744,19 @@ function ScopedContextEditor({
|
||||
href={
|
||||
source?.kind === 'portfolio'
|
||||
? source.href
|
||||
: view.context.selection.portfolio?.href
|
||||
: view.context.selection.portfolio
|
||||
?.href
|
||||
}
|
||||
>
|
||||
{source?.kind === 'portfolio'
|
||||
? source.title
|
||||
: view.context.selection.portfolio?.title}
|
||||
: view.context.selection.portfolio
|
||||
?.title}
|
||||
</a>
|
||||
. A ficha é conservada como origem. Escolha o sector
|
||||
e a localização do investimento abaixo; a cobertura
|
||||
documental não é uma implantação atribuída.
|
||||
. A ficha é conservada como origem. Escolha o
|
||||
sector e a localização do investimento abaixo; a
|
||||
cobertura documental não é uma implantação
|
||||
atribuída.
|
||||
</p>
|
||||
)}
|
||||
{entryTerritory &&
|
||||
@@ -743,13 +766,15 @@ function ScopedContextEditor({
|
||||
<p role="status">
|
||||
A pesquisa indicava {entryTerritory.title}.
|
||||
Conservou-se a localização guardada,{' '}
|
||||
{view.context.selection.territory.title}; pode
|
||||
alterá-la explicitamente abaixo e conferir os
|
||||
impactos.
|
||||
{view.context.selection.territory.title};
|
||||
pode alterá-la explicitamente abaixo e
|
||||
conferir os impactos.
|
||||
</p>
|
||||
)}
|
||||
<ContextDocuments
|
||||
source={source ?? view.context.selection.opportunity}
|
||||
source={
|
||||
source ?? view.context.selection.opportunity
|
||||
}
|
||||
/>
|
||||
{view.context.revision > 0 &&
|
||||
!Object.keys(changes).length &&
|
||||
@@ -766,16 +791,18 @@ function ScopedContextEditor({
|
||||
)}
|
||||
<details
|
||||
open={relatedOpen}
|
||||
onToggle={(e) => setRelatedOpen(e.currentTarget.open)}
|
||||
onToggle={(e) =>
|
||||
setRelatedOpen(e.currentTarget.open)
|
||||
}
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Oportunidades relacionadas (opcional)
|
||||
</summary>
|
||||
<p>
|
||||
Pode preparar a sua ideia sem associar um anuncio ou
|
||||
corredor. Pesquise apenas se uma oportunidade puder
|
||||
apoiar este investimento.
|
||||
Pode preparar a sua ideia sem associar um
|
||||
anuncio ou corredor. Pesquise apenas se uma
|
||||
oportunidade puder apoiar este investimento.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<label className="min-w-0 flex-1">
|
||||
@@ -783,7 +810,9 @@ function ScopedContextEditor({
|
||||
<input
|
||||
className={input}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onChange={(e) =>
|
||||
setQuery(e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
@@ -839,7 +868,8 @@ function ScopedContextEditor({
|
||||
'business:',
|
||||
) &&
|
||||
!choices.some(
|
||||
(c) => c.opportunity.key === o.key,
|
||||
(c) =>
|
||||
c.opportunity.key === o.key,
|
||||
)
|
||||
) {
|
||||
setChoices([
|
||||
@@ -855,7 +885,8 @@ function ScopedContextEditor({
|
||||
},
|
||||
territory: null,
|
||||
location_reason: '',
|
||||
location_state: 'undetermined',
|
||||
location_state:
|
||||
'undetermined',
|
||||
},
|
||||
]);
|
||||
setManageChoices(true);
|
||||
@@ -877,7 +908,8 @@ function ScopedContextEditor({
|
||||
(o) =>
|
||||
!choices.some(
|
||||
(c) =>
|
||||
c.opportunity.key === o.key,
|
||||
c.opportunity.key ===
|
||||
o.key,
|
||||
),
|
||||
)
|
||||
.map((o) => (
|
||||
@@ -889,7 +921,9 @@ function ScopedContextEditor({
|
||||
? choices.length > 0
|
||||
: selected(
|
||||
'opportunity',
|
||||
).startsWith('business:')
|
||||
).startsWith(
|
||||
'business:',
|
||||
)
|
||||
}
|
||||
>
|
||||
{o.title} —{' '}
|
||||
@@ -899,17 +933,23 @@ function ScopedContextEditor({
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{selected('opportunity').startsWith('business:') && (
|
||||
{selected('opportunity').startsWith(
|
||||
'business:',
|
||||
) && (
|
||||
<p>
|
||||
{options.opportunities.find(
|
||||
(o) => o.key === selected('opportunity'),
|
||||
(o) =>
|
||||
o.key === selected('opportunity'),
|
||||
)?.title ??
|
||||
view.context.selection.opportunity?.title}
|
||||
view.context.selection.opportunity
|
||||
?.title}
|
||||
<button
|
||||
type="button"
|
||||
className="ml-3 underline"
|
||||
disabled={busy}
|
||||
onClick={() => change('opportunity', '')}
|
||||
onClick={() =>
|
||||
change('opportunity', '')
|
||||
}
|
||||
>
|
||||
Retirar esta referencia
|
||||
</button>
|
||||
@@ -929,7 +969,9 @@ function ScopedContextEditor({
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
disabled={busy}
|
||||
value={selected('sector')}
|
||||
onChange={(e) => change('sector', e.target.value)}
|
||||
onChange={(e) =>
|
||||
change('sector', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Sem sector escolhido</option>
|
||||
{view.context.selection.sector &&
|
||||
@@ -941,11 +983,15 @@ function ScopedContextEditor({
|
||||
<option
|
||||
disabled
|
||||
value={
|
||||
view.context.selection.sector.key
|
||||
view.context.selection.sector
|
||||
.key
|
||||
}
|
||||
>
|
||||
{view.context.selection.sector.title} —
|
||||
referência histórica mantida
|
||||
{
|
||||
view.context.selection.sector
|
||||
.title
|
||||
}{' '}
|
||||
— referência histórica mantida
|
||||
</option>
|
||||
)}
|
||||
{options.sectors.map((s) => (
|
||||
@@ -963,7 +1009,9 @@ function ScopedContextEditor({
|
||||
? 'Zona ou parque da primeira oportunidade'
|
||||
: 'ZEE, ZFI ou parque consultado'}
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
className={
|
||||
input + ' max-w-full min-w-0'
|
||||
}
|
||||
disabled={
|
||||
busy ||
|
||||
corridorLoading ||
|
||||
@@ -1004,7 +1052,8 @@ function ScopedContextEditor({
|
||||
{!manageChoices && (
|
||||
<>
|
||||
<h3 className="font-semibold">
|
||||
Localização — escolher até ao nível conhecido
|
||||
Localização — escolher até ao nível
|
||||
conhecido
|
||||
</h3>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
@@ -1068,30 +1117,40 @@ function ScopedContextEditor({
|
||||
disabled={busy || !view.can_write}
|
||||
values={{ ...view.context.fields, ...declarations }}
|
||||
onChange={(field, value) => {
|
||||
setDeclarations((old) => ({ ...old, [field]: value }));
|
||||
setDeclarations((old) => ({
|
||||
...old,
|
||||
[field]: value,
|
||||
}));
|
||||
setPlan(null);
|
||||
}}
|
||||
/>
|
||||
<DemographicContext territoryId={consultationPath.at(-1)?.id} />
|
||||
<section className={card + ' space-y-3'}>
|
||||
<DemographicContext
|
||||
territoryId={consultationPath.at(-1)?.id}
|
||||
/>
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
data-investment-step="help-declarations"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Declarações deste investimento
|
||||
</h2>
|
||||
<HelpAtStep code="help-declarations" />
|
||||
<details className="rounded border p-3">
|
||||
<summary>
|
||||
Enquadramento da entidade e fiscal, quando
|
||||
necessário
|
||||
</summary>
|
||||
<p>
|
||||
Estes campos pertencem ao processo. Alterá-los não
|
||||
muda o cadastro da oportunidade nem o perfil da
|
||||
organização.
|
||||
Estes campos pertencem ao processo. Alterá-los
|
||||
não muda o cadastro da oportunidade nem o perfil
|
||||
da organização.
|
||||
</p>
|
||||
<p>
|
||||
Origem do investidor, residência fiscal e
|
||||
constituição da entidade são declarações distintas.
|
||||
A localização não confirma benefícios. A prévia
|
||||
identifica o impacto antes de guardar.
|
||||
constituição da entidade são declarações
|
||||
distintas. A localização não confirma
|
||||
benefícios. A prévia identifica o impacto antes
|
||||
de guardar.
|
||||
</p>
|
||||
{[
|
||||
[
|
||||
@@ -1144,7 +1203,8 @@ function ScopedContextEditor({
|
||||
}
|
||||
error={
|
||||
(declarations.currency ??
|
||||
view.context.fields.currency) &&
|
||||
view.context.fields
|
||||
.currency) &&
|
||||
!/^[A-Z]{3}$/.test(
|
||||
declarations.currency ??
|
||||
view.context.fields
|
||||
@@ -1176,7 +1236,8 @@ function ScopedContextEditor({
|
||||
onChange={(value) => {
|
||||
setDeclarations({
|
||||
...declarations,
|
||||
tax_residency_country: value,
|
||||
tax_residency_country:
|
||||
value,
|
||||
});
|
||||
setPlan(null);
|
||||
}}
|
||||
@@ -1187,20 +1248,28 @@ function ScopedContextEditor({
|
||||
disabled={busy}
|
||||
value={
|
||||
declarations[String(key)] ??
|
||||
view.context.fields[String(key)] ??
|
||||
view.context.fields[
|
||||
String(key)
|
||||
] ??
|
||||
''
|
||||
}
|
||||
onChange={(e) => {
|
||||
setDeclarations({
|
||||
...declarations,
|
||||
[String(key)]: e.target.value,
|
||||
[String(key)]:
|
||||
e.target.value,
|
||||
});
|
||||
setPlan(null);
|
||||
}}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
<option value="">
|
||||
Por indicar
|
||||
</option>
|
||||
{choices.map(([value, text]) => (
|
||||
<option key={value} value={value}>
|
||||
<option
|
||||
key={value}
|
||||
value={value}
|
||||
>
|
||||
{text}
|
||||
</option>
|
||||
))}
|
||||
@@ -1224,13 +1293,16 @@ function ScopedContextEditor({
|
||||
}
|
||||
value={
|
||||
declarations[String(key)] ??
|
||||
view.context.fields[String(key)] ??
|
||||
view.context.fields[
|
||||
String(key)
|
||||
] ??
|
||||
''
|
||||
}
|
||||
onChange={(e) => {
|
||||
setDeclarations({
|
||||
...declarations,
|
||||
[String(key)]: e.target.value,
|
||||
[String(key)]:
|
||||
e.target.value,
|
||||
});
|
||||
setPlan(null);
|
||||
}}
|
||||
@@ -1294,6 +1366,12 @@ function ScopedContextEditor({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
data-investment-step="help-review"
|
||||
>
|
||||
<HelpAtStep code="help-review" />
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
@@ -1302,7 +1380,6 @@ function ScopedContextEditor({
|
||||
>
|
||||
Rever dados antes de guardar
|
||||
</button>
|
||||
</section>
|
||||
{plan && (
|
||||
<section
|
||||
className={card + ' space-y-4'}
|
||||
@@ -1316,7 +1393,9 @@ function ScopedContextEditor({
|
||||
choices={plan.opportunity_choices}
|
||||
/>
|
||||
)}
|
||||
<SelectedComplements items={plan.complements ?? []} />
|
||||
<SelectedComplements
|
||||
items={plan.complements ?? []}
|
||||
/>
|
||||
<InvestmentRequirements
|
||||
assessment={plan.requirements_assessment}
|
||||
contextId={view.case.id}
|
||||
@@ -1325,7 +1404,9 @@ function ScopedContextEditor({
|
||||
<table className="w-full min-w-[36rem] table-fixed text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-44 p-2">Tratamento</th>
|
||||
<th className="w-44 p-2">
|
||||
Tratamento
|
||||
</th>
|
||||
<th>Impacto concreto</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -1349,8 +1430,9 @@ function ScopedContextEditor({
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
: conserva «{x.value}»;
|
||||
a fonte propõe «
|
||||
: conserva «
|
||||
{x.value}»; a
|
||||
fonte propõe «
|
||||
{x.proposed}».
|
||||
</p>
|
||||
))}
|
||||
@@ -1385,15 +1467,21 @@ function ScopedContextEditor({
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
{Object.values(plan.selection).map(
|
||||
{Object.values(
|
||||
plan.selection,
|
||||
).map(
|
||||
(r) =>
|
||||
r && (
|
||||
<p key={r.key}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={r.href}
|
||||
href={
|
||||
r.href
|
||||
}
|
||||
>
|
||||
{r.title}
|
||||
{
|
||||
r.title
|
||||
}
|
||||
</Link>
|
||||
</p>
|
||||
),
|
||||
@@ -1402,15 +1490,20 @@ function ScopedContextEditor({
|
||||
</tr>
|
||||
<tr>
|
||||
<th className="p-2 align-top">
|
||||
Precisa de revisão ou recálculo
|
||||
Precisa de revisão ou
|
||||
recálculo
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.dependent_results.length}{' '}
|
||||
resultados financeiros afectados.
|
||||
Etapas a rever:{' '}
|
||||
{plan.review_steps.length}. Dados já
|
||||
preenchidos nos formulários
|
||||
conservam-se até à sua conferência.
|
||||
{
|
||||
plan.dependent_results
|
||||
.length
|
||||
}{' '}
|
||||
resultados financeiros
|
||||
afectados. Etapas a rever:{' '}
|
||||
{plan.review_steps.length}.
|
||||
Dados já preenchidos nos
|
||||
formulários conservam-se até
|
||||
à sua conferência.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -1418,9 +1511,9 @@ function ScopedContextEditor({
|
||||
Preservado no histórico
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.requests.length} pedidos e os
|
||||
dados, decisões e resultados
|
||||
anteriores.{' '}
|
||||
{plan.requests.length}{' '}
|
||||
pedidos e os dados, decisões
|
||||
e resultados anteriores.{' '}
|
||||
{plan.requests.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.protocol ||
|
||||
@@ -1433,7 +1526,9 @@ function ScopedContextEditor({
|
||||
</table>
|
||||
</div>
|
||||
{plan.private_investment && (
|
||||
<PreparationImpact {...plan.private_investment} />
|
||||
<PreparationImpact
|
||||
{...plan.private_investment}
|
||||
/>
|
||||
)}
|
||||
<p>{plan.notice}</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
@@ -1462,6 +1557,7 @@ function ScopedContextEditor({
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Resultados e submissões conservados
|
||||
@@ -1492,6 +1588,7 @@ function ScopedContextEditor({
|
||||
))}
|
||||
</section>
|
||||
</div>
|
||||
</InvestmentHelpGuide>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
HelpAtStep,
|
||||
InvestmentHelpGuide,
|
||||
} from '@/components/investment-step-help';
|
||||
import { investmentStageHelp } from '@/lib/investment-step-help';
|
||||
import type { SectorAnalysisSnapshot } from '@/lib/investor-dossier-report';
|
||||
import type { SectorResourceSelection } from '@/components/sector-resource-reference';
|
||||
import { InvestorDossierReports } from '@/components/investor-dossier-reports';
|
||||
@@ -250,6 +255,7 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
return (
|
||||
<Container
|
||||
id={step.code}
|
||||
data-investment-step={step.code}
|
||||
tabIndex={-1}
|
||||
open={licensing ? undefined : path.next?.code === step.code}
|
||||
className={`space-y-3 rounded-xl border p-4 ${licensing ? 'md:col-span-2' : ''}`}
|
||||
@@ -263,6 +269,7 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
>
|
||||
{step.title} · {pathStates[step.state]}
|
||||
</Heading>
|
||||
<HelpAtStep code={step.code} />
|
||||
{!licensing && <p>{pathStates[step.state]}</p>}
|
||||
{step.context_review_required && (
|
||||
<label className="block rounded border border-amber-600 bg-amber-50 p-3">
|
||||
@@ -615,12 +622,22 @@ export default function InvestmentPath(path: Path) {
|
||||
Os meus investimentos
|
||||
</Link>
|
||||
<h1 className="text-2xl font-semibold">{path.case.title}</h1>
|
||||
<InvestmentHelpGuide
|
||||
user={auth.user.id}
|
||||
flow="investor-path"
|
||||
initialCode={path.next?.code}
|
||||
steps={path.steps
|
||||
.filter((step) => step.preparation_allowed)
|
||||
.map((step) => investmentStageHelp(step.code, step.title))}
|
||||
>
|
||||
{path.investment_context?.selection.portfolio && (
|
||||
<p className="rounded border p-4">
|
||||
Origem documental:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={path.investment_context.selection.portfolio.href}
|
||||
href={
|
||||
path.investment_context.selection.portfolio.href
|
||||
}
|
||||
>
|
||||
{path.investment_context.selection.portfolio.title}
|
||||
</Link>
|
||||
@@ -658,9 +675,10 @@ export default function InvestmentPath(path: Path) {
|
||||
{!path.context_opportunity &&
|
||||
path.opportunity_options.length > 1 && (
|
||||
<p>
|
||||
Escolha para consultar as etapas, os requisitos
|
||||
e o pedido de terra correspondentes. Os dados
|
||||
comuns conservam-se.
|
||||
Escolha para consultar as etapas, os
|
||||
requisitos e o pedido de terra
|
||||
correspondentes. Os dados comuns
|
||||
conservam-se.
|
||||
</p>
|
||||
)}
|
||||
</label>
|
||||
@@ -678,7 +696,10 @@ export default function InvestmentPath(path: Path) {
|
||||
reference.locations_text}
|
||||
</p>
|
||||
<p>{reference.value_chain}</p>
|
||||
<Link className="underline" href={reference.href}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={reference.href}
|
||||
>
|
||||
Consultar a referência mineral
|
||||
</Link>
|
||||
</article>
|
||||
@@ -738,8 +759,8 @@ export default function InvestmentPath(path: Path) {
|
||||
)}
|
||||
<p>
|
||||
Oportunidade, sector e território são referências de
|
||||
preparação; não confirmam benefícios, disponibilidade ou
|
||||
autorizações.
|
||||
preparação; não confirmam benefícios,
|
||||
disponibilidade ou autorizações.
|
||||
</p>
|
||||
{path.canWrite && (
|
||||
<Link
|
||||
@@ -754,7 +775,8 @@ export default function InvestmentPath(path: Path) {
|
||||
{!!path.zone_contexts?.length && (
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2 className="font-semibold">
|
||||
Parques anteriormente consultados — histórico preservado
|
||||
Parques anteriormente consultados — histórico
|
||||
preservado
|
||||
</h2>
|
||||
{path.zone_contexts.map((zone) => (
|
||||
<article
|
||||
@@ -784,8 +806,9 @@ export default function InvestmentPath(path: Path) {
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Preparação privada nas mesmas cinco fases e 19 etapas; a
|
||||
escolha do setor não publica uma oportunidade.
|
||||
Preparação privada nas mesmas cinco fases e 19
|
||||
etapas; a escolha do setor não publica uma
|
||||
oportunidade.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
@@ -799,9 +822,12 @@ export default function InvestmentPath(path: Path) {
|
||||
simulator={path.tools.simulator}
|
||||
fromArticle={
|
||||
path.content_sources.some(
|
||||
(source) => source.return_href === '/tech-fintech',
|
||||
(source) =>
|
||||
source.return_href === '/tech-fintech',
|
||||
) ||
|
||||
path.sector_contexts.some((s) => s.slug === 'fintech')
|
||||
path.sector_contexts.some(
|
||||
(s) => s.slug === 'fintech',
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
@@ -822,8 +848,8 @@ export default function InvestmentPath(path: Path) {
|
||||
{!path.investment_context?.opportunity_choices?.length && (
|
||||
<ProactiveSummary
|
||||
value={proactiveView(
|
||||
path.investment_context?.selection.opportunity?.analysis
|
||||
?.proactive,
|
||||
path.investment_context?.selection.opportunity
|
||||
?.analysis?.proactive,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
@@ -831,7 +857,9 @@ export default function InvestmentPath(path: Path) {
|
||||
items={path.investment_context?.complements ?? []}
|
||||
/>
|
||||
<InvestmentRequirements
|
||||
assessment={path.investment_context?.requirements_assessment}
|
||||
assessment={
|
||||
path.investment_context?.requirements_assessment
|
||||
}
|
||||
contextId={path.case.id}
|
||||
excludedSteps={path.steps
|
||||
.filter((step) => !step.preparation_allowed)
|
||||
@@ -865,9 +893,9 @@ export default function InvestmentPath(path: Path) {
|
||||
</Link>
|
||||
{source.analysis_review_required && (
|
||||
<p role="status">
|
||||
A fonte foi alterada ou deixou de estar
|
||||
disponível. Reveja a hipótese; o trecho
|
||||
guardado foi preservado.
|
||||
A fonte foi alterada ou deixou de
|
||||
estar disponível. Reveja a hipótese;
|
||||
o trecho guardado foi preservado.
|
||||
</p>
|
||||
)}
|
||||
{(source.analyses ?? []).map((analysis) => (
|
||||
@@ -876,21 +904,22 @@ export default function InvestmentPath(path: Path) {
|
||||
key={analysis.key}
|
||||
>
|
||||
<summary>
|
||||
Hipótese guardada: {analysis.title}
|
||||
Hipótese guardada:{' '}
|
||||
{analysis.title}
|
||||
</summary>
|
||||
<p>
|
||||
{analysis.location_label ??
|
||||
'Implantação por definir'}
|
||||
. Contexto da fonte, sem atribuição
|
||||
distrital automática.
|
||||
. Contexto da fonte, sem
|
||||
atribuição distrital automática.
|
||||
</p>
|
||||
<blockquote>
|
||||
{analysis.quote}
|
||||
</blockquote>
|
||||
<p>
|
||||
Edição: {analysis.source_date}.
|
||||
Preserve este fundamento e reveja-o
|
||||
se a fonte mudar.
|
||||
Preserve este fundamento e
|
||||
reveja-o se a fonte mudar.
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
@@ -919,7 +948,8 @@ export default function InvestmentPath(path: Path) {
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Pode preparar etapas independentes enquanto aguarda
|
||||
informação. As etapas abaixo adaptam-se às suas escolhas.
|
||||
informação. As etapas abaixo adaptam-se às suas
|
||||
escolhas.
|
||||
</p>
|
||||
</section>
|
||||
<nav
|
||||
@@ -935,7 +965,8 @@ export default function InvestmentPath(path: Path) {
|
||||
{
|
||||
funding:
|
||||
'Instituições financeiras e apoios',
|
||||
preparation: 'Preparação APIEX e SWOT',
|
||||
preparation:
|
||||
'Preparação APIEX e SWOT',
|
||||
simulator: 'Plano e simulador',
|
||||
desk: 'Balcão e histórico',
|
||||
library: 'Biblioteca',
|
||||
@@ -987,7 +1018,9 @@ export default function InvestmentPath(path: Path) {
|
||||
facts.setData(key, e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="unknown">Por determinar</option>
|
||||
<option value="unknown">
|
||||
Por determinar
|
||||
</option>
|
||||
<option value="yes">Sim</option>
|
||||
<option value="no">Não</option>
|
||||
</select>
|
||||
@@ -1005,7 +1038,9 @@ export default function InvestmentPath(path: Path) {
|
||||
<option value="unknown">Por determinar</option>
|
||||
<option value="proceed">Prosseguir</option>
|
||||
<option value="reformulate">Reformular</option>
|
||||
<option value="archive">Arquivar a ideia</option>
|
||||
<option value="archive">
|
||||
Arquivar a ideia
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
@@ -1053,8 +1088,8 @@ export default function InvestmentPath(path: Path) {
|
||||
))}
|
||||
</ul>
|
||||
<p className="text-sm">
|
||||
Pode rever estas escolhas acima. Os dados e o histórico
|
||||
destas etapas ficam conservados.
|
||||
Pode rever estas escolhas acima. Os dados e o
|
||||
histórico destas etapas ficam conservados.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
@@ -1108,8 +1143,8 @@ export default function InvestmentPath(path: Path) {
|
||||
</ul>
|
||||
{!path.results.length && (
|
||||
<p>
|
||||
Nenhum resultado financeiro disponível para esta conta
|
||||
neste dossier.
|
||||
Nenhum resultado financeiro disponível para esta
|
||||
conta neste dossier.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
@@ -1139,8 +1174,8 @@ export default function InvestmentPath(path: Path) {
|
||||
Preparar pedido com dados do dossier
|
||||
</button>
|
||||
<p className="text-sm">
|
||||
Cria um rascunho; reveja os dados no Balcão antes de
|
||||
submeter.
|
||||
Cria um rascunho; reveja os dados no Balcão
|
||||
antes de submeter.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
@@ -1151,10 +1186,13 @@ export default function InvestmentPath(path: Path) {
|
||||
className="underline"
|
||||
href={`/balcao-virtual/pedidos/${item.id}`}
|
||||
>
|
||||
{item.protocol ?? 'Rascunho'} · {item.status}
|
||||
{item.context_state === 'historical_submission'
|
||||
{item.protocol ?? 'Rascunho'} ·{' '}
|
||||
{item.status}
|
||||
{item.context_state ===
|
||||
'historical_submission'
|
||||
? ' · Submissão preservada num contexto anterior'
|
||||
: item.context_state === 'review_required'
|
||||
: item.context_state ===
|
||||
'review_required'
|
||||
? ' · Rever os dados deste rascunho'
|
||||
: ''}
|
||||
</Link>
|
||||
@@ -1183,7 +1221,10 @@ export default function InvestmentPath(path: Path) {
|
||||
Preparar os dados para a constituição da empresa
|
||||
</Link>
|
||||
{path.tools.preparation && (
|
||||
<Link className="underline" href={path.tools.preparation}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={path.tools.preparation}
|
||||
>
|
||||
Preparação APIEX e análise SWOT deste investimento
|
||||
</Link>
|
||||
)}
|
||||
@@ -1229,8 +1270,8 @@ export default function InvestmentPath(path: Path) {
|
||||
{row.title} · versão consultada {row.version}
|
||||
</h3>
|
||||
<p>
|
||||
{row.product?.title ?? 'Produto por confirmar'} ·{' '}
|
||||
{row.need}
|
||||
{row.product?.title ?? 'Produto por confirmar'}{' '}
|
||||
· {row.need}
|
||||
</p>
|
||||
<p>
|
||||
{row.product?.conditions ||
|
||||
@@ -1252,7 +1293,8 @@ export default function InvestmentPath(path: Path) {
|
||||
{row.location && (
|
||||
<section>
|
||||
<h4>
|
||||
Sede/balcão escolhido: {row.location.label}
|
||||
Sede/balcão escolhido:{' '}
|
||||
{row.location.label}
|
||||
</h4>
|
||||
<p>
|
||||
{row.location.location_text} ·{' '}
|
||||
@@ -1276,13 +1318,16 @@ export default function InvestmentPath(path: Path) {
|
||||
className="underline"
|
||||
href={`/fundos/${row.programme_id}?context=${path.case.id}${row.opportunity ? '&opportunity=' + encodeURIComponent(row.opportunity) : ''}`}
|
||||
>
|
||||
Consultar ficha actual (pode ter sido alterada ou
|
||||
retirada)
|
||||
Consultar ficha actual (pode ter sido alterada
|
||||
ou retirada)
|
||||
</Link>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<details id="tarefas" className="space-y-3 rounded-xl border p-4">
|
||||
<details
|
||||
id="tarefas"
|
||||
className="space-y-3 rounded-xl border p-4"
|
||||
>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Acompanhamento interno
|
||||
</summary>
|
||||
@@ -1320,7 +1365,9 @@ export default function InvestmentPath(path: Path) {
|
||||
}
|
||||
>
|
||||
{path.steps
|
||||
.filter((step) => step.preparation_allowed)
|
||||
.filter(
|
||||
(step) => step.preparation_allowed,
|
||||
)
|
||||
.map((step) => (
|
||||
<option
|
||||
key={step.code}
|
||||
@@ -1359,7 +1406,10 @@ export default function InvestmentPath(path: Path) {
|
||||
type="checkbox"
|
||||
checked={task.data.consent}
|
||||
onChange={(e) =>
|
||||
task.setData('consent', e.target.checked)
|
||||
task.setData(
|
||||
'consent',
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
Assumo esta tarefa no acompanhamento interno.
|
||||
@@ -1393,11 +1443,13 @@ export default function InvestmentPath(path: Path) {
|
||||
{(item.assignee_user_id === auth.user.id ||
|
||||
path.canReview) && (
|
||||
<div className="mt-2 flex flex-wrap gap-3">
|
||||
{['in_progress', 'done'].map((status) => (
|
||||
{['in_progress', 'done'].map(
|
||||
(status) => (
|
||||
<button
|
||||
key={status}
|
||||
disabled={
|
||||
taskReason.trim().length < 3
|
||||
taskReason.trim()
|
||||
.length < 3
|
||||
}
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
@@ -1411,11 +1463,15 @@ export default function InvestmentPath(path: Path) {
|
||||
},
|
||||
{
|
||||
preserveScroll: true,
|
||||
onError: (errors) =>
|
||||
onError: (
|
||||
errors,
|
||||
) =>
|
||||
setError(
|
||||
Object.values(
|
||||
errors,
|
||||
).join('; '),
|
||||
).join(
|
||||
'; ',
|
||||
),
|
||||
),
|
||||
},
|
||||
)
|
||||
@@ -1425,7 +1481,8 @@ export default function InvestmentPath(path: Path) {
|
||||
? 'Registar conclusão'
|
||||
: 'Iniciar tarefa'}
|
||||
</button>
|
||||
))}
|
||||
),
|
||||
)}
|
||||
{path.canReview && (
|
||||
<button
|
||||
disabled={
|
||||
@@ -1443,7 +1500,9 @@ export default function InvestmentPath(path: Path) {
|
||||
auth.user.id,
|
||||
reason: taskReason,
|
||||
},
|
||||
{ preserveScroll: true },
|
||||
{
|
||||
preserveScroll: true,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
@@ -1456,6 +1515,7 @@ export default function InvestmentPath(path: Path) {
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
</InvestmentHelpGuide>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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("@/")
|
||||
: 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