411 lines
35 KiB
Diff
411 lines
35 KiB
Diff
--- base/resources/js/lib/portal-navigation.ts
|
|
+++ QA/resources/js/lib/portal-navigation.ts
|
|
@@ -25,7 +25,7 @@
|
|
});
|
|
|
|
/** One route catalogue for the public shell and authenticated pages. */
|
|
-export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
|
+export function legacyPortalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
|
const opportunities = access.manager ? access.opportunityManagement : null;
|
|
const groups: PortalNavItem[] = [
|
|
{
|
|
@@ -410,3 +410,29 @@
|
|
for (const group of groups) visit(group.children ?? []);
|
|
return best.id;
|
|
}
|
|
+
|
|
+
|
|
+/** QA organization only. Existing capability filters still determine private destinations. */
|
|
+export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
|
+ const previous = legacyPortalNavigation(access);
|
|
+ return [
|
|
+ { id: 'discovery', label: 'Descoberta', children: [
|
|
+ link('home', 'Início', '/'), link('why', 'Porquê investir em Moçambique', '/qa/navegacao?area=porque'),
|
|
+ link('opportunities', 'Oportunidades de investimento', '/oportunidades'), link('sectors', 'Sectores de investimento', '/sectores'), link('locations', 'Localizações', '/oportunidades?view=map'),
|
|
+ ] },
|
|
+ { id: 'realization', label: 'Realização', children: [
|
|
+ link('start', 'Iniciar investimento', '/investimentos'), link('simulator', 'Incentivos e simulador fiscal', '/simulador-fiscal'),
|
|
+ link('licensing', 'Licenciamento', '/qa/navegacao?area=licenciamento'), link('land', 'Acesso à terra', '/terra-duat'),
|
|
+ ] },
|
|
+ { id: 'support', label: 'Suporte', children: [
|
|
+ link('services', 'Serviços ao investidor', '/balcao-virtual'), link('followup', 'Acompanhamento do projecto', '/investimentos'), link('help', 'Apoio ao investidor', '/apoio'),
|
|
+ ] },
|
|
+ ...previous.filter(group => ['account', 'management', 'profile-opportunities'].includes(group.id)),
|
|
+ ...(access.authenticated && access.businesses && access.businessReviewUrl ? [{ id: 'business-work', label: 'Revisão de negócios', children: [link('review-businesses', 'Revisão de negócios', access.businessReviewUrl)] }] : []),
|
|
+ ...(access.authenticated ? [{ id: 'personal-activity', label: 'A minha atividade', children: [
|
|
+ link('my-partnerships', 'As minhas parcerias', '/parcerias/painel'),
|
|
+ ...(access.businesses ? [link('my-businesses', 'Os meus negócios', '/investidor/negocios')] : []),
|
|
+
|
|
+ ] }] : []),
|
|
+ ];
|
|
+}
|
|
--- base/resources/js/components/portal-grouped-menu.tsx
|
|
+++ QA/resources/js/components/portal-grouped-menu.tsx
|
|
@@ -192,7 +192,7 @@
|
|
)}
|
|
<nav aria-label="Áreas do portal">
|
|
<ul className="flex flex-wrap gap-2">
|
|
- {groups.map((group) => (
|
|
+ {groups.filter(group => ['discovery', 'realization', 'support'].includes(group.id)).map((group) => (
|
|
<li
|
|
key={group.id}
|
|
className="relative w-full sm:w-auto"
|
|
@@ -238,6 +238,10 @@
|
|
))}
|
|
</ul>
|
|
</nav>
|
|
+ <nav aria-label="Conta e trabalho por papel" className="mt-3 grid gap-3 sm:grid-cols-2">
|
|
+ <details className="rounded border p-3"><summary className="cursor-pointer font-semibold">A minha conta e atividade</summary><ul className="mt-2 space-y-1">{items(groups.filter(g => ['account','personal-activity'].includes(g.id)))}</ul></details>
|
|
+ {groups.some(g => ['management','profile-opportunities','business-work'].includes(g.id)) && <details className="rounded border p-3"><summary className="cursor-pointer font-semibold">Área de trabalho — criação, revisão, publicação e administração</summary><p className="my-2 text-xs">Destinos disponíveis segundo o papel e âmbito existentes; não exige percorrer a jornada do investidor.</p><ul className="space-y-1">{items(groups.filter(g => ['management','profile-opportunities','business-work'].includes(g.id)))}</ul></details>}
|
|
+ </nav>
|
|
</div>
|
|
</header>
|
|
);
|
|
--- base/resources/js/layouts/portal-navigation.tsx
|
|
+++ QA/resources/js/layouts/portal-navigation.tsx
|
|
@@ -2,7 +2,7 @@
|
|
import { createContext, useContext } from 'react';
|
|
import { PortalGroupedMenu } from '@/components/portal-grouped-menu';
|
|
import type { ReactNode } from 'react';
|
|
-import { JourneyCompanion } from '@/components/journey-companion';
|
|
+import { NavigationContextProvider, NavigationContextSummary } from '@/components/navigation-context';
|
|
|
|
const MenuPlacement = createContext(false);
|
|
|
|
@@ -60,6 +60,7 @@
|
|
component,
|
|
) ||
|
|
[
|
|
+ 'qa/',
|
|
'portal/',
|
|
'investment/',
|
|
'portfolio/',
|
|
@@ -93,7 +94,7 @@
|
|
? 'Definições da conta'
|
|
: 'Detalhes');
|
|
return (
|
|
- <MenuPlacement.Provider value={true}>
|
|
+ <NavigationContextProvider><MenuPlacement.Provider value={true}>
|
|
<div
|
|
className={`pb-8 lg:pb-24 [&_button]:scroll-mb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24 ${printable ? 'print:pb-0' : ''}`}
|
|
>
|
|
@@ -140,7 +141,7 @@
|
|
<div id="portal-content" tabIndex={-1}>
|
|
{portalShell && (
|
|
<div className={printable ? 'print:hidden' : undefined}>
|
|
- <JourneyCompanion />
|
|
+ <NavigationContextSummary />
|
|
</div>
|
|
)}
|
|
{children}
|
|
@@ -157,7 +158,7 @@
|
|
</a>
|
|
</aside>
|
|
</div>
|
|
- </MenuPlacement.Provider>
|
|
+ </MenuPlacement.Provider></NavigationContextProvider>
|
|
);
|
|
}
|
|
|
|
--- base/resources/js/pages/investment/catalogue.tsx
|
|
+++ QA/resources/js/pages/investment/catalogue.tsx
|
|
@@ -1,3 +1,4 @@
|
|
+import CatalogueNavigation from '@/components/catalogue-navigation';
|
|
import { ClassificationFilters } from '@/components/opportunity-classification';
|
|
import { Link, router, useForm, usePage } from '@inertiajs/react';
|
|
import { useEffect, useRef, useState } from 'react';
|
|
@@ -263,53 +264,7 @@
|
|
}
|
|
>
|
|
<PartnershipSearchResults query={String(filters.q ?? '')} />
|
|
- <nav
|
|
- aria-label="Dimensões do catálogo"
|
|
- className="grid gap-3 sm:grid-cols-4"
|
|
- >
|
|
- <Link className={card} href={dimensionUrl('cluster')}>
|
|
- Por Cluster
|
|
- </Link>
|
|
- <Link className={card} href={dimensionUrl('corridor')}>
|
|
- Por Corredor
|
|
- </Link>
|
|
- <Link className={card} href={dimensionUrl('zee')}>
|
|
- Por ZEE
|
|
- </Link>
|
|
- <Link className={card} href={dimensionUrl('zfi')}>
|
|
- Por ZFI
|
|
- </Link>
|
|
- <Link className={card} href="/zonas?category=zee">
|
|
- Fichas de ZEE
|
|
- </Link>
|
|
- <Link className={card} href="/zonas?category=zfi">
|
|
- Fichas de ZFI
|
|
- </Link>
|
|
- <Link className={card} href="/zonas?category=industrial_park">
|
|
- Parques industriais
|
|
- </Link>
|
|
- <Link className={card} href="/carteira?kind=project">
|
|
- Projectos âncora documentados
|
|
- </Link>
|
|
- <Link
|
|
- className={card}
|
|
- href="/negocios?modality=company_purchase"
|
|
- >
|
|
- Comprar uma empresa
|
|
- </Link>
|
|
- <Link className={card} href="/negocios?modality=company_sale">
|
|
- Vender uma empresa
|
|
- </Link>
|
|
- <Link className={card} href="/negocios?modality=real_estate">
|
|
- Imobiliário
|
|
- </Link>
|
|
- <Link className={card} href="/negocios?modality=land_right">
|
|
- Terrenos e direitos fundiários
|
|
- </Link>
|
|
- <Link className={card} href="/negocios">
|
|
- Todos os negócios publicados
|
|
- </Link>
|
|
- </nav>
|
|
+ <CatalogueNavigation dimensionUrl={dimensionUrl} />
|
|
<p>
|
|
Combine contexto territorial, dimensão e necessidades. As fichas
|
|
documentais e as oportunidades mantêm a sua origem e natureza.
|
|
--- base/resources/js/app.tsx
|
|
+++ QA/resources/js/app.tsx
|
|
@@ -24,6 +24,7 @@
|
|
case name === 'welcome':
|
|
case name === 'PortalInvestidor':
|
|
case name === 'management-access':
|
|
+ case name.startsWith('qa/'):
|
|
case name.startsWith('portal/'):
|
|
case name.startsWith('investment/'):
|
|
case name.startsWith('portfolio/'):
|
|
--- base/resources/js/layouts/app/app-sidebar-layout.tsx
|
|
+++ QA/resources/js/layouts/app/app-sidebar-layout.tsx
|
|
@@ -2,7 +2,7 @@
|
|
import { AppShell } from '@/components/app-shell';
|
|
import { AppSidebar } from '@/components/app-sidebar';
|
|
import { AppSidebarHeader } from '@/components/app-sidebar-header';
|
|
-import { JourneyCompanion } from '@/components/journey-companion';
|
|
+import { NavigationContextSummary } from '@/components/navigation-context';
|
|
import { PortalMenu } from '@/layouts/portal-navigation';
|
|
import type { AppLayoutProps } from '@/types';
|
|
|
|
@@ -16,7 +16,7 @@
|
|
<AppContent variant="sidebar" className="min-w-0 overflow-x-clip">
|
|
<AppSidebarHeader breadcrumbs={breadcrumbs} />
|
|
<PortalMenu primary />
|
|
- <JourneyCompanion />
|
|
+ <NavigationContextSummary />
|
|
{children}
|
|
</AppContent>
|
|
</AppShell>
|
|
--- base/routes/web.php
|
|
+++ QA/routes/web.php
|
|
@@ -265,3 +265,20 @@
|
|
$managementRoute->block(10, 10);
|
|
}
|
|
}
|
|
+
|
|
+
|
|
+// QA-only navigation preview; no business write route and no new permissions.
|
|
+if (app()->environment('testing') && config('database.connections.pgsql.host') === '127.0.0.1' && (int) config('database.connections.pgsql.port') === 55441 && str_ends_with(config('database.connections.pgsql.database'), '_test')) {
|
|
+ Route::get('/qa/navegacao', function (\Illuminate\Http\Request $request) {
|
|
+ $input=$request->validate(['area'=>'nullable|in:inicio,porque,licenciamento', 'entrada'=>'nullable|in:ideia,oportunidade,sector,localizacao', 'context'=>'nullable|uuid']);
|
|
+ $sources=[];
|
|
+ foreach(\App\Models\Opportunity::published()->with('sector:id,name,slug')->orderBy('title')->get() as $o){
|
|
+ $values=['title'=>$o->title];if($o->sector){$values['sector']=$o->sector->name;}
|
|
+ if($o->province){$values['province']=$o->province;}if($o->district){$values['district']=$o->district;}
|
|
+ $sources[]=['key'=>'opportunity:'.$o->id,'kind'=>'oportunidade','title'=>$o->title,'href'=>'/oportunidades/'.$o->slug,'version'=>$o->version_no ?? $o->updated_at?->toIso8601String(),'values'=>$values];
|
|
+ }
|
|
+ foreach(\App\Models\Sector::where('is_active',true)->orderBy('name')->get() as $s){$sources[]=['key'=>'sector:'.$s->id,'kind'=>'sector','title'=>$s->name,'href'=>'/sectores/'.$s->slug,'version'=>$s->updated_at?->toIso8601String(),'values'=>['sector'=>$s->name]];}
|
|
+ foreach(app(\App\Services\InvestmentZones::class)->visible()->where('category','industrial_park')->orderBy('name')->get() as $z){$sources[]=['key'=>'zone:'.$z->id,'kind'=>'localizacao','title'=>$z->name,'href'=>'/zonas/'.$z->id,'version'=>$z->version_no,'values'=>array_filter(['province'=>$z->province, 'district'=>$z->district],fn($v)=>is_string($v) && trim($v)!=='')];}
|
|
+ return Inertia::render('qa/navigation',['sources'=>$sources,'area'=>$input['area'] ?? 'inicio']);
|
|
+ });
|
|
+}
|
|
--- base/resources/js/components/navigation-context.tsx
|
|
+++ QA/resources/js/components/navigation-context.tsx
|
|
@@ -0,0 +1,88 @@
|
|
+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>;
|
|
+}
|
|
--- base/resources/js/components/catalogue-navigation.tsx
|
|
+++ QA/resources/js/components/catalogue-navigation.tsx
|
|
@@ -0,0 +1,16 @@
|
|
+import { Link, usePage } from '@inertiajs/react';
|
|
+export default function CatalogueNavigation({ dimensionUrl }: { dimensionUrl?: (dimension: string) => string }) {
|
|
+ const { url, props } = usePage<{ educationEnabled?: boolean; legacyContentEnabled?: boolean; existingBusinessEnabled?: boolean }>();
|
|
+ const context = new URL(url, 'https://qa.invalid').searchParams.get('context');
|
|
+ const withContext = (href: string) => { const u = new URL(href, 'https://qa.invalid'); if (u.pathname === '/oportunidades' && u.searchParams.has('dimension') && dimensionUrl) return dimensionUrl(u.searchParams.get('dimension')!); if (context) u.searchParams.set('context', context); return u.pathname + u.search; };
|
|
+ const sections = {
|
|
+ 'Enquadramento e filtros': [['Clusters', '/oportunidades?dimension=cluster'], ['Corredores', '/oportunidades?dimension=corridor'], ['ZEE', '/oportunidades?dimension=zee'], ['ZFI', '/oportunidades?dimension=zfi']],
|
|
+ 'Modalidade e vistas': [...(props.existingBusinessEnabled ? [['Comprar uma empresa', '/negocios?modality=company_purchase'], ['Vender uma empresa', '/negocios?modality=company_sale'], ['Imobiliário', '/negocios?modality=real_estate'], ['Terrenos e direitos fundiários', '/negocios?modality=land_right'], ['Todos os negócios publicados', '/negocios']] : []), ['Parcerias', '/parcerias']],
|
|
+ 'Pesquisa transversal': [['Sectores de investimento', '/sectores'], ['Localizações e mapa', '/oportunidades?view=map']],
|
|
+ 'Consulta relacionada': [['Projectos âncora', '/carteira?kind=project'], ['Parques industriais', '/zonas?physical_category=industrial_park'], ['Zonas e enquadramentos', '/zonas'], ['Carteira e estruturas', '/carteira'], ['Fichas de clusters', '/carteira?kind=cluster'], ['Fichas de corredores', '/carteira?kind=corridor'], ['Fichas ZEE', '/zonas?category=zee'], ['Fichas ZFI', '/zonas?category=zfi'], ...(props.educationEnabled ? [['Educação e competências', '/educacao']] : []), ...(props.legacyContentEnabled ? [['Artigos setoriais', '/explorar/agronegocio']] : []), ['Documentos', '/documentos'], ['Legislação', '/legislacao'], ['Como investir', '/como-investir']],
|
|
+ };
|
|
+ return <nav className="my-4 grid gap-3 rounded-xl border bg-white p-4 sm:grid-cols-2 lg:grid-cols-4" aria-label="Explorar dentro do catálogo">
|
|
+ {Object.entries(sections).map(([title, items]) => <section key={title}><h2 className="mb-2 font-semibold">{title}</h2><ul className="space-y-2">{items.map(([label, href]) => <li key={label}><Link className="underline" href={withContext(href)}>{label}</Link></li>)}</ul></section>)}
|
|
+ <p className="text-sm sm:col-span-2 lg:col-span-4">Filtros e vistas reutilizam os catálogos existentes. Comprar/vender continua no consumidor /negocios; não duplica anúncios nem unifica contagens. Selecionar um parque ou projeto específico usa os filtros existentes; a ficha relacionada não é uma oportunidade.</p>
|
|
+ </nav>;
|
|
+}
|
|
--- base/resources/js/pages/qa/navigation.tsx
|
|
+++ QA/resources/js/pages/qa/navigation.tsx
|
|
@@ -0,0 +1,73 @@
|
|
+import { Head, Link, usePage } from '@inertiajs/react';
|
|
+import { useEffect, useState } from 'react';
|
|
+import CatalogueNavigation from '@/components/catalogue-navigation';
|
|
+import { useNavigationContext } from '@/components/navigation-context';
|
|
+
|
|
+type Source = { key: string; kind: string; title: string; href: string; version: string | number | null; values: Partial<Values> };
|
|
+type Values = { title: string; sector: string; province: string; district: string };
|
|
+const labels: Record<keyof Values, string> = { title: 'Investimento', sector: 'Sector', province: 'Província', district: 'Distrito' };
|
|
+const keys = Object.keys(labels) as (keyof Values)[];
|
|
+const blank: Values = { title: '', sector: '', province: '', district: '' };
|
|
+export default function NavigationPrototype({ sources, area }: { sources: Source[]; area: string }) {
|
|
+ const { actor, active, view, cases, choose } = useNavigationContext();
|
|
+ const { url } = usePage();
|
|
+ const entry = new URL(url, 'https://qa.invalid').searchParams.get('entrada') ?? 'ideia';
|
|
+ const [values, setValues] = useState<Values>(blank);
|
|
+ const [dirty, setDirty] = useState<Partial<Record<keyof Values, boolean>>>({});
|
|
+ const [pending, setPending] = useState(''); const [selected, setSelected] = useState<Source | null>(null);
|
|
+ const [acceptSource, setAcceptSource] = useState<Partial<Record<keyof Values, boolean>>>({});
|
|
+ const [message, setMessage] = useState('');
|
|
+ useEffect(() => {
|
|
+ if (!view) { setValues(blank); return; }
|
|
+ const zone = view.zone_contexts.length === 1 ? view.zone_contexts[0] : null;
|
|
+ setValues({ title: view.case.title, sector: view.sector_contexts.length === 1 ? view.sector_contexts[0].name : '', province: zone?.province ?? '', district: zone?.district ?? '' });
|
|
+ setDirty({});setSelected(null);setPending('');setMessage('Dados existentes recuperados do mesmo dossier; campos sem correspondência inequívoca ficam por confirmar.');
|
|
+ }, [view?.case.id, actor]); // Values are a temporary preview; never replace local edits on a background refresh.
|
|
+ const candidate = sources.find(s => s.key === pending);
|
|
+ const changed = !!selected;
|
|
+ function confirm() {
|
|
+ if (!candidate) return;
|
|
+ const next = { ...values };
|
|
+ for (const key of keys) { const proposed = candidate.values[key]; if (proposed !== undefined && (!dirty[key] || acceptSource[key])) next[key] = proposed; }
|
|
+ setValues(next);setSelected(candidate);setPending('');setAcceptSource({});
|
|
+ setMessage('Mudança confirmada apenas nesta prévia de navegação. O dossier, os resultados e as submissões do servidor não foram alterados.');
|
|
+ }
|
|
+ return <main className="mx-auto max-w-6xl min-w-0 [overflow-wrap:anywhere] space-y-6 p-4 md:p-8">
|
|
+ <Head title="Organização da navegação — QA" />
|
|
+ <h1 className="text-2xl font-bold">{area === 'porque' ? 'Porquê investir em Moçambique' : area === 'licenciamento' ? 'Licenciamento no investimento atual' : 'Navegação do investidor — protótipo QA'}</h1>
|
|
+ <p className="rounded border border-amber-300 bg-amber-50 p-3" role="status">Prévia de organização. Lê os cadastros e dossiers autorizados; não cria cadastros nem grava mudanças de contexto, resultados ou submissões. As lacunas abaixo são explícitas.</p>
|
|
+ {area === 'porque' && <p>Página dedicada por consolidar. <Link className="underline" href="/">Conteúdo público atual</Link> e <Link className="underline" href="/sectores">sectores existentes</Link> mantidos; não foram inventados factos ou incentivos.</p>}
|
|
+ <nav className="grid gap-3 sm:grid-cols-4" aria-label="Quatro pontos de entrada">
|
|
+ {[['ideia', 'Ideia'], ['oportunidade', 'Oportunidade'], ['sector', 'Sector'], ['localizacao', 'Localização']].map(([code, label]) => <Link key={code} className={`rounded-xl border p-4 font-semibold ${entry === code ? 'border-emerald-700 bg-emerald-50' : 'bg-white'}`} href={`/qa/navegacao?entrada=${code}${active ? `&context=${active}` : ''}`}>Entrar por {label.toLocaleLowerCase()}</Link>)}
|
|
+ </nav>
|
|
+ {!actor ? <p><Link className="font-semibold underline" href={`/investimentos`}>Entrar para continuar um dossier existente</Link>. Nenhuma conta é necessária para explorar conteúdos e oportunidades.</p> : <label className="grid gap-1">Continuar no mesmo dossier<select className="min-w-0 w-full max-w-full rounded border p-3" value={active} onChange={e => choose(e.target.value)}><option value="">Selecionar dossier autorizado</option>{cases.map(c => <option key={c.id} value={c.id}>{c.title}</option>)}</select></label>}
|
|
+ {view && <section className="space-y-4 rounded-xl border bg-white p-4" aria-label="Prévia de contexto e preenchimento">
|
|
+ <h2 className="text-lg font-semibold">Mesmo dossier: {view.case.title}</h2><p>UUID {active} · versão {view.case.version}. Entrada atual: {entry}. Não foi criado outro processo.</p>
|
|
+ {area === 'licenciamento' && <Link className="block font-semibold underline" href={`/investimentos/${active}#S08`}>Abrir S08 — Licenciamento prévio</Link>}
|
|
+ <label className="grid gap-1">Nova oportunidade, sector ou localização<select className="min-w-0 w-full max-w-full rounded border p-3" value={pending} onChange={e => { setPending(e.target.value); setAcceptSource({}); }}><option value="">Selecionar para comparar antes de aplicar</option>{sources.filter(s => entry === 'ideia' || s.kind === entry).map(s => <option key={s.key} value={s.key}>{s.title} · {s.kind}</option>)}</select></label>
|
|
+ {candidate && <section className="space-y-3 rounded border border-emerald-300 p-3" aria-label="Prévia do impacto da mudança">
|
|
+ <h3 className="font-semibold">Comparar: {selected?.title ?? 'contexto guardado'} → {candidate.title}</h3>
|
|
+ <p>Origem: <a className="underline" href={candidate.href}>{candidate.href}</a> · versão/data: {candidate.version ?? 'não exposta pelo cadastro'}</p>
|
|
+ <div className="overflow-x-auto"><table className="w-full text-left text-sm"><thead><tr><th>Tratamento</th><th>Informação concreta</th></tr></thead><tbody>
|
|
+ <tr><th>Mantido</th><td>Identificação do dossier, {view.documents.length} documentos, campos não afetados e alterações locais abaixo.</td></tr>
|
|
+ <tr><th>Atualizado pela nova seleção</th><td>{keys.filter(k => candidate.values[k] !== undefined).map(k => <div key={k}>{labels[k]}: {values[k] || 'não informado'} → {candidate.values[k] || 'não informado'} {dirty[k] && <label><input type="checkbox" checked={!!acceptSource[k]} onChange={e => setAcceptSource({ ...acceptSource, [k]: e.target.checked })} /> Usar este valor em vez da minha alteração (por defeito conservada)</label>}</div>)}</td></tr>
|
|
+ <tr><th>Precisa de revisão ou recálculo</th><td>{view.results.length} resultados existentes; confirmar pressupostos fiscais/territoriais e requisitos dependentes. O protótipo não recalcula nem declara estes resultados atuais no novo cenário.</td></tr>
|
|
+ <tr><th>Preservado no histórico</th><td>{view.requests.length} pedidos/submissões, decisões e snapshots anteriores. Não são reescritos.</td></tr>
|
|
+ </tbody></table></div>
|
|
+ <button className="mr-4 rounded border px-4 py-2" onClick={() => { setPending(''); setMessage('Mudança cancelada; valores e contexto da prévia preservados.'); }}>Cancelar mudança</button><button className="rounded bg-emerald-800 px-4 py-2 text-white" onClick={confirm}>Confirmar apenas a prévia</button>
|
|
+ </section>}
|
|
+ {message && <p role="status">{message}</p>}
|
|
+ {selected && <p className="rounded bg-emerald-50 p-3">Contexto em prévia: {selected.title}. Não representa associação gravada. Associar não confirma incentivos, licenças, disponibilidade de terra ou autorizações.</p>}
|
|
+ <div className="grid gap-4 sm:grid-cols-2">{keys.map(k => <label key={k} className="grid gap-1">{labels[k]}<input className="min-w-0 rounded border p-3" value={values[k]} onChange={e => { setValues({ ...values, [k]: e.target.value }); setDirty({ ...dirty, [k]: true }); }} /><span className="text-xs">{dirty[k] ? 'Alteração do utilizador nesta prévia — não gravada' : selected?.values[k] !== undefined ? `Referência selecionada: ${selected.title}, ${selected.version ?? 'versão não exposta'}` : `Dossier ${active}, v${view.case.version}; desconhecido se vazio`}</span></label>)}</div>
|
|
+ <p>Campos preenchidos a partir das referências autorizadas; dados mestres são só leitura. Valores desta prévia não substituem declarações ou snapshots do processo. Alterações locais não persistem após sair desta página.</p>
|
|
+ <h3 className="font-semibold">Resultados e submissões anteriores</h3>
|
|
+ {view.results.length === 0 && <p>Não há resultado registado neste dossier; revisão/recálculo não demonstrados num resultado real.</p>}
|
|
+ {view.results.map(r => <p key={r.id}>{r.engine} · {r.recorded_at} · {changed ? 'Pressupostos a rever no cenário em prévia; original preservado' : 'Resultado guardado no contexto original'}</p>)}
|
|
+ {view.requests.map(r => <p key={r.id}>{r.protocol} · v{r.version} · {r.status} · conteúdo enviado preservado</p>)}
|
|
+ <nav className="flex flex-wrap gap-4" aria-label="Realizar neste investimento"><Link className="underline" href={`/investimentos/${active}`}>Abrir o mesmo dossier</Link>{view.tools.simulator && <Link className="underline" href={view.tools.simulator}>Incentivos e simulador neste contexto</Link>}<Link className="underline" href={`/investimentos/${active}#S08`}>Licenciamento S08</Link>{view.facts.land_needed === 'no' ? <span>Terra: ramo dispensado segundo o processo</span> : view.tools.land && <Link className="underline" href={view.tools.land}>Acesso à terra neste contexto</Link>}<Link className="underline" href={view.tools.desk}>Serviços e apoio deste dossier</Link></nav>
|
|
+ <details><summary className="cursor-pointer font-semibold">Cinco fases e 19 etapas existentes — orientação livre</summary>{Object.entries(view.phases).map(([n, title]) => <section key={n}><h3 className="my-2 font-semibold">{n}. {title}</h3><ul>{view.steps.filter(s => s.phase === Number(n)).map(s => <li key={s.code}><Link className="underline" href={`/investimentos/${active}#${s.code}`}>{s.code} — {s.title}</Link> · {s.state === 'dispensed' ? 'Ramo dispensado; não é obrigatório' : s.state}</li>)}</ul></section>)}</details>
|
|
+ </section>}
|
|
+ <CatalogueNavigation />
|
|
+ <section className="space-y-2 rounded-xl border border-amber-300 p-4"><h2 className="font-semibold">Lacunas para a consolidação posterior</h2><ul className="list-disc space-y-1 pl-5"><li>Associação persistente genérica de oportunidade ou território ao dossier, com impacto transversal, ainda não disponível.</li><li>Troca transacional de contexto, invalidação/revalidação e recálculo de todos os consumidores: prévia visual, não operação de negócio.</li><li>Resumo de oportunidade e etapa atualmente consultada não é exposto integralmente pelo serviço de contexto atual; não inferir pelos nomes.</li><li>Página dedicada «Porquê investir» por consolidar. Consolidação do manual apenas depois da avaliação desta organização.</li></ul></section>
|
|
+ </main>;
|
|
+}
|