89 lines
8.2 KiB
TypeScript
89 lines
8.2 KiB
TypeScript
import { Link, usePage } from '@inertiajs/react';
|
|
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
|
|
export type NavigationView = {
|
|
case: { id: string; title: string; version: number }; phases: Record<string, string>;
|
|
steps: { code: string; title: string; phase: number; state: string; applicability: string }[];
|
|
next: { code: string; title: string; action: string; href: string } | null;
|
|
facts: { land_needed: string }; sector_contexts: { id: number; name: string; slug: string }[];
|
|
zone_contexts: { zone_id: string; title: string; province: string | null; district: string | null; consulted_public_version: number }[];
|
|
results: { id: string; engine: string; recorded_at: string }[]; requests: { id: string; protocol: string; status: string; version: number }[];
|
|
documents: { id: string; file_name: string; status: string }[]; tools: { simulator: string | null; desk: string; land: string | null };
|
|
};
|
|
type NavigationState = { active: string; cases: { id: string; title: string; version: number }[]; view: NavigationView | null; error: string; actor?: number; choose: (id: string) => void };
|
|
const Context = createContext<NavigationState>({ active: '', cases: [], view: null, error: '', choose: () => {} });
|
|
export const useNavigationContext = () => useContext(Context);
|
|
export function NavigationContextProvider({ children }: { children: ReactNode }) {
|
|
const { props, url } = usePage<{ auth: { user: { id: number } | null }; investorPathEnabled?: boolean }>();
|
|
const actor = props.auth?.user?.id;
|
|
const [selection, setSelection] = useState<{ actor: number; id: string } | null>(null);
|
|
const [listing, setListing] = useState<{ actor: number; cases: NavigationState['cases'] } | null>(null);
|
|
const [loaded, setLoaded] = useState<{ actor: number; id: string; view: NavigationView } | null>(null);
|
|
const [error, setError] = useState('');
|
|
const active = selection?.actor === actor ? selection?.id ?? '' : '';
|
|
const cases = listing?.actor === actor ? listing?.cases ?? [] : [];
|
|
const view = loaded?.actor === actor && loaded?.id === active ? loaded?.view ?? null : null;
|
|
function choose(id: string) {
|
|
if (!actor || !cases.some(c => c.id === id)) return;
|
|
setSelection({ actor, id });
|
|
try { localStorage.setItem(`investmoz-nav-qa:${actor}`, id); } catch { setError('Seleção mantida nesta página; armazenamento local indisponível.'); }
|
|
}
|
|
useEffect(() => {
|
|
setError('');
|
|
if (!actor || !props.investorPathEnabled) return;
|
|
const controller = new AbortController();
|
|
void fetch('/investimentos', { headers: { Accept: 'application/json' }, signal: controller.signal }).then(async r => {
|
|
if (!r.ok) throw new Error('Não foi possível recuperar os dossiers autorizados.');
|
|
return r.json() as Promise<{ contexts: NavigationState['cases'] }>;
|
|
}).then(data => {
|
|
if (controller.signal.aborted) return;
|
|
setListing({ actor, cases: data.contexts });
|
|
const direct = url.match(/^\/investimentos\/([a-f0-9-]{36})(?:[/?#]|$)/i)?.[1] ?? new URL(url, 'https://qa.invalid').searchParams.get('context');
|
|
let remembered = ''; try { remembered = localStorage.getItem(`investmoz-nav-qa:${actor}`) ?? ''; } catch { /* Still works with route context. */ }
|
|
const id = [direct, remembered].find(x => data.contexts.some(c => c.id === x));
|
|
if (id) { setSelection({ actor, id }); try { localStorage.setItem(`investmoz-nav-qa:${actor}`, id); } catch { /* Identifier only. */ } }
|
|
else setSelection(null);
|
|
}).catch(e => { if (!controller.signal.aborted) setError(e instanceof Error ? e.message : 'Contexto indisponível.'); });
|
|
return () => controller.abort();
|
|
}, [actor, url, props.investorPathEnabled]);
|
|
useEffect(() => {
|
|
if (!actor || !active || !cases.some(c => c.id === active)) return;
|
|
const controller = new AbortController();
|
|
void fetch(`/investimentos/${active}`, { headers: { Accept: 'application/json' }, signal: controller.signal }).then(async r => {
|
|
if (!r.ok) throw new Error('Contexto não autorizado ou indisponível; não foi criado outro dossier.');
|
|
return r.json() as Promise<NavigationView>;
|
|
}).then(value => { if (!controller.signal.aborted) setLoaded({ actor, id: active, view: value }); }).catch(e => { if (!controller.signal.aborted) { setLoaded(null); setError(e instanceof Error ? e.message : 'Falha na recuperação.'); } });
|
|
return () => controller.abort();
|
|
}, [actor, active, listing]);
|
|
return <Context.Provider value={{ actor, active, cases, view, error, choose }}>{children}</Context.Provider>;
|
|
}
|
|
|
|
export function NavigationContextSummary() {
|
|
const { actor, active, cases, view, error, choose } = useNavigationContext();
|
|
const { url } = usePage();
|
|
const [open, setOpen] = useState(false); const [pending, setPending] = useState('');
|
|
if (/^\/(management|perfis|minhas-oportunidades|dashboard)(\/|$)/.test(url)) return null;
|
|
const sectors = view?.sector_contexts.map(s => s.name).join(' · ') || 'Não indicado';
|
|
const locations = view?.zone_contexts.map(z => `${z.title} (v${z.consulted_public_version})`).join(' · ') || 'Não indicada';
|
|
return <aside className="sticky top-0 z-30 border-y border-emerald-200 bg-emerald-50 px-4 py-3 text-xs text-slate-900 shadow-sm" aria-label="Resumo do investimento atual">
|
|
<dl className="mx-auto grid max-w-7xl grid-cols-2 gap-x-4 gap-y-2 sm:grid-cols-3 lg:grid-cols-6">
|
|
{Object.entries({ 'Investimento / dossier': view?.case.title || 'Selecione um dossier', 'Oportunidade': 'Associação não exposta no resumo atual', 'Sector': sectors, 'Localização': locations, 'Etapa atual': view?.next ? `${view.next.code} — em preparação sugerida` : 'A consultar', 'Próxima ação': view?.next?.title || 'Escolher ou recuperar investimento' }).map(([label, value]) => <div key={label} className="min-w-0"><dt className="font-semibold">{label}</dt><dd className="truncate" title={value}>{value}</dd></div>)}
|
|
</dl>
|
|
<div className="mx-auto mt-2 flex max-w-7xl flex-wrap gap-3">
|
|
{view && <Link className="font-semibold underline" href={`/investimentos/${active}`}>Abrir dossier atual</Link>}
|
|
{view?.next && <Link className="underline" href={`/investimentos/${active}#${view.next.code}`}>Preparar {view.next.code}</Link>}
|
|
<button type="button" className="underline" aria-expanded={open} onClick={() => setOpen(!open)}>Detalhes e mudar contexto</button>
|
|
<Link className="underline" href="/oportunidades">Pesquisar oportunidades</Link>
|
|
</div>
|
|
{open && <div className="mx-auto mt-3 max-w-7xl space-y-3 rounded border bg-white p-3">
|
|
{!actor ? <p><Link className="underline" href="/investimentos">Entrar para recuperar o mesmo dossier</Link>. A consulta pública continua disponível.</p> : <>
|
|
<label className="grid gap-1">Dossier autorizado<select className="min-w-0 w-full max-w-full rounded border p-2" value={pending || active} onChange={e => setPending(e.target.value)}><option value="">Escolher investimento</option>{cases.map(c => <option key={c.id} value={c.id}>{c.title}</option>)}</select></label>
|
|
{pending && pending !== active && <div role="status"><p>Muda apenas o dossier em foco. Documentos, submissões e decisões de ambos permanecem nos respetivos processos.</p><button className="mr-4 underline" onClick={() => setPending('')}>Cancelar mudança de dossier</button><button className="underline" onClick={() => { choose(pending); setPending(''); }}>Confirmar dossier em foco</button></div>}
|
|
{view && <p>UUID: {view.case.id} · versão {view.case.version} · {view.steps.length} etapas em {Object.keys(view.phases).length} fases. Sector: {sectors}. Localização: {locations}.</p>}
|
|
<Link className="underline" href={`/qa/navegacao${active ? `?context=${active}` : ''}`}>Comparar mudança de oportunidade, sector ou localização</Link>
|
|
{view?.tools.simulator && <Link className="ml-3 underline" href={view.tools.simulator}>Simulador deste investimento</Link>}
|
|
</>}
|
|
{error && <p role="alert">{error}</p>}
|
|
</div>}
|
|
</aside>;
|
|
}
|