@@ -29,6 +29,7 @@ void createInertiaApp({
|
||||
case name.startsWith('portfolio/'):
|
||||
case name.startsWith('land-assistance/'):
|
||||
case name.startsWith('desk/'):
|
||||
case name.startsWith('investor-path/'):
|
||||
return PortalNavigation;
|
||||
case name.startsWith('auth/'):
|
||||
return [PortalNavigation, AuthLayout];
|
||||
|
||||
@@ -179,11 +179,17 @@ export function AppHeader({ breadcrumbs = [] }: Props) {
|
||||
<div className="ml-auto flex items-center space-x-2">
|
||||
<div className="relative flex items-center space-x-1">
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="group h-9 w-9 cursor-pointer"
|
||||
>
|
||||
<Search className="!size-5 opacity-80 group-hover:opacity-100" />
|
||||
<Link
|
||||
href="/oportunidades"
|
||||
aria-label="Pesquisar oportunidades"
|
||||
>
|
||||
<Search className="!size-5 opacity-80 group-hover:opacity-100" />
|
||||
</Link>
|
||||
</Button>
|
||||
<div className="ml-1 hidden gap-1 lg:flex">
|
||||
{rightNavItems.map((item) => (
|
||||
|
||||
@@ -1,20 +1,79 @@
|
||||
import { useState } from 'react';
|
||||
import { useId, useState } from 'react';
|
||||
|
||||
export type Country = { code: string; name: string; name_en: string };
|
||||
|
||||
export default function CountrySelect({ countries, value, onChange, id, disabled = false }: {
|
||||
countries: Country[]; value: string; onChange: (value: string) => void; id: string; disabled?: boolean;
|
||||
export default function CountrySelect({
|
||||
countries,
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
disabled = false,
|
||||
label = 'País',
|
||||
required = false,
|
||||
allowLegacyValue = false,
|
||||
}: {
|
||||
countries: Country[];
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
id?: string;
|
||||
disabled?: boolean;
|
||||
label?: string;
|
||||
required?: boolean;
|
||||
allowLegacyValue?: boolean;
|
||||
}) {
|
||||
const generatedId = useId();
|
||||
const [search, setSearch] = useState('');
|
||||
const matches = countries.filter((country) => country.code === value ||
|
||||
`${country.name} ${country.name_en} ${country.code}`.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase()
|
||||
.includes(search.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase()));
|
||||
return <div className="space-y-2">
|
||||
<input disabled={disabled} className="w-full rounded border p-2" aria-label="Pesquisar país" value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Pesquisar nome ou código do país" />
|
||||
<select disabled={disabled} id={id} className="w-full rounded border p-2" value={value} onChange={(event) => onChange(event.target.value)}>
|
||||
<option value="">Não informado</option>
|
||||
{matches.map((country) => <option key={country.code} value={country.code}>{country.name} ({country.code})</option>)}
|
||||
</select>
|
||||
{matches.length === 0 && <p role="status">Nenhum país corresponde à pesquisa.</p>}
|
||||
</div>;
|
||||
const matches = countries.filter(
|
||||
(country) =>
|
||||
country.code === value ||
|
||||
`${country.name} ${country.name_en} ${country.code}`
|
||||
.normalize('NFD')
|
||||
.replace(/\p{Diacritic}/gu, '')
|
||||
.toLowerCase()
|
||||
.includes(
|
||||
search
|
||||
.normalize('NFD')
|
||||
.replace(/\p{Diacritic}/gu, '')
|
||||
.toLowerCase(),
|
||||
),
|
||||
);
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
disabled={disabled}
|
||||
className="w-full rounded border p-2"
|
||||
aria-label={`Pesquisar ${label.toLowerCase()}`}
|
||||
maxLength={100}
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="Pesquisar nome ou código do país"
|
||||
/>
|
||||
<select
|
||||
disabled={disabled}
|
||||
id={id ?? generatedId}
|
||||
aria-label={label}
|
||||
required={required}
|
||||
className="w-full rounded border p-2"
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
>
|
||||
<option value="">Não informado</option>
|
||||
{allowLegacyValue &&
|
||||
value &&
|
||||
!countries.some((country) => country.code === value) && (
|
||||
<option value={value}>
|
||||
{value} (valor anterior conservado)
|
||||
</option>
|
||||
)}
|
||||
{matches.map((country) => (
|
||||
<option key={country.code} value={country.code}>
|
||||
{country.name} ({country.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{matches.length === 0 && (
|
||||
<p role="status">Nenhum país corresponde à pesquisa.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ export type InvestmentMapFeature = {
|
||||
};
|
||||
};
|
||||
export type InvestmentMapArea = {
|
||||
purpose?: string;
|
||||
geometry: GeoJsonObject;
|
||||
title: string;
|
||||
source_reference?: string | null;
|
||||
@@ -30,9 +31,11 @@ const noAreas: InvestmentMapArea[] = [];
|
||||
export default function InteractiveInvestmentMap({
|
||||
points,
|
||||
areas = noAreas,
|
||||
contextOnly = false,
|
||||
}: {
|
||||
points: InvestmentMapFeature[] | null;
|
||||
areas?: InvestmentMapArea[];
|
||||
contextOnly?: boolean;
|
||||
}) {
|
||||
const element = useRef<HTMLDivElement>(null);
|
||||
const map = useRef<LeafletMap | null>(null);
|
||||
@@ -73,8 +76,19 @@ export default function InteractiveInvestmentMap({
|
||||
const bounds: [number, number][] = [];
|
||||
for (const area of areas) {
|
||||
const label = document.createElement('p');
|
||||
label.textContent = `${area.title} · Polígono cadastrado, limites oficiais por verificar · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
|
||||
const layer = L.geoJSON(area.geometry)
|
||||
label.textContent = `${area.title} · ${area.purpose === 'administrative_boundary' ? 'Limite administrativo da edição indicada; não representa um local de investimento' : 'Polígono cadastrado, limites oficiais por verificar'} · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
|
||||
const layer = L.geoJSON(
|
||||
area.geometry,
|
||||
area.purpose === 'administrative_boundary'
|
||||
? {
|
||||
style: {
|
||||
color: '#2563eb',
|
||||
dashArray: '5 5',
|
||||
fillOpacity: 0.06,
|
||||
},
|
||||
}
|
||||
: {},
|
||||
)
|
||||
.bindPopup(label)
|
||||
.addTo(instance);
|
||||
const extent = layer.getBounds();
|
||||
@@ -160,12 +174,22 @@ export default function InteractiveInvestmentMap({
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded-xl border bg-white p-4 text-slate-900"
|
||||
aria-label="Mapa interactivo dos investimentos"
|
||||
aria-label={
|
||||
contextOnly
|
||||
? 'Mapa dos limites administrativos'
|
||||
: 'Mapa interactivo dos investimentos'
|
||||
}
|
||||
>
|
||||
<h2 className="text-xl font-bold">Mapa dos investimentos</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
{contextOnly
|
||||
? 'Contexto administrativo'
|
||||
: 'Mapa dos investimentos'}
|
||||
</h2>
|
||||
<p>
|
||||
Arraste para navegar; use +/− para ampliar. Pode seleccionar um
|
||||
investimento na lista para o localizar.
|
||||
{contextOnly
|
||||
? 'limite cadastrado para consultar a sua edição.'
|
||||
: 'investimento na lista para o localizar.'}
|
||||
</p>
|
||||
{error && <p role="status">{error}</p>}
|
||||
<div
|
||||
@@ -177,7 +201,9 @@ export default function InteractiveInvestmentMap({
|
||||
<p role="status">A carregar localizações…</p>
|
||||
) : (
|
||||
<p role="status">
|
||||
{points.length} locais com coordenadas disponíveis.
|
||||
{contextOnly
|
||||
? `${areas.length} limites administrativos disponíveis.`
|
||||
: `${points.length} locais com coordenadas disponíveis.`}
|
||||
</p>
|
||||
)}
|
||||
<ul className="grid gap-2 md:grid-cols-2">
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState } from "react";
|
||||
import TerritoryGeometryPreview from "./territory-geometry-preview";
|
||||
import InteractiveInvestmentMap, {
|
||||
type InvestmentMapFeature,
|
||||
type InvestmentMapArea,
|
||||
} from './interactive-investment-map';
|
||||
} from "./interactive-investment-map";
|
||||
|
||||
export default function InvestmentMapPanel({
|
||||
filters,
|
||||
territoryId,
|
||||
}: {
|
||||
filters: Record<string, string | number>;
|
||||
territoryId?: string;
|
||||
}) {
|
||||
const key = JSON.stringify(filters);
|
||||
const [points, setPoints] = useState<InvestmentMapFeature[] | null>(null);
|
||||
const [missing, setMissing] = useState<
|
||||
{ id: number; title: string; url: string }[]
|
||||
>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [error, setError] = useState("");
|
||||
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
@@ -23,10 +26,10 @@ export default function InvestmentMapPanel({
|
||||
setAreas([]);
|
||||
fetch(`/api/v1/investment/map?${params}`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
headers: { Accept: "application/json" },
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error('Mapa indisponível.');
|
||||
if (!response.ok) throw new Error("Mapa indisponível.");
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
@@ -36,8 +39,8 @@ export default function InvestmentMapPanel({
|
||||
setMissing(data.unlocated ?? []);
|
||||
setError(
|
||||
data.truncated
|
||||
? 'Cobertura limitada: refine os filtros.'
|
||||
: '',
|
||||
? "Cobertura limitada: refine os filtros."
|
||||
: "",
|
||||
);
|
||||
})
|
||||
.catch((e) => {
|
||||
@@ -49,6 +52,19 @@ export default function InvestmentMapPanel({
|
||||
<section className="space-y-3">
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<InteractiveInvestmentMap points={points} areas={areas} />
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={
|
||||
territoryId ||
|
||||
String(
|
||||
filters.locality_id ||
|
||||
filters.admin_post_id ||
|
||||
filters.district_id ||
|
||||
filters.province_id ||
|
||||
filters.geo_location_id ||
|
||||
"",
|
||||
)
|
||||
}
|
||||
/>
|
||||
{missing.length > 0 && (
|
||||
<div>
|
||||
<p>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import { api } from '@/pages/investment/shared';
|
||||
import { replaceTerritoryPath } from '@/lib/territory-path.js';
|
||||
import TerritoryGeometryPreview from './territory-geometry-preview';
|
||||
|
||||
export type TerritoryOption = {
|
||||
id: string;
|
||||
@@ -38,51 +39,77 @@ export function ProvinceSelect({
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
fetch(`${endpoint}?type=province&page=1`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok)
|
||||
throw new Error('Não foi possível carregar as províncias.');
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => setOptions(data.data))
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted)
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Erro de ligação.',
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [endpoint, retry]);
|
||||
const timer = setTimeout(
|
||||
() =>
|
||||
fetch(
|
||||
`${endpoint}?${new URLSearchParams({ type: 'province', page: '1', q: search })}`,
|
||||
{
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
)
|
||||
.then(async (response) => {
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
'Não foi possível carregar as províncias.',
|
||||
);
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
if (!controller.signal.aborted) setOptions(data.data);
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted)
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Erro de ligação.',
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}),
|
||||
250,
|
||||
);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [endpoint, retry, search]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
className={className}
|
||||
aria-label={`Pesquisar ${label}`}
|
||||
maxLength={100}
|
||||
placeholder="Pesquisar nome ou código"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
/>
|
||||
<select
|
||||
id={id}
|
||||
aria-label={label}
|
||||
className={className}
|
||||
required={required}
|
||||
value={
|
||||
options.some((option) => option.name === value) ? value : ''
|
||||
}
|
||||
value={value}
|
||||
disabled={loading || Boolean(error)}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
{loading ? 'A carregar províncias…' : placeholder}
|
||||
</option>
|
||||
{value && !options.some((option) => option.name === value) && (
|
||||
<option value={value}>
|
||||
{value} (seleção guardada; conferir cadastro)
|
||||
</option>
|
||||
)}
|
||||
{options.map((option) => (
|
||||
<option key={option.id} value={option.name}>
|
||||
{option.name}
|
||||
@@ -108,10 +135,12 @@ export function TerritoryFields({
|
||||
initial = emptyTerritoryPath,
|
||||
onChange,
|
||||
endpoint = '/api/v1/investment/territory-options',
|
||||
disabled = false,
|
||||
}: {
|
||||
initial?: TerritoryOption[];
|
||||
onChange?: (path: TerritoryOption[]) => void;
|
||||
endpoint?: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [path, setPath] = useState(initial);
|
||||
useEffect(() => setPath(initial), [initial]);
|
||||
@@ -132,6 +161,7 @@ export function TerritoryFields({
|
||||
value={path[index]?.id ?? ''}
|
||||
/>
|
||||
<TerritoryLevel
|
||||
disabled={disabled}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
@@ -148,6 +178,10 @@ export function TerritoryFields({
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management={endpoint.startsWith('/management/')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -159,6 +193,7 @@ export function TerritoryLevel({
|
||||
onChange,
|
||||
endpoint = '/management/territory-options',
|
||||
fieldError,
|
||||
disabled = false,
|
||||
}: {
|
||||
index: number;
|
||||
parent: string;
|
||||
@@ -166,6 +201,7 @@ export function TerritoryLevel({
|
||||
onChange: (value?: Option) => void;
|
||||
endpoint?: string;
|
||||
fieldError?: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const id = useId();
|
||||
const [page, setPage] = useState(1);
|
||||
@@ -175,8 +211,11 @@ export function TerritoryLevel({
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [search, setSearch] = useState('');
|
||||
const enabled = index === 0 || Boolean(parent);
|
||||
useEffect(() => { setPage(1); setSearch(''); }, [parent, index]);
|
||||
const enabled = !disabled && (index === 0 || Boolean(parent));
|
||||
useEffect(() => {
|
||||
setPage(1);
|
||||
setSearch('');
|
||||
}, [parent, index]);
|
||||
useEffect(() => {
|
||||
setOptions([]);
|
||||
setMore(false);
|
||||
@@ -224,7 +263,18 @@ export function TerritoryLevel({
|
||||
<label htmlFor={id} className="font-medium">
|
||||
{labels[index]}
|
||||
</label>
|
||||
<input className={control} aria-label={`Pesquisar ${labels[index]}`} disabled={!enabled} maxLength={100} value={search} onChange={(event) => { setSearch(event.target.value); setPage(1); }} placeholder={`Pesquisar ${labels[index].toLowerCase()}`} />
|
||||
<input
|
||||
className={control}
|
||||
aria-label={`Pesquisar ${labels[index]}`}
|
||||
disabled={!enabled}
|
||||
maxLength={100}
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
setSearch(event.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={`Pesquisar ${labels[index].toLowerCase()}`}
|
||||
/>
|
||||
<select
|
||||
id={id}
|
||||
aria-invalid={Boolean(fieldError)}
|
||||
@@ -345,6 +395,10 @@ export default function InvestmentTerritory({
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="bg-primary text-primary-foreground rounded px-4 py-2 disabled:opacity-50"
|
||||
|
||||
@@ -4,10 +4,15 @@ import type { Guidance } from './investor-guidance';
|
||||
|
||||
/** Carries only an account-scoped case identifier between modules; never a contact/document payload. */
|
||||
export function JourneyCompanion() {
|
||||
const { props, url } = usePage<{ auth: { user: { id: number } | null } }>();
|
||||
const { props, url } = usePage<{
|
||||
auth: { user: { id: number } | null };
|
||||
investorPathEnabled?: boolean;
|
||||
}>();
|
||||
const actor = props.auth?.user?.id;
|
||||
const [open, setOpen] = useState(false);
|
||||
const [cases, setCases] = useState<{ id: string; title: string }[]>([]);
|
||||
const [cases, setCases] = useState<
|
||||
{ id: string; title: string; path_supported?: boolean }[]
|
||||
>([]);
|
||||
const [active, setActive] = useState('');
|
||||
const [guidance, setGuidance] = useState<Guidance | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
@@ -19,15 +24,27 @@ export function JourneyCompanion() {
|
||||
if (!actor) return;
|
||||
try {
|
||||
const key = `investmoz-guidance-case:${actor}`;
|
||||
const routeId = url.match(
|
||||
/^\/balcao-virtual\/dossiers\/([a-f0-9-]{36})/i,
|
||||
)?.[1];
|
||||
const context = new URL(
|
||||
url,
|
||||
'https://investmoz.invalid',
|
||||
).searchParams.get('context');
|
||||
const pathId = props.investorPathEnabled
|
||||
? url.match(/^\/investimentos\/([a-f0-9-]{36})/i)?.[1]
|
||||
: null;
|
||||
const routeId =
|
||||
pathId ??
|
||||
(props.investorPathEnabled &&
|
||||
context &&
|
||||
/^[a-f0-9-]{36}$/i.test(context)
|
||||
? context
|
||||
: null) ??
|
||||
url.match(/^\/balcao-virtual\/dossiers\/([a-f0-9-]{36})/i)?.[1];
|
||||
if (routeId) sessionStorage.setItem(key, routeId);
|
||||
setActive(routeId ?? sessionStorage.getItem(key) ?? '');
|
||||
} catch {
|
||||
setMessage('Selecção de contexto disponível apenas nesta página.');
|
||||
}
|
||||
}, [actor, url]);
|
||||
}, [actor, url, props.investorPathEnabled]);
|
||||
useEffect(() => {
|
||||
if (!open || !actor) return;
|
||||
const controller = new AbortController();
|
||||
@@ -42,7 +59,11 @@ export function JourneyCompanion() {
|
||||
'Acompanhamento em preparação; os pedidos anteriores continuam no Balcão Virtual.',
|
||||
);
|
||||
return r.json() as Promise<{
|
||||
cases: { id: string; title: string }[];
|
||||
cases: {
|
||||
id: string;
|
||||
title: string;
|
||||
path_supported?: boolean;
|
||||
}[];
|
||||
}>;
|
||||
})
|
||||
.then((data) => setCases(data.cases))
|
||||
@@ -110,6 +131,25 @@ export function JourneyCompanion() {
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
{props.investorPathEnabled && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href="/investimentos"
|
||||
>
|
||||
Os meus investimentos e próxima acção
|
||||
</Link>
|
||||
)}
|
||||
{cases.some(
|
||||
(item) =>
|
||||
item.id === active && item.path_supported,
|
||||
) && (
|
||||
<Link
|
||||
className="block font-semibold underline"
|
||||
href={`/investimentos/${active}`}
|
||||
>
|
||||
Voltar ao percurso deste investimento
|
||||
</Link>
|
||||
)}
|
||||
<label className="block">
|
||||
Contexto do projecto
|
||||
<select
|
||||
|
||||
@@ -63,10 +63,10 @@ import {
|
||||
} from '@/lib/simulation-api';
|
||||
|
||||
type Choice = { id: string; label: string };
|
||||
const draftKey = 'investmoz-simulation-draft-v1';
|
||||
const idempotencyStorageKey = 'investmoz-simulation-idempotency-v1';
|
||||
const draftCreateKey = 'investmoz-simulation-draft-create-key-v1';
|
||||
const draftIdKey = 'investmoz-simulation-draft-id-v1';
|
||||
const legacyDraftKey = 'investmoz-simulation-draft-v1';
|
||||
const legacyIdempotencyStorageKey = 'investmoz-simulation-idempotency-v1';
|
||||
const legacyDraftCreateKey = 'investmoz-simulation-draft-create-key-v1';
|
||||
const legacyDraftIdKey = 'investmoz-simulation-draft-id-v1';
|
||||
const idempotencyKey = () => crypto.randomUUID();
|
||||
|
||||
function csrfToken(): string {
|
||||
@@ -397,6 +397,26 @@ function useChoices(
|
||||
let url: URL;
|
||||
if (source === 'sector') {
|
||||
url = new URL('/api/v1/sectors', window.location.origin);
|
||||
} else if (source === 'country') {
|
||||
url = new URL(
|
||||
'/api/v1/catalogs/countries',
|
||||
window.location.origin,
|
||||
);
|
||||
url.searchParams.set('q', query);
|
||||
url.searchParams.set('per_page', '100');
|
||||
} else if (
|
||||
['province', 'district', 'admin_post', 'locality'].includes(
|
||||
source,
|
||||
)
|
||||
) {
|
||||
url = new URL(
|
||||
'/api/v1/investment/territory-options',
|
||||
window.location.origin,
|
||||
);
|
||||
url.searchParams.set('type', source);
|
||||
url.searchParams.set('q', query);
|
||||
if (source !== 'province')
|
||||
url.searchParams.set('parent_id', parent);
|
||||
} else {
|
||||
url = new URL(
|
||||
'/api/v1/catalogs/' +
|
||||
@@ -427,6 +447,7 @@ function useChoices(
|
||||
'Não foi possível carregar as opções. Tente novamente.',
|
||||
);
|
||||
const payload = await readSimulationApiJson(response);
|
||||
if (controller.signal.aborted) return;
|
||||
setChoices(simulationCatalogChoices(payload));
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted)
|
||||
@@ -489,12 +510,15 @@ function SearchChoice({
|
||||
retry,
|
||||
} = useChoices(source, query, parent, !disabled && open);
|
||||
const chosen = Array.isArray(value) ? value : value ? [value] : [];
|
||||
const searchText = (text: string) =>
|
||||
text
|
||||
.normalize('NFD')
|
||||
.replace(/\p{Diacritic}/gu, '')
|
||||
.toLocaleLowerCase();
|
||||
const filtered = choices.filter(
|
||||
(option) =>
|
||||
option.label
|
||||
.toLocaleLowerCase()
|
||||
.includes(query.toLocaleLowerCase()) ||
|
||||
option.id.toLocaleLowerCase().includes(query.toLocaleLowerCase()),
|
||||
searchText(option.label).includes(searchText(query)) ||
|
||||
searchText(option.id).includes(searchText(query)),
|
||||
);
|
||||
useEffect(() => {
|
||||
if (open) activeOptionRef.current?.scrollIntoView({ block: 'nearest' });
|
||||
@@ -746,6 +770,28 @@ export function SimulationForm() {
|
||||
const { auth } = usePage<{
|
||||
auth: { user: { email_verified_at?: string | null } | null };
|
||||
}>().props;
|
||||
const pageUrl = usePage().url;
|
||||
const draftContext = useMemo(() => {
|
||||
const params = new URL(pageUrl, 'https://investmoz.invalid')
|
||||
.searchParams;
|
||||
return {
|
||||
context: params.get('context'),
|
||||
requestedDraft: params.get('draft'),
|
||||
};
|
||||
}, [pageUrl]);
|
||||
const contextId = draftContext.context;
|
||||
const storageScope = contextId
|
||||
? `:case:${contextId}`
|
||||
: draftContext.requestedDraft
|
||||
? `:draft:${draftContext.requestedDraft}`
|
||||
: '';
|
||||
const draftKey = legacyDraftKey + storageScope;
|
||||
const draftCreateKey = legacyDraftCreateKey + storageScope;
|
||||
const draftIdKey = legacyDraftIdKey + storageScope;
|
||||
const idempotencyStorageKey = legacyIdempotencyStorageKey + storageScope;
|
||||
const currentDraftUrl = contextId
|
||||
? `/api/v1/simulation-drafts/current?context=${encodeURIComponent(contextId)}`
|
||||
: '/api/v1/simulation-drafts/current';
|
||||
const canSavePersonalData = Boolean(auth?.user);
|
||||
const canAssociateDraft = Boolean(auth?.user?.email_verified_at);
|
||||
const [draft, setDraft] = useState<SimulationDraft>({});
|
||||
@@ -1123,9 +1169,9 @@ export function SimulationForm() {
|
||||
}
|
||||
try {
|
||||
const response = await fetch(
|
||||
requestedDraftId
|
||||
requestedDraftId && !contextId
|
||||
? `/api/v1/simulation-drafts/${encodeURIComponent(requestedDraftId)}`
|
||||
: '/api/v1/simulation-drafts/current',
|
||||
: currentDraftUrl,
|
||||
{
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
@@ -1140,7 +1186,7 @@ export function SimulationForm() {
|
||||
throw new Error(
|
||||
'O servidor devolveu um rascunho com formato inválido.',
|
||||
);
|
||||
if (canSavePersonalData) {
|
||||
if (canSavePersonalData && !contextId) {
|
||||
const [listResponse, previewResponse] =
|
||||
await Promise.all([
|
||||
fetch('/api/v1/simulation-drafts', {
|
||||
@@ -1222,9 +1268,19 @@ export function SimulationForm() {
|
||||
if (storedId) sessionStorage.removeItem(draftIdKey);
|
||||
setDraft(local);
|
||||
}
|
||||
} else if (contextId || requestedDraftId) {
|
||||
saveConflictRef.current = true;
|
||||
setHasSaveConflict(true);
|
||||
setSaveStatus(
|
||||
'Dossier indisponível para esta conta. Nenhum outro rascunho foi aberto.',
|
||||
);
|
||||
} else if (!canSavePersonalData && Object.keys(local).length)
|
||||
setDraft(local);
|
||||
} catch {
|
||||
if (contextId || requestedDraftId) {
|
||||
saveConflictRef.current = true;
|
||||
setHasSaveConflict(true);
|
||||
}
|
||||
if (!canSavePersonalData && Object.keys(local).length)
|
||||
setDraft(local);
|
||||
setSaveStatus(
|
||||
@@ -1236,7 +1292,7 @@ export function SimulationForm() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [canSavePersonalData]);
|
||||
}, [canSavePersonalData, contextId, currentDraftUrl, draftIdKey, draftKey]);
|
||||
useEffect(() => {
|
||||
if (!ready || !draft.purpose) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
@@ -1268,15 +1324,12 @@ export function SimulationForm() {
|
||||
'X-XSRF-TOKEN': csrfToken(),
|
||||
};
|
||||
if (!draftIdRef.current) {
|
||||
const currentResponse = await fetch(
|
||||
'/api/v1/simulation-drafts/current',
|
||||
{
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
const currentResponse = await fetch(currentDraftUrl, {
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
);
|
||||
});
|
||||
const currentPayload: unknown = currentResponse.ok
|
||||
? await readSimulationApiJson(currentResponse)
|
||||
: { data: null };
|
||||
@@ -1313,7 +1366,12 @@ export function SimulationForm() {
|
||||
...headers,
|
||||
'If-Match': draftEtagRef.current,
|
||||
},
|
||||
body: JSON.stringify(snapshots),
|
||||
body: JSON.stringify({
|
||||
...snapshots,
|
||||
...(contextId
|
||||
? { context: contextId }
|
||||
: {}),
|
||||
}),
|
||||
},
|
||||
);
|
||||
} else {
|
||||
@@ -1326,7 +1384,10 @@ export function SimulationForm() {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { ...headers, 'Idempotency-Key': key },
|
||||
body: JSON.stringify(snapshots),
|
||||
body: JSON.stringify({
|
||||
...snapshots,
|
||||
...(contextId ? { context: contextId } : {}),
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (response.status === 412 || response.status === 428) {
|
||||
@@ -1401,7 +1462,87 @@ export function SimulationForm() {
|
||||
});
|
||||
}, 450);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [draft, ready, canSavePersonalData, accountDrafts]);
|
||||
}, [
|
||||
draft,
|
||||
ready,
|
||||
canSavePersonalData,
|
||||
accountDrafts,
|
||||
contextId,
|
||||
currentDraftUrl,
|
||||
draftCreateKey,
|
||||
draftIdKey,
|
||||
draftKey,
|
||||
]);
|
||||
|
||||
async function returnToInvestment() {
|
||||
if (!contextId || !draftIdRef.current) return;
|
||||
setContinuityError('');
|
||||
try {
|
||||
await saveQueueRef.current;
|
||||
const current = await fetch(
|
||||
`/api/v1/simulation-drafts/${draftIdRef.current}`,
|
||||
{
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
},
|
||||
);
|
||||
const saved: unknown = await readSimulationApiJson(current);
|
||||
if (
|
||||
!current.ok ||
|
||||
!isApiSimulationDraftReadResponseV1(saved) ||
|
||||
!saved.data
|
||||
)
|
||||
throw new Error(
|
||||
'Não foi possível recuperar o rascunho guardado.',
|
||||
);
|
||||
if (
|
||||
saved.data.economic_snapshot.financial_tools_snapshot !==
|
||||
draft.financial_tools_snapshot
|
||||
)
|
||||
throw new Error(
|
||||
'Aguarde a gravação das entradas da ferramenta e tente novamente.',
|
||||
);
|
||||
const dossier = await fetch(`/investimentos/${contextId}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!dossier.ok)
|
||||
throw new Error('Dossier indisponível para esta conta.');
|
||||
const view = (await dossier.json()) as {
|
||||
case: { version: number };
|
||||
};
|
||||
const response = await fetch(
|
||||
`/investimentos/${contextId}/resultados`,
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': csrfToken(),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
version: view.case.version,
|
||||
draft_id: saved.data.id,
|
||||
draft_version: saved.data.version_no,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
response.status === 409
|
||||
? 'O dossier mudou. Recupere a versão actual antes de devolver o resultado.'
|
||||
: 'Não foi possível devolver as entradas financeiras guardadas ao dossier.',
|
||||
);
|
||||
window.location.assign(`/investimentos/${contextId}`);
|
||||
} catch (cause) {
|
||||
setContinuityError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Erro ao devolver o resultado.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function openOwnedDraft(id: string) {
|
||||
setContinuityError('');
|
||||
@@ -2264,6 +2405,32 @@ export function SimulationForm() {
|
||||
id={draftIdRef.current}
|
||||
/>
|
||||
)}
|
||||
{contextId && (
|
||||
<section
|
||||
className="rounded-lg border p-4"
|
||||
aria-label="Contexto do investimento"
|
||||
>
|
||||
<p>
|
||||
Ferramenta ligada ao dossier actual. As entradas são
|
||||
guardadas no rascunho deste investimento.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="mt-2 rounded border px-3 py-2"
|
||||
disabled={!ready || hasSaveConflict || !draftVersionNo}
|
||||
onClick={() => void returnToInvestment()}
|
||||
>
|
||||
Guardar resultado financeiro e voltar ao dossier
|
||||
</button>
|
||||
{continuityError && <p role="alert">{continuityError}</p>}
|
||||
<a
|
||||
className="ml-3 underline"
|
||||
href={`/investimentos/${contextId}`}
|
||||
>
|
||||
Ver dossier
|
||||
</a>
|
||||
</section>
|
||||
)}
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2
|
||||
@@ -2465,6 +2632,7 @@ export function SimulationForm() {
|
||||
</section>
|
||||
)}
|
||||
{canSavePersonalData &&
|
||||
!contextId &&
|
||||
!showDraftChoice &&
|
||||
accountDrafts.length > 0 && (
|
||||
<section
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import InteractiveInvestmentMap, {
|
||||
type InvestmentMapArea,
|
||||
} from './interactive-investment-map';
|
||||
|
||||
const noPoints: [] = [];
|
||||
type Context = {
|
||||
selected_geometry_available: boolean;
|
||||
context_geometry_count: number;
|
||||
areas: InvestmentMapArea[];
|
||||
truncated: boolean;
|
||||
};
|
||||
export default function TerritoryGeometryPreview({
|
||||
territoryId,
|
||||
management = false,
|
||||
}: {
|
||||
territoryId?: string;
|
||||
management?: boolean;
|
||||
}) {
|
||||
const [context, setContext] = useState<Context | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
setContext(null);
|
||||
setError('');
|
||||
if (!territoryId) return;
|
||||
const controller = new AbortController();
|
||||
const endpoint = management
|
||||
? '/management/territory-geometries'
|
||||
: '/api/v1/investment/territory-geometries';
|
||||
void fetch(
|
||||
`${endpoint}?${new URLSearchParams({ territory_id: territoryId })}`,
|
||||
{
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
)
|
||||
.then(async (response) => {
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
'Não foi possível consultar os limites administrativos.',
|
||||
);
|
||||
return response.json() as Promise<Context>;
|
||||
})
|
||||
.then((data) => {
|
||||
if (!controller.signal.aborted) setContext(data);
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (!controller.signal.aborted)
|
||||
setError(
|
||||
e instanceof Error ? e.message : 'Erro de ligação.',
|
||||
);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [territoryId, management]);
|
||||
if (!territoryId) return null;
|
||||
return (
|
||||
<section
|
||||
className="space-y-2 md:col-span-full"
|
||||
aria-label="Cobertura cartográfica da seleção"
|
||||
>
|
||||
<p>Território selecionado no cadastro.</p>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{!context && !error && <p role="status">A consultar geometria…</p>}
|
||||
{context && (
|
||||
<>
|
||||
<p role="status">
|
||||
{context.selected_geometry_available
|
||||
? 'Limite administrativo disponível para este território.'
|
||||
: 'Sem limite administrativo disponível para este território.'}
|
||||
</p>
|
||||
<p>
|
||||
{context.context_geometry_count} limites disponíveis na
|
||||
hierarquia selecionada. São contexto administrativo, não
|
||||
perímetro nem disponibilidade de investimento. A edição
|
||||
e a atualidade jurídica são informações distintas.
|
||||
</p>
|
||||
{context.truncated && (
|
||||
<p role="alert">
|
||||
Exibidos os primeiros 100 limites; cobertura
|
||||
incompleta.
|
||||
</p>
|
||||
)}
|
||||
{context.areas.length > 0 && (
|
||||
<InteractiveInvestmentMap
|
||||
points={noPoints}
|
||||
areas={context.areas}
|
||||
contextOnly
|
||||
/>
|
||||
)}
|
||||
<ul>
|
||||
{context.areas.map((area, index) => (
|
||||
<li key={index}>
|
||||
{area.title} · Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} ·
|
||||
Edição: {area.source_date ?? 'Não indicada'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -36,6 +36,7 @@ const names: Record<string, string> = {
|
||||
'/manifestar-interesse': 'Manifestar interesse',
|
||||
'/carteira': 'Corredores, clusters e projectos',
|
||||
'/investidor': 'O meu painel',
|
||||
'/investimentos': 'Os meus investimentos',
|
||||
'/login': 'Entrar',
|
||||
'/register': 'Criar conta',
|
||||
'/dashboard': 'Painel',
|
||||
@@ -60,6 +61,7 @@ export default function PortalNavigation({
|
||||
'investment/',
|
||||
'portfolio/',
|
||||
'desk/',
|
||||
'investor-path/',
|
||||
'auth/',
|
||||
'land-assistance/',
|
||||
].some((prefix) => component.startsWith(prefix));
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
calculateBreakEven,
|
||||
calculateFundingGap,
|
||||
restoreFinancialToolsSnapshot,
|
||||
} from './financial-calculators.ts';
|
||||
|
||||
export const pathStates: Record<string, string> = {
|
||||
not_started: 'Por iniciar',
|
||||
preparing: 'Em preparação',
|
||||
ready_to_submit: 'Pronto para submeter',
|
||||
submitted: 'Submetido',
|
||||
reviewing: 'Validação interna',
|
||||
correction_required: 'Correcção pedida',
|
||||
waiting_external: 'Aguarda informação externa',
|
||||
approved: 'Acto externo favorável documentado',
|
||||
rejected: 'Acto externo desfavorável documentado',
|
||||
dispensed: 'Preparação dispensada pelo promotor',
|
||||
completed: 'Concluído',
|
||||
expired: 'Acto externo expirado',
|
||||
};
|
||||
export type PathResult = {
|
||||
id: string;
|
||||
financial_snapshot: string;
|
||||
currency: string | null;
|
||||
draft_id: string;
|
||||
draft_version: number;
|
||||
engine: string;
|
||||
recorded_at: string;
|
||||
};
|
||||
export function recoverPathResult(result: PathResult) {
|
||||
if (result.engine !== 'financial-calculators:v1')
|
||||
throw new Error(
|
||||
'Versão do cálculo indisponível; as entradas foram preservadas.',
|
||||
);
|
||||
const snapshot = restoreFinancialToolsSnapshot(result.financial_snapshot);
|
||||
if (!snapshot)
|
||||
throw new Error(
|
||||
'Entradas incompatíveis; a evidência original foi preservada.',
|
||||
);
|
||||
const independent = <T>(
|
||||
run: () => T,
|
||||
): { value: T | null; error: string | null } => {
|
||||
try {
|
||||
return { value: run(), error: null };
|
||||
} catch (error) {
|
||||
return {
|
||||
value: null,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Cálculo indeterminado',
|
||||
};
|
||||
}
|
||||
};
|
||||
return {
|
||||
breakEven: independent(() =>
|
||||
calculateBreakEven(
|
||||
snapshot.breakEven.fixed,
|
||||
snapshot.breakEven.price,
|
||||
snapshot.breakEven.variable,
|
||||
),
|
||||
),
|
||||
funding: independent(() =>
|
||||
calculateFundingGap(
|
||||
snapshot.funding.total,
|
||||
snapshot.funding.secured,
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -72,6 +72,7 @@ export type Filters = {
|
||||
};
|
||||
|
||||
export type InterestFormData = {
|
||||
declared_origin_country_code?: string;
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
@@ -195,6 +196,7 @@ export function newSubmissionKey(): string {
|
||||
export function fieldErrors(error: PortalApiError): FormErrors {
|
||||
const result: FormErrors = {};
|
||||
const fields: (keyof InterestFormData)[] = [
|
||||
'declared_origin_country_code',
|
||||
'name',
|
||||
'email',
|
||||
'phone',
|
||||
|
||||
@@ -3,6 +3,7 @@ import { router } from '@inertiajs/react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import { ProvinceSelect } from '@/components/investment-territory';
|
||||
import { MATURITY_LEVELS } from '@/lib/investment-maturity';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
import type { Dispatch, FormEvent, ReactNode, SetStateAction } from 'react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { usePortalQuery } from '@/hooks/use-portal-query';
|
||||
@@ -668,9 +669,11 @@ function OpportunityDetail({
|
||||
function InterestForm({
|
||||
preselected,
|
||||
onSubmitted,
|
||||
countries,
|
||||
}: {
|
||||
preselected: Opportunity | null;
|
||||
onSubmitted: () => void;
|
||||
countries: Country[];
|
||||
}) {
|
||||
const sectors = useContext(SectorContext);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
@@ -682,7 +685,8 @@ function InterestForm({
|
||||
email: '',
|
||||
phone: '',
|
||||
investorType: '',
|
||||
country: 'Moçambique',
|
||||
country: '',
|
||||
declared_origin_country_code: '',
|
||||
sectorInterest: preselected?.sectorName ?? '',
|
||||
opportunityReference: preselected ? preselected.reference : '',
|
||||
investmentRange: '',
|
||||
@@ -857,13 +861,32 @@ function InterestForm({
|
||||
</Field>
|
||||
|
||||
<Field label="País" error={errors.country}>
|
||||
<input
|
||||
className="input"
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.country}
|
||||
onChange={(e) => update('country', e.target.value)}
|
||||
onChange={(value) => update('country', value)}
|
||||
required
|
||||
allowLegacyValue
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
label="País de origem declarado desta solicitação"
|
||||
error={errors.declared_origin_country_code}
|
||||
>
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.declared_origin_country_code ?? ''}
|
||||
onChange={(value) =>
|
||||
update('declared_origin_country_code', value)
|
||||
}
|
||||
/>
|
||||
<p className="text-sm">
|
||||
Origem opcional; não é deduzida do país acima nem do
|
||||
IP.
|
||||
</p>
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
label="Sector de interesse"
|
||||
error={errors.sectorInterest}
|
||||
@@ -1013,12 +1036,14 @@ export default function PortalInvestidorApp({
|
||||
initialSector = '',
|
||||
initialQuery = '',
|
||||
essentialResources = [],
|
||||
countries = [],
|
||||
}: {
|
||||
initialView?: View;
|
||||
initialOpportunity?: OpportunityRecord;
|
||||
initialSector?: string;
|
||||
initialQuery?: string;
|
||||
essentialResources?: { id: number; title: string }[];
|
||||
countries?: Country[];
|
||||
}) {
|
||||
const view = initialView;
|
||||
const home = usePortalQuery<HomeResponse>('/api/v1/home');
|
||||
@@ -1299,6 +1324,7 @@ export default function PortalInvestidorApp({
|
||||
<InterestForm
|
||||
key={selected?.reference ?? 'general'}
|
||||
preselected={selected}
|
||||
countries={countries}
|
||||
onSubmitted={() => setRequestCount((c) => c + 1)}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Form, Head } from '@inertiajs/react';
|
||||
import { Form, Head, usePage } from '@inertiajs/react';
|
||||
import InputError from '@/components/input-error';
|
||||
import PasswordInput from '@/components/password-input';
|
||||
import TextLink from '@/components/text-link';
|
||||
@@ -19,13 +19,32 @@ import PasskeyVerify from '@/components/passkey-verify';
|
||||
type Props = {
|
||||
status?: string;
|
||||
canResetPassword: boolean;
|
||||
qaAccount?: { id: number; email: string };
|
||||
};
|
||||
|
||||
export default function Login({ status, canResetPassword }: Props) {
|
||||
export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||
// A redirect from another page (e.g. MFA) creates a new Form with empty local errors.
|
||||
const pageErrors = usePage<{ errors: { email?: string } }>().props.errors;
|
||||
return (
|
||||
<>
|
||||
<Head title="Log in" />
|
||||
|
||||
{qaAccount && (
|
||||
<aside
|
||||
className="mb-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm text-slate-900"
|
||||
aria-label="Conta de ensaio QA"
|
||||
>
|
||||
<p className="font-semibold">
|
||||
Ambiente QA — conta {qaAccount.id}
|
||||
</p>
|
||||
<p>
|
||||
Para os cenários A/B: {qaAccount.email}. Use a password e
|
||||
o autenticador desta conta. Outros perfis devem usar as
|
||||
respetivas contas sintéticas QA.
|
||||
</p>
|
||||
</aside>
|
||||
)}
|
||||
|
||||
{/* @chisel-passkeys */}
|
||||
<PasskeyVerify />
|
||||
{/* @end-chisel-passkeys */}
|
||||
@@ -49,8 +68,11 @@ export default function Login({ status, canResetPassword }: Props) {
|
||||
tabIndex={1}
|
||||
autoComplete="email"
|
||||
placeholder="email@example.com"
|
||||
defaultValue={qaAccount?.email}
|
||||
/>
|
||||
<InputError
|
||||
message={errors.email ?? pageErrors.email}
|
||||
/>
|
||||
<InputError message={errors.email} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
|
||||
@@ -12,7 +12,11 @@ import {
|
||||
import { OTP_MAX_LENGTH } from '@/hooks/use-two-factor-auth';
|
||||
import { store } from '@/routes/two-factor/login';
|
||||
|
||||
export default function TwoFactorChallenge() {
|
||||
export default function TwoFactorChallenge({
|
||||
qaAccount,
|
||||
}: {
|
||||
qaAccount?: { id: number; email: string };
|
||||
}) {
|
||||
const [showRecoveryInput, setShowRecoveryInput] = useState<boolean>(false);
|
||||
const [code, setCode] = useState<string>('');
|
||||
|
||||
@@ -53,6 +57,16 @@ export default function TwoFactorChallenge() {
|
||||
<>
|
||||
<Head title="Two-factor authentication" />
|
||||
|
||||
{qaAccount && (
|
||||
<p
|
||||
className="mb-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm text-slate-900"
|
||||
role="status"
|
||||
>
|
||||
MFA da conta QA {qaAccount.id}: {qaAccount.email}. Confirme
|
||||
com o autenticador desta conta.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-6">
|
||||
<Form
|
||||
{...store.form()}
|
||||
|
||||
@@ -23,6 +23,7 @@ export default function Leads({
|
||||
originStatistics: {
|
||||
interests: { code: string | null; name: string; count: number }[];
|
||||
desk: { code: string | null; name: string; count: number }[];
|
||||
businesses: { code: string | null; name: string; count: number }[];
|
||||
};
|
||||
}) {
|
||||
const form = useForm({
|
||||
@@ -91,12 +92,14 @@ export default function Leads({
|
||||
Este filtro aplica-se apenas às contagens de solicitações. A
|
||||
lista de leads mantém os filtros abaixo.
|
||||
</p>
|
||||
{(['interests', 'desk'] as const).map((group) => (
|
||||
{(['interests', 'desk', 'businesses'] as const).map((group) => (
|
||||
<section key={group}>
|
||||
<h2>
|
||||
{group === 'interests'
|
||||
? 'Manifestações recebidas'
|
||||
: 'Pedidos do Balcão em acompanhamento'}
|
||||
: group === 'desk'
|
||||
? 'Pedidos do Balcão em acompanhamento'
|
||||
: 'Negócios submetidos (rascunhos excluídos)'}
|
||||
</h2>
|
||||
{originStatistics[group].length ? (
|
||||
<ul>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { InvestmentContext } from '@/pages/investor-path/index';
|
||||
|
||||
type Summary = {
|
||||
requestsByStatus: Record<string, number>;
|
||||
@@ -23,7 +24,23 @@ const states: Record<string, string> = {
|
||||
const card =
|
||||
'rounded-xl border p-5 transition-colors hover:bg-muted focus-visible:outline-2 focus-visible:outline-primary';
|
||||
|
||||
export default function Dashboard({ summary }: { summary: Summary | null }) {
|
||||
export default function Dashboard({
|
||||
summary,
|
||||
investorPath,
|
||||
}: {
|
||||
summary: Summary | null;
|
||||
investorPath?: {
|
||||
contexts: InvestmentContext[];
|
||||
current: {
|
||||
id: string;
|
||||
next: { code: string; title: string } | null;
|
||||
pending: number;
|
||||
documents: number;
|
||||
results: number;
|
||||
tasks: number;
|
||||
} | null;
|
||||
} | null;
|
||||
}) {
|
||||
return (
|
||||
<main className="space-y-8 p-4 md:p-8">
|
||||
<Head title="Painel" />
|
||||
@@ -160,6 +177,60 @@ export default function Dashboard({ summary }: { summary: Summary | null }) {
|
||||
</Link>
|
||||
</nav>
|
||||
</>
|
||||
) : investorPath ? (
|
||||
<section className="space-y-4 rounded-xl border p-6">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Os meus investimentos
|
||||
</h2>
|
||||
{investorPath.current && (
|
||||
<div className="space-y-2">
|
||||
<p>
|
||||
{investorPath.current.pending} etapas pendentes
|
||||
· {investorPath.current.documents} documentos ·{' '}
|
||||
{investorPath.current.results} resultados ·{' '}
|
||||
{investorPath.current.tasks} tarefas
|
||||
</p>
|
||||
{investorPath.current.next && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${investorPath.current.id}#${investorPath.current.next.code}`}
|
||||
>
|
||||
Próxima acção:{' '}
|
||||
{investorPath.current.next.code} ·{' '}
|
||||
{investorPath.current.next.title}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{investorPath.contexts.map((item, index) => (
|
||||
<div className="rounded border p-4" key={item.id}>
|
||||
<p>
|
||||
{index === 0
|
||||
? 'Investimento actualizado mais recentemente'
|
||||
: 'Outro investimento'}
|
||||
</p>
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={`/investimentos/${item.id}`}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
<p>
|
||||
Percurso, pendências, documentos, resultados e
|
||||
próxima acção no dossier.
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
{!investorPath.contexts.length && (
|
||||
<p>
|
||||
Comece pela sua ideia e prepare as etapas ao seu
|
||||
ritmo.
|
||||
</p>
|
||||
)}
|
||||
<Link className="underline" href="/investimentos">
|
||||
Preparar ou escolher um investimento
|
||||
</Link>
|
||||
</section>
|
||||
) : (
|
||||
<section className="max-w-2xl space-y-4 rounded-xl border p-6">
|
||||
<h2 className="text-lg font-semibold">
|
||||
|
||||
@@ -13,6 +13,10 @@ export default function Install({
|
||||
scanner,
|
||||
rollback,
|
||||
databaseReady,
|
||||
baseDeskInstalled,
|
||||
pathInstalled,
|
||||
pathEnabled,
|
||||
pathQaVerified,
|
||||
}: {
|
||||
hash: string;
|
||||
installed: boolean;
|
||||
@@ -26,6 +30,10 @@ export default function Install({
|
||||
scanner: { available: boolean; reason_code: string | null };
|
||||
rollback: string;
|
||||
databaseReady: boolean;
|
||||
baseDeskInstalled: boolean;
|
||||
pathInstalled: boolean;
|
||||
pathEnabled: boolean;
|
||||
pathQaVerified: boolean;
|
||||
}) {
|
||||
const form = useForm({ hash, confirm: false });
|
||||
const service = useForm({ code: 'project-preparation', confirm: false });
|
||||
@@ -51,10 +59,18 @@ export default function Install({
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Serão criadas as tabelas internas do Balcão; acrescentadas
|
||||
associações opcionais ao dossier e às tarefas existentes.
|
||||
Não se migram ou apagam pedidos anteriores, não se publicam
|
||||
serviços nem se enviam dados externos.
|
||||
Balcão existente:{' '}
|
||||
{baseDeskInstalled ? 'Instalado' : 'Pendente'}. Apenas as
|
||||
migrations ausentes serão executadas; nenhuma instalação já
|
||||
registada será repetida.
|
||||
</p>
|
||||
<p>
|
||||
Extensão do percurso:{' '}
|
||||
{pathInstalled ? 'Instalada' : 'Pendente'}.
|
||||
Disponibilização:{' '}
|
||||
{pathEnabled ? 'Configurada' : 'Desativada'}. Instalar não
|
||||
disponibiliza o percurso, não converte dossiers antigos nem
|
||||
apaga dados ou publica serviços.
|
||||
</p>
|
||||
<ul>
|
||||
{changes.map((c) => (
|
||||
@@ -70,6 +86,13 @@ export default function Install({
|
||||
Compatibilidade e reversão em cópia restaurada:{' '}
|
||||
{compatibilityVerified ? 'Verificadas' : 'Pendentes'}.
|
||||
</p>
|
||||
<p>
|
||||
Percursos A/B completos na interface desta versão:{' '}
|
||||
{pathQaVerified
|
||||
? 'Demonstrados'
|
||||
: 'Pendentes — API ou build não substituem a demonstração visual'}
|
||||
.
|
||||
</p>
|
||||
<p>
|
||||
Permissões da conexão para criar o esquema e estender
|
||||
tarefas:{' '}
|
||||
@@ -120,6 +143,7 @@ export default function Install({
|
||||
!backupVerified ||
|
||||
!qaVerified ||
|
||||
!compatibilityVerified ||
|
||||
!pathQaVerified ||
|
||||
!databaseReady
|
||||
}
|
||||
>
|
||||
@@ -132,7 +156,7 @@ export default function Install({
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
{installed && (
|
||||
{baseDeskInstalled && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
|
||||
@@ -67,9 +67,16 @@ export default function Panel({
|
||||
journey_id: ['Percurso territorial existente', journeys],
|
||||
} as const;
|
||||
const derivedTitle = useRef('');
|
||||
const contextTitle = journeys.find((item) => item.id === form.data.journey_id)?.name ?? submissions.find((item) => item.id === form.data.submission_id)?.name ?? companies.find((item) => item.id === form.data.company_id)?.name ?? '';
|
||||
const contextTitle =
|
||||
journeys.find((item) => item.id === form.data.journey_id)?.name ??
|
||||
submissions.find((item) => item.id === form.data.submission_id)?.name ??
|
||||
companies.find((item) => item.id === form.data.company_id)?.name ??
|
||||
'';
|
||||
useEffect(() => {
|
||||
if ((!form.data.title || form.data.title === derivedTitle.current) && contextTitle) {
|
||||
if (
|
||||
(!form.data.title || form.data.title === derivedTitle.current) &&
|
||||
contextTitle
|
||||
) {
|
||||
form.setData('title', contextTitle.slice(0, 200));
|
||||
derivedTitle.current = contextTitle.slice(0, 200);
|
||||
}
|
||||
@@ -110,7 +117,12 @@ export default function Panel({
|
||||
</section>
|
||||
<details className={card}>
|
||||
<summary>Preparar acompanhamento de um projecto</summary>
|
||||
<p>Selecione um percurso ou investimento da sua conta. O título é recuperado do registo existente quando disponível; pode corrigi-lo antes de guardar. A associação requer a sua autorização abaixo.</p>
|
||||
<p>
|
||||
Selecione um percurso ou investimento da sua conta. O título
|
||||
é recuperado do registo existente quando disponível; pode
|
||||
corrigi-lo antes de guardar. A associação requer a sua
|
||||
autorização abaixo.
|
||||
</p>
|
||||
<form
|
||||
className="mt-4 space-y-3"
|
||||
onSubmit={(e) => {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import {
|
||||
DocumentReview,
|
||||
RequestOperations,
|
||||
@@ -28,7 +32,7 @@ export default function RequestPage({
|
||||
findings,
|
||||
messages,
|
||||
analysts,
|
||||
territories,
|
||||
territoryPaths,
|
||||
events,
|
||||
documents,
|
||||
payments,
|
||||
@@ -71,7 +75,7 @@ export default function RequestPage({
|
||||
created_at: string;
|
||||
}[];
|
||||
analysts: { id: number; name: string }[];
|
||||
territories: { id: string; name: string }[];
|
||||
territoryPaths: Record<string, TerritoryOption[]>;
|
||||
documents: DeskDocument[];
|
||||
payments: DeskPayment[];
|
||||
caseVersion: number;
|
||||
@@ -168,97 +172,182 @@ export default function RequestPage({
|
||||
form.put(`/balcao-virtual/pedidos/${request.id}`);
|
||||
}}
|
||||
>
|
||||
<label className="block" htmlFor="declared-origin-country">País de origem declarado desta solicitação</label>
|
||||
<CountrySelect id="declared-origin-country" countries={countries} value={form.data.payload.declared_origin_country_code ?? ''} disabled={!canEdit || form.processing || (request.status === 'returned' && !request.editable_fields.includes('declared_origin_country_code'))} onChange={(value) => form.setData('payload', { ...form.data.payload, declared_origin_country_code: value })} />
|
||||
<p>A origem não é deduzida do IP nem do país de residência. Pedidos antigos sem declaração mantêm “não informado”.</p>
|
||||
{form.errors['payload.declared_origin_country_code'] && <p role="alert">{form.errors['payload.declared_origin_country_code']}</p>}
|
||||
<label className="block" htmlFor="request-country">
|
||||
País do requerente (opcional)
|
||||
</label>
|
||||
<CountrySelect
|
||||
id="request-country"
|
||||
countries={countries}
|
||||
value={form.data.payload.country ?? ''}
|
||||
allowLegacyValue
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
country: value,
|
||||
})
|
||||
}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes('country'))
|
||||
}
|
||||
/>
|
||||
{form.errors['payload.country'] && (
|
||||
<p role="alert">{form.errors['payload.country']}</p>
|
||||
)}
|
||||
<label className="block" htmlFor="declared-origin-country">
|
||||
País de origem declarado desta solicitação
|
||||
</label>
|
||||
<CountrySelect
|
||||
id="declared-origin-country"
|
||||
countries={countries}
|
||||
value={form.data.payload.declared_origin_country_code ?? ''}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
form.processing ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
'declared_origin_country_code',
|
||||
))
|
||||
}
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
declared_origin_country_code: value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p>
|
||||
A origem não é deduzida do IP nem do país de residência.
|
||||
Pedidos antigos sem declaração mantêm “não informado”.
|
||||
</p>
|
||||
{form.errors['payload.declared_origin_country_code'] && (
|
||||
<p role="alert">
|
||||
{form.errors['payload.declared_origin_country_code']}
|
||||
</p>
|
||||
)}
|
||||
{Object.entries(definition.fields)
|
||||
.filter(
|
||||
([, f]) =>
|
||||
!f.when ||
|
||||
form.data.payload[f.when.field] === f.when.equals,
|
||||
)
|
||||
.map(([key, f]) => (
|
||||
<label className="block" key={key}>
|
||||
{f.label}
|
||||
{f.required ? ' *' : ''}
|
||||
{f.type === 'select' || f.type === 'territory' ? (
|
||||
<select
|
||||
className={input}
|
||||
.map(([key, f]) =>
|
||||
f.type === 'territory' ? (
|
||||
<fieldset
|
||||
key={key}
|
||||
className="space-y-2 rounded border p-3"
|
||||
>
|
||||
<legend>
|
||||
{f.label}
|
||||
{f.required ? ' *' : ''}
|
||||
</legend>
|
||||
<TerritoryFields
|
||||
initial={territoryPaths[key]}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
form.processing ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
onChange={(path) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Por preencher</option>
|
||||
{(f.type === 'territory'
|
||||
? territories.map((t) => [t.id, t.name])
|
||||
: Object.entries(f.options ?? {})
|
||||
).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : f.type === 'textarea' ? (
|
||||
<textarea
|
||||
className={input}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
[key]: path.at(-1)?.id ?? '',
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type={
|
||||
f.type === 'date'
|
||||
? 'date'
|
||||
: f.type === 'number'
|
||||
? 'number'
|
||||
: 'text'
|
||||
}
|
||||
step={
|
||||
f.type === 'number' ? '0.01' : undefined
|
||||
}
|
||||
className={input}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
{form.errors[`payload.${key}`] && (
|
||||
<p role="alert">
|
||||
{form.errors[`payload.${key}`]}
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
) : (
|
||||
<label className="block" key={key}>
|
||||
{f.label}
|
||||
{f.required ? ' *' : ''}
|
||||
{f.type === 'select' ? (
|
||||
<select
|
||||
className={input}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Por preencher</option>
|
||||
{Object.entries(f.options ?? {}).map(
|
||||
([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
) : f.type === 'textarea' ? (
|
||||
<textarea
|
||||
className={input}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type={
|
||||
f.type === 'date'
|
||||
? 'date'
|
||||
: f.type === 'number'
|
||||
? 'number'
|
||||
: 'text'
|
||||
}
|
||||
step={
|
||||
f.type === 'number'
|
||||
? '0.01'
|
||||
: undefined
|
||||
}
|
||||
className={input}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
{canEdit && (
|
||||
<>
|
||||
<label>
|
||||
@@ -368,7 +457,13 @@ export default function RequestPage({
|
||||
{decision.data.status === 'returned' && (
|
||||
<fieldset>
|
||||
<legend>Campos autorizados para correcção</legend>
|
||||
{Object.entries(definition.fields).map(([k, f]) => (
|
||||
{Object.entries({
|
||||
...definition.fields,
|
||||
country: { label: 'País do requerente' },
|
||||
declared_origin_country_code: {
|
||||
label: 'Origem declarada da solicitação',
|
||||
},
|
||||
}).map(([k, f]) => (
|
||||
<label className="block" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Link } from '@inertiajs/react';
|
||||
import type { FormEvent } from 'react';
|
||||
import { newSubmissionKey } from '@/lib/portal-api';
|
||||
import { Frame, Field, button, card, input } from './shared';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
|
||||
type Opportunity = {
|
||||
id: string;
|
||||
@@ -10,8 +11,14 @@ type Opportunity = {
|
||||
title: string;
|
||||
sector?: { name: string } | null;
|
||||
};
|
||||
type Props = { record: Opportunity; modalities: string[]; returnUrl?: string };
|
||||
type Props = {
|
||||
record: Opportunity;
|
||||
modalities: string[];
|
||||
returnUrl?: string;
|
||||
countries: Country[];
|
||||
};
|
||||
type Form = {
|
||||
declared_origin_country_code: string;
|
||||
fullName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
@@ -29,13 +36,15 @@ export default function BusinessInterest({
|
||||
record,
|
||||
modalities,
|
||||
returnUrl = '/negocios',
|
||||
countries,
|
||||
}: Props) {
|
||||
const [form, setForm] = useState<Form>({
|
||||
declared_origin_country_code: '',
|
||||
fullName: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
investorType: 'empresa',
|
||||
country: 'MZ',
|
||||
country: '',
|
||||
sectorInterest: record.sector?.name ?? '',
|
||||
modality: modalities[0] ?? '',
|
||||
investmentRange: '',
|
||||
@@ -114,6 +123,19 @@ export default function BusinessInterest({
|
||||
</section>
|
||||
) : (
|
||||
<form className={`${card} space-y-4`} onSubmit={submit}>
|
||||
<Field label="País de origem declarado desta solicitação">
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.declared_origin_country_code}
|
||||
onChange={(value) =>
|
||||
update('declared_origin_country_code', value)
|
||||
}
|
||||
/>
|
||||
<p className="text-sm">
|
||||
Origem opcional e independente do país do
|
||||
investidor.
|
||||
</p>
|
||||
</Field>
|
||||
<Field label="Nome ou denominação">
|
||||
<input
|
||||
className={input}
|
||||
@@ -161,12 +183,12 @@ export default function BusinessInterest({
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="País">
|
||||
<input
|
||||
className={input}
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
required
|
||||
maxLength={100}
|
||||
allowLegacyValue
|
||||
value={form.country}
|
||||
onChange={(e) => update('country', e.target.value)}
|
||||
onChange={(value) => update('country', value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Sector de interesse">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { router } from '@inertiajs/react';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
import { Frame, Field, input, button, card, api } from './shared';
|
||||
import type { Business } from './business-types';
|
||||
import { businessModalities } from './business-types';
|
||||
@@ -27,6 +28,7 @@ export type FormSchema = Record<
|
||||
}
|
||||
>;
|
||||
type Props = {
|
||||
countries: Country[];
|
||||
record: Business;
|
||||
modalities: string[];
|
||||
formSchema: FormSchema;
|
||||
@@ -207,6 +209,7 @@ function opportunityTypeFor(modality: string): string {
|
||||
}
|
||||
|
||||
export default function BusinessWizard({
|
||||
countries,
|
||||
record,
|
||||
formSchema,
|
||||
objects,
|
||||
@@ -706,6 +709,18 @@ export default function BusinessWizard({
|
||||
*
|
||||
</span>
|
||||
</span>
|
||||
) : field.type === 'country' ? (
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={payload[key] ?? ''}
|
||||
allowLegacyValue={key === 'country'}
|
||||
onChange={(value) =>
|
||||
update(key, value)
|
||||
}
|
||||
label={
|
||||
english ? field.en : field.pt
|
||||
}
|
||||
/>
|
||||
) : field.type === 'territory' ? (
|
||||
<TerritoryField
|
||||
name={english ? field.en : field.pt}
|
||||
|
||||
@@ -9,8 +9,10 @@ import BusinessVerifications from './business-verifications';
|
||||
import type { BusinessVerification } from './business-verifications';
|
||||
import BusinessWizard from './business-wizard';
|
||||
import type { FormSchema } from './business-wizard';
|
||||
import type { Country } from '@/components/country-select';
|
||||
|
||||
type Props = {
|
||||
countries: Country[];
|
||||
formSchema: FormSchema;
|
||||
sectors: { id: number; name: string }[];
|
||||
record: Business;
|
||||
|
||||
@@ -3,11 +3,14 @@ import { useState } from 'react';
|
||||
import { Frame, Field, input, button, card, api } from './shared';
|
||||
import { businessModalities, businessStates } from './business-types';
|
||||
import type { Business } from './business-types';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
|
||||
export default function Businesses({
|
||||
records,
|
||||
management,
|
||||
modalities,
|
||||
filters,
|
||||
countries,
|
||||
}: {
|
||||
records: {
|
||||
data: Business[];
|
||||
@@ -16,11 +19,15 @@ export default function Businesses({
|
||||
};
|
||||
management: boolean;
|
||||
modalities: string[];
|
||||
countries: Country[];
|
||||
filters: { country?: string; origin?: string };
|
||||
}) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [modality, setModality] = useState(modalities[0]);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [country, setCountry] = useState(filters.country ?? '');
|
||||
const [origin, setOrigin] = useState(filters.origin ?? '');
|
||||
return (
|
||||
<Frame title={management ? 'Revisão de negócios' : 'Os meus negócios'}>
|
||||
<p>
|
||||
@@ -28,6 +35,43 @@ export default function Businesses({
|
||||
titularidade, validade ou transmissibilidade do negócio, activo
|
||||
ou direito.
|
||||
</p>
|
||||
<form
|
||||
className={`${card} flex flex-wrap gap-3`}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
router.get(
|
||||
management
|
||||
? '/management/negocios'
|
||||
: '/investidor/negocios',
|
||||
{ country, origin },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={country}
|
||||
onChange={setCountry}
|
||||
label="Filtrar país do proponente"
|
||||
/>
|
||||
<label>
|
||||
Origem declarada
|
||||
<select
|
||||
aria-label="Filtrar origem declarada"
|
||||
className={input}
|
||||
value={origin}
|
||||
onChange={(e) => setOrigin(e.target.value)}
|
||||
>
|
||||
<option value="">Todas</option>
|
||||
<option value="unknown">Não informada</option>
|
||||
{countries.map((c) => (
|
||||
<option key={c.code} value={c.code}>
|
||||
{c.name} ({c.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button className={button}>Filtrar negócios</button>
|
||||
</form>
|
||||
{!management && (
|
||||
<form
|
||||
className={`${card} space-y-4`}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import Map from '@/components/interactive-investment-map';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import type { InvestmentMapArea } from '@/components/interactive-investment-map';
|
||||
import {
|
||||
TerritoryLevel,
|
||||
@@ -98,7 +99,9 @@ export default function Catalogue({
|
||||
{ id: number; title: string; location: string; url: string }[]
|
||||
>([]);
|
||||
const [truncated, setTruncated] = useState(false);
|
||||
const [mapContext, setMapContext] = useState<{ id: string; title: string; kind: string; url: string }[]>([]);
|
||||
const [mapContext, setMapContext] = useState<
|
||||
{ id: string; title: string; kind: string; url: string }[]
|
||||
>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [suggestions, setSuggestions] = useState<
|
||||
{ title: string; slug: string }[]
|
||||
@@ -230,7 +233,14 @@ export default function Catalogue({
|
||||
const dimensionUrl = (dimension: string) => {
|
||||
const params = new URLSearchParams(query());
|
||||
params.set('dimension', dimension);
|
||||
['cluster_id', 'corridor_id', 'zee_id', 'zfi_id', 'park_id', 'project_id'].forEach((key) => params.delete(key));
|
||||
[
|
||||
'cluster_id',
|
||||
'corridor_id',
|
||||
'zee_id',
|
||||
'zfi_id',
|
||||
'park_id',
|
||||
'project_id',
|
||||
].forEach((key) => params.delete(key));
|
||||
params.delete('page');
|
||||
return `${catalogueUrl}?${params}`;
|
||||
};
|
||||
@@ -391,28 +401,39 @@ export default function Catalogue({
|
||||
['zfi_id', 'zfi', 'ZFI'],
|
||||
['park_id', 'industrial_park', 'Parque industrial'],
|
||||
] as const
|
||||
).filter(([field]) => !form.data.dimension || field === `${form.data.dimension}_id` || !!form.data[field]).map(([field, category, label]) => (
|
||||
<Field key={field} label={label}>
|
||||
<select
|
||||
className={input}
|
||||
value={form.data[field]}
|
||||
onChange={(e) =>
|
||||
form.setData(field, e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{(references.zones ?? [])
|
||||
.filter(
|
||||
(zone) => zone.category === category,
|
||||
)
|
||||
.map((zone) => (
|
||||
<option key={zone.id} value={zone.id}>
|
||||
{zone.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
)
|
||||
.filter(
|
||||
([field]) =>
|
||||
!form.data.dimension ||
|
||||
field === `${form.data.dimension}_id` ||
|
||||
!!form.data[field],
|
||||
)
|
||||
.map(([field, category, label]) => (
|
||||
<Field key={field} label={label}>
|
||||
<select
|
||||
className={input}
|
||||
value={form.data[field]}
|
||||
onChange={(e) =>
|
||||
form.setData(field, e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{(references.zones ?? [])
|
||||
.filter(
|
||||
(zone) =>
|
||||
zone.category === category,
|
||||
)
|
||||
.map((zone) => (
|
||||
<option
|
||||
key={zone.id}
|
||||
value={zone.id}
|
||||
>
|
||||
{zone.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
{(['clusters', 'corridors', 'projects'] as const).map(
|
||||
(group, index) => {
|
||||
const key = (
|
||||
@@ -429,7 +450,12 @@ export default function Catalogue({
|
||||
'Projecto âncora',
|
||||
] as const
|
||||
)[index];
|
||||
if (form.data.dimension && key !== `${form.data.dimension}_id` && !form.data[key]) return null;
|
||||
if (
|
||||
form.data.dimension &&
|
||||
key !== `${form.data.dimension}_id` &&
|
||||
!form.data[key]
|
||||
)
|
||||
return null;
|
||||
return (
|
||||
<Field key={group} label={label}>
|
||||
<select
|
||||
@@ -1091,11 +1117,47 @@ export default function Catalogue({
|
||||
</div>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{!error && <Map points={points} areas={areas} />}
|
||||
{['map', 'combined'].includes(view) && !error && mapContext.length > 0 && <section className={card} aria-label="Estruturas territoriais consultáveis">
|
||||
<h2 className="text-xl font-bold">Estruturas territoriais e projetos</h2>
|
||||
<p>Estas fichas continuam consultáveis independentemente de terem coordenadas. A lista não atribui implantação às oportunidades nem cria pontos no mapa. Até 30 fichas por conjunto; refine a localização para pesquisar.</p>
|
||||
<ul>{mapContext.map((record) => <li key={record.id}><Link className="underline" href={record.url}>{record.kind}: {record.title}</Link></li>)}</ul>
|
||||
</section>}
|
||||
{['map', 'combined'].includes(view) && (
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={
|
||||
form.data.locality_id ||
|
||||
form.data.admin_post_id ||
|
||||
form.data.district_id ||
|
||||
form.data.province_id
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{['map', 'combined'].includes(view) &&
|
||||
!error &&
|
||||
mapContext.length > 0 && (
|
||||
<section
|
||||
className={card}
|
||||
aria-label="Estruturas territoriais consultáveis"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Estruturas territoriais e projetos
|
||||
</h2>
|
||||
<p>
|
||||
Estas fichas continuam consultáveis
|
||||
independentemente de terem coordenadas. A lista não
|
||||
atribui implantação às oportunidades nem cria pontos
|
||||
no mapa. Até 30 fichas por conjunto; refine a
|
||||
localização para pesquisar.
|
||||
</p>
|
||||
<ul>
|
||||
{mapContext.map((record) => (
|
||||
<li key={record.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={record.url}
|
||||
>
|
||||
{record.kind}: {record.title}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{truncated && (
|
||||
<p role="alert">
|
||||
O mapa atingiu o limite de 1.000 registos; refine os
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import InvestmentMapPanel from '@/components/investment-map-panel';
|
||||
import { Link, router, usePage } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import InvestmentMapPanel from "@/components/investment-map-panel";
|
||||
import StructureGeographyPanel, {
|
||||
LocationList,
|
||||
} from '@/components/structure-geography';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
import TerritorialSources from '@/components/territorial-source-evidence';
|
||||
import { Frame, card, button, money, groupLabels } from './shared';
|
||||
import type { Opportunity, Context } from './shared';
|
||||
} from "@/components/structure-geography";
|
||||
import PartnershipSourceLinks from "@/components/partnership-source-links";
|
||||
import TerritorialSources from "@/components/territorial-source-evidence";
|
||||
import { Frame, card, button, money, groupLabels } from "./shared";
|
||||
import type { Opportunity, Context } from "./shared";
|
||||
export default function Detail({
|
||||
record: r,
|
||||
context: c,
|
||||
zone_origin,
|
||||
returnUrl = '/oportunidades',
|
||||
returnUrl = "/oportunidades",
|
||||
dossierOrigin,
|
||||
}: {
|
||||
record: Opportunity;
|
||||
@@ -22,7 +22,7 @@ export default function Detail({
|
||||
dossierOrigin?: { id: string; title: string } | null;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: { user: unknown } }>().props;
|
||||
const [sharing, setSharing] = useState('');
|
||||
const [sharing, setSharing] = useState("");
|
||||
return (
|
||||
<Frame title={r.title}>
|
||||
<PartnershipSourceLinks type="investment" id={r.id} />
|
||||
@@ -52,7 +52,7 @@ export default function Detail({
|
||||
)}
|
||||
<p className="text-xl">{r.summary}</p>
|
||||
<TerritorialSources sources={c.source_evidence} />
|
||||
<section className={card + ' space-y-3'}>
|
||||
<section className={card + " space-y-3"}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Implantação declarada da oportunidade
|
||||
</h2>
|
||||
@@ -70,15 +70,18 @@ export default function Detail({
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
<InvestmentMapPanel filters={{ opportunity_id: r.id }} />
|
||||
<InvestmentMapPanel
|
||||
filters={{ opportunity_id: r.id }}
|
||||
territoryId={c.primary_territory_path?.at(-1)?.id}
|
||||
/>
|
||||
{c.primary_territory_path &&
|
||||
c.primary_territory_path.length > 0 && (
|
||||
<p>
|
||||
Território principal cadastrado (implantação por
|
||||
confirmar):{' '}
|
||||
confirmar):{" "}
|
||||
{c.primary_territory_path
|
||||
.map((node) => node.name)
|
||||
.join(' → ')}
|
||||
.join(" → ")}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
@@ -86,12 +89,12 @@ export default function Detail({
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post('/investidor/manifestacoes', {
|
||||
router.post("/investidor/manifestacoes", {
|
||||
opportunity_id: r.id,
|
||||
...(zone_origin
|
||||
? {
|
||||
zone_id: zone_origin.id,
|
||||
intent: 'interest',
|
||||
intent: "interest",
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
@@ -115,16 +118,16 @@ export default function Detail({
|
||||
onClick={() => {
|
||||
if (!navigator.clipboard) {
|
||||
setSharing(
|
||||
'Copie a ligação na barra de endereço do navegador.',
|
||||
"Copie a ligação na barra de endereço do navegador.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
navigator.clipboard
|
||||
.writeText(window.location.href)
|
||||
.then(() => setSharing('Ligação copiada.'))
|
||||
.then(() => setSharing("Ligação copiada."))
|
||||
.catch(() =>
|
||||
setSharing(
|
||||
'Copie a ligação na barra de endereço do navegador.',
|
||||
"Copie a ligação na barra de endereço do navegador.",
|
||||
),
|
||||
);
|
||||
}}
|
||||
@@ -145,11 +148,11 @@ export default function Detail({
|
||||
href={`/zonas?category=${z.category}&q=${encodeURIComponent(z.name)}`}
|
||||
>
|
||||
{z.name}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
{z.association_type === 'official'
|
||||
? 'Associação documental validada'
|
||||
: 'Relação ' + z.association_type}{' '}
|
||||
</Link>{" "}
|
||||
·{" "}
|
||||
{z.association_type === "official"
|
||||
? "Associação documental validada"
|
||||
: "Relação " + z.association_type}{" "}
|
||||
· Fonte: {z.source_reference}
|
||||
</p>
|
||||
))}
|
||||
@@ -161,42 +164,42 @@ export default function Detail({
|
||||
)}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<section
|
||||
className={card + ' whitespace-pre-line lg:col-span-2'}
|
||||
className={card + " whitespace-pre-line lg:col-span-2"}
|
||||
>
|
||||
<h2 className="mb-3 text-xl font-bold">O investimento</h2>
|
||||
{r.description || 'Descrição por completar.'}
|
||||
{r.description || "Descrição por completar."}
|
||||
</section>
|
||||
<dl className={card + ' space-y-4'}>
|
||||
<dl className={card + " space-y-4"}>
|
||||
{[
|
||||
['Promotor', r.promoter_name],
|
||||
['Investimento', money(r)],
|
||||
['Maturidade', r.maturity_label],
|
||||
['Parceria', r.financing_modality],
|
||||
['Impacto', r.expected_impact],
|
||||
['Calendário', c.profile?.target_date],
|
||||
["Promotor", r.promoter_name],
|
||||
["Investimento", money(r)],
|
||||
["Maturidade", r.maturity_label],
|
||||
["Parceria", r.financing_modality],
|
||||
["Impacto", r.expected_impact],
|
||||
["Calendário", c.profile?.target_date],
|
||||
].map(([key, value]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-bold">{key}</dt>
|
||||
<dd>{value || 'Não indicado'}</dd>
|
||||
<dd>{value || "Não indicado"}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
{c.profile && (
|
||||
<section className={card + ' space-y-4'}>
|
||||
<section className={card + " space-y-4"}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Viabilidade e preparação
|
||||
</h2>
|
||||
{[
|
||||
['Modelo de negócio', c.profile.business_model],
|
||||
['Requisitos', c.profile.requirements],
|
||||
['Riscos', c.profile.risks],
|
||||
['Fonte', c.profile.source_reference],
|
||||
["Modelo de negócio", c.profile.business_model],
|
||||
["Requisitos", c.profile.requirements],
|
||||
["Riscos", c.profile.risks],
|
||||
["Fonte", c.profile.source_reference],
|
||||
].map(([label, text]) => (
|
||||
<div key={label}>
|
||||
<h3 className="font-bold">{label}</h3>
|
||||
<p className="whitespace-pre-line">
|
||||
{text || 'Não indicado'}
|
||||
{text || "Não indicado"}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
@@ -209,16 +212,16 @@ export default function Detail({
|
||||
)}
|
||||
<section className="grid gap-4 md:grid-cols-4">
|
||||
{(
|
||||
['clusters', 'corridors', 'projects', 'locations'] as const
|
||||
["clusters", "corridors", "projects", "locations"] as const
|
||||
).map((key, i) => (
|
||||
<div className={card} key={key}>
|
||||
<h2 className="font-bold">
|
||||
{
|
||||
[
|
||||
'Clusters',
|
||||
'Corredores',
|
||||
'Projectos âncora',
|
||||
'Territórios',
|
||||
"Clusters",
|
||||
"Corredores",
|
||||
"Projectos âncora",
|
||||
"Territórios",
|
||||
][i]
|
||||
}
|
||||
</h2>
|
||||
@@ -238,14 +241,14 @@ export default function Detail({
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
'/oportunidades?' +
|
||||
"/oportunidades?" +
|
||||
[
|
||||
'cluster_id',
|
||||
'corridor_id',
|
||||
'project_id',
|
||||
'geo_location_id',
|
||||
"cluster_id",
|
||||
"corridor_id",
|
||||
"project_id",
|
||||
"geo_location_id",
|
||||
][i] +
|
||||
'=' +
|
||||
"=" +
|
||||
entity.id
|
||||
}
|
||||
>
|
||||
@@ -257,7 +260,7 @@ export default function Detail({
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
{(['projects', 'clusters'] as const).flatMap((key) =>
|
||||
{(["projects", "clusters"] as const).flatMap((key) =>
|
||||
c[key]
|
||||
.filter(
|
||||
(entity) => entity.geography && entity.dossiers?.length,
|
||||
@@ -266,7 +269,7 @@ export default function Detail({
|
||||
<StructureGeographyPanel
|
||||
key={`${key}-${entity.id}`}
|
||||
geography={entity.geography!}
|
||||
cluster={key === 'clusters'}
|
||||
cluster={key === "clusters"}
|
||||
dossierId={entity.dossiers![0].id}
|
||||
/>
|
||||
)),
|
||||
|
||||
@@ -127,7 +127,10 @@ function Editor({
|
||||
const form = useForm({
|
||||
version: record.version,
|
||||
payload: Object.fromEntries(
|
||||
[...fields, 'country'].map((key) => [key, record.payload[key] ?? '']),
|
||||
[...fields, 'country'].map((key) => [
|
||||
key,
|
||||
record.payload[key] ?? '',
|
||||
]),
|
||||
),
|
||||
});
|
||||
return (
|
||||
@@ -146,33 +149,56 @@ function Editor({
|
||||
}}
|
||||
>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{record.payload.country && <p>País anteriormente registado: {record.payload.country}. Conservado sem atribuir automaticamente residência, constituição ou origem da solicitação.</p>}
|
||||
{record.payload.country && (
|
||||
<p>
|
||||
País anteriormente registado: {record.payload.country}.
|
||||
Conservado sem atribuir automaticamente residência,
|
||||
constituição ou origem da solicitação.
|
||||
</p>
|
||||
)}
|
||||
{fields.map((key) => (
|
||||
<Field key={key} label={labels[key]}>
|
||||
{key.endsWith('_country_code') ? <CountrySelect id={key + (record.id ?? 'account')} countries={countries} value={form.data.payload[key]} onChange={(value) => form.setData('payload', { ...form.data.payload, [key]: value })} /> :
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.payload[key]}
|
||||
required={
|
||||
isCompany &&
|
||||
['name', 'country', 'role'].includes(key)
|
||||
}
|
||||
maxLength={
|
||||
key === 'description' || key === 'experience'
|
||||
? 2000
|
||||
: key === 'investment_capacity'
|
||||
? 1000
|
||||
: 200
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
}
|
||||
{form.errors[`payload.${key}`] && <p role="alert" className="text-red-700">{form.errors[`payload.${key}`]}</p>}
|
||||
{key.endsWith('_country_code') ? (
|
||||
<CountrySelect
|
||||
id={key + (record.id ?? 'account')}
|
||||
countries={countries}
|
||||
value={form.data.payload[key]}
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.payload[key]}
|
||||
required={
|
||||
isCompany &&
|
||||
['name', 'country', 'role'].includes(key)
|
||||
}
|
||||
maxLength={
|
||||
key === 'description' ||
|
||||
key === 'experience'
|
||||
? 2000
|
||||
: key === 'investment_capacity'
|
||||
? 1000
|
||||
: 200
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{form.errors[`payload.${key}`] && (
|
||||
<p role="alert" className="text-red-700">
|
||||
{form.errors[`payload.${key}`]}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -358,12 +358,57 @@ function Editor({
|
||||
{text('full_name', 'Nome completo', true)}
|
||||
{text('email', 'Email', true, 'email')}
|
||||
{text('phone', 'Telefone')}
|
||||
{form.data.payload.country && <p>País anteriormente registado: {form.data.payload.country}. Não foi convertido em residência, constituição ou origem.</p>}
|
||||
{(['residence_country_code', 'incorporation_country_code', 'declared_origin_country_code'] as const).map((key) => <Field key={key} label={{ residence_country_code: 'País de residência', incorporation_country_code: 'País de constituição da entidade', declared_origin_country_code: 'País de origem declarado desta solicitação' }[key]}>
|
||||
<CountrySelect disabled={readonly} id={key} countries={countries} value={form.data.payload[key] ?? ''} onChange={(value) => form.setData('payload', { ...form.data.payload, [key]: value })} />
|
||||
{form.errors[`payload.${key}`] && <p role="alert">{form.errors[`payload.${key}`]}</p>}
|
||||
</Field>)}
|
||||
<p>A origem da solicitação é uma declaração sua; não é deduzida da residência, da entidade ou do endereço IP.</p>
|
||||
{form.data.payload.country && (
|
||||
<p>
|
||||
País anteriormente registado:{' '}
|
||||
{form.data.payload.country}. Não foi convertido
|
||||
em residência, constituição ou origem.
|
||||
</p>
|
||||
)}
|
||||
{(
|
||||
[
|
||||
'residence_country_code',
|
||||
'incorporation_country_code',
|
||||
'declared_origin_country_code',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
residence_country_code:
|
||||
'País de residência',
|
||||
incorporation_country_code:
|
||||
'País de constituição da entidade',
|
||||
declared_origin_country_code:
|
||||
'País de origem declarado desta solicitação',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<CountrySelect
|
||||
disabled={readonly}
|
||||
id={key}
|
||||
countries={countries}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
{form.errors[`payload.${key}`] && (
|
||||
<p role="alert">
|
||||
{form.errors[`payload.${key}`]}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
<p>
|
||||
A origem da solicitação é uma declaração sua; não é
|
||||
deduzida da residência, da entidade ou do endereço
|
||||
IP.
|
||||
</p>
|
||||
{option(
|
||||
'profile_id',
|
||||
'investor_profile',
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
|
||||
export type InvestmentContext = {
|
||||
id: string;
|
||||
title: string;
|
||||
version: number;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export default function InvestmentContexts({
|
||||
contexts,
|
||||
}: {
|
||||
contexts: InvestmentContext[];
|
||||
}) {
|
||||
const [key] = useState(() => globalThis.crypto.randomUUID());
|
||||
const form = useForm({ title: '', client_key: key, reuse_consent: false });
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-4 md:p-8">
|
||||
<Head title="Os meus investimentos" />
|
||||
<h1 className="text-2xl font-semibold">Os meus investimentos</h1>
|
||||
<p>
|
||||
Prepare cada investimento no seu dossier. Pode trabalhar em
|
||||
várias etapas em paralelo.
|
||||
</p>
|
||||
<ul className="grid gap-4 md:grid-cols-2">
|
||||
{contexts.map((item) => (
|
||||
<li key={item.id} className="rounded-xl border p-4">
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={`/investimentos/${item.id}`}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
Guardado em{' '}
|
||||
{new Date(item.updated_at).toLocaleString('pt-MZ')}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{!contexts.length && (
|
||||
<p>Ainda não criou um investimento neste percurso.</p>
|
||||
)}
|
||||
<form
|
||||
className="max-w-xl space-y-4 rounded-xl border p-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post('/investimentos');
|
||||
}}
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Preparar um investimento
|
||||
</h2>
|
||||
<label className="grid gap-1">
|
||||
Título
|
||||
<input
|
||||
required
|
||||
maxLength={200}
|
||||
className="rounded border p-2"
|
||||
value={form.data.title}
|
||||
onChange={(event) =>
|
||||
form.setData('title', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.reuse_consent}
|
||||
onChange={(event) =>
|
||||
form.setData('reuse_consent', event.target.checked)
|
||||
}
|
||||
/>
|
||||
Autorizo reutilizar o meu perfil neste dossier privado.
|
||||
</label>
|
||||
{Object.values(form.errors).map((error, index) => (
|
||||
<p key={index} role="alert">
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
disabled={form.processing}
|
||||
className="bg-primary text-primary-foreground rounded px-4 py-2"
|
||||
>
|
||||
Criar e guardar dossier
|
||||
</button>
|
||||
</form>
|
||||
<nav className="flex flex-wrap gap-4" aria-label="Ferramentas">
|
||||
<Link className="underline" href="/simulador-fiscal">
|
||||
Simulador
|
||||
</Link>
|
||||
<Link className="underline" href="/balcao-virtual/painel">
|
||||
Balcão
|
||||
</Link>
|
||||
<Link className="underline" href="/investidor">
|
||||
Oportunidades guardadas
|
||||
</Link>
|
||||
<Link className="underline" href="/dashboard">
|
||||
Painel
|
||||
</Link>
|
||||
</nav>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,744 @@
|
||||
import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
pathStates,
|
||||
recoverPathResult,
|
||||
type PathResult,
|
||||
} from '@/lib/investor-path';
|
||||
|
||||
type Step = {
|
||||
code: string;
|
||||
title: string;
|
||||
phase: number;
|
||||
state: string;
|
||||
saved_state: string;
|
||||
reason: string;
|
||||
applicability: string;
|
||||
preparation_allowed: boolean;
|
||||
action_gaps: Record<string, string[]>;
|
||||
detail: { scope?: string };
|
||||
source_paragraph: number;
|
||||
};
|
||||
type Path = {
|
||||
case: { id: string; title: string; version: number; closed: boolean };
|
||||
phases: Record<string, string>;
|
||||
steps: Step[];
|
||||
definition_version: number;
|
||||
facts: { land_needed: string; external_funding: string; viability: string };
|
||||
fact_reasons: Record<string, string>;
|
||||
canWrite: boolean;
|
||||
canReview: boolean;
|
||||
next: { code: string; title: string; href: string; action: string } | null;
|
||||
tools: Record<string, string | null>;
|
||||
results: PathResult[];
|
||||
documents: {
|
||||
id: string;
|
||||
document_id: string;
|
||||
file_name: string;
|
||||
status: string;
|
||||
malware_scan_status: string;
|
||||
}[];
|
||||
requests: { id: string; status: string; protocol: string | null }[];
|
||||
services: { id: string; title: string }[];
|
||||
tasks: {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
version_no: number;
|
||||
assignee_user_id: number;
|
||||
due_at: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
function Result({ result }: { result: PathResult }) {
|
||||
try {
|
||||
const values = recoverPathResult(result);
|
||||
return (
|
||||
<li className="space-y-1 rounded border p-3">
|
||||
<p>
|
||||
Resultado financeiro ·{' '}
|
||||
{result.currency ?? 'moeda por indicar'}
|
||||
</p>
|
||||
<p>
|
||||
Ponto de equilíbrio:{' '}
|
||||
{values.breakEven.value?.breakEvenUnits ??
|
||||
values.breakEven.error}{' '}
|
||||
unidades
|
||||
</p>
|
||||
<p>
|
||||
Necessidade de financiamento:{' '}
|
||||
{values.funding.value?.gap ?? values.funding.error}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Estimativa recalculada pelas fórmulas da ferramenta a partir
|
||||
das entradas guardadas, versão {result.draft_version}. Não
|
||||
constitui decisão de financiamento.
|
||||
</p>
|
||||
<p className="text-xs break-all">
|
||||
Evidência {result.id} · {result.engine}
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
} catch (error) {
|
||||
return (
|
||||
<li role="alert">
|
||||
{error instanceof Error
|
||||
? error.message
|
||||
: 'Resultado indisponível'}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
const form = useForm({
|
||||
version: path.case.version,
|
||||
state: path.canWrite ? 'preparing' : 'reviewing',
|
||||
action: path.canWrite ? 'prepare' : 'review',
|
||||
reason: '',
|
||||
document_id: '',
|
||||
authority: '',
|
||||
reference: '',
|
||||
decision_date: '',
|
||||
});
|
||||
const ownerStates = [
|
||||
'not_started',
|
||||
'preparing',
|
||||
'ready_to_submit',
|
||||
'submitted',
|
||||
'waiting_external',
|
||||
'completed',
|
||||
];
|
||||
const reviewStates = [
|
||||
'reviewing',
|
||||
'correction_required',
|
||||
'approved',
|
||||
'rejected',
|
||||
'expired',
|
||||
];
|
||||
const states = path.canWrite ? ownerStates : reviewStates;
|
||||
return (
|
||||
<article id={step.code} className="space-y-3 rounded-xl border p-4">
|
||||
<h3 className="font-semibold">
|
||||
{step.code} · {step.title}
|
||||
</h3>
|
||||
<p>{pathStates[step.state]}</p>
|
||||
{step.reason && (
|
||||
<p className="text-sm">Fundamento: {step.reason}</p>
|
||||
)}
|
||||
{step.applicability === 'undetermined' && (
|
||||
<p className="text-sm">
|
||||
Aplicabilidade por determinar. A preparação pode avançar.
|
||||
</p>
|
||||
)}
|
||||
{step.state === 'dispensed' && (
|
||||
<p className="text-sm">
|
||||
Dispensa apenas de preparação deste ramo; não é dispensa
|
||||
legal. O estado anterior e o histórico foram preservados.
|
||||
</p>
|
||||
)}
|
||||
{Object.entries(step.action_gaps)
|
||||
.filter(([, gaps]) => gaps.length)
|
||||
.map(([action, gaps]) => (
|
||||
<p key={action} className="text-sm">
|
||||
{action === 'submit'
|
||||
? 'Submissão'
|
||||
: action === 'operate'
|
||||
? 'Operação'
|
||||
: 'Execução'}{' '}
|
||||
aguarda {gaps.join(', ')}. Pode continuar a preparar.
|
||||
</p>
|
||||
))}
|
||||
<p className="text-xs">
|
||||
Documento original, parágrafo {step.source_paragraph}.{' '}
|
||||
{step.detail.scope === 'internal_validation'
|
||||
? 'Conferência interna; não equivale a decisão externa.'
|
||||
: step.detail.scope === 'external_document_recorded'
|
||||
? 'Acto externo registado a partir de documento.'
|
||||
: 'Preparação declarada pelo promotor.'}
|
||||
</p>
|
||||
{step.preparation_allowed && (path.canWrite || path.canReview) && (
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
Registar avanço ou pendência
|
||||
</summary>
|
||||
<form
|
||||
className="mt-3 grid gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
version: path.case.version,
|
||||
document_id: data.document_id || null,
|
||||
decision_date: data.decision_date || null,
|
||||
}));
|
||||
form.post(
|
||||
`/investimentos/${path.case.id}/etapas/${step.code}`,
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label className="grid gap-1">
|
||||
Estado
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={form.data.state}
|
||||
onChange={(e) =>
|
||||
form.setData('state', e.target.value)
|
||||
}
|
||||
>
|
||||
{states.map((state) => (
|
||||
<option key={state} value={state}>
|
||||
{pathStates[state]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Acção
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={form.data.action}
|
||||
onChange={(e) =>
|
||||
form.setData('action', e.target.value)
|
||||
}
|
||||
>
|
||||
{(path.canWrite
|
||||
? [
|
||||
['prepare', 'Preparar'],
|
||||
['submit', 'Registar submissão'],
|
||||
['execute', 'Executar'],
|
||||
['operate', 'Operar'],
|
||||
]
|
||||
: [
|
||||
['review', 'Conferência interna'],
|
||||
[
|
||||
'record_external',
|
||||
'Registar acto externo',
|
||||
],
|
||||
]
|
||||
).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Fundamento
|
||||
<textarea
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={3000}
|
||||
className="rounded border p-2"
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Referência de submissão ou decisão
|
||||
<input
|
||||
className="rounded border p-2"
|
||||
value={form.data.reference}
|
||||
onChange={(e) =>
|
||||
form.setData('reference', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{path.canReview && (
|
||||
<>
|
||||
<label className="grid gap-1">
|
||||
Documento de suporte
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={form.data.document_id}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'document_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
{path.documents.map((doc) => (
|
||||
<option
|
||||
key={doc.id}
|
||||
value={doc.document_id}
|
||||
>
|
||||
{doc.file_name} ·{' '}
|
||||
{doc.malware_scan_status}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Entidade externa
|
||||
<input
|
||||
className="rounded border p-2"
|
||||
value={form.data.authority}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'authority',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Data do acto
|
||||
<input
|
||||
type="date"
|
||||
className="rounded border p-2"
|
||||
value={form.data.decision_date}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'decision_date',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
{Object.values(form.errors).map((error, i) => (
|
||||
<p key={i} role="alert">
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
disabled={form.processing}
|
||||
className="rounded border p-2"
|
||||
>
|
||||
Guardar registo
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export default function InvestmentPath(path: Path) {
|
||||
const { auth, flash } = usePage<{
|
||||
auth: { user: { id: number } };
|
||||
flash: { success?: string };
|
||||
}>().props;
|
||||
const facts = useForm({
|
||||
version: path.case.version,
|
||||
...path.facts,
|
||||
reason: '',
|
||||
});
|
||||
const task = useForm({
|
||||
version: path.case.version,
|
||||
code: 'S02',
|
||||
title: '',
|
||||
due_at: '',
|
||||
consent: false,
|
||||
});
|
||||
const [service, setService] = useState(path.services[0]?.id ?? '');
|
||||
const [requestKey] = useState(() => crypto.randomUUID());
|
||||
const [taskReason, setTaskReason] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
function support() {
|
||||
router.post(
|
||||
`/balcao-virtual/dossiers/${path.case.id}/pedidos`,
|
||||
{ service_version_id: service, client_key: requestKey },
|
||||
{ onError: (errors) => setError(Object.values(errors).join('; ')) },
|
||||
);
|
||||
}
|
||||
return (
|
||||
<main className="mx-auto max-w-6xl space-y-6 p-4 md:p-8">
|
||||
<Head title={path.case.title} />
|
||||
<Link className="underline" href="/investimentos">
|
||||
Os meus investimentos
|
||||
</Link>
|
||||
<h1 className="text-2xl font-semibold">{path.case.title}</h1>
|
||||
{flash?.success && <output>{flash.success}</output>}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<section className="rounded-xl border p-4">
|
||||
<h2 className="font-semibold">Próxima acção</h2>
|
||||
{path.next ? (
|
||||
<a className="underline" href={path.next.href}>
|
||||
{path.next.action}: {path.next.code} · {path.next.title}
|
||||
</a>
|
||||
) : (
|
||||
<p>Reveja as pendências e o acompanhamento.</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Pode preparar etapas independentes enquanto aguarda
|
||||
informação. Percurso v{path.definition_version}; os outros
|
||||
roteiros mantêm a numeração original.
|
||||
</p>
|
||||
</section>
|
||||
<nav
|
||||
className="flex flex-wrap gap-4"
|
||||
aria-label="Ferramentas do investimento"
|
||||
>
|
||||
{Object.entries(path.tools)
|
||||
.filter(([key, url]) => url && key !== 'guidance')
|
||||
.map(([key, url]) => (
|
||||
<Link className="underline" key={key} href={url!}>
|
||||
{
|
||||
(
|
||||
{
|
||||
simulator: 'Plano e simulador',
|
||||
desk: 'Balcão e histórico',
|
||||
library: 'Biblioteca',
|
||||
opportunities: 'Oportunidades',
|
||||
territory: 'Território e mapas',
|
||||
partners: 'Parcerias',
|
||||
} as Record<string, string>
|
||||
)[key]
|
||||
}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
{path.canWrite && (
|
||||
<form
|
||||
className="grid gap-3 rounded-xl border p-4 sm:grid-cols-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
facts.transform((data) => ({
|
||||
...data,
|
||||
version: path.case.version,
|
||||
}));
|
||||
facts.post(
|
||||
`/investimentos/${path.case.id}/aplicabilidade`,
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h2 className="font-semibold sm:col-span-2">
|
||||
Decisões do promotor e aplicabilidade
|
||||
</h2>
|
||||
{(
|
||||
[
|
||||
['land_needed', 'Precisa de terra?'],
|
||||
[
|
||||
'external_funding',
|
||||
'Precisa de financiamento externo?',
|
||||
],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<label className="grid gap-1" key={key}>
|
||||
{label}
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={facts.data[key]}
|
||||
onChange={(e) =>
|
||||
facts.setData(key, e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="unknown">Por determinar</option>
|
||||
<option value="yes">Sim</option>
|
||||
<option value="no">Não</option>
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
<label className="grid gap-1">
|
||||
Decisão sobre viabilidade
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={facts.data.viability}
|
||||
onChange={(e) =>
|
||||
facts.setData('viability', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="unknown">Por determinar</option>
|
||||
<option value="proceed">Prosseguir</option>
|
||||
<option value="reformulate">Reformular</option>
|
||||
<option value="archive">Arquivar a ideia</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Fundamento
|
||||
<textarea
|
||||
required
|
||||
minLength={3}
|
||||
className="rounded border p-2"
|
||||
value={facts.data.reason}
|
||||
onChange={(e) =>
|
||||
facts.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{Object.values(facts.errors).map((message, i) => (
|
||||
<p key={i} role="alert">
|
||||
{message}
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
disabled={facts.processing}
|
||||
className="rounded border p-2"
|
||||
>
|
||||
Guardar decisões
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{Object.entries(path.phases).map(([number, label]) => (
|
||||
<section className="space-y-3" key={number}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</h2>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter((step) => step.phase === Number(number))
|
||||
.map((step) => (
|
||||
<Stage
|
||||
key={step.code}
|
||||
step={step}
|
||||
path={path}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Resultados devolvidos ao dossier
|
||||
</h2>
|
||||
<ul className="grid gap-3 md:grid-cols-2">
|
||||
{path.results.map((result) => (
|
||||
<Result key={result.id} result={result} />
|
||||
))}
|
||||
</ul>
|
||||
{!path.results.length && (
|
||||
<p>
|
||||
Nenhum resultado financeiro disponível para esta conta
|
||||
neste dossier.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
<section className="space-y-3 rounded-xl border p-4">
|
||||
<h2 className="text-lg font-semibold">Apoio no Balcão</h2>
|
||||
{path.canWrite && (
|
||||
<>
|
||||
<label className="grid gap-1">
|
||||
Serviço
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={service}
|
||||
onChange={(e) => setService(e.target.value)}
|
||||
>
|
||||
{path.services.map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
disabled={!service}
|
||||
className="rounded border p-2"
|
||||
onClick={support}
|
||||
>
|
||||
Preparar pedido com dados do dossier
|
||||
</button>
|
||||
<p className="text-sm">
|
||||
Cria um rascunho; reveja os dados no Balcão antes de
|
||||
submeter.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<ul>
|
||||
{path.requests.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/pedidos/${item.id}`}
|
||||
>
|
||||
{item.protocol ?? 'Rascunho'} · {item.status}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
<section className="space-y-3 rounded-xl border p-4">
|
||||
<h2 className="text-lg font-semibold">Documentos</h2>
|
||||
<ul>
|
||||
{path.documents.map((doc) => (
|
||||
<li key={doc.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${path.case.id}/documentos/${doc.id}`}
|
||||
>
|
||||
{doc.file_name}
|
||||
</Link>{' '}
|
||||
· {doc.status} · {doc.malware_scan_status}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Link className="underline" href={path.tools.desk!}>
|
||||
Anexar ou conferir no Balcão
|
||||
</Link>
|
||||
</section>
|
||||
<section className="space-y-3 rounded-xl border p-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Acompanhamento interno
|
||||
</h2>
|
||||
{path.canWrite && (
|
||||
<form
|
||||
className="grid gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
task.transform((data) => ({
|
||||
...data,
|
||||
version: path.case.version,
|
||||
}));
|
||||
task.post(
|
||||
`/investimentos/${path.case.id}/tarefas`,
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label className="grid gap-1">
|
||||
Etapa
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
value={task.data.code}
|
||||
onChange={(e) =>
|
||||
task.setData('code', e.target.value)
|
||||
}
|
||||
>
|
||||
{path.steps
|
||||
.filter((step) => step.preparation_allowed)
|
||||
.map((step) => (
|
||||
<option
|
||||
key={step.code}
|
||||
value={step.code}
|
||||
>
|
||||
{step.code} · {step.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Tarefa
|
||||
<input
|
||||
required
|
||||
className="rounded border p-2"
|
||||
value={task.data.title}
|
||||
onChange={(e) =>
|
||||
task.setData('title', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Prazo
|
||||
<input
|
||||
required
|
||||
type="datetime-local"
|
||||
className="rounded border p-2"
|
||||
value={task.data.due_at}
|
||||
onChange={(e) =>
|
||||
task.setData('due_at', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={task.data.consent}
|
||||
onChange={(e) =>
|
||||
task.setData('consent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Assumo esta tarefa no acompanhamento interno.
|
||||
</label>
|
||||
{Object.values(task.errors).map((message, i) => (
|
||||
<p key={i} role="alert">
|
||||
{message}
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
disabled={task.processing}
|
||||
className="rounded border p-2"
|
||||
>
|
||||
Guardar tarefa
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<label className="grid gap-1">
|
||||
Fundamento do resultado ou atribuição
|
||||
<input
|
||||
className="rounded border p-2"
|
||||
value={taskReason}
|
||||
onChange={(e) => setTaskReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<ul className="space-y-2">
|
||||
{path.tasks.map((item) => (
|
||||
<li className="rounded border p-3" key={item.id}>
|
||||
{item.title} · {item.status} · prazo{' '}
|
||||
{new Date(item.due_at).toLocaleString('pt-MZ')}
|
||||
{(item.assignee_user_id === auth.user.id ||
|
||||
path.canReview) && (
|
||||
<div className="mt-2 flex flex-wrap gap-3">
|
||||
{['in_progress', 'done'].map((status) => (
|
||||
<button
|
||||
key={status}
|
||||
disabled={
|
||||
taskReason.trim().length < 3
|
||||
}
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/balcao-virtual/dossiers/${path.case.id}/tarefas/${item.id}`,
|
||||
{
|
||||
version:
|
||||
item.version_no,
|
||||
status,
|
||||
reason: taskReason,
|
||||
},
|
||||
{
|
||||
preserveScroll: true,
|
||||
onError: (errors) =>
|
||||
setError(
|
||||
Object.values(
|
||||
errors,
|
||||
).join('; '),
|
||||
),
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
{status === 'done'
|
||||
? 'Registar conclusão'
|
||||
: 'Iniciar tarefa'}
|
||||
</button>
|
||||
))}
|
||||
{path.canReview && (
|
||||
<button
|
||||
disabled={
|
||||
taskReason.trim().length < 3
|
||||
}
|
||||
className="rounded border p-2"
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/balcao-virtual/dossiers/${path.case.id}/tarefas/${item.id}`,
|
||||
{
|
||||
version:
|
||||
item.version_no,
|
||||
status: item.status,
|
||||
assignee_user_id:
|
||||
auth.user.id,
|
||||
reason: taskReason,
|
||||
},
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
Assumir acompanhamento
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,9 @@ type Props = {
|
||||
}[];
|
||||
disclaimer: string;
|
||||
management: boolean;
|
||||
countryName: string;
|
||||
declaredOrigin: { code: string | null; name: string };
|
||||
territoryPaths: { id: string; name: string; location_type: string }[][];
|
||||
};
|
||||
const statusLabels: Record<string, string> = {
|
||||
draft: 'Rascunho privado',
|
||||
@@ -57,6 +60,9 @@ export default function LandCase({
|
||||
events,
|
||||
disclaimer,
|
||||
management,
|
||||
countryName,
|
||||
declaredOrigin,
|
||||
territoryPaths,
|
||||
}: Props) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [category, setCategory] = useState('other');
|
||||
@@ -149,6 +155,13 @@ export default function LandCase({
|
||||
<strong>Categoria:</strong>{' '}
|
||||
{payload.applicant_category ?? 'Por indicar'}
|
||||
</p>
|
||||
<p>
|
||||
<strong>País do requerente:</strong> {countryName}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Origem declarada da solicitação:</strong>{' '}
|
||||
{declaredOrigin.name}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Contacto preferido:</strong>{' '}
|
||||
{payload.preferred_contact ?? 'Por indicar'}
|
||||
@@ -169,6 +182,17 @@ export default function LandCase({
|
||||
.join('; ') || 'Por localizar/confirmar'}
|
||||
</p>
|
||||
<p className="text-sm sm:col-span-2">
|
||||
{territoryPaths.map(
|
||||
(path, index) =>
|
||||
path.length > 0 && (
|
||||
<span className="block" key={index}>
|
||||
Parcela {index + 1}:{' '}
|
||||
{path
|
||||
.map((territory) => territory.name)
|
||||
.join(' → ')}
|
||||
</span>
|
||||
),
|
||||
)}
|
||||
Dados e situação geográfica aqui exibidos são declarações do
|
||||
requerente; não confirmam direitos ou disponibilidade
|
||||
cadastral.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
@@ -30,6 +31,7 @@ const emptyPayload = (user: { name: string; email: string }): Payload => ({
|
||||
phone: '',
|
||||
preferred_contact: '',
|
||||
country: '',
|
||||
declared_origin_country_code: '',
|
||||
nationality: '',
|
||||
representative_name: '',
|
||||
representative_role: '',
|
||||
@@ -76,6 +78,7 @@ export default function LandForm({
|
||||
user,
|
||||
disclaimer,
|
||||
modelVersion,
|
||||
countries,
|
||||
}: {
|
||||
case: {
|
||||
id: string;
|
||||
@@ -87,6 +90,7 @@ export default function LandForm({
|
||||
user: { name: string; email: string };
|
||||
disclaimer: string;
|
||||
modelVersion: string;
|
||||
countries: Country[];
|
||||
}) {
|
||||
const [step, setStep] = useState(0);
|
||||
const initial = useMemo(
|
||||
@@ -272,7 +276,32 @@ export default function LandForm({
|
||||
<option value="any">Qualquer um indicado</option>
|
||||
</select>
|
||||
</label>
|
||||
{text('country', 'País, se aplicável')}
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={current.country ?? ''}
|
||||
onChange={(value) => update('country', value)}
|
||||
label="País, se aplicável"
|
||||
allowLegacyValue
|
||||
/>
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={current.declared_origin_country_code ?? ''}
|
||||
onChange={(value) =>
|
||||
update('declared_origin_country_code', value)
|
||||
}
|
||||
label="País de origem declarado da solicitação (opcional)"
|
||||
/>
|
||||
{(form.errors['payload.country'] ||
|
||||
form.errors[
|
||||
'payload.declared_origin_country_code'
|
||||
]) && (
|
||||
<p role="alert">
|
||||
{form.errors['payload.country'] ??
|
||||
form.errors[
|
||||
'payload.declared_origin_country_code'
|
||||
]}
|
||||
</p>
|
||||
)}
|
||||
{text('nationality', 'Nacionalidade, se aplicável')}
|
||||
{category === 'entity' && (
|
||||
<>
|
||||
|
||||
@@ -60,11 +60,13 @@ export default function InterestDetail({
|
||||
history = [],
|
||||
assignees = [],
|
||||
consents = [],
|
||||
declaredOrigin,
|
||||
}: {
|
||||
interest: Interest;
|
||||
history?: Transition[];
|
||||
assignees?: Assignee[];
|
||||
consents?: Consent[];
|
||||
declaredOrigin: { code: string | null; name: string };
|
||||
}) {
|
||||
const form = useForm({
|
||||
status: interest.status,
|
||||
@@ -81,6 +83,12 @@ export default function InterestDetail({
|
||||
['Telefone', interest.phone],
|
||||
['Tipo de investidor', interest.investor_type],
|
||||
['País', interest.country],
|
||||
[
|
||||
'Origem declarada da solicitação',
|
||||
declaredOrigin.code
|
||||
? `${declaredOrigin.name} (${declaredOrigin.code})`
|
||||
: declaredOrigin.name,
|
||||
],
|
||||
['Sector', interest.sector_interest],
|
||||
['Oportunidade', interest.opportunity_reference],
|
||||
['Negócio publicado', interest.existing_business_id],
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Management, Pagination, button, control, states } from './shared';
|
||||
import type { Paginated } from './shared';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
|
||||
type Interest = {
|
||||
id: number;
|
||||
@@ -15,17 +16,34 @@ type Interest = {
|
||||
next_action: string | null;
|
||||
next_action_due_at: string | null;
|
||||
status: string;
|
||||
countryName: string | null;
|
||||
declaredOrigin: { code: string | null; name: string };
|
||||
};
|
||||
export default function Interests({
|
||||
requests,
|
||||
filters,
|
||||
countries,
|
||||
originStatistics,
|
||||
}: {
|
||||
requests: Paginated<Interest>;
|
||||
filters: { q?: string; status?: string; follow_up?: string };
|
||||
filters: {
|
||||
q?: string;
|
||||
status?: string;
|
||||
follow_up?: string;
|
||||
country?: string;
|
||||
origin?: string;
|
||||
};
|
||||
countries: Country[];
|
||||
originStatistics: Record<
|
||||
string,
|
||||
{ code: string | null; name: string; count: number }[]
|
||||
>;
|
||||
}) {
|
||||
const [q, setQ] = useState(filters.q ?? '');
|
||||
const [status, setStatus] = useState(filters.status ?? '');
|
||||
const [followUp, setFollowUp] = useState(filters.follow_up ?? '');
|
||||
const [country, setCountry] = useState(filters.country ?? '');
|
||||
const [origin, setOrigin] = useState(filters.origin ?? '');
|
||||
return (
|
||||
<Management title="Manifestações de interesse">
|
||||
<form
|
||||
@@ -36,6 +54,8 @@ export default function Interests({
|
||||
q,
|
||||
status,
|
||||
follow_up: followUp,
|
||||
country,
|
||||
origin,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -91,6 +111,29 @@ export default function Interests({
|
||||
<option value="upcoming">Acções por vencer</option>
|
||||
<option value="unassigned">Sem responsável</option>
|
||||
</select>
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={country}
|
||||
onChange={setCountry}
|
||||
label="Filtrar país do requerente"
|
||||
/>
|
||||
<label>
|
||||
Origem declarada
|
||||
<select
|
||||
aria-label="Filtrar origem declarada"
|
||||
className={control}
|
||||
value={origin}
|
||||
onChange={(e) => setOrigin(e.target.value)}
|
||||
>
|
||||
<option value="">Todas as origens</option>
|
||||
<option value="unknown">Não informada</option>
|
||||
{countries.map((c) => (
|
||||
<option key={c.code} value={c.code}>
|
||||
{c.name} ({c.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
<div className="overflow-x-auto">
|
||||
@@ -101,6 +144,8 @@ export default function Interests({
|
||||
'Referência',
|
||||
'Nome',
|
||||
'Email',
|
||||
'País do requerente',
|
||||
'Origem declarada',
|
||||
'Sector',
|
||||
'Modalidade',
|
||||
'Responsável',
|
||||
@@ -129,6 +174,12 @@ export default function Interests({
|
||||
{item.full_name}
|
||||
</td>
|
||||
<td className="border-b p-3">{item.email}</td>
|
||||
<td className="border-b p-3">
|
||||
{item.countryName ?? 'Não informado'}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{item.declaredOrigin.name}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{item.sector_interest}
|
||||
</td>
|
||||
@@ -161,6 +212,45 @@ export default function Interests({
|
||||
</div>
|
||||
{!requests.data.length && <p>Nenhum pedido encontrado.</p>}
|
||||
<Pagination page={requests} />
|
||||
<details>
|
||||
<summary>
|
||||
Estatísticas de solicitações por origem declarada
|
||||
</summary>
|
||||
<p>
|
||||
Contagens por conjunto e filtro de origem; o filtro do país
|
||||
do requerente aplica-se à lista. Rascunhos de negócios e do
|
||||
Balcão são excluídos. Apoio fundiário recebido integra
|
||||
manifestações; não se soma como outro conjunto nem se contam
|
||||
investidores únicos.
|
||||
</p>
|
||||
{Object.entries(originStatistics).map(([group, counts]) => (
|
||||
<section key={group}>
|
||||
<h2>
|
||||
{
|
||||
(
|
||||
{
|
||||
interests:
|
||||
'Manifestações recebidas, incluindo apoio fundiário',
|
||||
desk: 'Pedidos do Balcão',
|
||||
businesses: 'Negócios submetidos',
|
||||
} as Record<string, string>
|
||||
)[group]
|
||||
}
|
||||
</h2>
|
||||
{counts.length ? (
|
||||
<ul>
|
||||
{counts.map((row) => (
|
||||
<li key={row.code ?? 'unknown'}>
|
||||
{row.name}: {row.count}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Sem solicitações neste conjunto.</p>
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
</details>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
TerritoryLevel,
|
||||
type TerritoryOption,
|
||||
} from "@/components/investment-territory";
|
||||
import { Management, Field, button, control } from "./shared";
|
||||
} from '@/components/investment-territory';
|
||||
import { Management, Field, button, control } from './shared';
|
||||
type Values = Record<string, string | number | null>;
|
||||
type Entry = {
|
||||
id: number;
|
||||
@@ -25,6 +26,7 @@ export default function OpportunityDraft({
|
||||
history,
|
||||
territoryPath,
|
||||
resourcesInstalled = false,
|
||||
maturityCatalogue,
|
||||
}: {
|
||||
record: Entry | null;
|
||||
values: Values;
|
||||
@@ -36,6 +38,12 @@ export default function OpportunityDraft({
|
||||
categories: string[];
|
||||
territoryPath: TerritoryOption[];
|
||||
resourcesInstalled?: boolean;
|
||||
maturityCatalogue: {
|
||||
version: string;
|
||||
stages: Record<string, string>;
|
||||
legacyVersion: string;
|
||||
legacyLabels: Record<string, string>;
|
||||
};
|
||||
history: {
|
||||
id: string;
|
||||
action: string;
|
||||
@@ -49,43 +57,43 @@ export default function OpportunityDraft({
|
||||
});
|
||||
const [busy, setBusy] = useState(false),
|
||||
[errors, setErrors] = useState<Record<string, string>>({}),
|
||||
[message, setMessage] = useState(""),
|
||||
[reason, setReason] = useState(""),
|
||||
[message, setMessage] = useState(''),
|
||||
[reason, setReason] = useState(''),
|
||||
[confirm, setConfirm] = useState(false),
|
||||
[token, setToken] = useState(etag);
|
||||
useEffect(() => setToken(etag), [etag]);
|
||||
const [path, setPath] = useState(territoryPath);
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === "archived",
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: "save" | "delete" | "restore") {
|
||||
async function send(action: 'save' | 'delete' | 'restore') {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
try {
|
||||
const cookie = document.cookie
|
||||
.split("; ")
|
||||
.find((c) => c.startsWith("XSRF-TOKEN="));
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith('XSRF-TOKEN='));
|
||||
const url =
|
||||
action === "save"
|
||||
action === 'save'
|
||||
? record
|
||||
? `/management/opportunities/${record.id}/draft`
|
||||
: "/management/opportunities/drafts"
|
||||
: '/management/opportunities/drafts'
|
||||
: `/management/opportunities/${record!.id}/lifecycle`;
|
||||
const response = await fetch(url, {
|
||||
method: action === "save" && record ? "PUT" : "POST",
|
||||
method: action === 'save' && record ? 'PUT' : 'POST',
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"X-XSRF-TOKEN": cookie
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': cookie
|
||||
? decodeURIComponent(cookie.slice(11))
|
||||
: "",
|
||||
: '',
|
||||
},
|
||||
body: JSON.stringify(
|
||||
action === "save"
|
||||
action === 'save'
|
||||
? { ...data, etag: token, reason }
|
||||
: { etag: token, action, reason, confirm },
|
||||
),
|
||||
@@ -96,13 +104,13 @@ export default function OpportunityDraft({
|
||||
Object.fromEntries(
|
||||
Object.entries(result.errors ?? {}).map(([k, v]) => [
|
||||
k,
|
||||
Array.isArray(v) ? v.join(" ") : String(v),
|
||||
Array.isArray(v) ? v.join(' ') : String(v),
|
||||
]),
|
||||
),
|
||||
);
|
||||
setMessage(
|
||||
result.message ??
|
||||
"Operação falhou; os dados preenchidos foram preservados.",
|
||||
'Operação falhou; os dados preenchidos foram preservados.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -110,15 +118,15 @@ export default function OpportunityDraft({
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (!record)
|
||||
router.visit(`/management/opportunities/${result.id}/edit`);
|
||||
else if (action !== "save") router.reload();
|
||||
else if (action !== 'save') router.reload();
|
||||
} catch {
|
||||
setMessage(
|
||||
"Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.",
|
||||
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
requestAnimationFrame(() =>
|
||||
document.getElementById("opportunity-result")?.focus(),
|
||||
document.getElementById('opportunity-result')?.focus(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -126,8 +134,8 @@ export default function OpportunityDraft({
|
||||
<Management
|
||||
title={
|
||||
record
|
||||
? `${readOnly ? "Ver" : "Editar"} oportunidade ${record.reference}`
|
||||
: "Nova oportunidade"
|
||||
? `${readOnly ? 'Ver' : 'Editar'} oportunidade ${record.reference}`
|
||||
: 'Nova oportunidade'
|
||||
}
|
||||
>
|
||||
<Link href="/management/opportunities">Voltar à gestão</Link>
|
||||
@@ -145,13 +153,13 @@ export default function OpportunityDraft({
|
||||
<div
|
||||
id="opportunity-result"
|
||||
tabIndex={-1}
|
||||
role={Object.keys(errors).length ? "alert" : "status"}
|
||||
role={Object.keys(errors).length ? 'alert' : 'status'}
|
||||
className="rounded border p-3"
|
||||
>
|
||||
{message}
|
||||
{errors.etag && (
|
||||
<p>
|
||||
{errors.etag}{" "}
|
||||
{errors.etag}{' '}
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
@@ -166,7 +174,7 @@ export default function OpportunityDraft({
|
||||
className="max-w-3xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send("save");
|
||||
void send('save');
|
||||
}}
|
||||
>
|
||||
<fieldset
|
||||
@@ -174,6 +182,10 @@ export default function OpportunityDraft({
|
||||
className="space-y-4"
|
||||
>
|
||||
<section aria-label="Localização registada">
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
/>
|
||||
<p>
|
||||
Hierarquia do cadastro territorial existente.
|
||||
Alterar esta seleção não cria relações com
|
||||
@@ -181,16 +193,16 @@ export default function OpportunityDraft({
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
"province_id",
|
||||
"district_id",
|
||||
"admin_post_id",
|
||||
"locality_id",
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${path[index - 1]?.id ?? ""}`}
|
||||
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ""}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint="/management/territory-options"
|
||||
fieldError={errors[key]}
|
||||
@@ -202,10 +214,10 @@ export default function OpportunityDraft({
|
||||
setPath(next);
|
||||
setData((previous) => ({
|
||||
...previous,
|
||||
province_id: next[0]?.id ?? "",
|
||||
district_id: next[1]?.id ?? "",
|
||||
admin_post_id: next[2]?.id ?? "",
|
||||
locality_id: next[3]?.id ?? "",
|
||||
province_id: next[0]?.id ?? '',
|
||||
district_id: next[1]?.id ?? '',
|
||||
admin_post_id: next[2]?.id ?? '',
|
||||
locality_id: next[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
@@ -217,9 +229,9 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.opportunity_category ?? "")}
|
||||
value={String(data.opportunity_category ?? '')}
|
||||
onChange={(e) =>
|
||||
set("opportunity_category", e.target.value)
|
||||
set('opportunity_category', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
@@ -229,22 +241,22 @@ export default function OpportunityDraft({
|
||||
</select>
|
||||
</Field>
|
||||
{Object.entries({
|
||||
title: "Título oficial",
|
||||
summary: "Resumo",
|
||||
description: "Descrição",
|
||||
promoter_name: "Promotor",
|
||||
title: 'Título oficial',
|
||||
summary: 'Resumo',
|
||||
description: 'Descrição',
|
||||
promoter_name: 'Promotor',
|
||||
}).map(([key, label]) => (
|
||||
<Field key={key} label={label} error={errors[key]}>
|
||||
{key === "description" || key === "summary" ? (
|
||||
{key === 'description' || key === 'summary' ? (
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data[key] ?? "")}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={String(data[key] ?? "")}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
@@ -253,8 +265,8 @@ export default function OpportunityDraft({
|
||||
<Field label="Sector" error={errors.sector_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.sector_id ?? "")}
|
||||
onChange={(e) => set("sector_id", e.target.value)}
|
||||
value={String(data.sector_id ?? '')}
|
||||
onChange={(e) => set('sector_id', e.target.value)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
@@ -270,21 +282,21 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.promoter_type ?? "")}
|
||||
value={String(data.promoter_type ?? '')}
|
||||
onChange={(e) =>
|
||||
set("promoter_type", e.target.value)
|
||||
set('promoter_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{values.promoter_type &&
|
||||
![
|
||||
"public",
|
||||
"private",
|
||||
"ppp",
|
||||
"cooperative",
|
||||
"association",
|
||||
"community",
|
||||
"other",
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].includes(String(values.promoter_type)) && (
|
||||
<option
|
||||
value={String(values.promoter_type)}
|
||||
@@ -294,43 +306,85 @@ export default function OpportunityDraft({
|
||||
</option>
|
||||
)}
|
||||
{[
|
||||
"public",
|
||||
"private",
|
||||
"ppp",
|
||||
"cooperative",
|
||||
"association",
|
||||
"community",
|
||||
"other",
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Maturidade existente"
|
||||
error={errors.maturity_level}
|
||||
label="Etapa de maturidade"
|
||||
error={errors.maturity_stage ?? errors.maturity_level}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.maturity_level ?? "")}
|
||||
onChange={(e) =>
|
||||
set("maturity_level", e.target.value)
|
||||
value={
|
||||
data.maturity_catalogue_version ===
|
||||
maturityCatalogue.version
|
||||
? String(data.maturity_stage ?? '')
|
||||
: data.maturity_level
|
||||
? `legacy:${data.maturity_level}`
|
||||
: ''
|
||||
}
|
||||
onChange={(e) => {
|
||||
const stage = e.target.value;
|
||||
if (stage.startsWith('legacy:')) {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.legacyVersion,
|
||||
maturity_level: Number(stage.slice(7)),
|
||||
maturity_stage: null,
|
||||
}));
|
||||
} else {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.version,
|
||||
maturity_stage: stage || null,
|
||||
maturity_level: stage
|
||||
? Object.keys(
|
||||
maturityCatalogue.stages,
|
||||
).indexOf(stage) + 1
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{[
|
||||
"Ideia identificada",
|
||||
"Pré-estudo disponível",
|
||||
"Estudo de viabilidade em curso",
|
||||
"Projecto estruturado",
|
||||
"Pronto para investimento",
|
||||
"Em negociação ou implementação",
|
||||
].map((c, index) => (
|
||||
<option key={c} value={index + 1}>
|
||||
{c}
|
||||
</option>
|
||||
))}
|
||||
{values.maturity_level &&
|
||||
values.maturity_catalogue_version !==
|
||||
maturityCatalogue.version && (
|
||||
<option
|
||||
value={`legacy:${values.maturity_level}`}
|
||||
>
|
||||
{
|
||||
maturityCatalogue.legacyLabels[
|
||||
String(values.maturity_level)
|
||||
]
|
||||
}{' '}
|
||||
(catálogo histórico; sem conversão)
|
||||
</option>
|
||||
)}
|
||||
{Object.entries(maturityCatalogue.stages).map(
|
||||
([code, label], index) => (
|
||||
<option key={code} value={code}>
|
||||
{index + 1}. {label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
<p>
|
||||
O catálogo de oito etapas é guardado com a sua
|
||||
versão. Os valores históricos conservam o
|
||||
significado anterior.
|
||||
</p>
|
||||
</Field>
|
||||
<Field
|
||||
label="Modalidade de financiamento existente"
|
||||
@@ -338,9 +392,9 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(data.financing_modality ?? "")}
|
||||
value={String(data.financing_modality ?? '')}
|
||||
onChange={(e) =>
|
||||
set("financing_modality", e.target.value)
|
||||
set('financing_modality', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
@@ -350,13 +404,13 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data.expected_impact ?? "")}
|
||||
value={String(data.expected_impact ?? '')}
|
||||
onChange={(e) =>
|
||||
set("expected_impact", e.target.value)
|
||||
set('expected_impact', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(data.opportunity_category === "investment_project" ||
|
||||
{(data.opportunity_category === 'investment_project' ||
|
||||
(!data.opportunity_category &&
|
||||
data.estimated_investment_amount != null)) && (
|
||||
<>
|
||||
@@ -367,11 +421,11 @@ export default function OpportunityDraft({
|
||||
<input
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_amount ?? "",
|
||||
data.estimated_investment_amount ?? '',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
"estimated_investment_amount",
|
||||
'estimated_investment_amount',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
@@ -385,17 +439,17 @@ export default function OpportunityDraft({
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_currency ??
|
||||
"",
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
"estimated_investment_currency",
|
||||
'estimated_investment_currency',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{["MZN", "USD", "EUR", "ZAR"].map((c) => (
|
||||
{['MZN', 'USD', 'EUR', 'ZAR'].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -403,7 +457,7 @@ export default function OpportunityDraft({
|
||||
</>
|
||||
)}
|
||||
{data.opportunity_category &&
|
||||
data.opportunity_category !== "investment_project" && (
|
||||
data.opportunity_category !== 'investment_project' && (
|
||||
<p>
|
||||
O módulo especializado desta categoria permanece
|
||||
pendente. Pode guardar a identificação
|
||||
@@ -439,11 +493,11 @@ export default function OpportunityDraft({
|
||||
onChange={(e) =>
|
||||
setConfirm(e.target.checked)
|
||||
}
|
||||
/>{" "}
|
||||
Confirmo a{" "}
|
||||
/>{' '}
|
||||
Confirmo a{' '}
|
||||
{unavailable
|
||||
? "restauração"
|
||||
: "exclusão lógica/arquivo"}
|
||||
? 'restauração'
|
||||
: 'exclusão lógica/arquivo'}
|
||||
, preservando histórico e relações
|
||||
</label>
|
||||
<button
|
||||
@@ -452,15 +506,15 @@ export default function OpportunityDraft({
|
||||
disabled={busy || !confirm}
|
||||
onClick={() =>
|
||||
void send(
|
||||
unavailable ? "restore" : "delete",
|
||||
unavailable ? 'restore' : 'delete',
|
||||
)
|
||||
}
|
||||
>
|
||||
{unavailable
|
||||
? "Restaurar"
|
||||
? 'Restaurar'
|
||||
: closedVersion
|
||||
? "Arquivar"
|
||||
: "Excluir rascunho"}
|
||||
? 'Arquivar'
|
||||
: 'Excluir rascunho'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
@@ -472,12 +526,12 @@ export default function OpportunityDraft({
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `/management/opportunities/${record.id}/resources`
|
||||
: "/management/opportunity-resources-install"
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
{resourcesInstalled
|
||||
? "Imagens, documentos e localizações"
|
||||
: "Plano de ativação de imagens, documentos e localizações"}
|
||||
? 'Imagens, documentos e localizações'
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record && (
|
||||
@@ -490,7 +544,7 @@ export default function OpportunityDraft({
|
||||
{history.length ? (
|
||||
history.map((e) => (
|
||||
<p key={e.id}>
|
||||
{e.action} · conta {e.actor_user_id} ·{" "}
|
||||
{e.action} · conta {e.actor_user_id} ·{' '}
|
||||
{e.occurred_at}
|
||||
</p>
|
||||
))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useForm } from "@inertiajs/react";
|
||||
import { Management, button } from "./shared";
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { Management, button } from './shared';
|
||||
export default function Install({
|
||||
installed,
|
||||
ready,
|
||||
@@ -9,7 +9,7 @@ export default function Install({
|
||||
migration,
|
||||
backupDate,
|
||||
rollback,
|
||||
actionUrl = "/management/opportunity-management-install",
|
||||
actionUrl = '/management/opportunity-management-install',
|
||||
imageProcessingAvailable,
|
||||
}: {
|
||||
installed: boolean;
|
||||
@@ -27,8 +27,8 @@ export default function Install({
|
||||
return (
|
||||
<Management title="Ativação da Gestão de Oportunidades">
|
||||
<p>
|
||||
Base: {target.database}:{target.port} ·{" "}
|
||||
{installed ? "Instalado" : "Ainda não aplicado"}
|
||||
Base: {target.database}:{target.port} ·{' '}
|
||||
{installed ? 'Instalado' : 'Ainda não aplicado'}
|
||||
</p>
|
||||
<ul>
|
||||
{changes.map((c) => (
|
||||
@@ -36,11 +36,26 @@ export default function Install({
|
||||
))}
|
||||
</ul>
|
||||
<p>Migração: {migration}</p>
|
||||
{imageProcessingAvailable !== undefined && <section className="rounded border border-amber-500 p-3" aria-label="Limitações dos anexos">
|
||||
<p>{imageProcessingAvailable ? 'GD/WebP disponível neste servidor; o processamento continua a exigir scan concluído do original.' : 'GD/WebP indisponível neste servidor: guardar imagens é possível; gerar miniaturas permanece pendente.'}</p>
|
||||
<p>Instalar recursos não confirma scans. Documentos e imagens com scan pendente ficam sem download ou pré-visualização; preparação de rascunhos e localizações continua disponível. ClamD real mantém uma pendência separada.</p>
|
||||
</section>}
|
||||
<p>Backup/restauro: {backupDate ?? "Prova ainda por preparar"}</p>
|
||||
{imageProcessingAvailable !== undefined && (
|
||||
<section
|
||||
className="rounded border border-amber-500 p-3"
|
||||
aria-label="Limitações dos anexos"
|
||||
>
|
||||
<p>
|
||||
{imageProcessingAvailable
|
||||
? 'GD/WebP disponível neste servidor; o processamento continua a exigir scan concluído do original.'
|
||||
: 'GD/WebP indisponível neste servidor: guardar imagens é possível; gerar miniaturas permanece pendente.'}
|
||||
</p>
|
||||
<p>
|
||||
Instalar recursos não confirma scans. Documentos e
|
||||
imagens com scan pendente ficam sem download ou
|
||||
pré-visualização; preparação de rascunhos e localizações
|
||||
continua disponível. ClamD real mantém uma pendência
|
||||
separada.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<p>Backup/restauro: {backupDate ?? 'Prova ainda por preparar'}</p>
|
||||
<p>{rollback}</p>
|
||||
<p>
|
||||
Este plano ativa apenas as alterações acima; workflow completo e
|
||||
@@ -57,9 +72,9 @@ export default function Install({
|
||||
type="checkbox"
|
||||
checked={form.data.confirm}
|
||||
onChange={(e) =>
|
||||
form.setData("confirm", e.target.checked)
|
||||
form.setData('confirm', e.target.checked)
|
||||
}
|
||||
/>{" "}
|
||||
/>{' '}
|
||||
Confirmo a aplicação deste plano
|
||||
</label>
|
||||
<button
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
TerritoryLevel,
|
||||
type TerritoryOption,
|
||||
} from "@/components/investment-territory";
|
||||
import { Management, Field, button, control } from "./shared";
|
||||
} from '@/components/investment-territory';
|
||||
import { Management, Field, button, control } from './shared';
|
||||
|
||||
type Payload = Record<string, string | number | boolean | null | object>;
|
||||
type Resource = {
|
||||
@@ -26,101 +27,101 @@ type Resource = {
|
||||
sha256: string;
|
||||
};
|
||||
};
|
||||
type Kind = "locations" | "images" | "documents";
|
||||
type Kind = 'locations' | 'images' | 'documents';
|
||||
const fields: Record<Kind, string[]> = {
|
||||
locations: [
|
||||
"title",
|
||||
"address",
|
||||
"operational_unit",
|
||||
"role_description",
|
||||
"area_value",
|
||||
"area_unit",
|
||||
"allocation_percentage",
|
||||
"multi_district_rationale",
|
||||
"source_reference",
|
||||
"source_date",
|
||||
'title',
|
||||
'address',
|
||||
'operational_unit',
|
||||
'role_description',
|
||||
'area_value',
|
||||
'area_unit',
|
||||
'allocation_percentage',
|
||||
'multi_district_rationale',
|
||||
'source_reference',
|
||||
'source_date',
|
||||
],
|
||||
images: [
|
||||
"title",
|
||||
"caption",
|
||||
"alt_text",
|
||||
"author_source",
|
||||
"captured_at",
|
||||
"rights_valid_until",
|
||||
"role_description",
|
||||
"sort_order",
|
||||
"source_reference",
|
||||
'title',
|
||||
'caption',
|
||||
'alt_text',
|
||||
'author_source',
|
||||
'captured_at',
|
||||
'rights_valid_until',
|
||||
'role_description',
|
||||
'sort_order',
|
||||
'source_reference',
|
||||
],
|
||||
documents: [
|
||||
"title",
|
||||
"category",
|
||||
"issuer",
|
||||
"edition",
|
||||
"source_date",
|
||||
"valid_until",
|
||||
"source_reference",
|
||||
"section",
|
||||
"supported_statement",
|
||||
'title',
|
||||
'category',
|
||||
'issuer',
|
||||
'edition',
|
||||
'source_date',
|
||||
'valid_until',
|
||||
'source_reference',
|
||||
'section',
|
||||
'supported_statement',
|
||||
],
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
role: "Papel da localização",
|
||||
imageRole: "Tipo de imagem",
|
||||
territorial_purpose: "Natureza da relação territorial",
|
||||
rights_status: "Direitos de utilização",
|
||||
visibility: "Âmbito de consulta",
|
||||
classification: "Classificação documental",
|
||||
location_id: "Localização associada",
|
||||
rights_document_id: "Comprovativo de direitos",
|
||||
title: "Título",
|
||||
address: "Referência física",
|
||||
operational_unit: "Unidade operacional",
|
||||
role_description: "Descrição do papel outro",
|
||||
area_value: "Área",
|
||||
area_unit: "Unidade de área",
|
||||
allocation_percentage: "Distribuição (%)",
|
||||
multi_district_rationale: "Fundamento multidistrito/interprovincial",
|
||||
source_reference: "Fonte / referência",
|
||||
source_date: "Data da fonte",
|
||||
caption: "Legenda",
|
||||
alt_text: "Texto alternativo",
|
||||
author_source: "Autor / fonte",
|
||||
captured_at: "Data da imagem",
|
||||
rights_valid_until: "Validade dos direitos",
|
||||
sort_order: "Ordem",
|
||||
category: "Categoria documental",
|
||||
issuer: "Emissor",
|
||||
edition: "Edição / versão",
|
||||
valid_until: "Validade",
|
||||
section: "Página / secção",
|
||||
supported_statement: "Afirmação fundamentada",
|
||||
role: 'Papel da localização',
|
||||
imageRole: 'Tipo de imagem',
|
||||
territorial_purpose: 'Natureza da relação territorial',
|
||||
rights_status: 'Direitos de utilização',
|
||||
visibility: 'Âmbito de consulta',
|
||||
classification: 'Classificação documental',
|
||||
location_id: 'Localização associada',
|
||||
rights_document_id: 'Comprovativo de direitos',
|
||||
title: 'Título',
|
||||
address: 'Referência física',
|
||||
operational_unit: 'Unidade operacional',
|
||||
role_description: 'Descrição do papel outro',
|
||||
area_value: 'Área',
|
||||
area_unit: 'Unidade de área',
|
||||
allocation_percentage: 'Distribuição (%)',
|
||||
multi_district_rationale: 'Fundamento multidistrito/interprovincial',
|
||||
source_reference: 'Fonte / referência',
|
||||
source_date: 'Data da fonte',
|
||||
caption: 'Legenda',
|
||||
alt_text: 'Texto alternativo',
|
||||
author_source: 'Autor / fonte',
|
||||
captured_at: 'Data da imagem',
|
||||
rights_valid_until: 'Validade dos direitos',
|
||||
sort_order: 'Ordem',
|
||||
category: 'Categoria documental',
|
||||
issuer: 'Emissor',
|
||||
edition: 'Edição / versão',
|
||||
valid_until: 'Validade',
|
||||
section: 'Página / secção',
|
||||
supported_statement: 'Afirmação fundamentada',
|
||||
};
|
||||
const choices: Record<string, string[]> = {
|
||||
role: [
|
||||
"headquarters",
|
||||
"production",
|
||||
"raw_material",
|
||||
"storage",
|
||||
"logistics",
|
||||
"market",
|
||||
"support",
|
||||
"other",
|
||||
'headquarters',
|
||||
'production',
|
||||
'raw_material',
|
||||
'storage',
|
||||
'logistics',
|
||||
'market',
|
||||
'support',
|
||||
'other',
|
||||
],
|
||||
imageRole: [
|
||||
"cover",
|
||||
"gallery",
|
||||
"location",
|
||||
"asset",
|
||||
"product",
|
||||
"plan",
|
||||
"rendering",
|
||||
"evidence",
|
||||
"other",
|
||||
'cover',
|
||||
'gallery',
|
||||
'location',
|
||||
'asset',
|
||||
'product',
|
||||
'plan',
|
||||
'rendering',
|
||||
'evidence',
|
||||
'other',
|
||||
],
|
||||
territorial_purpose: ["implementation", "context", "impact", "coverage"],
|
||||
rights_status: ["owned", "licensed", "authorized", "public_domain"],
|
||||
visibility: ["internal", "authenticated", "public"],
|
||||
classification: ["public", "internal", "confidential", "restricted"],
|
||||
territorial_purpose: ['implementation', 'context', 'impact', 'coverage'],
|
||||
rights_status: ['owned', 'licensed', 'authorized', 'public_domain'],
|
||||
visibility: ['internal', 'authenticated', 'public'],
|
||||
classification: ['public', 'internal', 'confidential', 'restricted'],
|
||||
};
|
||||
|
||||
export default function OpportunityResources({
|
||||
@@ -143,17 +144,17 @@ export default function OpportunityResources({
|
||||
assessment: string[];
|
||||
imageProcessingAvailable: boolean;
|
||||
}) {
|
||||
const [kind, setKind] = useState<Kind>("locations");
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({});
|
||||
const [path, setPath] = useState<TerritoryOption[]>([]);
|
||||
const [geometry, setGeometry] = useState("");
|
||||
const [geometry, setGeometry] = useState('');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [reason, setReason] = useState("");
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [key, setKey] = useState(() => crypto.randomUUID());
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [message, setMessage] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const set = (name: string, value: Payload[string]) =>
|
||||
setPayload((previous) => ({ ...previous, [name]: value }));
|
||||
@@ -165,57 +166,57 @@ export default function OpportunityResources({
|
||||
setGeometry(
|
||||
record?.payload.geometry
|
||||
? JSON.stringify(record.payload.geometry)
|
||||
: "",
|
||||
: '',
|
||||
);
|
||||
setFile(null);
|
||||
setKey(crypto.randomUUID());
|
||||
setConfirm(false);
|
||||
setErrors({});
|
||||
}
|
||||
async function execute(action: "save" | "delete" | "restore" | "prepare") {
|
||||
async function execute(action: 'save' | 'delete' | 'restore' | 'prepare') {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.set("etag", etag);
|
||||
form.set("reason", reason);
|
||||
form.set("creation_key", key);
|
||||
if (editing) form.set("version", String(editing.version));
|
||||
if (action === "save") {
|
||||
form.set('etag', etag);
|
||||
form.set('reason', reason);
|
||||
form.set('creation_key', key);
|
||||
if (editing) form.set('version', String(editing.version));
|
||||
if (action === 'save') {
|
||||
const values = { ...payload };
|
||||
if (kind === "locations") {
|
||||
if (kind === 'locations') {
|
||||
[
|
||||
"province_id",
|
||||
"district_id",
|
||||
"admin_post_id",
|
||||
"locality_id",
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
].forEach(
|
||||
(name, index) =>
|
||||
(values[name] = path[index]?.id ?? null),
|
||||
);
|
||||
values.geometry = geometry ? JSON.parse(geometry) : null;
|
||||
}
|
||||
form.set("payload", JSON.stringify(values));
|
||||
if (file) form.set("file", file);
|
||||
form.set('payload', JSON.stringify(values));
|
||||
if (file) form.set('file', file);
|
||||
} else {
|
||||
form.set("action", action);
|
||||
form.set("confirm", confirm ? "1" : "0");
|
||||
form.set('action', action);
|
||||
form.set('confirm', confirm ? '1' : '0');
|
||||
}
|
||||
const url = `/management/opportunities/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ""}${action === "save" ? "" : action === "prepare" ? "/prepare" : "/lifecycle"}`;
|
||||
const url = `/management/opportunities/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
|
||||
const csrf =
|
||||
document.cookie
|
||||
.split("; ")
|
||||
.find((v) => v.startsWith("XSRF-TOKEN="))
|
||||
?.split("=")
|
||||
.split('; ')
|
||||
.find((v) => v.startsWith('XSRF-TOKEN='))
|
||||
?.split('=')
|
||||
.slice(1)
|
||||
.join("=") ?? "";
|
||||
.join('=') ?? '';
|
||||
const result = await fetch(url, {
|
||||
method: "POST",
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"X-XSRF-TOKEN": decodeURIComponent(csrf),
|
||||
Accept: 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(csrf),
|
||||
},
|
||||
body: form,
|
||||
});
|
||||
@@ -227,7 +228,7 @@ export default function OpportunityResources({
|
||||
([name, value]) => [
|
||||
name,
|
||||
Array.isArray(value)
|
||||
? value.join(" ")
|
||||
? value.join(' ')
|
||||
: String(value),
|
||||
],
|
||||
),
|
||||
@@ -239,30 +240,30 @@ export default function OpportunityResources({
|
||||
setEditing(null);
|
||||
setPayload({});
|
||||
setPath([]);
|
||||
setGeometry("");
|
||||
setGeometry('');
|
||||
setFile(null);
|
||||
setKey(crypto.randomUUID());
|
||||
setConfirm(false);
|
||||
router.reload({
|
||||
onFinish: () =>
|
||||
document.getElementById("resource-result")?.focus(),
|
||||
document.getElementById('resource-result')?.focus(),
|
||||
});
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Falha de ligação; preenchimento preservado.",
|
||||
: 'Falha de ligação; preenchimento preservado.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
setTimeout(
|
||||
() => document.getElementById("resource-result")?.focus(),
|
||||
() => document.getElementById('resource-result')?.focus(),
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
const unavailable =
|
||||
!!opportunity.deleted_at || opportunity.status === "archived";
|
||||
!!opportunity.deleted_at || opportunity.status === 'archived';
|
||||
return (
|
||||
<Management title="Imagens, documentos e localizações">
|
||||
<Link href={`/management/opportunities/${opportunity.id}/edit`}>
|
||||
@@ -280,11 +281,29 @@ export default function OpportunityResources({
|
||||
className="rounded border p-3"
|
||||
>
|
||||
{message ||
|
||||
"Guardar é independente de validar, submeter e publicar."}
|
||||
'Guardar é independente de validar, submeter e publicar.'}
|
||||
{errors.etag && <p>{errors.etag}</p>}
|
||||
</div>
|
||||
{kind === 'images' && !imageProcessingAvailable && <p role="status" className="rounded border border-amber-500 p-3">Processamento de imagens indisponível: GD/WebP não está carregado no servidor. Pode guardar o original e os metadados; miniaturas e imagens para divulgação ficam pendentes.</p>}
|
||||
{kind !== 'locations' && <p className="rounded border p-3">Pode guardar anexos para preparação. Cada ficheiro permanece sem download ou pré-visualização enquanto o seu scan não estiver concluído. ClamD pendente não impede guardar metadados, locais ou rascunhos; testes com scanner simulado não verificam os seus ficheiros.</p>}
|
||||
{kind === 'images' && !imageProcessingAvailable && (
|
||||
<p
|
||||
role="status"
|
||||
className="rounded border border-amber-500 p-3"
|
||||
>
|
||||
Processamento de imagens indisponível: GD/WebP não está
|
||||
carregado no servidor. Pode guardar o original e os
|
||||
metadados; miniaturas e imagens para divulgação ficam
|
||||
pendentes.
|
||||
</p>
|
||||
)}
|
||||
{kind !== 'locations' && (
|
||||
<p className="rounded border p-3">
|
||||
Pode guardar anexos para preparação. Cada ficheiro permanece
|
||||
sem download ou pré-visualização enquanto o seu scan não
|
||||
estiver concluído. ClamD pendente não impede guardar
|
||||
metadados, locais ou rascunhos; testes com scanner simulado
|
||||
não verificam os seus ficheiros.
|
||||
</p>
|
||||
)}
|
||||
<section>
|
||||
<h2>Conferência e pendências</h2>
|
||||
<ul>
|
||||
@@ -304,18 +323,18 @@ export default function OpportunityResources({
|
||||
</section>
|
||||
)}
|
||||
<nav className="flex flex-wrap gap-3">
|
||||
{(["locations", "images", "documents"] as Kind[]).map((k) => (
|
||||
{(['locations', 'images', 'documents'] as Kind[]).map((k) => (
|
||||
<button
|
||||
className={button}
|
||||
key={k}
|
||||
disabled={busy}
|
||||
onClick={() => select(k)}
|
||||
>
|
||||
{k === "locations"
|
||||
? "Localizações"
|
||||
: k === "images"
|
||||
? "Imagens"
|
||||
: "Documentos"}
|
||||
{k === 'locations'
|
||||
? 'Localizações'
|
||||
: k === 'images'
|
||||
? 'Imagens'
|
||||
: 'Documentos'}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
@@ -326,21 +345,21 @@ export default function OpportunityResources({
|
||||
{String(
|
||||
r.payload.title ??
|
||||
r.file?.file_name ??
|
||||
"Recurso incompleto",
|
||||
)}{" "}
|
||||
· v{r.version} ·{" "}
|
||||
'Recurso incompleto',
|
||||
)}{' '}
|
||||
· v{r.version} ·{' '}
|
||||
{r.deleted_at
|
||||
? "eliminado logicamente"
|
||||
: "rascunho"}
|
||||
? 'eliminado logicamente'
|
||||
: 'rascunho'}
|
||||
</p>
|
||||
{r.file && (
|
||||
<p className="break-all">
|
||||
Scan: {r.file.malware_scan_status} · motor:{" "}
|
||||
{r.file.malware_engine ?? "não executado"} ·
|
||||
Scan: {r.file.malware_scan_status} · motor:{' '}
|
||||
{r.file.malware_engine ?? 'não executado'} ·
|
||||
hash: {r.file.sha256}
|
||||
</p>
|
||||
)}
|
||||
{kind === "images" &&
|
||||
{kind === 'images' &&
|
||||
!r.deleted_at &&
|
||||
!!r.derivativePreviews?.length && (
|
||||
<img
|
||||
@@ -348,14 +367,14 @@ export default function OpportunityResources({
|
||||
src={r.derivativePreviews[0].url}
|
||||
srcSet={r.derivativePreviews
|
||||
.map((p) => `${p.url} ${p.width}w`)
|
||||
.join(", ")}
|
||||
.join(', ')}
|
||||
alt={String(
|
||||
r.payload.alt_text ??
|
||||
"Pré-visualização interna pendente de descrição",
|
||||
'Pré-visualização interna pendente de descrição',
|
||||
)}
|
||||
onError={() =>
|
||||
setMessage(
|
||||
"Pré-visualização indisponível ou endereço expirado; recarregue. Dados preservados.",
|
||||
'Pré-visualização indisponível ou endereço expirado; recarregue. Dados preservados.',
|
||||
)
|
||||
}
|
||||
/>
|
||||
@@ -366,7 +385,7 @@ export default function OpportunityResources({
|
||||
>
|
||||
Ver / editar / restaurar
|
||||
</button>
|
||||
{r.file?.malware_scan_status === "clean" &&
|
||||
{r.file?.malware_scan_status === 'clean' &&
|
||||
!r.deleted_at && (
|
||||
<a
|
||||
href={`/management/opportunities/${opportunity.id}/resources/${kind}/${r.id}/download`}
|
||||
@@ -380,22 +399,26 @@ export default function OpportunityResources({
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void execute("save");
|
||||
void execute('save');
|
||||
}}
|
||||
className="space-y-3"
|
||||
>
|
||||
<h2>
|
||||
{editing
|
||||
? "Editar recurso / nova versão"
|
||||
: "Novo recurso incompleto"}
|
||||
? 'Editar recurso / nova versão'
|
||||
: 'Novo recurso incompleto'}
|
||||
</h2>
|
||||
{kind === "locations" && (
|
||||
{kind === 'locations' && (
|
||||
<div>
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
/>
|
||||
{[0, 1, 2, 3].map((index) => (
|
||||
<TerritoryLevel
|
||||
key={index}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ""}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
onChange={(value) =>
|
||||
setPath((previous) =>
|
||||
@@ -410,10 +433,10 @@ export default function OpportunityResources({
|
||||
fieldError={
|
||||
errors[
|
||||
[
|
||||
"province_id",
|
||||
"district_id",
|
||||
"admin_post_id",
|
||||
"locality_id",
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
][index]
|
||||
]
|
||||
}
|
||||
@@ -421,7 +444,7 @@ export default function OpportunityResources({
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{kind !== "locations" && (
|
||||
{kind !== 'locations' && (
|
||||
<Field
|
||||
label="Original / substituir por nova versão"
|
||||
error={errors.file}
|
||||
@@ -431,9 +454,9 @@ export default function OpportunityResources({
|
||||
aria-label="Original / substituir por nova versão"
|
||||
type="file"
|
||||
accept={
|
||||
kind === "images"
|
||||
? ".jpg,.jpeg,.png,.webp"
|
||||
: ".pdf,.docx,.xlsx,.png,.jpg,.jpeg"
|
||||
kind === 'images'
|
||||
? '.jpg,.jpeg,.png,.webp'
|
||||
: '.pdf,.docx,.xlsx,.png,.jpg,.jpeg'
|
||||
}
|
||||
onChange={(event) =>
|
||||
setFile(event.target.files?.[0] ?? null)
|
||||
@@ -454,13 +477,13 @@ export default function OpportunityResources({
|
||||
<input
|
||||
aria-label={labels[name]}
|
||||
className={control}
|
||||
value={String(payload[name] ?? "")}
|
||||
value={String(payload[name] ?? '')}
|
||||
type={
|
||||
name.includes("date") ||
|
||||
name.endsWith("_at") ||
|
||||
name.endsWith("_until")
|
||||
? "date"
|
||||
: "text"
|
||||
name.includes('date') ||
|
||||
name.endsWith('_at') ||
|
||||
name.endsWith('_until')
|
||||
? 'date'
|
||||
: 'text'
|
||||
}
|
||||
onChange={(event) =>
|
||||
set(name, event.target.value || null)
|
||||
@@ -468,19 +491,19 @@ export default function OpportunityResources({
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
{(kind === "locations"
|
||||
? ["role", "territorial_purpose"]
|
||||
: kind === "images"
|
||||
? ["imageRole", "rights_status", "visibility"]
|
||||
: ["classification", "visibility"]
|
||||
{(kind === 'locations'
|
||||
? ['role', 'territorial_purpose']
|
||||
: kind === 'images'
|
||||
? ['imageRole', 'rights_status', 'visibility']
|
||||
: ['classification', 'visibility']
|
||||
).map((name) => (
|
||||
<Field
|
||||
key={name}
|
||||
label={labels[name] ?? name}
|
||||
error={
|
||||
errors[name === "imageRole" ? "role" : name] ??
|
||||
errors[name === 'imageRole' ? 'role' : name] ??
|
||||
errors[
|
||||
`payload.${name === "imageRole" ? "role" : name}`
|
||||
`payload.${name === 'imageRole' ? 'role' : name}`
|
||||
]
|
||||
}
|
||||
>
|
||||
@@ -488,12 +511,12 @@ export default function OpportunityResources({
|
||||
className={control}
|
||||
aria-label={labels[name] ?? name}
|
||||
value={String(
|
||||
payload[name === "imageRole" ? "role" : name] ??
|
||||
"",
|
||||
payload[name === 'imageRole' ? 'role' : name] ??
|
||||
'',
|
||||
)}
|
||||
onChange={(event) =>
|
||||
set(
|
||||
name === "imageRole" ? "role" : name,
|
||||
name === 'imageRole' ? 'role' : name,
|
||||
event.target.value || null,
|
||||
)
|
||||
}
|
||||
@@ -505,7 +528,7 @@ export default function OpportunityResources({
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
{kind === "locations" && (
|
||||
{kind === 'locations' && (
|
||||
<Field
|
||||
label="GeoJSON documentado (opcional)"
|
||||
error={errors.geometry}
|
||||
@@ -523,8 +546,8 @@ export default function OpportunityResources({
|
||||
</p>
|
||||
</Field>
|
||||
)}
|
||||
{kind === "images" &&
|
||||
(["location_id", "rights_document_id"] as const).map(
|
||||
{kind === 'images' &&
|
||||
(['location_id', 'rights_document_id'] as const).map(
|
||||
(name) => (
|
||||
<Field
|
||||
key={name}
|
||||
@@ -535,16 +558,16 @@ export default function OpportunityResources({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(payload[name] ?? "")}
|
||||
value={String(payload[name] ?? '')}
|
||||
onChange={(event) =>
|
||||
set(name, event.target.value || null)
|
||||
}
|
||||
>
|
||||
<option value="">Pendente</option>
|
||||
{resources[
|
||||
name === "location_id"
|
||||
? "locations"
|
||||
: "documents"
|
||||
name === 'location_id'
|
||||
? 'locations'
|
||||
: 'documents'
|
||||
]
|
||||
.filter((r) => !r.deleted_at)
|
||||
.map((r) => (
|
||||
@@ -560,30 +583,30 @@ export default function OpportunityResources({
|
||||
</Field>
|
||||
),
|
||||
)}
|
||||
{kind !== "documents" && (
|
||||
{kind !== 'documents' && (
|
||||
<label>
|
||||
<input
|
||||
key={key}
|
||||
type="checkbox"
|
||||
checked={
|
||||
!!payload[
|
||||
kind === "images"
|
||||
? "is_cover"
|
||||
: "is_primary"
|
||||
kind === 'images'
|
||||
? 'is_cover'
|
||||
: 'is_primary'
|
||||
]
|
||||
}
|
||||
onChange={(event) =>
|
||||
set(
|
||||
kind === "images"
|
||||
? "is_cover"
|
||||
: "is_primary",
|
||||
kind === 'images'
|
||||
? 'is_cover'
|
||||
: 'is_primary',
|
||||
event.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
{kind === "images"
|
||||
? "Selecionar capa de preparação"
|
||||
: "Localização principal"}
|
||||
{kind === 'images'
|
||||
? 'Selecionar capa de preparação'
|
||||
: 'Localização principal'}
|
||||
</label>
|
||||
)}
|
||||
<Field
|
||||
@@ -610,12 +633,14 @@ export default function OpportunityResources({
|
||||
</label>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{kind === "images" && editing && !editing.deleted_at && (
|
||||
{kind === 'images' && editing && !editing.deleted_at && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || unavailable || !imageProcessingAvailable}
|
||||
onClick={() => void execute("prepare")}
|
||||
disabled={
|
||||
busy || unavailable || !imageProcessingAvailable
|
||||
}
|
||||
onClick={() => void execute('prepare')}
|
||||
>
|
||||
Preparar WebP e miniaturas
|
||||
</button>
|
||||
@@ -633,13 +658,13 @@ export default function OpportunityResources({
|
||||
disabled={busy || unavailable}
|
||||
onClick={() =>
|
||||
void execute(
|
||||
editing.deleted_at ? "restore" : "delete",
|
||||
editing.deleted_at ? 'restore' : 'delete',
|
||||
)
|
||||
}
|
||||
>
|
||||
{editing.deleted_at
|
||||
? "Restaurar recurso"
|
||||
: "Excluir recurso logicamente"}
|
||||
? 'Restaurar recurso'
|
||||
: 'Excluir recurso logicamente'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -60,7 +60,9 @@ export function Management({
|
||||
>
|
||||
<Link href="/management/interests">Pedidos de interesse</Link>
|
||||
<Link href="/management/sectors">Sectores</Link>
|
||||
<Link href="/management/opportunities">Gestão de Oportunidades</Link>
|
||||
<Link href="/management/opportunities">
|
||||
Gestão de Oportunidades
|
||||
</Link>
|
||||
<Link href="/management/opportunity-origin">
|
||||
Revisão da origem das oportunidades
|
||||
</Link>
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import { router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Management, Field, control, button } from "./shared";
|
||||
|
||||
type Plan = {
|
||||
level: number;
|
||||
expected: number;
|
||||
resolved: number;
|
||||
pending: number;
|
||||
hash: string;
|
||||
scan_ready: boolean;
|
||||
source_sha256: string;
|
||||
rows: {
|
||||
external_id: string;
|
||||
name: string;
|
||||
parent_name: string | null;
|
||||
location_id: string | null;
|
||||
status: string;
|
||||
}[];
|
||||
};
|
||||
export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
const [reason, setReason] = useState("");
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [batch, setBatch] = useState("");
|
||||
const [applyKey, setApplyKey] = useState(() => crypto.randomUUID());
|
||||
const [reverseKey, setReverseKey] = useState(() => crypto.randomUUID());
|
||||
const execute = async (reverse: boolean) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const cookie = document.cookie
|
||||
.split("; ")
|
||||
.find((v) => v.startsWith("XSRF-TOKEN="))
|
||||
?.slice(11);
|
||||
const response = await fetch(
|
||||
`/management/territory-geometry-import${reverse ? `/${batch}/reverse` : ""}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"X-XSRF-TOKEN": decodeURIComponent(cookie ?? ""),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
level: plan.level,
|
||||
hash: plan.hash,
|
||||
reason,
|
||||
confirm: confirmed,
|
||||
idempotency_key: reverse ? reverseKey : applyKey,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const result = await response.json();
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
result.message ??
|
||||
"Operação recusada. Reveja o plano e a autenticação.",
|
||||
);
|
||||
if (!reverse) setBatch(result.batch_id);
|
||||
setMessage(
|
||||
reverse
|
||||
? `Revertidas ${result.reversed}; preservadas ${result.reused_preserved} geometrias reutilizadas.`
|
||||
: `Criadas ${result.inserted}; reutilizadas ${result.reused}; pendentes ${result.pending}. Lote ${result.batch_id}. Nenhuma camada publicada.`,
|
||||
);
|
||||
} catch (e) {
|
||||
setMessage(e instanceof Error ? e.message : "Erro de ligação.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Management title="Importação cartográfica">
|
||||
<p>
|
||||
Exemplar INE de 07/06/2019 aceite. Correspondência exata de nome
|
||||
e pai; sem alterações de classificações territoriais,
|
||||
disponibilidade fundiária ou cálculos.
|
||||
</p>
|
||||
<Field label="Nível">
|
||||
<select
|
||||
className={control}
|
||||
value={plan.level}
|
||||
onChange={(e) => {
|
||||
setBatch("");
|
||||
setMessage("");
|
||||
setConfirmed(false);
|
||||
setApplyKey(crypto.randomUUID());
|
||||
setReverseKey(crypto.randomUUID());
|
||||
router.get("/management/territory-geometry-import", {
|
||||
level: Number(e.target.value),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value={1}>Províncias</option>
|
||||
<option value={2}>Distritos</option>
|
||||
<option value={3}>Postos administrativos</option>
|
||||
</select>
|
||||
</Field>
|
||||
<p>
|
||||
Esperado: {plan.expected}; resolvido: {plan.resolved}; pendente:{" "}
|
||||
{plan.pending}. Scan:{" "}
|
||||
{plan.scan_ready ? "limpo e atual" : "pendente ou inconclusivo"}
|
||||
.
|
||||
</p>
|
||||
<p className="break-all">
|
||||
SHA-256 do original: {plan.source_sha256}
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Identificador</th>
|
||||
<th>Nome</th>
|
||||
<th>Pai</th>
|
||||
<th>Correspondência</th>
|
||||
<th>Ação prevista</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{plan.rows.map((r) => (
|
||||
<tr key={r.external_id}>
|
||||
<td>{r.external_id}</td>
|
||||
<td>{r.name}</td>
|
||||
<td>{r.parent_name ?? "—"}</td>
|
||||
<td>{r.location_id ?? "Pendente"}</td>
|
||||
<td>{r.status}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Field label="Fundamento da aplicação ou reversão">
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{" "}
|
||||
Confirmei as correspondências. A aplicação mantém geometrias
|
||||
privadas e publicação separada.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy || !confirmed || reason.length < 20 || !plan.scan_ready
|
||||
}
|
||||
onClick={() => execute(false)}
|
||||
>
|
||||
Aplicar correspondências
|
||||
</button>
|
||||
<Field label="Lote a reverter">
|
||||
<input
|
||||
className={control}
|
||||
value={batch}
|
||||
onChange={(e) => {
|
||||
setBatch(e.target.value);
|
||||
setReverseKey(crypto.randomUUID());
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || !confirmed || reason.length < 20 || !batch}
|
||||
onClick={() => execute(true)}
|
||||
>
|
||||
Reverter apenas geometrias criadas pelo lote
|
||||
</button>
|
||||
<p role="status">{message}</p>
|
||||
<p>
|
||||
A reversão preserva originais, histórico e geometrias
|
||||
reutilizadas; recusa alterações ou relações posteriores.
|
||||
Publicação não é realizada nesta página.
|
||||
</p>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import TerritoryGeometryPreview from "@/components/territory-geometry-preview";
|
||||
import InteractiveInvestmentMap, {
|
||||
type InvestmentMapFeature,
|
||||
} from '@/components/interactive-investment-map';
|
||||
} from "@/components/interactive-investment-map";
|
||||
import {
|
||||
Frame,
|
||||
Field,
|
||||
@@ -10,10 +11,10 @@ import {
|
||||
button,
|
||||
type Catalogues,
|
||||
type Partnership,
|
||||
} from './shared';
|
||||
} from "./shared";
|
||||
type Result = Pick<
|
||||
Partnership,
|
||||
'id' | 'title' | 'kind' | 'partnership_type' | 'deadline'
|
||||
"id" | "title" | "kind" | "partnership_type" | "deadline"
|
||||
> & { summary: string | null; province: string; sector: string };
|
||||
export default function Catalogue(
|
||||
p: Catalogues & {
|
||||
@@ -41,22 +42,22 @@ export default function Catalogue(
|
||||
className="grid gap-4 rounded border p-5 md:grid-cols-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
router.get('/parcerias', filters);
|
||||
router.get("/parcerias", filters);
|
||||
}}
|
||||
>
|
||||
<Field label="Pesquisar">
|
||||
<input
|
||||
className={control}
|
||||
value={filters.q ?? ''}
|
||||
onChange={(e) => set('q', e.target.value)}
|
||||
value={filters.q ?? ""}
|
||||
onChange={(e) => set("q", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Tipo de parceria">
|
||||
<select
|
||||
className={control}
|
||||
value={filters.partnership_type ?? ''}
|
||||
value={filters.partnership_type ?? ""}
|
||||
onChange={(e) =>
|
||||
set('partnership_type', e.target.value)
|
||||
set("partnership_type", e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
@@ -70,8 +71,8 @@ export default function Catalogue(
|
||||
<Field label="Oferta ou procura">
|
||||
<select
|
||||
className={control}
|
||||
value={filters.kind ?? ''}
|
||||
onChange={(e) => set('kind', e.target.value)}
|
||||
value={filters.kind ?? ""}
|
||||
onChange={(e) => set("kind", e.target.value)}
|
||||
>
|
||||
<option value="">Ambas</option>
|
||||
<option value="offering">Oferta</option>
|
||||
@@ -81,8 +82,8 @@ export default function Catalogue(
|
||||
<Field label="Setor">
|
||||
<select
|
||||
className={control}
|
||||
value={filters.sector_id ?? ''}
|
||||
onChange={(e) => set('sector_id', e.target.value)}
|
||||
value={filters.sector_id ?? ""}
|
||||
onChange={(e) => set("sector_id", e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.sectors.map((x) => (
|
||||
@@ -95,8 +96,8 @@ export default function Catalogue(
|
||||
<Field label="Território">
|
||||
<select
|
||||
className={control}
|
||||
value={filters.territory_id ?? ''}
|
||||
onChange={(e) => set('territory_id', e.target.value)}
|
||||
value={filters.territory_id ?? ""}
|
||||
onChange={(e) => set("territory_id", e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.territories.map((x) => (
|
||||
@@ -118,24 +119,24 @@ export default function Catalogue(
|
||||
className="space-y-3 rounded border p-5"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link href={'/parcerias/' + item.id}>
|
||||
<Link href={"/parcerias/" + item.id}>
|
||||
{item.title}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{item.partnership_type
|
||||
? p.types[item.partnership_type]
|
||||
: 'Tipo por completar'}{' '}
|
||||
· {item.kind === 'offering' ? 'Oferta' : 'Procura'}
|
||||
: "Tipo por completar"}{" "}
|
||||
· {item.kind === "offering" ? "Oferta" : "Procura"}
|
||||
</p>
|
||||
<p>{item.summary}</p>
|
||||
<p>
|
||||
{item.sector || 'Setor por completar'} ·{' '}
|
||||
{item.province || 'Território na ficha'}
|
||||
{item.sector || "Setor por completar"} ·{" "}
|
||||
{item.province || "Território na ficha"}
|
||||
</p>
|
||||
{item.deadline && <p>Prazo: {item.deadline}</p>}
|
||||
<Link
|
||||
href={'/parcerias/' + item.id}
|
||||
href={"/parcerias/" + item.id}
|
||||
className="underline"
|
||||
>
|
||||
Consultar parceria
|
||||
@@ -159,6 +160,9 @@ export default function Catalogue(
|
||||
implantação da parceria.
|
||||
</p>
|
||||
<InteractiveInvestmentMap points={p.mapPoints} />
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={p.filters.territory_id}
|
||||
/>
|
||||
{!p.mapPoints.length && (
|
||||
<p>
|
||||
Sem coordenadas documentadas nos resultados. As fichas e
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ProvinceSelect } from '@/components/investment-territory';
|
||||
import { SimulationForm } from '@/components/simulation-form';
|
||||
import { InvestmentRoadmap } from '@/components/investment-roadmap';
|
||||
import { JourneyDocumentResources } from '@/components/journey-document-resources';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
|
||||
const input =
|
||||
'box-border w-full min-w-0 max-w-full rounded-lg border border-slate-300 bg-white p-3 text-slate-900';
|
||||
@@ -96,6 +97,7 @@ type Page<T> = {
|
||||
total: number;
|
||||
};
|
||||
type Props = {
|
||||
countries?: Country[];
|
||||
section: string;
|
||||
filters?: Record<string, string | string[]>;
|
||||
sectors?: {
|
||||
@@ -186,12 +188,15 @@ function RequestForm({
|
||||
const { auth } = usePage<{
|
||||
auth: { user: { name: string; email: string } | null };
|
||||
}>().props;
|
||||
const countries =
|
||||
usePage<{ countries?: Country[] }>().props.countries ?? [];
|
||||
const form = useForm({
|
||||
kind,
|
||||
fullName: auth.user?.name ?? '',
|
||||
email: auth.user?.email ?? '',
|
||||
phone: '',
|
||||
country: 'Moçambique',
|
||||
country: '',
|
||||
declared_origin_country_code: '',
|
||||
company: '',
|
||||
sectorInterest: '',
|
||||
message: '',
|
||||
@@ -256,19 +261,45 @@ function RequestForm({
|
||||
return (
|
||||
<label key={field} className="block space-y-1">
|
||||
<span>{labels[field]}</span>
|
||||
<input
|
||||
className={input}
|
||||
type={field === 'email' ? 'email' : 'text'}
|
||||
required={field !== 'phone'}
|
||||
maxLength={field === 'phone' ? 30 : 150}
|
||||
value={form.data[field]}
|
||||
onChange={(e) =>
|
||||
form.setData(field, e.target.value)
|
||||
}
|
||||
/>
|
||||
{field === 'country' ? (
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.data.country}
|
||||
onChange={(value) =>
|
||||
form.setData('country', value)
|
||||
}
|
||||
required
|
||||
allowLegacyValue
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={input}
|
||||
type={field === 'email' ? 'email' : 'text'}
|
||||
required={field !== 'phone'}
|
||||
maxLength={field === 'phone' ? 30 : 150}
|
||||
value={form.data[field]}
|
||||
onChange={(e) =>
|
||||
form.setData(field, e.target.value)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
<label className="block">
|
||||
País de origem declarado desta solicitação
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.data.declared_origin_country_code}
|
||||
onChange={(value) =>
|
||||
form.setData('declared_origin_country_code', value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
Origem opcional e independente do país acima. Sem declaração,
|
||||
permanece não informado nas estatísticas.
|
||||
</p>
|
||||
<label className="block">
|
||||
Descreva o pedido
|
||||
<textarea
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Layout, Field, control, button } from './shared';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
type Journey = {
|
||||
id: string;
|
||||
dossier_id: string | null;
|
||||
@@ -7,11 +8,20 @@ type Journey = {
|
||||
status: string;
|
||||
reference: string | null;
|
||||
request_status: string | null;
|
||||
country: string | null;
|
||||
declared_origin: { code: string | null; name: string };
|
||||
};
|
||||
function JourneyCard({ journey }: { journey: Journey }) {
|
||||
function JourneyCard({
|
||||
journey,
|
||||
countries,
|
||||
}: {
|
||||
journey: Journey;
|
||||
countries: Country[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
message: '',
|
||||
country: 'Moçambique',
|
||||
country: '',
|
||||
declared_origin_country_code: '',
|
||||
role: 'investir',
|
||||
horizon: '',
|
||||
privacy_consent: false,
|
||||
@@ -30,7 +40,6 @@ function JourneyCard({ journey }: { journey: Journey }) {
|
||||
journey.title
|
||||
)}
|
||||
</h2>
|
||||
<p className="text-sm break-all">Jornada: {journey.id}</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/painel?journey_id=${journey.id}`}
|
||||
@@ -42,6 +51,13 @@ function JourneyCard({ journey }: { journey: Journey }) {
|
||||
<p>
|
||||
Protocolo: <strong>{journey.reference}</strong>
|
||||
</p>
|
||||
<p>
|
||||
País declarado: {journey.country ?? 'Não informado'} ·
|
||||
Origem da solicitação: {journey.declared_origin.name}
|
||||
{journey.declared_origin.code
|
||||
? ` (${journey.declared_origin.code})`
|
||||
: ''}
|
||||
</p>
|
||||
<p>
|
||||
Estado:{' '}
|
||||
{(
|
||||
@@ -71,15 +87,29 @@ function JourneyCard({ journey }: { journey: Journey }) {
|
||||
Indique o objectivo para orientar o atendimento.
|
||||
</p>
|
||||
<Field label="País">
|
||||
<input
|
||||
className={control}
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.data.country}
|
||||
onChange={(e) =>
|
||||
form.setData('country', e.target.value)
|
||||
}
|
||||
onChange={(value) => form.setData('country', value)}
|
||||
required
|
||||
allowLegacyValue
|
||||
/>
|
||||
</Field>
|
||||
<Field label="País de origem declarado desta solicitação">
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.data.declared_origin_country_code}
|
||||
onChange={(value) =>
|
||||
form.setData(
|
||||
'declared_origin_country_code',
|
||||
value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
<p className="text-sm">
|
||||
Origem opcional, independente do país acima.
|
||||
</p>
|
||||
</Field>
|
||||
<Field label="Papel pretendido">
|
||||
<select
|
||||
className={control}
|
||||
@@ -154,7 +184,13 @@ function JourneyCard({ journey }: { journey: Journey }) {
|
||||
</article>
|
||||
);
|
||||
}
|
||||
export default function Workspace({ journeys }: { journeys: Journey[] }) {
|
||||
export default function Workspace({
|
||||
journeys,
|
||||
countries,
|
||||
}: {
|
||||
journeys: Journey[];
|
||||
countries: Country[];
|
||||
}) {
|
||||
return (
|
||||
<Layout title="O meu painel de investimento">
|
||||
<p>
|
||||
@@ -166,7 +202,7 @@ export default function Workspace({ journeys }: { journeys: Journey[] }) {
|
||||
</Link>
|
||||
<div className="space-y-5">
|
||||
{journeys.map((j) => (
|
||||
<JourneyCard key={j.id} journey={j} />
|
||||
<JourneyCard key={j.id} journey={j} countries={countries} />
|
||||
))}
|
||||
</div>
|
||||
{!journeys.length && (
|
||||
|
||||
Reference in New Issue
Block a user