@@ -62,7 +62,12 @@ export function AppSidebar() {
|
||||
});
|
||||
}
|
||||
}
|
||||
items.push(...profileLinks(profileAccess).map(link => ({...link, icon: LayoutGrid})));
|
||||
items.push(
|
||||
...profileLinks(profileAccess).map((link) => ({
|
||||
...link,
|
||||
icon: LayoutGrid,
|
||||
})),
|
||||
);
|
||||
return (
|
||||
<Sidebar collapsible="icon" variant="inset">
|
||||
<SidebarHeader>
|
||||
|
||||
@@ -11,6 +11,7 @@ export default function CountrySelect({
|
||||
label = 'País',
|
||||
required = false,
|
||||
allowLegacyValue = false,
|
||||
error,
|
||||
}: {
|
||||
countries: Country[];
|
||||
value: string;
|
||||
@@ -20,6 +21,7 @@ export default function CountrySelect({
|
||||
label?: string;
|
||||
required?: boolean;
|
||||
allowLegacyValue?: boolean;
|
||||
error?: string;
|
||||
}) {
|
||||
const generatedId = useId();
|
||||
const [search, setSearch] = useState('');
|
||||
@@ -52,6 +54,10 @@ export default function CountrySelect({
|
||||
disabled={disabled}
|
||||
id={id ?? generatedId}
|
||||
aria-label={label}
|
||||
aria-invalid={!!error}
|
||||
aria-describedby={
|
||||
error ? (id ?? generatedId) + '-error' : undefined
|
||||
}
|
||||
required={required}
|
||||
className="w-full rounded border p-2"
|
||||
value={value}
|
||||
@@ -71,6 +77,15 @@ export default function CountrySelect({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{error && (
|
||||
<p
|
||||
id={(id ?? generatedId) + '-error'}
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{matches.length === 0 && (
|
||||
<p role="status">Nenhum país corresponde à pesquisa.</p>
|
||||
)}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { card, input, button } from '@/pages/investment/shared';
|
||||
|
||||
@@ -197,7 +198,7 @@ export function RequestOperations({
|
||||
occurred_at: '',
|
||||
summary: '',
|
||||
evidence: '',
|
||||
client_key: crypto.randomUUID(),
|
||||
client_key: createOperationKey(),
|
||||
});
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
@@ -433,7 +434,7 @@ export function RequestOperations({
|
||||
communication.reset('summary', 'evidence');
|
||||
communication.setData(
|
||||
'client_key',
|
||||
crypto.randomUUID(),
|
||||
createOperationKey(),
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -194,7 +194,7 @@ export default function InteractiveInvestmentMap({
|
||||
{error && <p role="status">{error}</p>}
|
||||
<div
|
||||
ref={element}
|
||||
className="relative z-0 h-[460px] w-full rounded"
|
||||
className="relative z-0 h-[460px] w-full min-w-0 overflow-hidden rounded"
|
||||
role="region"
|
||||
aria-label="Mapa; navegação por setas e teclas mais e menos"
|
||||
/>
|
||||
@@ -256,10 +256,11 @@ export default function InteractiveInvestmentMap({
|
||||
<a className="underline" href={area.url}>
|
||||
{area.title}
|
||||
</a>{' '}
|
||||
· {area.purpose === 'administrative_boundary'
|
||||
·{' '}
|
||||
{area.purpose === 'administrative_boundary'
|
||||
? 'Limite administrativo da edição indicada; não representa um local de investimento'
|
||||
: 'Polígono cadastrado; comparação com limite administrativo pendente'} ·
|
||||
Fonte: {area.source_reference ?? 'Não indicada'} · Data:{' '}
|
||||
: 'Polígono cadastrado; comparação com limite administrativo pendente'}{' '}
|
||||
· Fonte: {area.source_reference ?? 'Não indicada'} · Data:{' '}
|
||||
{area.source_date ?? 'Não documentada'}
|
||||
</p>
|
||||
))}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import TerritoryGeometryPreview from "./territory-geometry-preview";
|
||||
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,
|
||||
@@ -17,7 +17,7 @@ export default function InvestmentMapPanel({
|
||||
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();
|
||||
@@ -26,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) => {
|
||||
@@ -39,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) => {
|
||||
@@ -61,7 +61,7 @@ export default function InvestmentMapPanel({
|
||||
filters.district_id ||
|
||||
filters.province_id ||
|
||||
filters.geo_location_id ||
|
||||
"",
|
||||
'',
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -40,7 +40,10 @@ export function ProvinceSelect({
|
||||
const [error, setError] = useState('');
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [search, setSearch] = useState('');
|
||||
const [geometrySelection, setGeometrySelection] = useState<{ value: string; id: string } | null>(null);
|
||||
const [geometrySelection, setGeometrySelection] = useState<{
|
||||
value: string;
|
||||
id: string;
|
||||
} | null>(null);
|
||||
const [geometryFeedback, setGeometryFeedback] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
@@ -49,19 +52,38 @@ export function ProvinceSelect({
|
||||
setGeometryFeedback('');
|
||||
if (!value) return;
|
||||
// Preserve historical text. Only one exact catalogue match supplies a map ID.
|
||||
void fetch(`${endpoint}?${new URLSearchParams({ type: 'province', page: '1', q: value })}`, {
|
||||
signal: controller.signal, headers: { Accept: 'application/json' },
|
||||
}).then(async (response) => {
|
||||
if (!response.ok) throw new Error('Não foi possível consultar a correspondência cartográfica.');
|
||||
const data = await response.json();
|
||||
const matches = (data.data as Option[]).filter((option) => option.name === value);
|
||||
if (controller.signal.aborted) return;
|
||||
if (matches.length === 1 && !data.next_page_url)
|
||||
setGeometrySelection({ value, id: matches[0].id });
|
||||
else setGeometryFeedback('Seleção guardada preservada; sem correspondência cartográfica inequívoca neste cadastro.');
|
||||
}).catch((cause: unknown) => {
|
||||
if (!controller.signal.aborted) setGeometryFeedback(cause instanceof Error ? cause.message : 'Erro de ligação.');
|
||||
});
|
||||
void fetch(
|
||||
`${endpoint}?${new URLSearchParams({ type: 'province', page: '1', q: value })}`,
|
||||
{
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
)
|
||||
.then(async (response) => {
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
'Não foi possível consultar a correspondência cartográfica.',
|
||||
);
|
||||
const data = await response.json();
|
||||
const matches = (data.data as Option[]).filter(
|
||||
(option) => option.name === value,
|
||||
);
|
||||
if (controller.signal.aborted) return;
|
||||
if (matches.length === 1 && !data.next_page_url)
|
||||
setGeometrySelection({ value, id: matches[0].id });
|
||||
else
|
||||
setGeometryFeedback(
|
||||
'Seleção guardada preservada; sem correspondência cartográfica inequívoca neste cadastro.',
|
||||
);
|
||||
})
|
||||
.catch((cause: unknown) => {
|
||||
if (!controller.signal.aborted)
|
||||
setGeometryFeedback(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Erro de ligação.',
|
||||
);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [endpoint, value, retry]);
|
||||
|
||||
@@ -153,9 +175,17 @@ export function ProvinceSelect({
|
||||
)}
|
||||
{geometryFeedback && <p role="status">{geometryFeedback}</p>}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={geometrySelection && geometrySelection.value === value ? geometrySelection.id : undefined}
|
||||
territoryId={
|
||||
geometrySelection && geometrySelection.value === value
|
||||
? geometrySelection.id
|
||||
: undefined
|
||||
}
|
||||
management={endpoint.startsWith('/management/')}
|
||||
endpoint={endpoint.startsWith('/minhas-oportunidades/') ? '/minhas-oportunidades/territory-geometries' : undefined}
|
||||
endpoint={
|
||||
endpoint.startsWith('/minhas-oportunidades/')
|
||||
? '/minhas-oportunidades/territory-geometries'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
@@ -211,7 +241,11 @@ export function TerritoryFields({
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management={endpoint.startsWith('/management/')}
|
||||
endpoint={endpoint.startsWith('/minhas-oportunidades/') ? '/minhas-oportunidades/territory-geometries' : undefined}
|
||||
endpoint={
|
||||
endpoint.startsWith('/minhas-oportunidades/')
|
||||
? '/minhas-oportunidades/territory-geometries'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,225 @@
|
||||
import { useState } from 'react';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
export default function OpportunityContactForm({
|
||||
id,
|
||||
etag,
|
||||
organization,
|
||||
investors,
|
||||
disabled,
|
||||
onSaved,
|
||||
}: {
|
||||
id: number;
|
||||
etag: string;
|
||||
organization: string | null;
|
||||
investors: { id: string; legal_name: string }[];
|
||||
disabled: boolean;
|
||||
onSaved: (contact: { id: string; full_name: string }) => void;
|
||||
}) {
|
||||
const [values, setValues] = useState({
|
||||
full_name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
investor_id: '',
|
||||
investor_type: '',
|
||||
});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [message, setMessage] = useState('');
|
||||
async function save() {
|
||||
if (busy || disabled) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage('');
|
||||
try {
|
||||
const xsrf = document.cookie
|
||||
.split('; ')
|
||||
.find((item) => item.startsWith('XSRF-TOKEN='));
|
||||
const response = await fetch(
|
||||
`/minhas-oportunidades/${id}/contacts`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': xsrf
|
||||
? decodeURIComponent(xsrf.slice(11))
|
||||
: '',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...values,
|
||||
investor_id: values.investor_id || null,
|
||||
investor_type: values.investor_type || null,
|
||||
etag,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const result = await response.json();
|
||||
setMessage(
|
||||
result.message ??
|
||||
'Não foi possível guardar o contacto. Os valores foram preservados.',
|
||||
);
|
||||
if (!response.ok) {
|
||||
setErrors(
|
||||
Object.fromEntries(
|
||||
Object.entries(result.errors ?? {}).map(
|
||||
([key, value]) => [
|
||||
key,
|
||||
Array.isArray(value)
|
||||
? value.join(' ')
|
||||
: String(value),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
onSaved(result.contact);
|
||||
} catch {
|
||||
setMessage(
|
||||
'Resposta indisponível. Recupere a oportunidade antes de repetir; os valores foram preservados.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
requestAnimationFrame(() =>
|
||||
document.getElementById('contact-result')?.focus(),
|
||||
);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<details className="rounded border p-3">
|
||||
<summary>Cadastrar contacto do promotor</summary>
|
||||
<p>
|
||||
Reutiliza o cadastro de contactos. Indique dados reais e
|
||||
autorizados do promotor desta oportunidade. O operador do portal
|
||||
não substitui o promotor real. A gravação não publica o
|
||||
contacto.
|
||||
</p>
|
||||
<fieldset disabled={disabled || busy} className="space-y-3">
|
||||
<legend>Dados do contacto</legend>
|
||||
{(['full_name', 'email', 'phone'] as const).map((field) => (
|
||||
<div key={field}>
|
||||
<label htmlFor={`contact-${field}`}>
|
||||
{
|
||||
{
|
||||
full_name: 'Nome completo',
|
||||
email: 'Email',
|
||||
phone: 'Telefone internacional (exemplo: +258…)',
|
||||
}[field]
|
||||
}
|
||||
</label>
|
||||
<input
|
||||
id={`contact-${field}`}
|
||||
className={control}
|
||||
type={
|
||||
field === 'email'
|
||||
? 'email'
|
||||
: field === 'phone'
|
||||
? 'tel'
|
||||
: 'text'
|
||||
}
|
||||
value={values[field]}
|
||||
onChange={(event) =>
|
||||
setValues({
|
||||
...values,
|
||||
[field]: event.target.value,
|
||||
})
|
||||
}
|
||||
aria-invalid={Boolean(errors[field])}
|
||||
aria-describedby={
|
||||
errors[field]
|
||||
? `contact-${field}-error`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{errors[field] && (
|
||||
<p id={`contact-${field}-error`} role="alert">
|
||||
{errors[field]}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{organization && investors.length > 1 && (
|
||||
<div>
|
||||
<label htmlFor="contact-investor_id">
|
||||
Cadastro mestre do promotor
|
||||
</label>
|
||||
<select
|
||||
id="contact-investor_id"
|
||||
className={control}
|
||||
value={values.investor_id}
|
||||
onChange={(event) =>
|
||||
setValues({
|
||||
...values,
|
||||
investor_id: event.target.value,
|
||||
})
|
||||
}
|
||||
aria-invalid={Boolean(errors.investor_id)}
|
||||
aria-describedby={
|
||||
errors.investor_id
|
||||
? 'contact-investor_id-error'
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<option value="">Por selecionar</option>
|
||||
{investors.map((investor) => (
|
||||
<option key={investor.id} value={investor.id}>
|
||||
{investor.legal_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.investor_id && (
|
||||
<p id="contact-investor_id-error" role="alert">
|
||||
{errors.investor_id}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{organization && investors.length === 0 && (
|
||||
<div>
|
||||
<label htmlFor="contact-investor_type">
|
||||
Classificação no cadastro do promotor
|
||||
</label>
|
||||
<select
|
||||
id="contact-investor_type"
|
||||
className={control}
|
||||
value={values.investor_type}
|
||||
onChange={(event) =>
|
||||
setValues({
|
||||
...values,
|
||||
investor_type: event.target.value,
|
||||
})
|
||||
}
|
||||
aria-invalid={Boolean(errors.investor_type)}
|
||||
aria-describedby="contact-investor-type-help"
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
<option value="domestic">Nacional</option>
|
||||
<option value="foreign">Estrangeiro</option>
|
||||
<option value="institutional">Institucional</option>
|
||||
<option value="individual">Individual</option>
|
||||
</select>
|
||||
<p id="contact-investor-type-help">
|
||||
A organização já cadastrada será ligada ao cadastro
|
||||
CRM existente, sem criar outra organização ou um
|
||||
pedido fictício.
|
||||
</p>
|
||||
{errors.investor_type && (
|
||||
<p role="alert">{errors.investor_type}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
onClick={() => void save()}
|
||||
>
|
||||
Guardar contacto e selecionar
|
||||
</button>
|
||||
</fieldset>
|
||||
<p id="contact-result" role="status" tabIndex={-1}>
|
||||
{message}
|
||||
</p>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import InteractiveInvestmentMap from "./interactive-investment-map";
|
||||
import { control } from "@/pages/management/shared";
|
||||
import type { MultiPolygon } from "geojson";
|
||||
import InteractiveInvestmentMap from './interactive-investment-map';
|
||||
import { control } from '@/pages/management/shared';
|
||||
import type { MultiPolygon } from 'geojson';
|
||||
|
||||
type Point = [number | null, number | null];
|
||||
export default function OpportunityParcelGeometry({
|
||||
@@ -11,13 +11,13 @@ export default function OpportunityParcelGeometry({
|
||||
onChange: (v: unknown) => void;
|
||||
}) {
|
||||
const data =
|
||||
value && typeof value === "object"
|
||||
value && typeof value === 'object'
|
||||
? (value as { coordinates?: Point[][][] })
|
||||
: {};
|
||||
const polygons = Array.isArray(data.coordinates) ? data.coordinates : [];
|
||||
function replace(p: number, r: number, points: Point[]) {
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons.map((poly, i) =>
|
||||
i === p
|
||||
? poly.map((ring, j) => (j === r ? points : ring))
|
||||
@@ -38,7 +38,7 @@ export default function OpportunityParcelGeometry({
|
||||
point.length === 2 &&
|
||||
point.every(
|
||||
(c) =>
|
||||
typeof c === "number" &&
|
||||
typeof c === 'number' &&
|
||||
Number.isFinite(c),
|
||||
),
|
||||
) &&
|
||||
@@ -57,25 +57,25 @@ export default function OpportunityParcelGeometry({
|
||||
<legend>Polígono {p + 1}</legend>
|
||||
{poly.map((ring, r) => (
|
||||
<section key={r}>
|
||||
<h4>
|
||||
<p className="font-medium">
|
||||
{r === 0
|
||||
? "Anel exterior"
|
||||
? 'Anel exterior'
|
||||
: `Anel interior ${r}`}
|
||||
</h4>
|
||||
</p>
|
||||
{ring.map((point, i) => (
|
||||
<div key={i} className="flex flex-wrap gap-2">
|
||||
{[0, 1].map((axis) => (
|
||||
<label key={axis}>
|
||||
{axis === 0
|
||||
? "Longitude"
|
||||
: "Latitude"}
|
||||
? 'Longitude'
|
||||
: 'Latitude'}
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
step="any"
|
||||
min={axis === 0 ? -180 : -90}
|
||||
max={axis === 0 ? 180 : 90}
|
||||
value={point[axis] ?? ""}
|
||||
value={point[axis] ?? ''}
|
||||
onChange={(e) =>
|
||||
replace(
|
||||
p,
|
||||
@@ -89,7 +89,7 @@ export default function OpportunityParcelGeometry({
|
||||
? e
|
||||
.target
|
||||
.value ===
|
||||
""
|
||||
''
|
||||
? null
|
||||
: Number(
|
||||
e
|
||||
@@ -121,7 +121,7 @@ export default function OpportunityParcelGeometry({
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline mr-4"
|
||||
className="mr-4 underline"
|
||||
onClick={() =>
|
||||
replace(p, r, [...ring, [null, null]])
|
||||
}
|
||||
@@ -130,7 +130,7 @@ export default function OpportunityParcelGeometry({
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="underline mr-4"
|
||||
className="mr-4 underline"
|
||||
disabled={
|
||||
!ring.length ||
|
||||
ring[0].some((c) => c === null)
|
||||
@@ -148,7 +148,7 @@ export default function OpportunityParcelGeometry({
|
||||
type="button"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons.map((v, i) =>
|
||||
i === p
|
||||
? v.filter((_, j) => j !== r)
|
||||
@@ -163,10 +163,10 @@ export default function OpportunityParcelGeometry({
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline mr-4"
|
||||
className="mr-4 underline"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons.map((v, i) =>
|
||||
i === p ? [...v, []] : v,
|
||||
),
|
||||
@@ -179,7 +179,7 @@ export default function OpportunityParcelGeometry({
|
||||
type="button"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons.filter((_, i) => i !== p),
|
||||
})
|
||||
}
|
||||
@@ -193,7 +193,7 @@ export default function OpportunityParcelGeometry({
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
onChange({
|
||||
type: "MultiPolygon",
|
||||
type: 'MultiPolygon',
|
||||
coordinates: [...polygons, [[]]],
|
||||
})
|
||||
}
|
||||
@@ -206,13 +206,13 @@ export default function OpportunityParcelGeometry({
|
||||
contextOnly
|
||||
areas={[
|
||||
{
|
||||
purpose: "declared_parcel",
|
||||
title: "Perímetro declarado pelo Promotor",
|
||||
purpose: 'declared_parcel',
|
||||
title: 'Perímetro declarado pelo Promotor',
|
||||
source_reference:
|
||||
"Declaração do Promotor; revisão cadastral pendente",
|
||||
url: "#",
|
||||
'Declaração do Promotor; revisão cadastral pendente',
|
||||
url: '#',
|
||||
geometry: {
|
||||
type: "MultiPolygon",
|
||||
type: 'MultiPolygon',
|
||||
coordinates: polygons as [number, number][][][],
|
||||
} as MultiPolygon,
|
||||
},
|
||||
|
||||
@@ -15,6 +15,8 @@ export default function OpportunityProfileActions({
|
||||
publishers = [],
|
||||
opinions = [],
|
||||
publicationVisibility,
|
||||
conditions = [],
|
||||
conditionResponsibles = [],
|
||||
}: {
|
||||
id: number;
|
||||
etag: string;
|
||||
@@ -23,6 +25,16 @@ export default function OpportunityProfileActions({
|
||||
documents: { id: string; title: string }[];
|
||||
approvalHash?: string;
|
||||
publicationVisibility?: string;
|
||||
conditions?: {
|
||||
id: string;
|
||||
gate: string;
|
||||
description: string;
|
||||
responsible_name: string;
|
||||
due_on: string | null;
|
||||
blocking_action: string;
|
||||
status: string;
|
||||
}[];
|
||||
conditionResponsibles?: { id: number; name: string }[];
|
||||
onErrors?: (errors: Record<string, string>) => void;
|
||||
publishers?: { id: number; name: string }[];
|
||||
participants?: {
|
||||
@@ -49,6 +61,11 @@ export default function OpportunityProfileActions({
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [recipient, setRecipient] = useState('');
|
||||
const [opinion, setOpinion] = useState('');
|
||||
const [conditionDescription, setConditionDescription] = useState('');
|
||||
const [conditionResponsible, setConditionResponsible] = useState('');
|
||||
const [conditionDue, setConditionDue] = useState('');
|
||||
const [conditionBlocking, setConditionBlocking] = useState('approve');
|
||||
const [resolvedConditions, setResolvedConditions] = useState<string[]>([]);
|
||||
const [actionErrors, setActionErrors] = useState<Record<string, string>>(
|
||||
{},
|
||||
);
|
||||
@@ -97,6 +114,23 @@ export default function OpportunityProfileActions({
|
||||
evidence_document_ids: evidence,
|
||||
}
|
||||
: {}),
|
||||
...(action === 'review_gate'
|
||||
? {
|
||||
resolve_condition_ids: resolvedConditions,
|
||||
...(conditionDescription.trim()
|
||||
? {
|
||||
condition: {
|
||||
description:
|
||||
conditionDescription.trim(),
|
||||
responsible_user_id:
|
||||
Number(conditionResponsible),
|
||||
due_on: conditionDue || null,
|
||||
blocking_action: conditionBlocking,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: {}),
|
||||
...(action === 'pending_opinion'
|
||||
? { gate, recipient_user_id: Number(recipient) }
|
||||
: {}),
|
||||
@@ -120,6 +154,14 @@ export default function OpportunityProfileActions({
|
||||
if (error instanceof ProfileValidationError) {
|
||||
setActionErrors(error.fields);
|
||||
onErrors?.(error.fields);
|
||||
const first = Object.keys(error.fields)[0];
|
||||
requestAnimationFrame(() =>
|
||||
document
|
||||
.getElementById(
|
||||
`workflow-${id}-${first?.startsWith('conditions.') ? 'conditions' : first}`,
|
||||
)
|
||||
?.focus(),
|
||||
);
|
||||
}
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
@@ -148,17 +190,56 @@ export default function OpportunityProfileActions({
|
||||
público e ação independente do Publicador; não representa uma
|
||||
decisão externa.
|
||||
</p>
|
||||
{conditions.length > 0 && (
|
||||
<section
|
||||
aria-label="Condições de revisão"
|
||||
id={`workflow-${id}-conditions`}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<h3>Condições e evidências</h3>
|
||||
{conditions.map((c) => (
|
||||
<p key={c.id}>
|
||||
{c.description} —{' '}
|
||||
{c.status === 'resolved'
|
||||
? 'Verificada internamente'
|
||||
: 'Pendente'}
|
||||
; responsável: {c.responsible_name}; prazo:{' '}
|
||||
{c.due_on ?? 'não definido'}; impede:{' '}
|
||||
{c.blocking_action === 'approve'
|
||||
? 'aprovação'
|
||||
: 'publicação'}
|
||||
. A verificação interna não constitui decisão
|
||||
externa.
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{!!actions.length && (
|
||||
<>
|
||||
<label className="block">
|
||||
Fundamentação
|
||||
<textarea
|
||||
id={`workflow-${id}-reason`}
|
||||
aria-invalid={!!actionErrors.reason}
|
||||
aria-describedby={
|
||||
actionErrors.reason
|
||||
? `workflow-${id}-reason-error`
|
||||
: undefined
|
||||
}
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
{actionErrors.reason && (
|
||||
<span
|
||||
id={`workflow-${id}-reason-error`}
|
||||
role="alert"
|
||||
>
|
||||
{actionErrors.reason}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
{actions.includes('request_correction') && (
|
||||
<label className="block">
|
||||
@@ -178,6 +259,7 @@ export default function OpportunityProfileActions({
|
||||
<label>
|
||||
Revisão
|
||||
<select
|
||||
id={`workflow-${id}-gate`}
|
||||
className={control}
|
||||
value={gate}
|
||||
onChange={(e) => setGate(e.target.value)}
|
||||
@@ -222,6 +304,145 @@ export default function OpportunityProfileActions({
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
{actions.includes('review_gate') && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend>Condição explícita desta revisão</legend>
|
||||
<p>
|
||||
Opcional. Só bloqueia a ação indicada. Sem prazo
|
||||
automático ou responsabilidade externa
|
||||
atribuída.
|
||||
</p>
|
||||
<label className="block">
|
||||
Descrição da condição
|
||||
<textarea
|
||||
className={control}
|
||||
id={`workflow-${id}-condition.description`}
|
||||
value={conditionDescription}
|
||||
onChange={(e) =>
|
||||
setConditionDescription(e.target.value)
|
||||
}
|
||||
aria-invalid={
|
||||
!!actionErrors['condition.description']
|
||||
}
|
||||
aria-describedby={
|
||||
actionErrors['condition.description']
|
||||
? `workflow-${id}-condition.description-error`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{actionErrors['condition.description'] && (
|
||||
<span
|
||||
id={`workflow-${id}-condition.description-error`}
|
||||
role="alert"
|
||||
>
|
||||
{actionErrors['condition.description']}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<label className="block">
|
||||
Responsável pela preparação da evidência
|
||||
<select
|
||||
className={control}
|
||||
id={`workflow-${id}-condition.responsible_user_id`}
|
||||
value={conditionResponsible}
|
||||
onChange={(e) =>
|
||||
setConditionResponsible(e.target.value)
|
||||
}
|
||||
aria-invalid={
|
||||
!!actionErrors[
|
||||
'condition.responsible_user_id'
|
||||
]
|
||||
}
|
||||
aria-describedby={
|
||||
actionErrors[
|
||||
'condition.responsible_user_id'
|
||||
]
|
||||
? `workflow-${id}-condition.responsible_user_id-error`
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<option value="">Selecione</option>
|
||||
{conditionResponsibles.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{actionErrors[
|
||||
'condition.responsible_user_id'
|
||||
] && (
|
||||
<span
|
||||
id={`workflow-${id}-condition.responsible_user_id-error`}
|
||||
role="alert"
|
||||
>
|
||||
{
|
||||
actionErrors[
|
||||
'condition.responsible_user_id'
|
||||
]
|
||||
}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<label className="block">
|
||||
Prazo específico da condição, se definido
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
id={`workflow-${id}-condition.due_on`}
|
||||
value={conditionDue}
|
||||
onChange={(e) =>
|
||||
setConditionDue(e.target.value)
|
||||
}
|
||||
aria-invalid={
|
||||
!!actionErrors['condition.due_on']
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Ação impedida até verificação
|
||||
<select
|
||||
className={control}
|
||||
value={conditionBlocking}
|
||||
onChange={(e) =>
|
||||
setConditionBlocking(e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="approve">Aprovação</option>
|
||||
<option value="publish">Publicação</option>
|
||||
</select>
|
||||
</label>
|
||||
{conditions
|
||||
.filter(
|
||||
(c) =>
|
||||
c.gate === gate && c.status === 'open',
|
||||
)
|
||||
.map((c) => (
|
||||
<label key={c.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={resolvedConditions.includes(
|
||||
c.id,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
setResolvedConditions(
|
||||
e.target.checked
|
||||
? [
|
||||
...resolvedConditions,
|
||||
c.id,
|
||||
]
|
||||
: resolvedConditions.filter(
|
||||
(id) =>
|
||||
id !== c.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
Verifiquei com os documentos
|
||||
selecionados: {c.description}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
{(actions.includes('assign_review') ||
|
||||
actions.includes('assign_publication')) && (
|
||||
<label className="block">
|
||||
@@ -297,7 +518,10 @@ export default function OpportunityProfileActions({
|
||||
.filter(([key]) => !key.startsWith('canonical'))
|
||||
.map(([key, msg]) => (
|
||||
<p key={key} role="alert">
|
||||
{key}: {msg}
|
||||
{key.startsWith('conditions.')
|
||||
? 'Condição de revisão'
|
||||
: key}
|
||||
: {msg}
|
||||
</p>
|
||||
))}
|
||||
{actions.includes('publish') && (
|
||||
|
||||
@@ -163,8 +163,9 @@ export function PortalGroupedMenu() {
|
||||
aria-label="Sessão da conta"
|
||||
className="mb-3 flex flex-wrap items-center justify-between gap-3 rounded-lg bg-slate-50 px-3 py-2"
|
||||
>
|
||||
<p className="min-w-0 break-words text-sm text-slate-700 [overflow-wrap:anywhere]">
|
||||
Sessão: {props.auth.user.name || props.auth.user.email}
|
||||
<p className="min-w-0 text-sm [overflow-wrap:anywhere] break-words text-slate-700">
|
||||
Sessão:{' '}
|
||||
{props.auth.user.name || props.auth.user.email}
|
||||
</p>
|
||||
<Link
|
||||
href={logout()}
|
||||
@@ -181,7 +182,9 @@ export function PortalGroupedMenu() {
|
||||
className="inline-flex min-h-11 shrink-0 items-center gap-2 rounded-lg border border-slate-400 bg-white px-3 py-2 text-sm font-semibold text-slate-900 hover:bg-slate-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700 disabled:cursor-wait disabled:opacity-60"
|
||||
>
|
||||
<LogOut aria-hidden="true" className="size-4" />
|
||||
{loggingOut ? 'A terminar sessão…' : 'Terminar sessão'}
|
||||
{loggingOut
|
||||
? 'A terminar sessão…'
|
||||
: 'Terminar sessão'}
|
||||
</Link>
|
||||
</nav>
|
||||
)}
|
||||
|
||||
@@ -293,7 +293,12 @@ export function SimulationCashflowPlanner({
|
||||
{projection.vatRefundRecognized}. Estes valores não
|
||||
foram somados à caixa.
|
||||
</p>
|
||||
<div className="overflow-x-auto focus-visible:outline-2" tabIndex={0} role="region" aria-label="Tabela do fluxo de caixa">
|
||||
<div
|
||||
className="overflow-x-auto focus-visible:outline-2"
|
||||
tabIndex={0}
|
||||
role="region"
|
||||
aria-label="Tabela do fluxo de caixa"
|
||||
>
|
||||
<table className="min-w-full text-sm">
|
||||
<caption className="sr-only">
|
||||
Projecção mensal de tesouraria
|
||||
|
||||
@@ -369,7 +369,12 @@ export function SimulationFinancialTools({
|
||||
efectiva converte a taxa anual para a
|
||||
periodicidade indicada.
|
||||
</p>
|
||||
<div className="max-h-64 overflow-auto focus-visible:outline-2" tabIndex={0} role="region" aria-label="Plano de reembolso indicativo">
|
||||
<div
|
||||
className="max-h-64 overflow-auto focus-visible:outline-2"
|
||||
tabIndex={0}
|
||||
role="region"
|
||||
aria-label="Plano de reembolso indicativo"
|
||||
>
|
||||
<table className="min-w-full text-xs">
|
||||
<caption className="sr-only">
|
||||
Plano de reembolso indicativo
|
||||
|
||||
+1973
-1853
File diff suppressed because it is too large
Load Diff
@@ -15,7 +15,7 @@ export default function TerritorialSources({
|
||||
}) {
|
||||
if (!sources?.length) return null;
|
||||
return (
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<section className="min-w-0 space-y-3 rounded border p-4 [overflow-wrap:anywhere]">
|
||||
<h2 className="text-xl font-bold">
|
||||
Fundamento documental das associações
|
||||
</h2>
|
||||
|
||||
@@ -14,10 +14,12 @@ export default function TerritoryGeometryPreview({
|
||||
territoryId,
|
||||
management = false,
|
||||
endpoint: suppliedEndpoint,
|
||||
label = 'Cobertura cartográfica da seleção',
|
||||
}: {
|
||||
territoryId?: string;
|
||||
management?: boolean;
|
||||
endpoint?: string;
|
||||
label?: string;
|
||||
}) {
|
||||
const [context, setContext] = useState<Context | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
@@ -26,9 +28,11 @@ export default function TerritoryGeometryPreview({
|
||||
setError('');
|
||||
if (!territoryId) return;
|
||||
const controller = new AbortController();
|
||||
const endpoint = suppliedEndpoint ?? (management
|
||||
? '/management/territory-geometries'
|
||||
: '/api/v1/investment/territory-geometries');
|
||||
const endpoint =
|
||||
suppliedEndpoint ??
|
||||
(management
|
||||
? '/management/territory-geometries'
|
||||
: '/api/v1/investment/territory-geometries');
|
||||
void fetch(
|
||||
`${endpoint}?${new URLSearchParams({ territory_id: territoryId })}`,
|
||||
{
|
||||
@@ -56,10 +60,7 @@ export default function TerritoryGeometryPreview({
|
||||
}, [territoryId, management, suppliedEndpoint]);
|
||||
if (!territoryId) return null;
|
||||
return (
|
||||
<section
|
||||
className="space-y-2 md:col-span-full"
|
||||
aria-label="Cobertura cartográfica da seleção"
|
||||
>
|
||||
<section className="space-y-2 md:col-span-full" aria-label={label}>
|
||||
<p>Território selecionado no cadastro.</p>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{!context && !error && <p role="status">A consultar geometria…</p>}
|
||||
|
||||
@@ -54,6 +54,7 @@ export default function PortalNavigation({
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { url, props, component } = usePage();
|
||||
const printable = component === 'land-assistance/print';
|
||||
const portalShell =
|
||||
['welcome', 'PortalInvestidor', 'management-access'].includes(
|
||||
component,
|
||||
@@ -93,19 +94,28 @@ export default function PortalNavigation({
|
||||
: 'Detalhes');
|
||||
return (
|
||||
<MenuPlacement.Provider value={true}>
|
||||
<div className="pb-8 lg:pb-24 [&_button]:scroll-mb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24">
|
||||
<nav aria-label="Atalho para o conteúdo">
|
||||
<a
|
||||
href="#portal-content"
|
||||
className="sr-only focus:not-sr-only focus:block focus:bg-white focus:p-4 focus:text-emerald-900"
|
||||
<div
|
||||
className={`pb-8 lg:pb-24 [&_button]:scroll-mb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24 ${printable ? 'print:pb-0' : ''}`}
|
||||
>
|
||||
<nav
|
||||
aria-label="Atalho para o conteúdo"
|
||||
className={printable ? 'print:hidden' : undefined}
|
||||
>
|
||||
Saltar para o conteúdo
|
||||
</a>
|
||||
<a
|
||||
href="#portal-content"
|
||||
className="sr-only focus:not-sr-only focus:block focus:bg-white focus:p-4 focus:text-emerald-900"
|
||||
>
|
||||
Saltar para o conteúdo
|
||||
</a>
|
||||
</nav>
|
||||
{portalShell && <PortalMenu primary />}
|
||||
{portalShell && (
|
||||
<div className={printable ? 'print:hidden' : undefined}>
|
||||
<PortalMenu primary />
|
||||
</div>
|
||||
)}
|
||||
<nav
|
||||
aria-label="Caminho de navegação"
|
||||
className="bg-background text-foreground flex flex-wrap items-center gap-2 border-b px-5 py-3 text-sm"
|
||||
className={`bg-background text-foreground flex flex-wrap items-center gap-2 border-b px-5 py-3 text-sm ${printable ? 'print:hidden' : ''}`}
|
||||
>
|
||||
{path === '/' ? (
|
||||
<span aria-current="page">Início</span>
|
||||
@@ -128,16 +138,23 @@ export default function PortalNavigation({
|
||||
)}
|
||||
</nav>
|
||||
<div id="portal-content" tabIndex={-1}>
|
||||
{portalShell && <JourneyCompanion />}
|
||||
{portalShell && (
|
||||
<div className={printable ? 'print:hidden' : undefined}>
|
||||
<JourneyCompanion />
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
<aside aria-label="Contacto de apoio ao investidor">
|
||||
<a
|
||||
href="/apoio"
|
||||
className="mx-3 mt-4 block max-w-[calc(100%-1.5rem)] rounded-xl bg-emerald-800 px-5 py-3 text-center text-sm font-semibold text-white shadow-xl focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-emerald-600"
|
||||
<aside
|
||||
aria-label="Contacto de apoio ao investidor"
|
||||
className={printable ? 'print:hidden' : undefined}
|
||||
>
|
||||
Contactar Apoio ao Investidor
|
||||
</a>
|
||||
<a
|
||||
href="/apoio"
|
||||
className="mx-3 mt-4 block max-w-[calc(100%-1.5rem)] rounded-xl bg-emerald-800 px-5 py-3 text-center text-sm font-semibold text-white shadow-xl focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-emerald-600"
|
||||
>
|
||||
Contactar Apoio ao Investidor
|
||||
</a>
|
||||
</aside>
|
||||
</div>
|
||||
</MenuPlacement.Provider>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/** UUID v4 for operation identifiers; retries keep the caller's existing key. */
|
||||
export function createOperationKey(): string {
|
||||
const secureRandom = globalThis.crypto;
|
||||
if (typeof secureRandom?.randomUUID === 'function') return secureRandom.randomUUID();
|
||||
if (typeof secureRandom?.getRandomValues !== 'function') {
|
||||
throw new Error('O navegador não disponibiliza geração criptográfica segura. Reabra o portal no endereço HTTPS configurado.');
|
||||
}
|
||||
const bytes = secureRandom.getRandomValues(new Uint8Array(16));
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
@@ -21,7 +21,7 @@ export async function profileJson(
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': cookie ? decodeURIComponent(cookie.slice(11)) : '',
|
||||
},
|
||||
body: method === 'GET' ? undefined : JSON.stringify(data),
|
||||
...(method === 'GET' ? {} : { body: JSON.stringify(data) }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Display a saved JSON value without silently rendering objects as "[object Object]". */
|
||||
export function valueText(value: unknown): string {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'string') return value;
|
||||
if (typeof value === 'number' || typeof value === 'boolean')
|
||||
return String(value);
|
||||
return JSON.stringify(value) ?? '';
|
||||
}
|
||||
@@ -102,7 +102,10 @@ function TopBar({
|
||||
requestCount: number;
|
||||
}) {
|
||||
return (
|
||||
<nav aria-label="Navegação das manifestações" className="sticky top-0 z-30 border-b border-slate-200 bg-white/95 backdrop-blur">
|
||||
<nav
|
||||
aria-label="Navegação das manifestações"
|
||||
className="sticky top-0 z-30 border-b border-slate-200 bg-white/95 backdrop-blur"
|
||||
>
|
||||
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-5 py-4">
|
||||
<button
|
||||
onClick={() => onNavigate('home')}
|
||||
@@ -1103,234 +1106,245 @@ export default function PortalInvestidorApp({
|
||||
<TopBar onNavigate={navigate} requestCount={requestCount} />
|
||||
<PortalMenu />
|
||||
<main>
|
||||
{view === 'home' && (
|
||||
<>
|
||||
<Hero
|
||||
query={heroQuery}
|
||||
setQuery={setHeroQuery}
|
||||
onSearch={handleHeroSearch}
|
||||
stats={home.data?.data.stats}
|
||||
onNavigate={navigate}
|
||||
/>
|
||||
<section className="mx-auto max-w-6xl space-y-5 px-5 py-10">
|
||||
<h2 className="text-2xl font-bold">
|
||||
Encontre o contexto do seu investimento
|
||||
</h2>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{[
|
||||
[
|
||||
'/clusters',
|
||||
'Clusters',
|
||||
'Cadeias de valor e lacunas produtivas.',
|
||||
],
|
||||
[
|
||||
'/corredores',
|
||||
'Corredores',
|
||||
'Territórios, logística e conexões.',
|
||||
],
|
||||
[
|
||||
'/projectos-ancora',
|
||||
'Projectos âncora',
|
||||
'Projectos estruturantes e relações.',
|
||||
],
|
||||
[
|
||||
'/educacao',
|
||||
'Educação',
|
||||
'Investimentos em competências e formação.',
|
||||
],
|
||||
[
|
||||
'/documentos',
|
||||
'Documentos e Formulários',
|
||||
'Legislação, procedimentos, formulários e materiais de apoio.',
|
||||
],
|
||||
].map(([href, title, text]) => (
|
||||
{view === 'home' && (
|
||||
<>
|
||||
<Hero
|
||||
query={heroQuery}
|
||||
setQuery={setHeroQuery}
|
||||
onSearch={handleHeroSearch}
|
||||
stats={home.data?.data.stats}
|
||||
onNavigate={navigate}
|
||||
/>
|
||||
<section className="mx-auto max-w-6xl space-y-5 px-5 py-10">
|
||||
<h2 className="text-2xl font-bold">
|
||||
Encontre o contexto do seu investimento
|
||||
</h2>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{[
|
||||
[
|
||||
'/clusters',
|
||||
'Clusters',
|
||||
'Cadeias de valor e lacunas produtivas.',
|
||||
],
|
||||
[
|
||||
'/corredores',
|
||||
'Corredores',
|
||||
'Territórios, logística e conexões.',
|
||||
],
|
||||
[
|
||||
'/projectos-ancora',
|
||||
'Projectos âncora',
|
||||
'Projectos estruturantes e relações.',
|
||||
],
|
||||
[
|
||||
'/educacao',
|
||||
'Educação',
|
||||
'Investimentos em competências e formação.',
|
||||
],
|
||||
[
|
||||
'/documentos',
|
||||
'Documentos e Formulários',
|
||||
'Legislação, procedimentos, formulários e materiais de apoio.',
|
||||
],
|
||||
].map(([href, title, text]) => (
|
||||
<a
|
||||
key={href}
|
||||
href={href}
|
||||
className="rounded-xl border bg-white p-5"
|
||||
>
|
||||
<h3 className="text-lg font-bold">
|
||||
{title}
|
||||
</h3>
|
||||
<p>{text}</p>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<QueryStatus
|
||||
loading={home.loading}
|
||||
error={home.error}
|
||||
retry={home.retry}
|
||||
/>
|
||||
{home.data && (
|
||||
<SectorGrid
|
||||
onSelectSector={handleSelectSector}
|
||||
/>
|
||||
)}
|
||||
|
||||
<section className="mx-auto max-w-6xl space-y-5 px-5 py-12">
|
||||
<h2 className="text-2xl font-black">
|
||||
Como Investir
|
||||
</h2>
|
||||
<div className="grid gap-5 md:grid-cols-3">
|
||||
{[
|
||||
[
|
||||
'1. Explorar',
|
||||
'Identifique o sector, território e oportunidade.',
|
||||
'/oportunidades',
|
||||
],
|
||||
[
|
||||
'2. Preparar',
|
||||
'Conheça o percurso e organize os documentos.',
|
||||
'/como-investir',
|
||||
],
|
||||
[
|
||||
'3. Acompanhar',
|
||||
'Envie o pedido e acompanhe o protocolo.',
|
||||
'/balcao-virtual',
|
||||
],
|
||||
].map(([title, text, href]) => (
|
||||
<a
|
||||
key={href}
|
||||
href={href}
|
||||
className="rounded-xl border bg-white p-6"
|
||||
>
|
||||
<h3 className="font-bold">
|
||||
{title}
|
||||
</h3>
|
||||
<p>{text}</p>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="border-t border-slate-200 bg-white py-16">
|
||||
<div className="mx-auto max-w-6xl px-5">
|
||||
<div className="mb-8 flex items-end justify-between">
|
||||
<h2 className="text-2xl font-black text-slate-900">
|
||||
Oportunidades em destaque
|
||||
</h2>
|
||||
<button
|
||||
onClick={goToOpportunities}
|
||||
className="text-sm font-bold text-emerald-700 hover:underline"
|
||||
>
|
||||
Ver todas →
|
||||
</button>
|
||||
</div>
|
||||
{home.data && featured.length === 0 && (
|
||||
<p className="text-slate-600">
|
||||
Não existem oportunidades em
|
||||
destaque neste momento.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{featured.map((o) => (
|
||||
<OpportunityCard
|
||||
key={o.reference}
|
||||
opportunity={o}
|
||||
onView={handleView}
|
||||
onInterest={handleInterest}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section className="mx-auto grid max-w-6xl gap-6 px-5 py-12 md:grid-cols-2">
|
||||
<div className="space-y-4 rounded-xl border bg-white p-6">
|
||||
<h2 className="text-2xl font-black">
|
||||
Documentos essenciais
|
||||
</h2>
|
||||
{essentialResources.length > 0 && (
|
||||
<ul className="space-y-2">
|
||||
{essentialResources.map(
|
||||
(resource) => (
|
||||
<li key={resource.id}>
|
||||
<a
|
||||
className="underline"
|
||||
href={`/documentos/${resource.id}/download`}
|
||||
>
|
||||
{resource.title}
|
||||
</a>
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
<p>
|
||||
Consulte legislação, referências e
|
||||
formulários publicados para preparar o
|
||||
seu investimento.
|
||||
</p>
|
||||
<a
|
||||
key={href}
|
||||
href={href}
|
||||
className="rounded-xl border bg-white p-5"
|
||||
className="font-semibold text-emerald-800 underline"
|
||||
href="/documentos"
|
||||
>
|
||||
<h3 className="text-lg font-bold">
|
||||
{title}
|
||||
</h3>
|
||||
<p>{text}</p>
|
||||
Abrir biblioteca documental
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<p>
|
||||
<a
|
||||
className="underline"
|
||||
href="/legislacao"
|
||||
>
|
||||
Legislação e Incentivos
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-4 rounded-xl bg-emerald-900 p-6 text-white">
|
||||
<h2 className="text-2xl font-black">
|
||||
Apoio ao Investidor
|
||||
</h2>
|
||||
<p>
|
||||
Peça orientação à equipa, proponha uma
|
||||
parceria ou acompanhe o seu pedido.
|
||||
</p>
|
||||
<a
|
||||
className="font-semibold underline"
|
||||
href="/apoio"
|
||||
>
|
||||
Contactar Apoio ao Investidor
|
||||
</a>
|
||||
<p>
|
||||
<a
|
||||
className="underline"
|
||||
href="/parcerias"
|
||||
>
|
||||
Bolsa de Parcerias
|
||||
</a>{' '}
|
||||
·{' '}
|
||||
<a
|
||||
className="underline"
|
||||
href="/simulador-fiscal"
|
||||
>
|
||||
Simulador Fiscal
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view !== 'home' && home.error && (
|
||||
<QueryStatus
|
||||
loading={home.loading}
|
||||
loading={false}
|
||||
error={home.error}
|
||||
retry={home.retry}
|
||||
/>
|
||||
{home.data && (
|
||||
<SectorGrid onSelectSector={handleSelectSector} />
|
||||
)}
|
||||
)}
|
||||
{view === 'opportunities' && (
|
||||
<OpportunitiesView
|
||||
filters={filters}
|
||||
setFilters={setFilters}
|
||||
onView={handleView}
|
||||
onInterest={handleInterest}
|
||||
/>
|
||||
)}
|
||||
|
||||
<section className="mx-auto max-w-6xl space-y-5 px-5 py-12">
|
||||
<h2 className="text-2xl font-black">
|
||||
Como Investir
|
||||
</h2>
|
||||
<div className="grid gap-5 md:grid-cols-3">
|
||||
{[
|
||||
[
|
||||
'1. Explorar',
|
||||
'Identifique o sector, território e oportunidade.',
|
||||
'/oportunidades',
|
||||
],
|
||||
[
|
||||
'2. Preparar',
|
||||
'Conheça o percurso e organize os documentos.',
|
||||
'/como-investir',
|
||||
],
|
||||
[
|
||||
'3. Acompanhar',
|
||||
'Envie o pedido e acompanhe o protocolo.',
|
||||
'/balcao-virtual',
|
||||
],
|
||||
].map(([title, text, href]) => (
|
||||
<a
|
||||
key={href}
|
||||
href={href}
|
||||
className="rounded-xl border bg-white p-6"
|
||||
>
|
||||
<h3 className="font-bold">{title}</h3>
|
||||
<p>{text}</p>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="border-t border-slate-200 bg-white py-16">
|
||||
<div className="mx-auto max-w-6xl px-5">
|
||||
<div className="mb-8 flex items-end justify-between">
|
||||
<h2 className="text-2xl font-black text-slate-900">
|
||||
Oportunidades em destaque
|
||||
</h2>
|
||||
<button
|
||||
onClick={goToOpportunities}
|
||||
className="text-sm font-bold text-emerald-700 hover:underline"
|
||||
>
|
||||
Ver todas →
|
||||
</button>
|
||||
</div>
|
||||
{home.data && featured.length === 0 && (
|
||||
<p className="text-slate-600">
|
||||
Não existem oportunidades em destaque
|
||||
neste momento.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{featured.map((o) => (
|
||||
<OpportunityCard
|
||||
key={o.reference}
|
||||
opportunity={o}
|
||||
onView={handleView}
|
||||
onInterest={handleInterest}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section className="mx-auto grid max-w-6xl gap-6 px-5 py-12 md:grid-cols-2">
|
||||
<div className="space-y-4 rounded-xl border bg-white p-6">
|
||||
<h2 className="text-2xl font-black">
|
||||
Documentos essenciais
|
||||
</h2>
|
||||
{essentialResources.length > 0 && (
|
||||
<ul className="space-y-2">
|
||||
{essentialResources.map((resource) => (
|
||||
<li key={resource.id}>
|
||||
<a
|
||||
className="underline"
|
||||
href={`/documentos/${resource.id}/download`}
|
||||
>
|
||||
{resource.title}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p>
|
||||
Consulte legislação, referências e
|
||||
formulários publicados para preparar o seu
|
||||
investimento.
|
||||
</p>
|
||||
<a
|
||||
className="font-semibold text-emerald-800 underline"
|
||||
href="/documentos"
|
||||
>
|
||||
Abrir biblioteca documental
|
||||
</a>
|
||||
<p>
|
||||
<a className="underline" href="/legislacao">
|
||||
Legislação e Incentivos
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-4 rounded-xl bg-emerald-900 p-6 text-white">
|
||||
<h2 className="text-2xl font-black">
|
||||
Apoio ao Investidor
|
||||
</h2>
|
||||
<p>
|
||||
Peça orientação à equipa, proponha uma
|
||||
parceria ou acompanhe o seu pedido.
|
||||
</p>
|
||||
<a
|
||||
className="font-semibold underline"
|
||||
href="/apoio"
|
||||
>
|
||||
Contactar Apoio ao Investidor
|
||||
</a>
|
||||
<p>
|
||||
<a className="underline" href="/parcerias">
|
||||
Bolsa de Parcerias
|
||||
</a>{' '}
|
||||
·{' '}
|
||||
<a
|
||||
className="underline"
|
||||
href="/simulador-fiscal"
|
||||
>
|
||||
Simulador Fiscal
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view !== 'home' && home.error && (
|
||||
<QueryStatus
|
||||
loading={false}
|
||||
error={home.error}
|
||||
retry={home.retry}
|
||||
/>
|
||||
)}
|
||||
{view === 'opportunities' && (
|
||||
<OpportunitiesView
|
||||
filters={filters}
|
||||
setFilters={setFilters}
|
||||
onView={handleView}
|
||||
onInterest={handleInterest}
|
||||
/>
|
||||
)}
|
||||
|
||||
{view === 'detail' && selected && (
|
||||
<OpportunityDetail
|
||||
opportunity={selected}
|
||||
onBack={goToOpportunities}
|
||||
onInterest={handleInterest}
|
||||
/>
|
||||
)}
|
||||
|
||||
{view === 'interest' && (
|
||||
<InterestForm
|
||||
key={selected?.reference ?? 'general'}
|
||||
preselected={selected}
|
||||
countries={countries}
|
||||
onSubmitted={() => setRequestCount((c) => c + 1)}
|
||||
/>
|
||||
)}
|
||||
{view === 'detail' && selected && (
|
||||
<OpportunityDetail
|
||||
opportunity={selected}
|
||||
onBack={goToOpportunities}
|
||||
onInterest={handleInterest}
|
||||
/>
|
||||
)}
|
||||
|
||||
{view === 'interest' && (
|
||||
<InterestForm
|
||||
key={selected?.reference ?? 'general'}
|
||||
preselected={selected}
|
||||
countries={countries}
|
||||
onSubmitted={() => setRequestCount((c) => c + 1)}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
<Footer />
|
||||
|
||||
|
||||
@@ -38,9 +38,9 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||
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.
|
||||
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>
|
||||
)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { InvestmentContext } from '@/pages/investor-path/index';
|
||||
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
|
||||
@@ -215,13 +215,15 @@ export default function Dashboard({
|
||||
aria-label="Acções rápidas"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
{summary.canCreateOpportunity !== false && <Link
|
||||
className="underline"
|
||||
href="/management/opportunities/create"
|
||||
>
|
||||
{opportunityManagement?.create.label ??
|
||||
'Criar oportunidade'}
|
||||
</Link>}
|
||||
{summary.canCreateOpportunity !== false && (
|
||||
<Link
|
||||
className="underline"
|
||||
href="/management/opportunities/create"
|
||||
>
|
||||
{opportunityManagement?.create.label ??
|
||||
'Criar oportunidade'}
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
className="underline"
|
||||
href="/management/sectors/create"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import {
|
||||
@@ -144,7 +145,7 @@ export default function Case({
|
||||
const actor = usePage<{ auth: { user: { id: number } } }>().props.auth.user;
|
||||
const requestForm = useForm({
|
||||
service_version_id: services[0]?.id ?? '',
|
||||
client_key: crypto.randomUUID(),
|
||||
client_key: createOperationKey(),
|
||||
});
|
||||
const stageForm = useForm({
|
||||
version: dossier.version,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Frame, input, button, card } from '@/pages/investment/shared';
|
||||
@@ -50,7 +51,7 @@ export default function Panel({
|
||||
const [failure, setFailure] = useState<string | null>(null);
|
||||
const form = useForm({
|
||||
title: '',
|
||||
client_key: crypto.randomUUID(),
|
||||
client_key: createOperationKey(),
|
||||
reuse_consent: false,
|
||||
company_id: '',
|
||||
submission_id: params.get('submission_id') ?? '',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
@@ -114,7 +115,7 @@ export default function RequestPage({
|
||||
reason: '',
|
||||
due_at: '',
|
||||
});
|
||||
const message = useForm({ body: '', client_key: crypto.randomUUID() });
|
||||
const message = useForm({ body: '', client_key: createOperationKey() });
|
||||
const canEdit = owner && fieldsEditable;
|
||||
return (
|
||||
<Frame title={definition.title}>
|
||||
@@ -150,26 +151,59 @@ export default function RequestPage({
|
||||
)}
|
||||
</section>
|
||||
{canEdit && toolPrefill && (
|
||||
<section className={card + ' space-y-3'} aria-label="Descrição guardada no projeto">
|
||||
<h2 className="text-xl font-bold">Reutilizar dados do projeto</h2>
|
||||
<p>A descrição está vazia neste pedido. Pode reutilizar o resumo já guardado na ferramenta deste dossier, versão {toolPrefill.draft_version}.</p>
|
||||
<blockquote className="rounded border p-3 whitespace-pre-wrap">{toolPrefill.description}</blockquote>
|
||||
<p>Esta ação guarda o rascunho com os dados preenchidos nesta página. Reveja-os antes de submeter.</p>
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-label="Descrição guardada no projeto"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Reutilizar dados do projeto
|
||||
</h2>
|
||||
<p>
|
||||
A descrição está vazia neste pedido. Pode reutilizar o
|
||||
resumo já guardado na ferramenta deste dossier, versão{' '}
|
||||
{toolPrefill.draft_version}.
|
||||
</p>
|
||||
<blockquote className="rounded border p-3 whitespace-pre-wrap">
|
||||
{toolPrefill.description}
|
||||
</blockquote>
|
||||
<p>
|
||||
Esta ação guarda o rascunho com os dados preenchidos
|
||||
nesta página. Reveja-os antes de submeter.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={form.processing || !!form.data.payload.description?.trim()}
|
||||
disabled={
|
||||
form.processing ||
|
||||
!!form.data.payload.description?.trim()
|
||||
}
|
||||
onClick={() => {
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
version: request.version,
|
||||
submit: false,
|
||||
payload: {...data.payload, description: toolPrefill.description},
|
||||
tool_prefill: {draft_id:toolPrefill.draft_id, draft_version:toolPrefill.draft_version, snapshot_sha256:toolPrefill.snapshot_sha256},
|
||||
payload: {
|
||||
...data.payload,
|
||||
description: toolPrefill.description,
|
||||
},
|
||||
tool_prefill: {
|
||||
draft_id: toolPrefill.draft_id,
|
||||
draft_version: toolPrefill.draft_version,
|
||||
snapshot_sha256:
|
||||
toolPrefill.snapshot_sha256,
|
||||
},
|
||||
}));
|
||||
form.put(`/balcao-virtual/pedidos/${request.id}`, {onSuccess: () => form.setData('payload', {...form.data.payload, description:toolPrefill.description})});
|
||||
form.put(`/balcao-virtual/pedidos/${request.id}`, {
|
||||
onSuccess: () =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
description: toolPrefill.description,
|
||||
}),
|
||||
});
|
||||
}}
|
||||
>Reutilizar descrição guardada e guardar rascunho</button>
|
||||
>
|
||||
Reutilizar descrição guardada e guardar rascunho
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<section className={card + ' space-y-3'}>
|
||||
@@ -207,6 +241,8 @@ export default function RequestPage({
|
||||
</label>
|
||||
<CountrySelect
|
||||
id="request-country"
|
||||
label="País do requerente (opcional)"
|
||||
error={form.errors['payload.country']}
|
||||
countries={countries}
|
||||
value={form.data.payload.country ?? ''}
|
||||
allowLegacyValue
|
||||
@@ -222,14 +258,13 @@ export default function RequestPage({
|
||||
!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"
|
||||
label="País de origem declarado desta solicitação"
|
||||
error={form.errors['payload.declared_origin_country_code']}
|
||||
countries={countries}
|
||||
value={form.data.payload.declared_origin_country_code ?? ''}
|
||||
disabled={
|
||||
@@ -251,11 +286,6 @@ export default function RequestPage({
|
||||
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]) =>
|
||||
@@ -634,7 +664,7 @@ export default function RequestPage({
|
||||
message.reset('body');
|
||||
message.setData(
|
||||
'client_key',
|
||||
crypto.randomUUID(),
|
||||
createOperationKey(),
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -645,6 +675,7 @@ export default function RequestPage({
|
||||
Mensagem privada
|
||||
<textarea
|
||||
className={input}
|
||||
disabled={message.processing}
|
||||
value={message.data.body}
|
||||
required
|
||||
onChange={(e) =>
|
||||
|
||||
@@ -127,6 +127,7 @@ export default function BusinessInterest({
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.declared_origin_country_code}
|
||||
label="País de origem declarado desta solicitação"
|
||||
onChange={(value) =>
|
||||
update('declared_origin_country_code', value)
|
||||
}
|
||||
@@ -186,6 +187,7 @@ export default function BusinessInterest({
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
required
|
||||
label="País do requerente"
|
||||
allowLegacyValue
|
||||
value={form.country}
|
||||
onChange={(value) => update('country', value)}
|
||||
|
||||
@@ -614,6 +614,10 @@ export default function BusinessWizard({
|
||||
<select
|
||||
className={input}
|
||||
value={sectorId ?? ''}
|
||||
aria-label={t(
|
||||
'Sector de actividade',
|
||||
'Sector of activity',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
setSectorId(
|
||||
e.target.value
|
||||
|
||||
@@ -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>
|
||||
@@ -78,10 +78,10 @@ export default function Detail({
|
||||
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">
|
||||
@@ -89,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',
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
@@ -118,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.',
|
||||
),
|
||||
);
|
||||
}}
|
||||
@@ -148,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>
|
||||
))}
|
||||
@@ -164,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>
|
||||
))}
|
||||
@@ -212,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>
|
||||
@@ -241,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
|
||||
}
|
||||
>
|
||||
@@ -260,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,
|
||||
@@ -269,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}
|
||||
/>
|
||||
)),
|
||||
|
||||
@@ -2,9 +2,25 @@ import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { Frame, Field, input, button, card } from './shared';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
import { useEffect, useId } from 'react';
|
||||
|
||||
type RecordData = { version: number; payload: Record<string, string> };
|
||||
type Company = RecordData & { id: string };
|
||||
type Company = RecordData & {
|
||||
id: string;
|
||||
countrySource?: {
|
||||
organization_id: string;
|
||||
organization_version: number;
|
||||
country: string;
|
||||
} | null;
|
||||
};
|
||||
type Organization = {
|
||||
id: string;
|
||||
name: string;
|
||||
version: number;
|
||||
country: string | null;
|
||||
canEdit: boolean;
|
||||
provenance: { reference: string; kind: string } | null;
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
phone: 'Telefone',
|
||||
country: 'País anteriormente registado',
|
||||
@@ -23,10 +39,14 @@ export default function Profile({
|
||||
account,
|
||||
companies,
|
||||
countries,
|
||||
organizations = [],
|
||||
organizationCountryAvailable = false,
|
||||
}: {
|
||||
account: RecordData;
|
||||
companies: Company[];
|
||||
countries: Country[];
|
||||
organizations?: Organization[];
|
||||
organizationCountryAvailable?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Frame title="Perfil de investimento e empresas">
|
||||
@@ -65,6 +85,21 @@ export default function Profile({
|
||||
<h3 className="text-xl font-bold">
|
||||
{company.payload.name}
|
||||
</h3>
|
||||
{company.countrySource && (
|
||||
<p>
|
||||
País reutilizado: {company.countrySource.country};
|
||||
organização{' '}
|
||||
{organizations.find(
|
||||
(o) =>
|
||||
o.id ===
|
||||
company.countrySource?.organization_id,
|
||||
)?.name ?? company.countrySource.organization_id}
|
||||
, versão{' '}
|
||||
{company.countrySource.organization_version}. O
|
||||
valor é uma cópia identificada; não é atualizado
|
||||
automaticamente quando o cadastro mestre muda.
|
||||
</p>
|
||||
)}
|
||||
<Editor
|
||||
key={company.version}
|
||||
record={company}
|
||||
@@ -78,6 +113,35 @@ export default function Profile({
|
||||
'description',
|
||||
]}
|
||||
/>
|
||||
{organizations
|
||||
.filter((o) => o.country)
|
||||
.map((org) => (
|
||||
<div key={org.id} className="mt-3 space-y-2">
|
||||
<p>
|
||||
País mestre de {org.name}: {org.country}. A
|
||||
reutilização altera somente esta declaração;
|
||||
manifestações anteriores conservam o seu
|
||||
valor.
|
||||
</p>
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/investidor/companies/${company.id}/organization-country`,
|
||||
{
|
||||
version: company.version,
|
||||
organization_id: org.id,
|
||||
organization_version:
|
||||
org.version,
|
||||
},
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
Reutilizar país de {org.name}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
className={button + ' mt-4'}
|
||||
onClick={() =>
|
||||
@@ -109,9 +173,129 @@ export default function Profile({
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
<h2 className="text-2xl font-bold">
|
||||
Organizações representadas — cadastro mestre
|
||||
</h2>
|
||||
<p>
|
||||
O país de constituição é independente da residência e da origem
|
||||
da solicitação. Não se associa uma empresa privada a uma
|
||||
organização por semelhança de nome. A declaração do
|
||||
representante não é uma decisão externa nem comprova por si a
|
||||
representação legal.
|
||||
</p>
|
||||
{!organizationCountryAvailable && (
|
||||
<p role="status">
|
||||
Extensão do país de constituição ainda não instalada neste
|
||||
ambiente.
|
||||
</p>
|
||||
)}
|
||||
{organizationCountryAvailable && organizations.length === 0 && (
|
||||
<p>
|
||||
Sem representação organizacional registada para esta conta.
|
||||
</p>
|
||||
)}
|
||||
{organizations.map((org) => (
|
||||
<OrganizationEditor
|
||||
key={org.id + org.version}
|
||||
organization={org}
|
||||
countries={countries}
|
||||
/>
|
||||
))}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
function OrganizationEditor({
|
||||
organization,
|
||||
countries,
|
||||
}: {
|
||||
organization: Organization;
|
||||
countries: Country[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
version: organization.version,
|
||||
country: organization.country ?? '',
|
||||
source_reference: organization.provenance?.reference ?? '',
|
||||
});
|
||||
const id = useId();
|
||||
useEffect(() => {
|
||||
if (Object.keys(form.errors).length)
|
||||
document
|
||||
.getElementById(id)
|
||||
?.querySelector<HTMLElement>('[aria-invalid="true"]')
|
||||
?.focus();
|
||||
}, [form.errors, id]);
|
||||
return (
|
||||
<section
|
||||
className={card}
|
||||
aria-label={`Cadastro mestre: ${organization.name}`}
|
||||
>
|
||||
<h3 className="text-xl font-bold">{organization.name}</h3>
|
||||
<p>
|
||||
Versão {organization.version}; origem do país:{' '}
|
||||
{organization.provenance?.kind === 'representative_declaration'
|
||||
? 'declaração do representante'
|
||||
: 'não informada'}
|
||||
.
|
||||
</p>
|
||||
<form
|
||||
className="mt-4 space-y-4"
|
||||
id={id}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.put(
|
||||
`/investidor/organizations/${organization.id}/country`,
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field label="País de constituição da organização">
|
||||
<CountrySelect
|
||||
id={id + '-country'}
|
||||
label="País de constituição da organização"
|
||||
countries={countries}
|
||||
value={form.data.country}
|
||||
disabled={!organization.canEdit}
|
||||
error={form.errors.country}
|
||||
onChange={(country) => form.setData('country', country)}
|
||||
/>
|
||||
</Field>
|
||||
<label className="block" htmlFor={id + '-source'}>
|
||||
Fonte ou referência deste país
|
||||
</label>
|
||||
<textarea
|
||||
id={id + '-source'}
|
||||
className={input}
|
||||
value={form.data.source_reference}
|
||||
disabled={!organization.canEdit}
|
||||
maxLength={2000}
|
||||
aria-invalid={!!form.errors.source_reference}
|
||||
aria-describedby={
|
||||
form.errors.source_reference
|
||||
? id + '-source-error'
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
form.setData('source_reference', event.target.value)
|
||||
}
|
||||
/>
|
||||
{form.errors.source_reference && (
|
||||
<p id={id + '-source-error'} role="alert">
|
||||
{form.errors.source_reference}
|
||||
</p>
|
||||
)}
|
||||
{form.errors.version && (
|
||||
<p role="alert">{form.errors.version}</p>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={!organization.canEdit || form.processing}
|
||||
>
|
||||
Guardar país no cadastro mestre
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function Editor({
|
||||
record,
|
||||
fields,
|
||||
@@ -162,6 +346,8 @@ function Editor({
|
||||
<CountrySelect
|
||||
id={key + (record.id ?? 'account')}
|
||||
countries={countries}
|
||||
label={labels[key]}
|
||||
error={form.errors[`payload.${key}`]}
|
||||
value={form.data.payload[key]}
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
@@ -194,11 +380,12 @@ function Editor({
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{form.errors[`payload.${key}`] && (
|
||||
<p role="alert" className="text-red-700">
|
||||
{form.errors[`payload.${key}`]}
|
||||
</p>
|
||||
)}
|
||||
{!key.endsWith('_country_code') &&
|
||||
form.errors[`payload.${key}`] && (
|
||||
<p role="alert" className="text-red-700">
|
||||
{form.errors[`payload.${key}`]}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, Field, input, button, card } from './shared';
|
||||
@@ -12,6 +13,11 @@ type Payload = {
|
||||
country: string;
|
||||
residence_country_code: string;
|
||||
incorporation_country_code: string;
|
||||
organization_country_snapshot?: {
|
||||
organization_id: string;
|
||||
organization_version: number;
|
||||
country: string;
|
||||
};
|
||||
declared_origin_country_code: string;
|
||||
organisation: string;
|
||||
representative_role: string;
|
||||
@@ -212,7 +218,7 @@ function Editor({
|
||||
);
|
||||
else setNote('');
|
||||
}}
|
||||
value={String(form.data.payload[key] ?? '')}
|
||||
value={valueText(form.data.payload[key] ?? '')}
|
||||
onChange={(e) => update(key, e.target.value as never)}
|
||||
maxLength={key === 'objective' ? 5000 : 2000}
|
||||
/>
|
||||
@@ -236,8 +242,8 @@ function Editor({
|
||||
(o) =>
|
||||
o.group === group &&
|
||||
(o.active ||
|
||||
String(o.id) ===
|
||||
String(form.data.payload[key])),
|
||||
valueText(o.id) ===
|
||||
valueText(form.data.payload[key])),
|
||||
)
|
||||
.map((o) => (
|
||||
<option value={o.id} key={o.id} disabled={!o.active}>
|
||||
@@ -388,6 +394,17 @@ function Editor({
|
||||
<CountrySelect
|
||||
disabled={readonly}
|
||||
id={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]
|
||||
}
|
||||
error={form.errors[`payload.${key}`]}
|
||||
countries={countries}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(value) =>
|
||||
@@ -397,13 +414,32 @@ function Editor({
|
||||
})
|
||||
}
|
||||
/>
|
||||
{form.errors[`payload.${key}`] && (
|
||||
<p role="alert">
|
||||
{form.errors[`payload.${key}`]}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
{s.payload.organization_country_snapshot && (
|
||||
<p className="md:col-span-2">
|
||||
País copiado do{' '}
|
||||
<Link
|
||||
href="/investidor/profile"
|
||||
className="underline"
|
||||
>
|
||||
cadastro mestre da organização
|
||||
</Link>
|
||||
, versão{' '}
|
||||
{
|
||||
s.payload.organization_country_snapshot
|
||||
.organization_version
|
||||
}
|
||||
:{' '}
|
||||
{
|
||||
s.payload.organization_country_snapshot
|
||||
.country
|
||||
}
|
||||
. Esta cópia conserva a origem; alterações
|
||||
posteriores do cadastro não alteram esta
|
||||
manifestação.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
A origem da solicitação é uma declaração sua; não é
|
||||
deduzida da residência, da entidade ou do endereço
|
||||
@@ -535,8 +571,8 @@ function Editor({
|
||||
const category =
|
||||
r.options.find(
|
||||
(o) =>
|
||||
String(o.id) ===
|
||||
String(need.category_id),
|
||||
valueText(o.id) ===
|
||||
valueText(need.category_id),
|
||||
)?.code ?? '';
|
||||
const group = category.startsWith('labour')
|
||||
? 'labour'
|
||||
@@ -575,8 +611,8 @@ function Editor({
|
||||
(o) =>
|
||||
o.group === optionGroup &&
|
||||
(o.active ||
|
||||
String(o.id) ===
|
||||
String(
|
||||
valueText(o.id) ===
|
||||
valueText(
|
||||
need[field],
|
||||
)),
|
||||
)
|
||||
@@ -776,9 +812,9 @@ function Editor({
|
||||
['Prazo', form.data.payload.horizon],
|
||||
[
|
||||
'Necessidades',
|
||||
String(form.data.needs.length),
|
||||
valueText(form.data.needs.length),
|
||||
],
|
||||
['Anexos', String(attachments.length)],
|
||||
['Anexos', valueText(attachments.length)],
|
||||
].map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
@@ -813,7 +849,7 @@ function Editor({
|
||||
form.data.payload.partnership_id,
|
||||
]
|
||||
.map(String)
|
||||
.includes(String(o.id)),
|
||||
.includes(valueText(o.id)),
|
||||
) &&
|
||||
text(
|
||||
'other_details',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import type { LegacyArticle } from '@/pages/portal/legacy';
|
||||
@@ -16,7 +17,7 @@ export default function InvestmentContexts({
|
||||
contexts: InvestmentContext[];
|
||||
contentSource?: LegacyArticle;
|
||||
}) {
|
||||
const [key] = useState(() => globalThis.crypto.randomUUID());
|
||||
const [key] = useState(() => createOperationKey());
|
||||
const form = useForm({
|
||||
title: '',
|
||||
client_key: key,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
@@ -345,7 +346,7 @@ export default function InvestmentPath(path: Path) {
|
||||
consent: false,
|
||||
});
|
||||
const [service, setService] = useState(path.services[0]?.id ?? '');
|
||||
const [requestKey] = useState(() => crypto.randomUUID());
|
||||
const [requestKey] = useState(() => createOperationKey());
|
||||
const [taskReason, setTaskReason] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
function support() {
|
||||
@@ -356,7 +357,7 @@ export default function InvestmentPath(path: Path) {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<main className="mx-auto min-w-0 max-w-6xl space-y-6 p-4 [overflow-wrap:anywhere] [&_label]:min-w-0 [&_select]:min-w-0 [&_select]:max-w-full [&_input]:min-w-0 [&_input]:max-w-full md:p-8">
|
||||
<main className="mx-auto max-w-6xl min-w-0 space-y-6 p-4 [overflow-wrap:anywhere] md:p-8 [&_input]:max-w-full [&_input]:min-w-0 [&_label]:min-w-0 [&_select]:max-w-full [&_select]:min-w-0">
|
||||
<Head title={path.case.title} />
|
||||
<Link className="underline" href="/investimentos">
|
||||
Os meus investimentos
|
||||
@@ -618,7 +619,7 @@ export default function InvestmentPath(path: Path) {
|
||||
</h2>
|
||||
{path.canWrite && (
|
||||
<form
|
||||
className="grid min-w-0 gap-3 [&_label]:min-w-0 [&_select]:min-w-0 [&_select]:max-w-full [&_input]:min-w-0 [&_input]:max-w-full"
|
||||
className="grid min-w-0 gap-3 [&_input]:max-w-full [&_input]:min-w-0 [&_label]:min-w-0 [&_select]:max-w-full [&_select]:min-w-0"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
task.transform((data) => ({
|
||||
|
||||
@@ -20,6 +20,22 @@ const emptyParcel = (): Parcel => ({
|
||||
coordinates: '',
|
||||
geometry_confidence: 'unknown',
|
||||
});
|
||||
const requiredLabels: Record<string, string> = {
|
||||
support_kind: 'Pretende apoio para',
|
||||
request_description: 'Descrição do pedido',
|
||||
applicant_category: 'Categoria do requerente',
|
||||
full_name: 'Nome ou denominação',
|
||||
preferred_contact: 'Canal preferido',
|
||||
area_status: 'Situação da localização',
|
||||
purpose: 'Finalidade pretendida',
|
||||
email: 'Email',
|
||||
contact_person: 'Pessoa de contacto',
|
||||
representative_role: 'Função da representação',
|
||||
truth_declaration: 'Declaração de informação',
|
||||
contact_consent: 'Autorização de contacto',
|
||||
country: 'País do requerente',
|
||||
declared_origin_country_code: 'Origem declarada da solicitação',
|
||||
};
|
||||
const emptyPayload = (user: { name: string; email: string }): Payload => ({
|
||||
support_kind: '',
|
||||
request_description: '',
|
||||
@@ -98,6 +114,49 @@ export default function LandForm({
|
||||
[existing?.id],
|
||||
);
|
||||
const form = useForm({ version: existing?.version ?? 1, payload: initial });
|
||||
const [pendingErrorField, setPendingErrorField] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
useEffect(() => {
|
||||
const first = Object.keys(form.errors)[0];
|
||||
if (!first) return;
|
||||
const field = first.replace(/^payload\./, '').split('.')[0];
|
||||
const errorStep = [
|
||||
'truth_declaration',
|
||||
'contact_consent',
|
||||
'additional_information',
|
||||
].includes(field)
|
||||
? 3
|
||||
: ['exploration_plan', 'consultation'].includes(field)
|
||||
? 2
|
||||
: [
|
||||
'area_status',
|
||||
'parcels',
|
||||
'purpose',
|
||||
'activity',
|
||||
'known_occupants',
|
||||
'known_improvements',
|
||||
'prior_right_status',
|
||||
'conflict_status',
|
||||
'official_process',
|
||||
].includes(field)
|
||||
? 1
|
||||
: 0;
|
||||
setStep(errorStep);
|
||||
setPendingErrorField(field);
|
||||
}, [form.errors]);
|
||||
useEffect(() => {
|
||||
if (!pendingErrorField) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
const target =
|
||||
document.getElementById(`land-field-${pendingErrorField}`) ??
|
||||
document.getElementById('land-error-summary');
|
||||
target?.focus();
|
||||
target?.scrollIntoView({ block: 'center' });
|
||||
setPendingErrorField(null);
|
||||
}, 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [pendingErrorField, step]);
|
||||
const update = (field: string, value: unknown) =>
|
||||
form.setData('payload', { ...form.data.payload, [field]: value });
|
||||
const updateParcel = (index: number, key: string, value: unknown) => {
|
||||
@@ -118,18 +177,28 @@ export default function LandForm({
|
||||
{required ? ' *' : ''}
|
||||
</span>
|
||||
<input
|
||||
id={`land-field-${key}`}
|
||||
className="w-full rounded border p-2"
|
||||
type={type}
|
||||
required={required}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(event) => update(key, event.target.value)}
|
||||
aria-invalid={Boolean(form.errors[`payload.${key}`])}
|
||||
aria-describedby={
|
||||
form.errors[`payload.${key}`]
|
||||
? `land-error-${key}`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{help && (
|
||||
<span className="block text-xs text-slate-600">{help}</span>
|
||||
)}
|
||||
{form.errors[`payload.${key}`] && (
|
||||
<span role="alert" className="text-sm text-red-700">
|
||||
<span
|
||||
id={`land-error-${key}`}
|
||||
role="alert"
|
||||
className="text-sm text-red-700"
|
||||
>
|
||||
{form.errors[`payload.${key}`]}
|
||||
</span>
|
||||
)}
|
||||
@@ -209,6 +278,15 @@ export default function LandForm({
|
||||
Pretende apoio para *
|
||||
</span>
|
||||
<select
|
||||
id="land-field-support_kind"
|
||||
aria-invalid={Boolean(
|
||||
form.errors['payload.support_kind'],
|
||||
)}
|
||||
aria-describedby={
|
||||
form.errors['payload.support_kind']
|
||||
? 'land-error-support_kind'
|
||||
: undefined
|
||||
}
|
||||
className="w-full rounded border p-2"
|
||||
required
|
||||
value={current.support_kind ?? ''}
|
||||
@@ -226,6 +304,15 @@ export default function LandForm({
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{form.errors['payload.support_kind'] && (
|
||||
<p
|
||||
id="land-error-support_kind"
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{form.errors['payload.support_kind']}
|
||||
</p>
|
||||
)}
|
||||
{text('request_description', 'Descrição do pedido', true)}
|
||||
{text(
|
||||
'project_reference',
|
||||
@@ -238,6 +325,15 @@ export default function LandForm({
|
||||
<select
|
||||
className="w-full rounded border p-2"
|
||||
required
|
||||
id="land-field-applicant_category"
|
||||
aria-invalid={Boolean(
|
||||
form.errors['payload.applicant_category'],
|
||||
)}
|
||||
aria-describedby={
|
||||
form.errors['payload.applicant_category']
|
||||
? 'land-error-applicant_category'
|
||||
: undefined
|
||||
}
|
||||
value={current.applicant_category ?? ''}
|
||||
onChange={(event) =>
|
||||
update('applicant_category', event.target.value)
|
||||
@@ -250,6 +346,15 @@ export default function LandForm({
|
||||
<option value="other">Outra</option>
|
||||
</select>
|
||||
</label>
|
||||
{form.errors['payload.applicant_category'] && (
|
||||
<p
|
||||
id="land-error-applicant_category"
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{form.errors['payload.applicant_category']}
|
||||
</p>
|
||||
)}
|
||||
{text('full_name', 'Nome ou denominação', true)}
|
||||
{category === 'community' &&
|
||||
text(
|
||||
@@ -266,6 +371,15 @@ export default function LandForm({
|
||||
className="w-full rounded border p-2"
|
||||
required
|
||||
value={current.preferred_contact ?? ''}
|
||||
id="land-field-preferred_contact"
|
||||
aria-invalid={Boolean(
|
||||
form.errors['payload.preferred_contact'],
|
||||
)}
|
||||
aria-describedby={
|
||||
form.errors['payload.preferred_contact']
|
||||
? 'land-error-preferred_contact'
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
update('preferred_contact', event.target.value)
|
||||
}
|
||||
@@ -276,32 +390,46 @@ export default function LandForm({
|
||||
<option value="any">Qualquer um indicado</option>
|
||||
</select>
|
||||
</label>
|
||||
<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'
|
||||
]}
|
||||
{form.errors['payload.preferred_contact'] && (
|
||||
<p
|
||||
id="land-error-preferred_contact"
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{form.errors['payload.preferred_contact']}
|
||||
</p>
|
||||
)}
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
País do requerente (opcional)
|
||||
</p>
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={current.country ?? ''}
|
||||
onChange={(value) => update('country', value)}
|
||||
label="País do requerente (opcional)"
|
||||
error={form.errors['payload.country']}
|
||||
allowLegacyValue
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
País de origem declarado da solicitação (opcional)
|
||||
</p>
|
||||
<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)"
|
||||
error={
|
||||
form.errors[
|
||||
'payload.declared_origin_country_code'
|
||||
]
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{text('nationality', 'Nacionalidade, se aplicável')}
|
||||
{category === 'entity' && (
|
||||
<>
|
||||
@@ -339,6 +467,15 @@ export default function LandForm({
|
||||
className="w-full rounded border p-2"
|
||||
required
|
||||
value={current.area_status ?? ''}
|
||||
id="land-field-area_status"
|
||||
aria-invalid={Boolean(
|
||||
form.errors['payload.area_status'],
|
||||
)}
|
||||
aria-describedby={
|
||||
form.errors['payload.area_status']
|
||||
? 'land-error-area_status'
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
update('area_status', event.target.value)
|
||||
}
|
||||
@@ -356,6 +493,15 @@ export default function LandForm({
|
||||
<option value="unknown">Ainda não sei</option>
|
||||
</select>
|
||||
</label>
|
||||
{form.errors['payload.area_status'] && (
|
||||
<p
|
||||
id="land-error-area_status"
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{form.errors['payload.area_status']}
|
||||
</p>
|
||||
)}
|
||||
{current.area_status !== 'seeking' &&
|
||||
current.area_status !== 'unknown' &&
|
||||
(current.parcels ?? []).map(
|
||||
@@ -953,6 +1099,15 @@ export default function LandForm({
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="land-field-truth_declaration"
|
||||
aria-invalid={Boolean(
|
||||
form.errors['payload.truth_declaration'],
|
||||
)}
|
||||
aria-describedby={
|
||||
form.errors['payload.truth_declaration']
|
||||
? 'land-error-truth_declaration'
|
||||
: undefined
|
||||
}
|
||||
checked={Boolean(current.truth_declaration)}
|
||||
onChange={(e) =>
|
||||
update('truth_declaration', e.target.checked)
|
||||
@@ -961,9 +1116,27 @@ export default function LandForm({
|
||||
Confirmo que as respostas correspondem à informação de
|
||||
que disponho e assinalei dúvidas conhecidas.
|
||||
</label>
|
||||
{form.errors['payload.truth_declaration'] && (
|
||||
<p
|
||||
id="land-error-truth_declaration"
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{form.errors['payload.truth_declaration']}
|
||||
</p>
|
||||
)}
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="land-field-contact_consent"
|
||||
aria-invalid={Boolean(
|
||||
form.errors['payload.contact_consent'],
|
||||
)}
|
||||
aria-describedby={
|
||||
form.errors['payload.contact_consent']
|
||||
? 'land-error-contact_consent'
|
||||
: undefined
|
||||
}
|
||||
checked={Boolean(current.contact_consent)}
|
||||
onChange={(e) =>
|
||||
update('contact_consent', e.target.checked)
|
||||
@@ -972,6 +1145,15 @@ export default function LandForm({
|
||||
Autorizo o contacto para responder a este pedido. Esta
|
||||
autorização não permite publicação dos documentos.
|
||||
</label>
|
||||
{form.errors['payload.contact_consent'] && (
|
||||
<p
|
||||
id="land-error-contact_consent"
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{form.errors['payload.contact_consent']}
|
||||
</p>
|
||||
)}
|
||||
<p className="rounded bg-amber-50 p-3 text-sm">
|
||||
Ainda não carregue actas, documentos de identidade ou
|
||||
informações sensíveis que não sejam necessárias à
|
||||
@@ -1033,11 +1215,21 @@ export default function LandForm({
|
||||
</div>
|
||||
</footer>
|
||||
{Object.keys(form.errors).length > 0 && (
|
||||
<div role="alert" className="rounded border border-red-500 p-3">
|
||||
<div
|
||||
id="land-error-summary"
|
||||
tabIndex={-1}
|
||||
role="alert"
|
||||
className="rounded border border-red-500 p-3"
|
||||
>
|
||||
<p>Revise os campos assinalados antes de continuar.</p>
|
||||
<ul>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
<li key={key}>{String(value)}</li>
|
||||
<li key={key}>
|
||||
{requiredLabels[
|
||||
key.replace(/^payload\./, '')
|
||||
] ?? 'Campo assinalado'}
|
||||
: {String(value)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -9,26 +9,33 @@ type Props = {
|
||||
};
|
||||
disclaimer: string;
|
||||
modelVersion: string;
|
||||
country: { code: string | null; name: string };
|
||||
declaredOrigin: { code: string | null; name: string };
|
||||
};
|
||||
export default function PrintCase({
|
||||
case: record,
|
||||
disclaimer,
|
||||
modelVersion,
|
||||
country,
|
||||
declaredOrigin,
|
||||
}: Props) {
|
||||
const p = record.payload ?? {};
|
||||
const text = (value: unknown): string =>
|
||||
value === null || value === undefined || value === ''
|
||||
? '—'
|
||||
? '—'
|
||||
: Array.isArray(value)
|
||||
? value.map(text).join(', ')
|
||||
: typeof value === 'object'
|
||||
? Object.values(value as Record<string, unknown>)
|
||||
.map(text)
|
||||
.filter((x) => x !== '—')
|
||||
.join(' · ')
|
||||
.filter((x) => x !== '—')
|
||||
.join(' · ')
|
||||
: displayValue(value);
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl space-y-5 p-8 print:max-w-none print:p-0">
|
||||
<main
|
||||
data-land-print
|
||||
className="mx-auto max-w-4xl space-y-5 p-8 print:max-w-none print:p-0"
|
||||
>
|
||||
<div className="flex justify-end print:hidden">
|
||||
<button
|
||||
className="rounded border px-4 py-2"
|
||||
@@ -38,35 +45,49 @@ export default function PrintCase({
|
||||
</button>
|
||||
</div>
|
||||
<header className="space-y-2 border-b pb-4">
|
||||
<p>InvestMoz · modelo de preparação · {modelVersion}</p>
|
||||
<p>InvestMoz · modelo de preparação · {modelVersion}</p>
|
||||
<h1 className="text-2xl font-bold">
|
||||
Terra e DUAT — dados preenchidos pelo requerente
|
||||
Terra e DUAT — dados preenchidos pelo requerente
|
||||
</h1>
|
||||
<p>
|
||||
Referência interna: {record.reference} · versão{' '}
|
||||
{record.version} · actualizada em{' '}
|
||||
Referência interna: {record.reference} · versão{' '}
|
||||
{record.version} · actualizada em{' '}
|
||||
{new Date(record.updated_at).toLocaleString('pt-MZ')}
|
||||
</p>
|
||||
<p className="font-semibold">{disclaimer}</p>
|
||||
<p>
|
||||
Esta cópia reflecte os dados guardados no InvestMoz e não
|
||||
é requerimento oficialmente recebido, tÃtulo, parecer,
|
||||
prova de consulta ou decisão.
|
||||
Esta cópia reflecte os dados guardados no InvestMoz e não é
|
||||
requerimento oficialmente recebido, título, parecer, prova
|
||||
de consulta ou decisão.
|
||||
</p>
|
||||
</header>
|
||||
<Section title="A. Pedido e requerente">
|
||||
{[
|
||||
['Tipo de apoio', p.support_kind],
|
||||
['Descrição', p.request_description],
|
||||
['Descrição', p.request_description],
|
||||
['Projecto/oportunidade', p.project_reference],
|
||||
['Categoria', p.applicant_category],
|
||||
['Nome/denominação', p.full_name],
|
||||
['Nome/denominação', p.full_name],
|
||||
[
|
||||
'País do requerente',
|
||||
country.code
|
||||
? `${country.name} (${country.code})`
|
||||
: p.country
|
||||
? `${p.country} (valor anteriormente registado)`
|
||||
: country.name,
|
||||
],
|
||||
[
|
||||
'Origem declarada desta solicitação',
|
||||
declaredOrigin.code
|
||||
? `${declaredOrigin.name} (${declaredOrigin.code})`
|
||||
: declaredOrigin.name,
|
||||
],
|
||||
['Contacto', p.contact_person],
|
||||
['Email', p.email],
|
||||
['Telefone', p.phone],
|
||||
['Canal preferido', p.preferred_contact],
|
||||
[
|
||||
'Representante/função',
|
||||
'Representante/função',
|
||||
`${text(p.representative_name)} / ${text(p.representative_role)}`,
|
||||
],
|
||||
['NUIT (se informado)', p.nuit],
|
||||
@@ -78,26 +99,26 @@ export default function PrintCase({
|
||||
/>
|
||||
))}
|
||||
</Section>
|
||||
<Section title="B. Localização e situação declaradas">
|
||||
<Section title="B. Localização e situação declaradas">
|
||||
{[
|
||||
['Situação da localização', p.area_status],
|
||||
['Situação da localização', p.area_status],
|
||||
['Uso pretendido', p.purpose],
|
||||
['Actividade', p.activity],
|
||||
[
|
||||
'Ocupantes/utilizações',
|
||||
`${text(p.known_occupants)} — ${text(p.occupant_description)}`,
|
||||
'Ocupantes/utilizações',
|
||||
`${text(p.known_occupants)} — ${text(p.occupant_description)}`,
|
||||
],
|
||||
[
|
||||
'Benfeitorias/usos',
|
||||
`${text(p.known_improvements)} — ${text(p.improvements_description)}`,
|
||||
`${text(p.known_improvements)} — ${text(p.improvements_description)}`,
|
||||
],
|
||||
[
|
||||
'Antecedentes',
|
||||
`${text(p.prior_right_status)} — ${text(p.prior_right_description)}`,
|
||||
`${text(p.prior_right_status)} — ${text(p.prior_right_description)}`,
|
||||
],
|
||||
[
|
||||
'Conflito comunicado',
|
||||
`${text(p.conflict_status)} — ${text(p.conflict_description)}`,
|
||||
`${text(p.conflict_status)} — ${text(p.conflict_description)}`,
|
||||
],
|
||||
].map(([label, value]) => (
|
||||
<Field
|
||||
@@ -107,35 +128,35 @@ export default function PrintCase({
|
||||
/>
|
||||
))}
|
||||
</Section>
|
||||
<Section title="Parcelas (declarações do requerente)">
|
||||
<Section title="Parcelas (declarações do requerente)">
|
||||
{(p.parcels ?? []).map((parcel: any, index: number) => (
|
||||
<article key={index} className="space-y-1 border-b pb-3">
|
||||
<h3 className="font-semibold">Parcela {index + 1}</h3>
|
||||
<p>{text(parcel.place_description)}</p>
|
||||
<p>
|
||||
Ãrea: {text(parcel.area)} {text(parcel.area_unit)}{' '}
|
||||
· Referência: {text(parcel.cadastral_reference)}
|
||||
Área: {text(parcel.area)} {text(parcel.area_unit)} ·
|
||||
Referência: {text(parcel.cadastral_reference)}
|
||||
</p>
|
||||
<p>
|
||||
Coordenadas/planta: {text(parcel.coordinates)} ·
|
||||
Precisão indicada:{' '}
|
||||
Coordenadas/planta: {text(parcel.coordinates)} ·
|
||||
Precisão indicada:{' '}
|
||||
{text(parcel.geometry_confidence)}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
A selecção no catálogo não verifica
|
||||
titularidade, limites ou disponibilidade.
|
||||
A selecção no catálogo não verifica titularidade,
|
||||
limites ou disponibilidade.
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</Section>
|
||||
<Section title="C. Processo externo indicado pelo requerente">
|
||||
{[
|
||||
['Número', p.official_process?.official_reference],
|
||||
['Número', p.official_process?.official_reference],
|
||||
['Entidade', p.official_process?.receiving_entity],
|
||||
['Data indicada', p.official_process?.presented_at],
|
||||
['Estado comunicado', p.official_process?.reported_status],
|
||||
[
|
||||
'Pendências comunicadas',
|
||||
'Pendências comunicadas',
|
||||
p.official_process?.pending_items,
|
||||
],
|
||||
].map(([label, value]) => (
|
||||
@@ -146,7 +167,7 @@ export default function PrintCase({
|
||||
/>
|
||||
))}
|
||||
</Section>
|
||||
<Section title="D. Plano de exploração facultativo">
|
||||
<Section title="D. Plano de exploração facultativo">
|
||||
{(p.exploration_plan?.activity_rows ?? []).length === 0 ? (
|
||||
<p>Sem linhas fornecidas.</p>
|
||||
) : (
|
||||
@@ -154,14 +175,14 @@ export default function PrintCase({
|
||||
(row: any, index: number) => (
|
||||
<article key={index} className="border-b pb-2">
|
||||
<p>
|
||||
<strong>{text(row.activity)}</strong> ·
|
||||
perÃodo {text(row.period)} ·{' '}
|
||||
<strong>{text(row.activity)}</strong> ·
|
||||
período {text(row.period)} ·{' '}
|
||||
{text(row.stage)}
|
||||
</p>
|
||||
<p>
|
||||
Ãrea {text(row.area)} {text(row.area_unit)}{' '}
|
||||
· metas: {text(row.targets)} · estruturas:{' '}
|
||||
{text(row.structures)} · investimento
|
||||
Área {text(row.area)} {text(row.area_unit)}{' '}
|
||||
· metas: {text(row.targets)} · estruturas:{' '}
|
||||
{text(row.structures)} · investimento
|
||||
declarado: {text(row.investment)}
|
||||
</p>
|
||||
</article>
|
||||
@@ -170,7 +191,7 @@ export default function PrintCase({
|
||||
)}
|
||||
<Field label="Notas" value={text(p.exploration_plan?.notes)} />
|
||||
</Section>
|
||||
<Section title="E. Consulta — preparação/informação indicada">
|
||||
<Section title="E. Consulta — preparação/informação indicada">
|
||||
{[
|
||||
['Estado', p.consultation?.status],
|
||||
[
|
||||
@@ -183,7 +204,7 @@ export default function PrintCase({
|
||||
.map(text)
|
||||
.join(' / '),
|
||||
],
|
||||
['LÃngua/tradução', p.consultation?.language],
|
||||
['Língua/tradução', p.consultation?.language],
|
||||
[
|
||||
'Participantes',
|
||||
(p.consultation?.participants ?? [])
|
||||
@@ -192,8 +213,8 @@ export default function PrintCase({
|
||||
)
|
||||
.join('; '),
|
||||
],
|
||||
['Intervenções', p.consultation?.interventions],
|
||||
['Divergências/oposição', p.consultation?.opposition],
|
||||
['Intervenções', p.consultation?.interventions],
|
||||
['Divergências/oposição', p.consultation?.opposition],
|
||||
['Acordos comunicados', p.consultation?.agreements],
|
||||
[
|
||||
'Acta/pareceres referidos',
|
||||
@@ -212,19 +233,19 @@ export default function PrintCase({
|
||||
/>
|
||||
))}
|
||||
</Section>
|
||||
<Section title="F. Informação complementar">
|
||||
<Section title="F. Informação complementar">
|
||||
<p>{text(p.additional_information)}</p>
|
||||
</Section>
|
||||
<footer className="space-y-2 border-t pt-4">
|
||||
<p>
|
||||
Gerado a partir dos dados guardados; sem assinatura
|
||||
electrónica ou validação de terceiros.
|
||||
electrónica ou validação de terceiros.
|
||||
</p>
|
||||
<p className="font-semibold">{disclaimer}</p>
|
||||
</footer>
|
||||
<style>
|
||||
{
|
||||
'@media print { button { display: none } section { break-inside: avoid } }'
|
||||
'@media print { main[data-land-print] { font-size: 11pt; line-height: 1.4; } main[data-land-print] button { display: none } main[data-land-print] section { break-inside: auto; box-shadow: none; } main[data-land-print] section > div, main[data-land-print] footer { break-inside: avoid; } main[data-land-print] h2, main[data-land-print] h3 { break-after: avoid; } }'
|
||||
}
|
||||
</style>
|
||||
</main>
|
||||
|
||||
@@ -23,6 +23,7 @@ type Interest = {
|
||||
reviewed_at: string | null;
|
||||
reviewed_by: number | null;
|
||||
created_at: string;
|
||||
source_page: string | null;
|
||||
metadata?: {
|
||||
submission_id?: string;
|
||||
journey_id?: string;
|
||||
@@ -83,6 +84,7 @@ export default function InterestDetail({
|
||||
['Telefone', interest.phone],
|
||||
['Tipo de investidor', interest.investor_type],
|
||||
['País', interest.country],
|
||||
['Página de entrada registada', interest.source_page],
|
||||
[
|
||||
'Origem declarada da solicitação',
|
||||
declaredOrigin.code
|
||||
|
||||
@@ -81,10 +81,14 @@ export default function Opportunities({
|
||||
{[
|
||||
'draft',
|
||||
'submitted',
|
||||
'needs_information',
|
||||
'in_review',
|
||||
'information_pending',
|
||||
'returned',
|
||||
'approved',
|
||||
'published',
|
||||
'suspended',
|
||||
'rejected',
|
||||
'archived',
|
||||
].map((s) => (
|
||||
<Link
|
||||
@@ -100,6 +104,10 @@ export default function Opportunities({
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
deleted: data.deleted ? '1' : '0',
|
||||
}));
|
||||
form.get(basePath);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import OpportunityProfileActions from '@/components/opportunity-profile-actions';
|
||||
import OpportunityContactForm from '@/components/opportunity-contact-form';
|
||||
import OpportunityCanonicalFields, {
|
||||
type CanonicalOptions,
|
||||
} from '@/components/opportunity-canonical-fields';
|
||||
@@ -64,6 +67,7 @@ export default function OpportunityDraft({
|
||||
profileActions = [],
|
||||
canonicalOptions,
|
||||
workflowState,
|
||||
canonicalResponse,
|
||||
workflowTasks = [],
|
||||
workflowParticipants,
|
||||
publicationPreview,
|
||||
@@ -77,7 +81,12 @@ export default function OpportunityDraft({
|
||||
profileActions?: string[];
|
||||
profileContext?: Record<string, unknown> | null;
|
||||
profileAccess?: {
|
||||
contexts: { organization_id: string | null; type: string }[];
|
||||
internalPromoter?: boolean;
|
||||
contexts: {
|
||||
organization_id: string | null;
|
||||
organization_name?: string;
|
||||
type: string;
|
||||
}[];
|
||||
} | null;
|
||||
publicationPreview?: {
|
||||
title: string;
|
||||
@@ -85,6 +94,7 @@ export default function OpportunityDraft({
|
||||
description: string;
|
||||
};
|
||||
workflowParticipants?: {
|
||||
condition_responsibles?: { id: number; name: string }[];
|
||||
publishers: { id: number; name: string }[];
|
||||
validators: {
|
||||
id: number;
|
||||
@@ -95,6 +105,15 @@ export default function OpportunityDraft({
|
||||
};
|
||||
canonicalOptions?: CanonicalOptions;
|
||||
workflowState?: string;
|
||||
canonicalResponse?: {
|
||||
completion: {
|
||||
percentage: number;
|
||||
filled: number;
|
||||
applicable: number;
|
||||
missing_paths: string[];
|
||||
};
|
||||
materiality?: { reopened: string[]; retained: string[] } | null;
|
||||
};
|
||||
publicationState?: {
|
||||
scope: string;
|
||||
label: string;
|
||||
@@ -116,14 +135,16 @@ export default function OpportunityDraft({
|
||||
? {
|
||||
organization_id: record
|
||||
? (profileOrganization ?? null)
|
||||
: (profileAccess?.contexts[0]?.organization_id ?? null),
|
||||
: profileAccess?.internalPromoter
|
||||
? null
|
||||
: (profileAccess?.contexts[0]?.organization_id ?? null),
|
||||
opportunity_category:
|
||||
values.opportunity_category ??
|
||||
profileAccess?.contexts[0]?.type ??
|
||||
'',
|
||||
}
|
||||
: {}),
|
||||
creation_key: crypto.randomUUID(),
|
||||
creation_key: createOperationKey(),
|
||||
});
|
||||
const [busy, setBusy] = useState(false),
|
||||
[errors, setErrors] = useState<Record<string, string>>({}),
|
||||
@@ -132,6 +153,9 @@ export default function OpportunityDraft({
|
||||
[confirm, setConfirm] = useState(false),
|
||||
[token, setToken] = useState(etag);
|
||||
useEffect(() => setToken(etag), [etag]);
|
||||
const [savedContacts, setSavedContacts] = useState<
|
||||
{ id: string; full_name: string }[]
|
||||
>([]);
|
||||
const [path, setPath] = useState(territoryPath);
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
@@ -175,7 +199,7 @@ 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(' ') : valueText(v),
|
||||
]),
|
||||
),
|
||||
);
|
||||
@@ -211,6 +235,42 @@ export default function OpportunityDraft({
|
||||
<Link href={basePath}>
|
||||
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'}
|
||||
</Link>
|
||||
{profileMode && (
|
||||
<section
|
||||
aria-label="Âmbito desta entrega"
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<h2>Âmbito desta entrega</h2>
|
||||
<p>
|
||||
Seis categorias base: projeto de investimento,
|
||||
imobiliário, fundiário, venda de negócio, parceria e
|
||||
franquia. Rascunho, correção, revisão independente e
|
||||
publicação são ações distintas; uma aprovação interna
|
||||
não atribui direitos nem substitui uma decisão externa.
|
||||
</p>
|
||||
<p>
|
||||
No imobiliário, a submissão inclui venda e arrendamento
|
||||
de imóvel concluído, desocupado e sem encargos ou
|
||||
limitações urbanísticas adicionais. Pode guardar e
|
||||
recuperar as outras variantes em preparação; a sua
|
||||
submissão permanece indisponível.
|
||||
</p>
|
||||
<p>
|
||||
Concessão, financiamento, fornecimento e outros,
|
||||
partilha individual de anexos, restauração de
|
||||
oportunidades e exportação normativa integral
|
||||
Response/§27 não estão incluídos. O Response disponível
|
||||
conserva o contrato de compatibilidade e o histórico.
|
||||
</p>
|
||||
<p>
|
||||
As restantes variantes económicas, societárias,
|
||||
territoriais, de contribuições e licenças exigem
|
||||
documentação e revisão aplicáveis. Esta entrega não
|
||||
certifica a viabilidade, a titularidade ou a decisão
|
||||
externa de cada caso.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && readOnly && canEditDraft && (
|
||||
<Link
|
||||
className="block underline"
|
||||
@@ -221,10 +281,11 @@ export default function OpportunityDraft({
|
||||
)}
|
||||
{profileMode && !record && (
|
||||
<label className="block">
|
||||
Organização e tipo autorizados
|
||||
Promotor real e categoria autorizada
|
||||
<select
|
||||
aria-label="Promotor real e categoria autorizada"
|
||||
className={control}
|
||||
value={`${String(data.organization_id ?? '')}|${String(data.opportunity_category ?? '')}`}
|
||||
value={`${valueText(data.organization_id ?? '')}|${valueText(data.opportunity_category ?? '')}`}
|
||||
onChange={(e) => {
|
||||
const [organization, type] =
|
||||
e.target.value.split('|');
|
||||
@@ -235,27 +296,57 @@ export default function OpportunityDraft({
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{profileAccess?.internalPromoter && (
|
||||
<option value="">
|
||||
Selecionar o promotor real da oportunidade
|
||||
</option>
|
||||
)}
|
||||
{(profileAccess?.contexts ?? []).map((c) => (
|
||||
<option
|
||||
key={`${c.organization_id}|${c.type}`}
|
||||
value={`${c.organization_id ?? ''}|${c.type}`}
|
||||
>
|
||||
{c.organization_id ?? 'Âmbito individual'} —{' '}
|
||||
{c.type}
|
||||
{c.organization_name ??
|
||||
c.organization_id ??
|
||||
'Âmbito individual'}{' '}
|
||||
— {c.type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<p>
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label="Estado da oportunidade"
|
||||
>
|
||||
Estado da preparação:{' '}
|
||||
{(workflowState ?? record.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[workflowState ?? record.status] ??
|
||||
: ((
|
||||
{
|
||||
draft: 'Rascunho',
|
||||
submitted: 'Submetida para validação',
|
||||
needs_information: 'Correções solicitadas',
|
||||
information_pending: 'Aguarda parecer',
|
||||
in_review: 'Em validação interna',
|
||||
approved: 'Aprovada internamente',
|
||||
rejected: 'Rejeitada',
|
||||
suspended: 'Suspensa',
|
||||
archived: 'Arquivada',
|
||||
} as Record<string, string>
|
||||
)[workflowState ?? record.status] ??
|
||||
states[workflowState ?? record.status] ??
|
||||
workflowState ??
|
||||
record.status)}
|
||||
. {publicationState?.label}.{' '}
|
||||
{profileContext?.review_cycle != null && (
|
||||
<>
|
||||
Ciclo de revisão interna:{' '}
|
||||
{valueText(profileContext.review_cycle)}.{' '}
|
||||
</>
|
||||
)}
|
||||
{profileContext?.request_archive
|
||||
? 'Pedido de arquivo registado; aguarda decisão independente.'
|
||||
: ''}{' '}
|
||||
@@ -264,8 +355,15 @@ export default function OpportunityDraft({
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Classificação de origem: {classification}. Esta classificação
|
||||
não cria associações territoriais.
|
||||
Classificação de origem:{' '}
|
||||
{(
|
||||
{
|
||||
real: 'Oportunidade real',
|
||||
example: 'Exemplo demonstrativo',
|
||||
undetermined: 'Origem ainda indeterminada',
|
||||
} as Record<string, string>
|
||||
)[classification] ?? classification}
|
||||
. Esta classificação não cria associações territoriais.
|
||||
</p>
|
||||
{closedVersion && (
|
||||
<p>
|
||||
@@ -275,6 +373,47 @@ export default function OpportunityDraft({
|
||||
revisão, aprovação e publicação independentes.
|
||||
</p>
|
||||
)}
|
||||
{profileMode && record && canonicalResponse && (
|
||||
<section
|
||||
aria-label="Preenchimento e revisões"
|
||||
aria-live="polite"
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
Preenchimento gravado:{' '}
|
||||
{canonicalResponse.completion.percentage}% (
|
||||
{canonicalResponse.completion.filled}/
|
||||
{canonicalResponse.completion.applicable} campos
|
||||
aplicáveis). Não equivale a validação ou aprovação.
|
||||
</p>
|
||||
{canonicalResponse.materiality && (
|
||||
<>
|
||||
<p>
|
||||
Revisões reabertas:{' '}
|
||||
{canonicalResponse.materiality.reopened.join(
|
||||
', ',
|
||||
) || 'Nenhuma'}
|
||||
.
|
||||
</p>
|
||||
<p>
|
||||
Revisões conservadas:{' '}
|
||||
{canonicalResponse.materiality.retained.join(
|
||||
', ',
|
||||
) || 'Nenhuma'}
|
||||
.
|
||||
</p>
|
||||
<p>
|
||||
A versão alterada exige nova aprovação
|
||||
independente; as assinaturas dos pareceres
|
||||
conservados permanecem no histórico.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<a href={`${basePath}/${record.id}/response`}>
|
||||
Abrir resposta canónica gravada
|
||||
</a>
|
||||
</section>
|
||||
)}
|
||||
<div
|
||||
id="opportunity-result"
|
||||
tabIndex={-1}
|
||||
@@ -364,7 +503,9 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.opportunity_category ?? '')}
|
||||
value={valueText(
|
||||
data.opportunity_category ?? '',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set('opportunity_category', e.target.value)
|
||||
}
|
||||
@@ -385,7 +526,7 @@ export default function OpportunityDraft({
|
||||
{key === 'description' || key === 'summary' ? (
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
value={valueText(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value)
|
||||
}
|
||||
@@ -393,7 +534,7 @@ export default function OpportunityDraft({
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
value={valueText(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value)
|
||||
}
|
||||
@@ -404,7 +545,7 @@ export default function OpportunityDraft({
|
||||
<Field label="Sector" error={errors.sector_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.sector_id ?? '')}
|
||||
value={valueText(data.sector_id ?? '')}
|
||||
onChange={(e) =>
|
||||
set('sector_id', e.target.value)
|
||||
}
|
||||
@@ -423,7 +564,7 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.promoter_type ?? '')}
|
||||
value={valueText(data.promoter_type ?? '')}
|
||||
onChange={(e) =>
|
||||
set('promoter_type', e.target.value)
|
||||
}
|
||||
@@ -439,12 +580,14 @@ export default function OpportunityDraft({
|
||||
'community',
|
||||
'other',
|
||||
].includes(
|
||||
String(values.promoter_type),
|
||||
valueText(values.promoter_type),
|
||||
) && (
|
||||
<option
|
||||
value={String(values.promoter_type)}
|
||||
value={valueText(
|
||||
values.promoter_type,
|
||||
)}
|
||||
>
|
||||
{String(values.promoter_type)}{' '}
|
||||
{valueText(values.promoter_type)}{' '}
|
||||
(valor existente)
|
||||
</option>
|
||||
)}
|
||||
@@ -472,9 +615,9 @@ export default function OpportunityDraft({
|
||||
value={
|
||||
data.maturity_catalogue_version ===
|
||||
maturityCatalogue.version
|
||||
? String(data.maturity_stage ?? '')
|
||||
? valueText(data.maturity_stage ?? '')
|
||||
: data.maturity_level
|
||||
? `legacy:${data.maturity_level}`
|
||||
? `legacy:${valueText(data.maturity_level)}`
|
||||
: ''
|
||||
}
|
||||
onChange={(e) => {
|
||||
@@ -509,11 +652,11 @@ export default function OpportunityDraft({
|
||||
values.maturity_catalogue_version !==
|
||||
maturityCatalogue.version && (
|
||||
<option
|
||||
value={`legacy:${values.maturity_level}`}
|
||||
value={`legacy:${valueText(values.maturity_level)}`}
|
||||
>
|
||||
{
|
||||
maturityCatalogue.legacyLabels[
|
||||
String(
|
||||
valueText(
|
||||
values.maturity_level,
|
||||
)
|
||||
]
|
||||
@@ -541,7 +684,7 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(data.financing_modality ?? '')}
|
||||
value={valueText(data.financing_modality ?? '')}
|
||||
onChange={(e) =>
|
||||
set('financing_modality', e.target.value)
|
||||
}
|
||||
@@ -553,7 +696,7 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data.expected_impact ?? '')}
|
||||
value={valueText(data.expected_impact ?? '')}
|
||||
onChange={(e) =>
|
||||
set('expected_impact', e.target.value)
|
||||
}
|
||||
@@ -569,7 +712,7 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(
|
||||
value={valueText(
|
||||
data.estimated_investment_amount ??
|
||||
'',
|
||||
)}
|
||||
@@ -587,7 +730,7 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(
|
||||
value={valueText(
|
||||
data.estimated_investment_currency ??
|
||||
'',
|
||||
)}
|
||||
@@ -712,6 +855,35 @@ export default function OpportunityDraft({
|
||||
)}
|
||||
{profileMode && canonicalOptions && (
|
||||
<section>
|
||||
{record && !readOnly && !unavailable && (
|
||||
<OpportunityContactForm
|
||||
id={record.id}
|
||||
etag={token ?? ''}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
investors={canonicalOptions.contactInvestors ?? []}
|
||||
disabled={busy || !token}
|
||||
onSaved={(contact) => {
|
||||
setSavedContacts((prior) => [
|
||||
...prior.filter(
|
||||
(row) => row.id !== contact.id,
|
||||
),
|
||||
contact,
|
||||
]);
|
||||
setData((prior) => ({
|
||||
...prior,
|
||||
canonical: {
|
||||
...((prior.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>) ?? {}),
|
||||
internal_contact_id: contact.id,
|
||||
},
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
(data.canonical ?? {}) as Record<string, unknown>
|
||||
@@ -719,9 +891,20 @@ export default function OpportunityDraft({
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, canonical: v }))
|
||||
}
|
||||
options={canonicalOptions}
|
||||
options={{
|
||||
...canonicalOptions,
|
||||
contacts: [
|
||||
...canonicalOptions.contacts.filter(
|
||||
(row) =>
|
||||
!savedContacts.some(
|
||||
(saved) => saved.id === row.id,
|
||||
),
|
||||
),
|
||||
...savedContacts,
|
||||
],
|
||||
}}
|
||||
errors={errors}
|
||||
category={String(data.opportunity_category ?? '')}
|
||||
category={valueText(data.opportunity_category ?? '')}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
@@ -770,6 +953,20 @@ export default function OpportunityDraft({
|
||||
)}
|
||||
{profileMode && record && etag && (
|
||||
<OpportunityProfileActions
|
||||
conditions={
|
||||
Object.values(profileContext?.conditions ?? {}) as {
|
||||
id: string;
|
||||
gate: string;
|
||||
description: string;
|
||||
responsible_name: string;
|
||||
due_on: string | null;
|
||||
blocking_action: string;
|
||||
status: string;
|
||||
}[]
|
||||
}
|
||||
conditionResponsibles={
|
||||
workflowParticipants?.condition_responsibles
|
||||
}
|
||||
participants={workflowParticipants?.validators}
|
||||
publishers={workflowParticipants?.publishers}
|
||||
opinions={Object.values(
|
||||
@@ -787,7 +984,7 @@ export default function OpportunityDraft({
|
||||
id={record.id}
|
||||
etag={token ?? etag}
|
||||
actions={profileActions}
|
||||
publicationVisibility={String(
|
||||
publicationVisibility={valueText(
|
||||
(data.canonical as Record<string, unknown> | undefined)
|
||||
?.visibility ?? 'internal',
|
||||
)}
|
||||
|
||||
@@ -11,6 +11,8 @@ export default function Install({
|
||||
rollback,
|
||||
actionUrl = '/management/opportunity-management-install',
|
||||
imageProcessingAvailable,
|
||||
extension = false,
|
||||
operationKey,
|
||||
}: {
|
||||
installed: boolean;
|
||||
ready: boolean;
|
||||
@@ -22,10 +24,23 @@ export default function Install({
|
||||
rollback: string;
|
||||
actionUrl?: string;
|
||||
imageProcessingAvailable?: boolean;
|
||||
extension?: boolean;
|
||||
operationKey?: string;
|
||||
}) {
|
||||
const form = useForm({ hash, confirm: false });
|
||||
const form = useForm({
|
||||
hash,
|
||||
confirm: false,
|
||||
idempotency_key: operationKey ?? '',
|
||||
reason: '',
|
||||
});
|
||||
return (
|
||||
<Management title="Ativação da Gestão de Oportunidades">
|
||||
<Management
|
||||
title={
|
||||
migration.endsWith('extend_organization_country')
|
||||
? 'Instalação do país de constituição'
|
||||
: 'Ativação da Gestão de Oportunidades'
|
||||
}
|
||||
>
|
||||
<p>
|
||||
Base: {target.database}:{target.port} ·{' '}
|
||||
{installed ? 'Instalado' : 'Ainda não aplicado'}
|
||||
@@ -77,17 +92,40 @@ export default function Install({
|
||||
/>{' '}
|
||||
Confirmo a aplicação deste plano
|
||||
</label>
|
||||
{extension && (
|
||||
<div>
|
||||
<label htmlFor="installation-reason" className="block">
|
||||
Fundamentação da instalação
|
||||
</label>
|
||||
<textarea
|
||||
id="installation-reason"
|
||||
value={form.data.reason}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
required
|
||||
onChange={(event) =>
|
||||
form.setData('reason', event.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
installed ||
|
||||
!ready ||
|
||||
!form.data.confirm ||
|
||||
(extension && !operationKey) ||
|
||||
form.processing
|
||||
}
|
||||
>
|
||||
Aplicar plano de gestão
|
||||
{migration.endsWith('extend_organization_country')
|
||||
? 'Aplicar extensão do país'
|
||||
: 'Aplicar plano de gestão'}
|
||||
</button>
|
||||
{extension && !operationKey && (
|
||||
<p role="alert">Atualize a prévia para obter a chave desta operação.</p>
|
||||
)}
|
||||
{!ready && (
|
||||
<p>
|
||||
Aplicação indisponível até comprovar QA,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState } from 'react';
|
||||
@@ -144,26 +146,39 @@ export default function OpportunityResources({
|
||||
assessment: string[];
|
||||
imageProcessingAvailable: boolean;
|
||||
}) {
|
||||
const { basePath = '/management/opportunities', readOnly = false, countries = [] } = usePage<{basePath?: string; readOnly?: boolean; countries?: {code:string;name:string}[]}>().props;
|
||||
const {
|
||||
basePath = '/management/opportunities',
|
||||
readOnly = false,
|
||||
countries = [],
|
||||
} = usePage<{
|
||||
basePath?: string;
|
||||
readOnly?: boolean;
|
||||
countries?: { code: string; name: string }[];
|
||||
}>().props;
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({country_code:'MZ'});
|
||||
const [payload, setPayload] = useState<Payload>({ country_code: 'MZ' });
|
||||
const [path, setPath] = useState<TerritoryOption[]>([]);
|
||||
const [geometry, setGeometry] = useState('');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [key, setKey] = useState(() => crypto.randomUUID());
|
||||
const [key, setKey] = useState(() => createOperationKey());
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const foreignCountry = Boolean(payload.country_code && payload.country_code !== 'MZ');
|
||||
const foreignCountry = Boolean(
|
||||
payload.country_code && payload.country_code !== 'MZ',
|
||||
);
|
||||
const set = (name: string, value: Payload[string]) =>
|
||||
setPayload((previous) => ({ ...previous, [name]: value }));
|
||||
function select(nextKind: Kind, record: Resource | null = null) {
|
||||
setKind(nextKind);
|
||||
setEditing(record);
|
||||
setPayload(record?.payload ?? (nextKind === 'locations' ? {country_code:'MZ'} : {}));
|
||||
setPayload(
|
||||
record?.payload ??
|
||||
(nextKind === 'locations' ? { country_code: 'MZ' } : {}),
|
||||
);
|
||||
setPath(record?.territoryPath ?? []);
|
||||
setGeometry(
|
||||
record?.payload.geometry
|
||||
@@ -171,7 +186,7 @@ export default function OpportunityResources({
|
||||
: '',
|
||||
);
|
||||
setFile(null);
|
||||
setKey(crypto.randomUUID());
|
||||
setKey(createOperationKey());
|
||||
setConfirm(false);
|
||||
setErrors({});
|
||||
}
|
||||
@@ -185,7 +200,7 @@ export default function OpportunityResources({
|
||||
form.set('etag', etag);
|
||||
form.set('reason', reason);
|
||||
form.set('creation_key', key);
|
||||
if (editing) form.set('version', String(editing.version));
|
||||
if (editing) form.set('version', valueText(editing.version));
|
||||
if (action === 'save') {
|
||||
const values = { ...payload };
|
||||
if (kind === 'locations') {
|
||||
@@ -231,7 +246,7 @@ export default function OpportunityResources({
|
||||
name,
|
||||
Array.isArray(value)
|
||||
? value.join(' ')
|
||||
: String(value),
|
||||
: valueText(value),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -240,11 +255,11 @@ export default function OpportunityResources({
|
||||
}
|
||||
setMessage(data.message);
|
||||
setEditing(null);
|
||||
setPayload(kind === 'locations' ? {country_code:'MZ'} : {});
|
||||
setPayload(kind === 'locations' ? { country_code: 'MZ' } : {});
|
||||
setPath([]);
|
||||
setGeometry('');
|
||||
setFile(null);
|
||||
setKey(crypto.randomUUID());
|
||||
setKey(createOperationKey());
|
||||
setConfirm(false);
|
||||
router.reload({
|
||||
onFinish: () =>
|
||||
@@ -273,9 +288,9 @@ export default function OpportunityResources({
|
||||
</Link>
|
||||
<p>
|
||||
Recursos de preparação. Não alteram automaticamente a ficha
|
||||
pública ou relações territoriais aceites. O estado e o motor
|
||||
do scan são apresentados por ficheiro e versão; um scan
|
||||
simulado nunca verifica ficheiros reais.
|
||||
pública ou relações territoriais aceites. O estado e o motor do
|
||||
scan são apresentados por ficheiro e versão; um scan simulado
|
||||
nunca verifica ficheiros reais.
|
||||
</p>
|
||||
<div
|
||||
id="resource-result"
|
||||
@@ -302,10 +317,18 @@ export default function OpportunityResources({
|
||||
<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. Guardar metadados, locais ou rascunhos
|
||||
é independente do scan e não publica ficheiros.
|
||||
estiver concluído. Guardar metadados, locais ou rascunhos é
|
||||
independente do scan e não publica ficheiros.
|
||||
</p>
|
||||
)}
|
||||
{kind !== 'locations' && (
|
||||
<section aria-label="Privacidade dos anexos" className="rounded border p-3">
|
||||
<h2>Privacidade dos anexos</h2>
|
||||
<p>Os anexos pertencem à oportunidade. Podem ser consultados pelos Promotores autorizados da organização, pelos Validadores e Publicadores com acesso ao tipo e âmbito e pelos Auditores autorizados. O Superutilizador precisa também de perfil operacional no âmbito e de elevação temporária para consulta, aprovada por outro titular. O gestor da biblioteca, por si só, não obtém esse acesso.</p>
|
||||
<p>Classificação e âmbito de consulta são metadados; escolher «public» ou «authenticated» não divulga o ficheiro. Publicar o anúncio não publica os anexos. A retirada lógica impede a entrega do ficheiro; a revogação do perfil impede acessos futuros.</p>
|
||||
<p>Partilhar um anexo com um destinatário individual ou restringi-lo a alguns membros da organização permanece indisponível. Não guarde neste fluxo um ficheiro que exija essa restrição individual. Não é possível retirar cópias já descarregadas.</p>
|
||||
</section>
|
||||
)}
|
||||
<section>
|
||||
<h2>Conferência e pendências</h2>
|
||||
<ul>
|
||||
@@ -329,7 +352,7 @@ export default function OpportunityResources({
|
||||
<button
|
||||
className={button}
|
||||
key={k}
|
||||
disabled={busy || readOnly}
|
||||
disabled={busy}
|
||||
onClick={() => select(k)}
|
||||
>
|
||||
{k === 'locations'
|
||||
@@ -344,7 +367,7 @@ export default function OpportunityResources({
|
||||
{resources[kind].map((r) => (
|
||||
<article key={r.id} className="my-3 rounded border p-3">
|
||||
<p>
|
||||
{String(
|
||||
{valueText(
|
||||
r.payload.title ??
|
||||
r.file?.file_name ??
|
||||
'Recurso incompleto',
|
||||
@@ -370,7 +393,7 @@ export default function OpportunityResources({
|
||||
srcSet={r.derivativePreviews
|
||||
.map((p) => `${p.url} ${p.width}w`)
|
||||
.join(', ')}
|
||||
alt={String(
|
||||
alt={valueText(
|
||||
r.payload.alt_text ??
|
||||
'Pré-visualização interna pendente de descrição',
|
||||
)}
|
||||
@@ -385,7 +408,9 @@ export default function OpportunityResources({
|
||||
className={button}
|
||||
onClick={() => select(kind, r)}
|
||||
>
|
||||
Ver / editar / restaurar
|
||||
{readOnly
|
||||
? 'Ver recurso'
|
||||
: 'Ver / editar / restaurar'}
|
||||
</button>
|
||||
{r.file?.malware_scan_status === 'clean' &&
|
||||
!r.deleted_at && (
|
||||
@@ -412,39 +437,72 @@ export default function OpportunityResources({
|
||||
</h2>
|
||||
{kind === 'locations' && (
|
||||
<div>
|
||||
<Field label="País da localização" error={errors.country_code}>
|
||||
<Field
|
||||
label="País da localização"
|
||||
error={errors.country_code}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
disabled={readOnly}
|
||||
value={String(payload.country_code ?? '')}
|
||||
value={valueText(payload.country_code ?? '')}
|
||||
onChange={(event) => {
|
||||
const country = event.target.value;
|
||||
set('country_code', country || null);
|
||||
if (country && country !== 'MZ' && path.length) {
|
||||
if (
|
||||
country &&
|
||||
country !== 'MZ' &&
|
||||
path.length
|
||||
) {
|
||||
setPath([]);
|
||||
setMessage('A seleção territorial de Moçambique foi retirada do preenchimento ao mudar de país. Guarde para registar a alteração; a geometria própria foi preservada.');
|
||||
setMessage(
|
||||
'A seleção territorial de Moçambique foi retirada do preenchimento ao mudar de país. Guarde para registar a alteração; a geometria própria foi preservada.',
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{countries.map(c=><option key={c.code} value={c.code}>{c.name}</option>)}
|
||||
{countries.map((c) => (
|
||||
<option key={c.code} value={c.code}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{foreignCountry && (
|
||||
<p>A hierarquia abaixo corresponde a Moçambique e não é aplicável ao país escolhido. Pode guardar uma localização incompleta noutro país sem esta hierarquia.</p>
|
||||
<p>
|
||||
A hierarquia abaixo corresponde a Moçambique e
|
||||
não é aplicável ao país escolhido. Pode guardar
|
||||
uma localização incompleta noutro país sem esta
|
||||
hierarquia.
|
||||
</p>
|
||||
)}
|
||||
{foreignCountry && path.length > 0 && (
|
||||
<p role="alert">
|
||||
Este registo conserva uma seleção territorial de Moçambique incompatível com o país. Escolha Moçambique ou{' '}
|
||||
<button type="button" className="underline" disabled={readOnly} onClick={() => setPath([])}>
|
||||
retirar a seleção territorial deste preenchimento
|
||||
</button>. O registo guardado só muda quando guardar.
|
||||
Este registo conserva uma seleção territorial de
|
||||
Moçambique incompatível com o país. Escolha
|
||||
Moçambique ou{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={readOnly}
|
||||
onClick={() => setPath([])}
|
||||
>
|
||||
retirar a seleção territorial deste
|
||||
preenchimento
|
||||
</button>
|
||||
. O registo guardado só muda quando guardar.
|
||||
</p>
|
||||
)}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={foreignCountry ? undefined : path.at(-1)?.id}
|
||||
territoryId={
|
||||
foreignCountry ? undefined : path.at(-1)?.id
|
||||
}
|
||||
management
|
||||
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-geometries' : undefined}
|
||||
endpoint={
|
||||
basePath === '/minhas-oportunidades'
|
||||
? '/minhas-oportunidades/territory-geometries'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{[0, 1, 2, 3].map((index) => (
|
||||
<TerritoryLevel
|
||||
@@ -453,7 +511,11 @@ export default function OpportunityResources({
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
disabled={readOnly || foreignCountry}
|
||||
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-options' : '/management/territory-options'}
|
||||
endpoint={
|
||||
basePath === '/minhas-oportunidades'
|
||||
? '/minhas-oportunidades/territory-options'
|
||||
: '/management/territory-options'
|
||||
}
|
||||
onChange={(value) =>
|
||||
setPath((previous) =>
|
||||
value
|
||||
@@ -511,7 +573,7 @@ export default function OpportunityResources({
|
||||
<input
|
||||
aria-label={labels[name]}
|
||||
className={control}
|
||||
value={String(payload[name] ?? '')}
|
||||
value={valueText(payload[name] ?? '')}
|
||||
type={
|
||||
name.includes('date') ||
|
||||
name.endsWith('_at') ||
|
||||
@@ -544,7 +606,7 @@ export default function OpportunityResources({
|
||||
<select
|
||||
className={control}
|
||||
aria-label={labels[name] ?? name}
|
||||
value={String(
|
||||
value={valueText(
|
||||
payload[name === 'imageRole' ? 'role' : name] ??
|
||||
'',
|
||||
)}
|
||||
@@ -592,7 +654,7 @@ export default function OpportunityResources({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(payload[name] ?? '')}
|
||||
value={valueText(payload[name] ?? '')}
|
||||
onChange={(event) =>
|
||||
set(name, event.target.value || null)
|
||||
}
|
||||
@@ -606,7 +668,7 @@ export default function OpportunityResources({
|
||||
.filter((r) => !r.deleted_at)
|
||||
.map((r) => (
|
||||
<option value={r.id} key={r.id}>
|
||||
{String(
|
||||
{valueText(
|
||||
r.payload.title ??
|
||||
r.file?.file_name ??
|
||||
r.id,
|
||||
@@ -672,7 +734,10 @@ export default function OpportunityResources({
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy || readOnly || unavailable || !imageProcessingAvailable
|
||||
busy ||
|
||||
readOnly ||
|
||||
unavailable ||
|
||||
!imageProcessingAvailable
|
||||
}
|
||||
onClick={() => void execute('prepare')}
|
||||
>
|
||||
@@ -681,7 +746,12 @@ export default function OpportunityResources({
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || readOnly || unavailable || !!editing?.deleted_at}
|
||||
disabled={
|
||||
busy ||
|
||||
readOnly ||
|
||||
unavailable ||
|
||||
!!editing?.deleted_at
|
||||
}
|
||||
>
|
||||
Guardar recurso
|
||||
</button>
|
||||
|
||||
@@ -38,6 +38,9 @@ export const states: Record<string, string> = {
|
||||
returned: 'Devolvida',
|
||||
approved: 'Aprovada internamente',
|
||||
suspended: 'Suspensa',
|
||||
needs_information: 'Correções solicitadas',
|
||||
information_pending: 'Aguarda parecer',
|
||||
rejected: 'Rejeitada',
|
||||
};
|
||||
|
||||
export function Management({
|
||||
@@ -48,7 +51,7 @@ export function Management({
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { flash, educationEnabled, aiEnabled, auth, basePath } = usePage<{
|
||||
auth?: {canManagePortal?: boolean};
|
||||
auth?: { canManagePortal?: boolean };
|
||||
basePath?: string;
|
||||
flash?: { success?: string };
|
||||
educationEnabled?: boolean;
|
||||
@@ -57,55 +60,61 @@ export function Management({
|
||||
return (
|
||||
<div className="space-y-6 p-4 md:p-8">
|
||||
<Head title={title} />
|
||||
{auth?.canManagePortal && basePath !== '/minhas-oportunidades' ? <nav
|
||||
className="flex flex-wrap gap-4 text-sm underline"
|
||||
aria-label="Gestão do portal"
|
||||
>
|
||||
<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/opportunity-origin">
|
||||
Revisão da origem das oportunidades
|
||||
</Link>
|
||||
<Link href="/management/history">Histórico</Link>
|
||||
<Link href="/management/crm/leads">CRM</Link>
|
||||
<Link href="/management/crm/investors">Investidores</Link>
|
||||
<Link href="/management/projects">Projectos</Link>
|
||||
<Link href="/management/clusters">Clusters</Link>
|
||||
<Link href="/management/relationship-repair">
|
||||
Revisão das associações documentadas
|
||||
</Link>
|
||||
<Link href="/management/partnerships-install">
|
||||
Aplicação da Bolsa de Parcerias
|
||||
</Link>
|
||||
<Link href="/management/corridors">Corredores</Link>
|
||||
<Link href="/management/territory-associations">
|
||||
Localizações dos investimentos
|
||||
</Link>
|
||||
<Link href="/management/investment/zones">
|
||||
ZEE, ZFI e parques
|
||||
</Link>
|
||||
{educationEnabled && (
|
||||
<Link href="/management/education">
|
||||
Competências e formação
|
||||
{auth?.canManagePortal && basePath !== '/minhas-oportunidades' ? (
|
||||
<nav
|
||||
className="flex flex-wrap gap-4 text-sm underline"
|
||||
aria-label="Gestão do portal"
|
||||
>
|
||||
<Link href="/management/interests">
|
||||
Pedidos de interesse
|
||||
</Link>
|
||||
)}
|
||||
{aiEnabled && (
|
||||
<Link href="/management/ai">Assistência e fontes</Link>
|
||||
)}
|
||||
<Link href="/management/portfolio">
|
||||
Corredores e matriz de investimento
|
||||
</Link>
|
||||
<Link href="/management/portal-services">
|
||||
Documentos e parcerias
|
||||
</Link>
|
||||
<Link href="/management/investment/references">
|
||||
Referências e formulários
|
||||
</Link>
|
||||
<a href="/">Portal público</a>
|
||||
</nav> : <ProfileNavigation />}
|
||||
<Link href="/management/sectors">Sectores</Link>
|
||||
<Link href="/management/opportunities">
|
||||
Gestão de Oportunidades
|
||||
</Link>
|
||||
<Link href="/management/opportunity-origin">
|
||||
Revisão da origem das oportunidades
|
||||
</Link>
|
||||
<Link href="/management/history">Histórico</Link>
|
||||
<Link href="/management/crm/leads">CRM</Link>
|
||||
<Link href="/management/crm/investors">Investidores</Link>
|
||||
<Link href="/management/projects">Projectos</Link>
|
||||
<Link href="/management/clusters">Clusters</Link>
|
||||
<Link href="/management/relationship-repair">
|
||||
Revisão das associações documentadas
|
||||
</Link>
|
||||
<Link href="/management/partnerships-install">
|
||||
Aplicação da Bolsa de Parcerias
|
||||
</Link>
|
||||
<Link href="/management/corridors">Corredores</Link>
|
||||
<Link href="/management/territory-associations">
|
||||
Localizações dos investimentos
|
||||
</Link>
|
||||
<Link href="/management/investment/zones">
|
||||
ZEE, ZFI e parques
|
||||
</Link>
|
||||
{educationEnabled && (
|
||||
<Link href="/management/education">
|
||||
Competências e formação
|
||||
</Link>
|
||||
)}
|
||||
{aiEnabled && (
|
||||
<Link href="/management/ai">Assistência e fontes</Link>
|
||||
)}
|
||||
<Link href="/management/portfolio">
|
||||
Corredores e matriz de investimento
|
||||
</Link>
|
||||
<Link href="/management/portal-services">
|
||||
Documentos e parcerias
|
||||
</Link>
|
||||
<Link href="/management/investment/references">
|
||||
Referências e formulários
|
||||
</Link>
|
||||
<a href="/">Portal público</a>
|
||||
</nav>
|
||||
) : (
|
||||
<ProfileNavigation />
|
||||
)}
|
||||
<h1 className="text-2xl font-semibold break-words">{title}</h1>
|
||||
{flash?.success && (
|
||||
<p
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Management, Field, control, button } from "./shared";
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Management, Field, control, button } from './shared';
|
||||
|
||||
type Plan = {
|
||||
level: number;
|
||||
@@ -17,32 +18,36 @@ type Plan = {
|
||||
parent_name: string | null;
|
||||
location_id: string | null;
|
||||
status: string;
|
||||
correspondence: { target_name: string; target_source_code: string; basis: string } | null;
|
||||
correspondence: {
|
||||
target_name: string;
|
||||
target_source_code: string;
|
||||
basis: string;
|
||||
} | null;
|
||||
}[];
|
||||
};
|
||||
export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
const [reason, setReason] = useState("");
|
||||
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 [message, setMessage] = useState('');
|
||||
const [batch, setBatch] = useState('');
|
||||
const [applyKey, setApplyKey] = useState(() => createOperationKey());
|
||||
const [reverseKey, setReverseKey] = useState(() => createOperationKey());
|
||||
const execute = async (reverse: boolean) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const cookie = document.cookie
|
||||
.split("; ")
|
||||
.find((v) => v.startsWith("XSRF-TOKEN="))
|
||||
.split('; ')
|
||||
.find((v) => v.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11);
|
||||
const response = await fetch(
|
||||
`/management/territory-geometry-import${reverse ? `/${batch}/reverse` : ""}`,
|
||||
`/management/territory-geometry-import${reverse ? `/${batch}/reverse` : ''}`,
|
||||
{
|
||||
method: "POST",
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"X-XSRF-TOKEN": decodeURIComponent(cookie ?? ""),
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(cookie ?? ''),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
level: plan.level,
|
||||
@@ -57,7 +62,7 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
result.message ??
|
||||
"Operação recusada. Reveja o plano e a autenticação.",
|
||||
'Operação recusada. Reveja o plano e a autenticação.',
|
||||
);
|
||||
if (!reverse) setBatch(result.batch_id);
|
||||
setMessage(
|
||||
@@ -66,7 +71,7 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
: `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.");
|
||||
setMessage(e instanceof Error ? e.message : 'Erro de ligação.');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -75,21 +80,21 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<Management title="Importação cartográfica">
|
||||
<p>
|
||||
Exemplar INE de 07/06/2019 aceite. Correspondência exata de nome
|
||||
e pai, ou correspondência explícita fundamentada abaixo;
|
||||
sem alterações de classificações territoriais,
|
||||
disponibilidade fundiária ou cálculos.
|
||||
e pai, ou correspondência explícita fundamentada abaixo; 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("");
|
||||
setBatch('');
|
||||
setMessage('');
|
||||
setConfirmed(false);
|
||||
setApplyKey(crypto.randomUUID());
|
||||
setReverseKey(crypto.randomUUID());
|
||||
router.get("/management/territory-geometry-import", {
|
||||
setApplyKey(createOperationKey());
|
||||
setReverseKey(createOperationKey());
|
||||
router.get('/management/territory-geometry-import', {
|
||||
level: Number(e.target.value),
|
||||
});
|
||||
}}
|
||||
@@ -100,20 +105,26 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
</select>
|
||||
</Field>
|
||||
<p>
|
||||
Esperado: {plan.expected}; resolvido: {plan.resolved}; pendente:{" "}
|
||||
{plan.pending}. Scan:{" "}
|
||||
{plan.scan_ready ? "limpo e atual" : "pendente ou inconclusivo"}
|
||||
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>
|
||||
<p>Versão das correspondências: {plan.correspondence_version}.</p>
|
||||
<button className={button} disabled={busy} onClick={() => {
|
||||
setApplyKey(crypto.randomUUID());
|
||||
setConfirmed(false);
|
||||
router.reload({ only: ["plan"] });
|
||||
}}>Atualizar pré-visualização</button>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setApplyKey(createOperationKey());
|
||||
setConfirmed(false);
|
||||
router.reload({ only: ['plan'] });
|
||||
}}
|
||||
>
|
||||
Atualizar pré-visualização
|
||||
</button>
|
||||
<div className="overflow-x-auto">
|
||||
<table>
|
||||
<thead>
|
||||
@@ -131,12 +142,23 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<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.correspondence ? <>
|
||||
{r.correspondence.target_name} (código {r.correspondence.target_source_code})
|
||||
<p>{r.correspondence.basis}</p>
|
||||
</> : "Nome único sob o pai correspondido"}</td>
|
||||
<td>{r.parent_name ?? '—'}</td>
|
||||
<td>{r.location_id ?? 'Pendente'}</td>
|
||||
<td>
|
||||
{r.correspondence ? (
|
||||
<>
|
||||
{r.correspondence.target_name}{' '}
|
||||
(código{' '}
|
||||
{
|
||||
r.correspondence
|
||||
.target_source_code
|
||||
}
|
||||
)<p>{r.correspondence.basis}</p>
|
||||
</>
|
||||
) : (
|
||||
'Nome único sob o pai correspondido'
|
||||
)}
|
||||
</td>
|
||||
<td>{r.status}</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -157,7 +179,7 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
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>
|
||||
@@ -176,7 +198,7 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
value={batch}
|
||||
onChange={(e) => {
|
||||
setBatch(e.target.value);
|
||||
setReverseKey(crypto.randomUUID());
|
||||
setReverseKey(createOperationKey());
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import TerritoryGeometryPreview from "@/components/territory-geometry-preview";
|
||||
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,
|
||||
@@ -11,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 & {
|
||||
@@ -42,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>
|
||||
@@ -71,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>
|
||||
@@ -82,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) => (
|
||||
@@ -96,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) => (
|
||||
@@ -119,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
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
@@ -22,7 +23,7 @@ type Props = Catalogues & {
|
||||
};
|
||||
function Editor(p: Props) {
|
||||
const form = useForm({
|
||||
client_key: crypto.randomUUID(),
|
||||
client_key: createOperationKey(),
|
||||
version: p.record?.version ?? null,
|
||||
title: p.record?.title ?? '',
|
||||
offer: p.record?.offer ?? '',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { useForm, usePage, Link, router } from '@inertiajs/react';
|
||||
import {
|
||||
Frame,
|
||||
@@ -137,7 +138,7 @@ export default function Page(p: Props) {
|
||||
}
|
||||
function RoomPage(p: Props) {
|
||||
const { auth } = usePage<{ auth: { user: { id: number } } }>().props;
|
||||
const message = useForm({ body: '', client_key: crypto.randomUUID() });
|
||||
const message = useForm({ body: '', client_key: createOperationKey() });
|
||||
const agreement = useForm({
|
||||
version: p.room.version,
|
||||
action: 'record',
|
||||
@@ -195,7 +196,7 @@ function RoomPage(p: Props) {
|
||||
onSuccess: () => {
|
||||
message.setData({
|
||||
body: '',
|
||||
client_key: crypto.randomUUID(),
|
||||
client_key: createOperationKey(),
|
||||
});
|
||||
},
|
||||
},
|
||||
@@ -205,6 +206,7 @@ function RoomPage(p: Props) {
|
||||
<Field label="Mensagem privada">
|
||||
<textarea
|
||||
className={control}
|
||||
disabled={message.processing}
|
||||
value={message.data.body}
|
||||
onChange={(e) =>
|
||||
message.setData('body', e.target.value)
|
||||
@@ -231,6 +233,15 @@ function RoomPage(p: Props) {
|
||||
antimalware limpa e hash correspondente. Anexar não
|
||||
confirma autenticidade nem vigência.
|
||||
</p>
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label="Documentos disponíveis nesta sala"
|
||||
>
|
||||
{p.documents.length
|
||||
? `${p.documents.length} documento(s) disponível(is) para esta conta.`
|
||||
: 'Nenhum documento está autorizado para consulta por esta conta nesta sala.'}
|
||||
</p>
|
||||
{p.documents.map((d) => (
|
||||
<article key={d.id}>
|
||||
<p>
|
||||
|
||||
@@ -113,7 +113,7 @@ export function Frame({
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Layout title={title}>
|
||||
<Layout title={title} mainLandmark={false}>
|
||||
<nav className="mb-6 flex flex-wrap gap-5 underline">
|
||||
<Link href="/parcerias">Catálogo</Link>
|
||||
<Link href="/parcerias/painel">O meu painel</Link>
|
||||
|
||||
@@ -13,7 +13,12 @@ export type LegacyArticle = {
|
||||
landing_href: string;
|
||||
start_href: string;
|
||||
group: { label: string; heading: string };
|
||||
related_articles: { id: number; slug: string; title: string; href: string }[];
|
||||
related_articles: {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
href: string;
|
||||
}[];
|
||||
html: string;
|
||||
library_href: string;
|
||||
image: { href: string; alt: string; source_url: string } | null;
|
||||
@@ -48,7 +53,9 @@ export default function LegacySector({
|
||||
<main className="legacy-agronegocio mx-auto max-w-6xl space-y-8 rounded-2xl bg-[#f6f3ea] p-4 sm:p-8">
|
||||
<Head
|
||||
title={
|
||||
view === 'landing' ? `Explorar ${article.group.label}` : article.title
|
||||
view === 'landing'
|
||||
? `Explorar ${article.group.label}`
|
||||
: article.title
|
||||
}
|
||||
/>
|
||||
<style>{`
|
||||
@@ -62,7 +69,10 @@ export default function LegacySector({
|
||||
.legacy-article ol { list-style: decimal; padding-inline-start: 1.6em; }
|
||||
.legacy-article a { text-decoration: underline; }
|
||||
`}</style>
|
||||
<nav className="flex flex-wrap gap-4" aria-label={article.group.label}>
|
||||
<nav
|
||||
className="flex flex-wrap gap-4"
|
||||
aria-label={article.group.label}
|
||||
>
|
||||
<Link href={article.landing_href} className="underline">
|
||||
Explorar {article.group.label}
|
||||
</Link>
|
||||
@@ -141,24 +151,31 @@ export default function LegacySector({
|
||||
</form>
|
||||
{match ? (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{articles.map((item) => (
|
||||
<article key={item.id} className="space-y-3 rounded-xl border bg-white p-5">
|
||||
<h3 className="text-xl font-semibold">
|
||||
<Link className="underline" href={item.href}>
|
||||
{item.title}
|
||||
</Link>
|
||||
</h3>
|
||||
<p>
|
||||
Conteúdo editorial preservado do portal Tempo.
|
||||
</p>
|
||||
<Link
|
||||
className="inline-block rounded bg-[#10352b] px-5 py-3 text-white"
|
||||
href={item.href}
|
||||
>
|
||||
Ler o artigo
|
||||
</Link>
|
||||
</article>
|
||||
))}
|
||||
{articles.map((item) => (
|
||||
<article
|
||||
key={item.id}
|
||||
className="space-y-3 rounded-xl border bg-white p-5"
|
||||
>
|
||||
<h3 className="text-xl font-semibold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={item.href}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
</h3>
|
||||
<p>
|
||||
Conteúdo editorial preservado do portal
|
||||
Tempo.
|
||||
</p>
|
||||
<Link
|
||||
className="inline-block rounded bg-[#10352b] px-5 py-3 text-white"
|
||||
href={item.href}
|
||||
>
|
||||
Ler o artigo
|
||||
</Link>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p role="status">
|
||||
@@ -175,10 +192,16 @@ export default function LegacySector({
|
||||
)}
|
||||
{view === 'article' && article.related_articles.length > 0 && (
|
||||
<section className="space-y-3" aria-labelledby="related-title">
|
||||
<h2 id="related-title" className="text-2xl font-semibold">Outras leituras no setor</h2>
|
||||
<h2 id="related-title" className="text-2xl font-semibold">
|
||||
Outras leituras no setor
|
||||
</h2>
|
||||
<ul className="grid gap-3 sm:grid-cols-2">
|
||||
{article.related_articles.map((item) => (
|
||||
<li key={item.id}><Link className="underline" href={item.href}>{item.title}</Link></li>
|
||||
<li key={item.id}>
|
||||
<Link className="underline" href={item.href}>
|
||||
{item.title}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -535,7 +535,13 @@ export default function Manage({
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={legacyContentEnabled ? 'Assunto (opcional)' : 'Assunto'}>
|
||||
<Field
|
||||
label={
|
||||
legacyContentEnabled
|
||||
? 'Assunto (opcional)'
|
||||
: 'Assunto'
|
||||
}
|
||||
>
|
||||
<input
|
||||
required={!legacyContentEnabled}
|
||||
className={control}
|
||||
|
||||
@@ -36,13 +36,16 @@ export const kind = (
|
||||
export function Layout({
|
||||
title,
|
||||
children,
|
||||
mainLandmark = true,
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
mainLandmark?: boolean;
|
||||
}) {
|
||||
const { flash } = usePage<{ flash?: { success?: string } }>().props;
|
||||
const Container = mainLandmark ? 'main' : 'div';
|
||||
return (
|
||||
<main className="mx-auto w-full max-w-6xl min-w-0 space-y-6 p-4 break-words md:p-8">
|
||||
<Container className="mx-auto w-full max-w-6xl min-w-0 space-y-6 p-4 break-words md:p-8">
|
||||
<Head title={title} />
|
||||
<nav
|
||||
className="flex flex-wrap gap-5 text-sm underline"
|
||||
@@ -61,6 +64,6 @@ export function Layout({
|
||||
</p>
|
||||
)}
|
||||
{children}
|
||||
</main>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -90,6 +90,8 @@ function JourneyCard({
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.data.country}
|
||||
label="País do requerente"
|
||||
error={form.errors.country}
|
||||
onChange={(value) => form.setData('country', value)}
|
||||
required
|
||||
allowLegacyValue
|
||||
@@ -99,6 +101,8 @@ function JourneyCard({
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
value={form.data.declared_origin_country_code}
|
||||
label="País de origem declarado desta solicitação"
|
||||
error={form.errors.declared_origin_country_code}
|
||||
onChange={(value) =>
|
||||
form.setData(
|
||||
'declared_origin_country_code',
|
||||
|
||||
@@ -1,76 +1,694 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
type Entry = {id: string; user_id: number; status: string; version: number; opportunity_types: string; document_ids: string; reason: string};
|
||||
type SecurityEntry = {id: string; kind: string; requested_by: number; subject_user_id: number; scope: string; reason: string; approved_by: number | null; consumed_at: string | null; expires_at: string};
|
||||
type Pair = {first_user_id: number; second_user_id: number; version: number};
|
||||
function Grant({types, organizations}: {types: string[]; organizations: {id: string; name: string}[]}) {
|
||||
const [user, setUser] = useState(''); const [role, setRole] = useState('validator'); const [organization, setOrganization] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]); const [responsibilities, setResponsibilities] = useState<string[]>([]);
|
||||
const [reason, setReason] = useState(''); const [expires, setExpires] = useState(''); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
const available = role === 'validator' ? ['validation_coordinator','technical_reviewer','legal_reviewer','appeal_reviewer'] : role === 'publisher' ? ['publication_coordinator'] : [];
|
||||
const toggle = (values: string[], value: string) => values.includes(value) ? values.filter(v => v !== value) : [...values,value];
|
||||
async function send() { setBusy(true); try { await profileJson('/perfis/atribuicoes', {user_id: Number(user), role, organization_id: organization || null, opportunity_types: selected, responsibilities, expires_at: expires || null, reason}); setMessage('Atribuição registada.'); router.reload(); } catch(error) {setMessage(error instanceof Error ? error.message : 'Resposta indisponível.');} finally {setBusy(false);} }
|
||||
return <section className="space-y-3"><h2 className="text-xl font-semibold">Atribuir papel operacional</h2><p>Promotor exige pedido documental independente. Superutilizador é gerido pela dupla, sem terceira atribuição.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send();}}>
|
||||
<label className="block">ID da conta existente<input className={control} type="number" min={1} required value={user} onChange={e => setUser(e.target.value)} /></label>
|
||||
<label className="block">Papel<select className={control} value={role} onChange={e => {setRole(e.target.value); setResponsibilities([]);}}>{['validator','publisher','auditor'].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">Âmbito organizacional<select className={control} value={organization} onChange={e => setOrganization(e.target.value)}><option value="">Todos os âmbitos para os tipos selecionados</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}</select></label>
|
||||
<fieldset><legend>Tipos autorizados</legend>{types.map(v => <label className="block" key={v}><input type="checkbox" checked={selected.includes(v)} onChange={() => setSelected(toggle(selected,v))} /> {v}</label>)}</fieldset>
|
||||
<fieldset><legend>Responsabilidades adicionais</legend>{available.map(v => <label className="block" key={v}><input type="checkbox" checked={responsibilities.includes(v)} onChange={() => setResponsibilities(toggle(responsibilities,v))} /> {v}</label>)}<p>Atribuir a responsabilidade não conclui filas, recursos ou escalamentos ainda em desenvolvimento.</p></fieldset>
|
||||
<label className="block">Validade opcional<input className={control} type="datetime-local" value={expires} onChange={e => setExpires(e.target.value)} /></label>
|
||||
<label className="block">Fundamento<textarea required className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Atribuir com auditoria</button><p role="status">{message}</p>
|
||||
</form></section>;
|
||||
}
|
||||
function Security({pair, entries, actorId}: {pair: Pair; entries: SecurityEntry[]; actorId: number}) {
|
||||
const [old, setOld] = useState(String(pair.second_user_id)); const [candidate, setCandidate] = useState(''); const [reason, setReason] = useState('');
|
||||
const [action, setAction] = useState('edit'); const [record, setRecord] = useState(''); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
async function send(path: string, data: object) {setBusy(true); try {const result = await profileJson(path, data); setMessage(result.message ?? `Pedido registado: ${result.id}`); router.reload();} catch(error) {setMessage(error instanceof Error ? error.message : 'Resposta indisponível.');} finally {setBusy(false);}}
|
||||
return <section className="space-y-3"><h2 className="text-xl font-semibold">Operações críticas</h2>
|
||||
<label className="block">Fundamento<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send('/perfis/substituicoes', {old_user_id: Number(old), new_user_id: Number(candidate), reason});}}>
|
||||
<label className="block">Titular a substituir<select className={control} value={old} onChange={e => setOld(e.target.value)}>{[pair.first_user_id,pair.second_user_id].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">ID do candidato com MFA confirmado<input className={control} type="number" min={1} required value={candidate} onChange={e => setCandidate(e.target.value)} /></label><button className={button} disabled={busy}>Preparar substituição atómica</button>
|
||||
type Entry = {
|
||||
id: string;
|
||||
user_id: number;
|
||||
status: string;
|
||||
version: number;
|
||||
opportunity_types: string;
|
||||
document_ids: string;
|
||||
reason: string;
|
||||
};
|
||||
type SecurityEntry = {
|
||||
id: string;
|
||||
kind: string;
|
||||
requested_by: number;
|
||||
subject_user_id: number;
|
||||
scope: string;
|
||||
reason: string;
|
||||
approved_by: number | null;
|
||||
consumed_at: string | null;
|
||||
expires_at: string;
|
||||
};
|
||||
type Pair = { first_user_id: number; second_user_id: number; version: number };
|
||||
type OperatorOrganization = { id: string; name: string; nuit: string; contact: string; director: string };
|
||||
|
||||
function OperatorOrganizationForm() {
|
||||
const [operationKey] = useState(createOperationKey);
|
||||
const [name, setName] = useState('Tempo Lda');
|
||||
const [nuit, setNuit] = useState('400993114');
|
||||
const [contact, setContact] = useState('+258868010880');
|
||||
const [director, setDirector] = useState('Osmane Nala');
|
||||
const [source, setSource] = useState('Dados e designação interna confirmados pelo responsável da Tempo em 11/10/2026.');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await profileJson('/perfis/organizacao-operadora', { operation_key: operationKey, name, nuit, contact, director, function: 'portal_owner_operator', source_reference: source });
|
||||
setMessage(result.message); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
return <section className="space-y-3" aria-label="Organização operadora">
|
||||
<h2 className="text-xl font-semibold">Organização proprietária e operadora</h2>
|
||||
<p>Reutiliza o cadastro mestre e conserva o histórico. Estes dados não atribuem representação empresarial nem papéis às contas.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => { e.preventDefault(); void save(); }}>
|
||||
<label className="block">Denominação<input required className={control} value={name} onChange={e => setName(e.target.value)} /></label>
|
||||
<label className="block">NUIT<input required className={control} value={nuit} onChange={e => setNuit(e.target.value)} pattern="[0-9]{9}" /></label>
|
||||
<label className="block">Contacto<input required type="tel" className={control} value={contact} onChange={e => setContact(e.target.value)} /></label>
|
||||
<label className="block">Director Geral<input required className={control} value={director} onChange={e => setDirector(e.target.value)} /></label>
|
||||
<label className="block">Origem dos dados<textarea aria-label="Origem dos dados" required minLength={20} maxLength={1000} className={control} value={source} onChange={e => setSource(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Guardar organização operadora</button>
|
||||
<p role="status">{message}</p>
|
||||
</form>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send('/perfis/elevacoes', {action, record_id: record ? Number(record) : null, reason});}}>
|
||||
<label className="block">Operação a elevar<select className={control} value={action} onChange={e => setAction(e.target.value)}>{['create','edit','validate','publish','archive'].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">ID da oportunidade<input className={control} type="number" min={1} required={action !== 'create'} value={record} onChange={e => setRecord(e.target.value)} /></label><button className={button} disabled={busy}>Pedir elevação temporária</button><p>Exige aprovação do outro titular e papel operacional válido. Não remove impedimentos de autoria ou Auditor.</p>
|
||||
</form>
|
||||
{entries.map(entry => <article key={entry.id} className="space-y-2 border p-3"><p>{entry.kind} — {entry.id} — solicitante {entry.requested_by}, destinatário {entry.subject_user_id}</p><p>{entry.reason}; validade: {entry.expires_at}</p><p>Âmbito: {entry.scope}</p>
|
||||
{!entry.consumed_at && !entry.approved_by && entry.requested_by !== actorId && entry.subject_user_id !== actorId && <button disabled={busy} className={button} onClick={() => void send(`/perfis/seguranca/${entry.id}/aprovar`, {})}>Aprovar independentemente</button>}
|
||||
{!entry.consumed_at && entry.approved_by && entry.requested_by === actorId && entry.kind === 'replacement' && <button disabled={busy} className={button} onClick={() => void send(`/perfis/substituicoes/${entry.id}/aplicar`, {})}>Aplicar substituição aprovada</button>}
|
||||
<p>{entry.consumed_at ? 'Aplicado' : entry.approved_by ? `Aprovado pela conta ${entry.approved_by}` : 'Aguarda aprovação independente'}</p>
|
||||
</article>)}<p role="status">{message}</p></section>;
|
||||
</section>;
|
||||
}
|
||||
function Decision({ entry }: {entry: Entry}) {
|
||||
const [reason, setReason] = useState(''); const [verified, setVerified] = useState(false); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
|
||||
function InternalStaffGrant({ types, organizations, operators }: { types: string[]; organizations: { id: string; name: string }[]; operators: OperatorOrganization[] }) {
|
||||
const [operationKey, setOperationKey] = useState(createOperationKey);
|
||||
const [subject, setSubject] = useState('');
|
||||
const [role, setRole] = useState('promoter');
|
||||
const [operator, setOperator] = useState('');
|
||||
const [scope, setScope] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [reason, setReason] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
await profileJson('/perfis/atribuicoes', { internal_designation: true, operation_key: operationKey,
|
||||
user_id: Number(subject), role, operator_organization_id: operator,
|
||||
organization_id: role === 'promoter' ? operator : scope || null,
|
||||
opportunity_types: selected, responsibilities: [], reason, confirmed_internal_designation: confirmed });
|
||||
setMessage('Designação interna atribuída e auditada.'); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
return <section className="space-y-3" aria-label="Designação interna">
|
||||
<h2 className="text-xl font-semibold">Atribuir função interna do portal</h2>
|
||||
<p>A proprietária define as funções da sua equipa. Esta atribuição não exige comprovativos de Promotor externo nem concede gestão empresarial. Cada oportunidade conserva o promotor real e a autorização de divulgação.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => { e.preventDefault(); void save(); }}>
|
||||
<label className="block">Conta da pessoa designada<input required type="number" min={1} className={control} value={subject} onChange={e => setSubject(e.target.value)} /></label>
|
||||
<label className="block">Função interna<select aria-label="Função interna" required className={control} value={role} onChange={e => setRole(e.target.value)}>{['promoter', 'validator', 'publisher'].map(v => <option key={v} value={v}>{v === 'promoter' ? 'Promotor' : v === 'validator' ? 'Validador' : 'Publicador'}</option>)}</select></label>
|
||||
<label className="block">Vínculo à organização operadora<select aria-label="Vínculo à organização operadora" required className={control} value={operator} onChange={e => setOperator(e.target.value)}><option value="">Selecionar organização</option>{operators.map(o => <option key={o.id} value={o.id}>{o.name} — NUIT {o.nuit}</option>)}</select></label>
|
||||
{role !== 'promoter' && <label className="block">Âmbito da função interna<select aria-label="Âmbito da função interna" className={control} value={scope} onChange={e => setScope(e.target.value)}><option value="">Todas as organizações para as categorias selecionadas</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}</select></label>}
|
||||
<fieldset><legend>Categorias da função interna</legend>{types.map(v => <label className="block" key={v}><input type="checkbox" checked={selected.includes(v)} onChange={() => setSelected(old => old.includes(v) ? old.filter(x => x !== v) : [...old, v])} /> {v}</label>)}</fieldset>
|
||||
<label className="block"><input type="checkbox" required checked={confirmed} onChange={e => setConfirmed(e.target.checked)} /> Confirmo a designação interna expressa pelo responsável da organização operadora.</label>
|
||||
<label className="block">Fundamento da designação interna<textarea aria-label="Fundamento da designação interna" required minLength={20} maxLength={1000} className={control} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Atribuir função interna com auditoria</button>
|
||||
<button type="button" className={button} disabled={busy} onClick={() => { setOperationKey(createOperationKey()); setSubject(''); setConfirmed(false); setMessage('Nova atribuição preparada.'); }}>Preparar outra atribuição</button>
|
||||
<p role="status">{message}</p>
|
||||
</form>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function Grant({
|
||||
types,
|
||||
organizations,
|
||||
}: {
|
||||
types: string[];
|
||||
organizations: { id: string; name: string }[];
|
||||
}) {
|
||||
const [user, setUser] = useState('');
|
||||
const [role, setRole] = useState('validator');
|
||||
const [organization, setOrganization] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [responsibilities, setResponsibilities] = useState<string[]>([]);
|
||||
const [reason, setReason] = useState('');
|
||||
const [expires, setExpires] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const available =
|
||||
role === 'validator'
|
||||
? [
|
||||
'validation_coordinator',
|
||||
'technical_reviewer',
|
||||
'legal_reviewer',
|
||||
'appeal_reviewer',
|
||||
]
|
||||
: role === 'publisher'
|
||||
? ['publication_coordinator']
|
||||
: [];
|
||||
const toggle = (values: string[], value: string) =>
|
||||
values.includes(value)
|
||||
? values.filter((v) => v !== value)
|
||||
: [...values, value];
|
||||
async function send() {
|
||||
setBusy(true);
|
||||
try {
|
||||
await profileJson('/perfis/atribuicoes', {
|
||||
user_id: Number(user),
|
||||
role,
|
||||
organization_id: organization || null,
|
||||
opportunity_types: selected,
|
||||
responsibilities,
|
||||
expires_at: expires || null,
|
||||
reason,
|
||||
});
|
||||
setMessage('Atribuição registada.');
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Atribuir papel operacional
|
||||
</h2>
|
||||
<p>
|
||||
Promotor externo usa o pedido documental. Funções internas usam a designação da proprietária. Superutilizador é
|
||||
gerido pela dupla, sem terceira atribuição.
|
||||
</p>
|
||||
<form
|
||||
className="max-w-2xl space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send();
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
ID da conta existente
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={user}
|
||||
onChange={(e) => setUser(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Papel
|
||||
<select
|
||||
aria-label="Papel"
|
||||
className={control}
|
||||
value={role}
|
||||
onChange={(e) => {
|
||||
setRole(e.target.value);
|
||||
setResponsibilities([]);
|
||||
}}
|
||||
>
|
||||
{['validator', 'publisher', 'auditor'].map((v) => (
|
||||
<option key={v}>{v}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Âmbito organizacional
|
||||
<select
|
||||
aria-label="Âmbito organizacional"
|
||||
className={control}
|
||||
value={organization}
|
||||
onChange={(e) => setOrganization(e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Todos os âmbitos para os tipos selecionados
|
||||
</option>
|
||||
{organizations.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<fieldset>
|
||||
<legend>Tipos autorizados</legend>
|
||||
{types.map((v) => (
|
||||
<label className="block" key={v}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(v)}
|
||||
onChange={() =>
|
||||
setSelected(toggle(selected, v))
|
||||
}
|
||||
/>{' '}
|
||||
{v}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Responsabilidades adicionais</legend>
|
||||
{available.map((v) => (
|
||||
<label className="block" key={v}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={responsibilities.includes(v)}
|
||||
onChange={() =>
|
||||
setResponsibilities(
|
||||
toggle(responsibilities, v),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{v}
|
||||
</label>
|
||||
))}
|
||||
<p>
|
||||
Atribuir a responsabilidade não conclui filas, recursos
|
||||
ou escalamentos ainda em desenvolvimento.
|
||||
</p>
|
||||
</fieldset>
|
||||
<label className="block">
|
||||
Validade opcional
|
||||
<input
|
||||
className={control}
|
||||
type="datetime-local"
|
||||
value={expires}
|
||||
onChange={(e) => setExpires(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Fundamento
|
||||
<textarea
|
||||
required
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={busy}>
|
||||
Atribuir com auditoria
|
||||
</button>
|
||||
<p role="status">{message}</p>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function Security({
|
||||
pair,
|
||||
entries,
|
||||
actorId,
|
||||
}: {
|
||||
pair: Pair;
|
||||
entries: SecurityEntry[];
|
||||
actorId: number;
|
||||
}) {
|
||||
const [old, setOld] = useState(String(pair.second_user_id));
|
||||
const [candidate, setCandidate] = useState('');
|
||||
const [reason, setReason] = useState('');
|
||||
const [action, setAction] = useState('edit');
|
||||
const [record, setRecord] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function send(path: string, data: object) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await profileJson(path, data);
|
||||
setMessage(result.message ?? `Pedido registado: ${result.id}`);
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">Operações críticas</h2>
|
||||
<label className="block">
|
||||
Fundamento
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<form
|
||||
className="max-w-2xl space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send('/perfis/substituicoes', {
|
||||
old_user_id: Number(old),
|
||||
new_user_id: Number(candidate),
|
||||
reason,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Titular a substituir
|
||||
<select
|
||||
className={control}
|
||||
value={old}
|
||||
onChange={(e) => setOld(e.target.value)}
|
||||
>
|
||||
{[pair.first_user_id, pair.second_user_id].map((v) => (
|
||||
<option key={v}>{v}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
ID do candidato com MFA confirmado
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={candidate}
|
||||
onChange={(e) => setCandidate(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={busy}>
|
||||
Preparar substituição atómica
|
||||
</button>
|
||||
</form>
|
||||
<form
|
||||
className="max-w-2xl space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send('/perfis/elevacoes', {
|
||||
action,
|
||||
record_id: record ? Number(record) : null,
|
||||
reason,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Operação a elevar
|
||||
<select
|
||||
className={control}
|
||||
value={action}
|
||||
onChange={(e) => setAction(e.target.value)}
|
||||
>
|
||||
{[
|
||||
'view',
|
||||
'create',
|
||||
'edit',
|
||||
'validate',
|
||||
'publish',
|
||||
'archive',
|
||||
].map((v) => (
|
||||
<option key={v} value={v}>{v === 'view' ? 'Consultar dossier e anexos' : v}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
ID da oportunidade
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min={1}
|
||||
required={action !== 'create'}
|
||||
value={record}
|
||||
onChange={(e) => setRecord(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={busy}>
|
||||
Pedir elevação temporária
|
||||
</button>
|
||||
<p>
|
||||
Exige aprovação do outro titular e papel operacional válido.
|
||||
Não remove impedimentos de autoria ou Auditor.
|
||||
</p>
|
||||
</form>
|
||||
{entries.map((entry) => (
|
||||
<article key={entry.id} className="space-y-2 border p-3">
|
||||
<p>
|
||||
{entry.kind} — {entry.id} — solicitante{' '}
|
||||
{entry.requested_by}, destinatário{' '}
|
||||
{entry.subject_user_id}
|
||||
</p>
|
||||
<p>
|
||||
{entry.reason}; validade: {entry.expires_at}
|
||||
</p>
|
||||
<p>Âmbito: {entry.scope}</p>
|
||||
{!entry.consumed_at &&
|
||||
!entry.approved_by &&
|
||||
entry.requested_by !== actorId &&
|
||||
entry.subject_user_id !== actorId && (
|
||||
<button
|
||||
disabled={busy}
|
||||
className={button}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/perfis/seguranca/${entry.id}/aprovar`,
|
||||
{},
|
||||
)
|
||||
}
|
||||
>
|
||||
Aprovar independentemente
|
||||
</button>
|
||||
)}
|
||||
{!entry.consumed_at &&
|
||||
entry.approved_by &&
|
||||
entry.requested_by === actorId &&
|
||||
entry.kind === 'replacement' && (
|
||||
<button
|
||||
disabled={busy}
|
||||
className={button}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/perfis/substituicoes/${entry.id}/aplicar`,
|
||||
{},
|
||||
)
|
||||
}
|
||||
>
|
||||
Aplicar substituição aprovada
|
||||
</button>
|
||||
)}
|
||||
<p>
|
||||
{entry.consumed_at
|
||||
? 'Aplicado'
|
||||
: entry.approved_by
|
||||
? `Aprovado pela conta ${entry.approved_by}`
|
||||
: 'Aguarda aprovação independente'}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
<p role="status">{message}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function Decision({ entry }: { entry: Entry }) {
|
||||
const [reason, setReason] = useState('');
|
||||
const [verified, setVerified] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const types: string[] = JSON.parse(entry.opportunity_types);
|
||||
const [approved, setApproved] = useState<string[]>([]);
|
||||
async function send(decision: string) {
|
||||
setBusy(true); try { await profileJson(`/perfis/pedidos/${entry.id}/decisao`, {version: entry.version, decision, reason, approved_types: approved,
|
||||
verified_identity: verified, verified_representation: verified, verified_documents: verified}); router.reload(); }
|
||||
catch(error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); } finally { setBusy(false); }
|
||||
setBusy(true);
|
||||
try {
|
||||
await profileJson(`/perfis/pedidos/${entry.id}/decisao`, {
|
||||
version: entry.version,
|
||||
decision,
|
||||
reason,
|
||||
approved_types: approved,
|
||||
verified_identity: verified,
|
||||
verified_representation: verified,
|
||||
verified_documents: verified,
|
||||
});
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return <article className="space-y-2 rounded border p-4"><h3>Pedido {entry.id} — conta {entry.user_id} — {entry.status}</h3><p>{entry.reason}</p><p>Comprovativos canónicos: {(JSON.parse(entry.document_ids) as string[]).map(id => <Link className="mr-3 underline" key={id} href={`/perfis/pedidos/${entry.id}/documentos/${id}`} target="_blank">Consultar {id}</Link>)}</p>
|
||||
{entry.status === 'pending' && <><fieldset><legend>Tipos efetivamente aprovados</legend>{types.map(type => <label className="block" key={type}><input type="checkbox" checked={approved.includes(type)} onChange={() => setApproved(v => v.includes(type) ? v.filter(x => x !== type) : [...v,type])} /> {type}</label>)}</fieldset>
|
||||
<label className="block"><input type="checkbox" checked={verified} onChange={e => setVerified(e.target.checked)} /> Conferi identidade, representação e comprovativos; esta declaração fica auditada.</label>
|
||||
<label className="block">Fundamento<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy} onClick={() => void send('approved')}>Aprovar tipos selecionados</button> <button className={button} disabled={busy} onClick={() => void send('rejected')}>Rejeitar pedido</button></>}
|
||||
<p role="status">{message}</p></article>;
|
||||
return (
|
||||
<article className="space-y-2 rounded border p-4">
|
||||
<h3>
|
||||
Pedido {entry.id} — conta {entry.user_id} — {entry.status}
|
||||
</h3>
|
||||
<p>{entry.reason}</p>
|
||||
<p>
|
||||
Comprovativos canónicos:{' '}
|
||||
{(JSON.parse(entry.document_ids) as string[]).map((id) => (
|
||||
<Link
|
||||
className="mr-3 underline"
|
||||
key={id}
|
||||
href={`/perfis/pedidos/${entry.id}/documentos/${id}`}
|
||||
target="_blank"
|
||||
>
|
||||
Consultar {id}
|
||||
</Link>
|
||||
))}
|
||||
</p>
|
||||
{entry.status === 'pending' && (
|
||||
<>
|
||||
<fieldset>
|
||||
<legend>Tipos efetivamente aprovados</legend>
|
||||
{types.map((type) => (
|
||||
<label className="block" key={type}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={approved.includes(type)}
|
||||
onChange={() =>
|
||||
setApproved((v) =>
|
||||
v.includes(type)
|
||||
? v.filter((x) => x !== type)
|
||||
: [...v, type],
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{type}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={verified}
|
||||
onChange={(e) => setVerified(e.target.checked)}
|
||||
/>{' '}
|
||||
Conferi identidade, representação e comprovativos; esta
|
||||
declaração fica auditada.
|
||||
</label>
|
||||
<label className="block">
|
||||
Fundamento
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('approved')}
|
||||
>
|
||||
Aprovar tipos selecionados
|
||||
</button>{' '}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('rejected')}
|
||||
>
|
||||
Rejeitar pedido
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<p role="status">{message}</p>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
export default function Administration({requests, pair, assignments, securityAlerts, actorId, types, organizations, securityRequests}: {actorId: number; types: string[]; organizations: {id: string; name: string}[]; securityRequests: SecurityEntry[]; securityAlerts: {id: string; action: string; actor_user_id: number; occurred_at: string}[]; requests: Entry[]; pair: Pair; assignments: {id: string; user_id: number; role: string; revoked_at: string | null}[]}) {
|
||||
const [message, setMessage] = useState(''); const [reason, setReason] = useState('');
|
||||
async function revoke(id: string) { try { await profileJson(`/perfis/atribuicoes/${id}/revogar`, {reason}); router.reload(); } catch(error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); } }
|
||||
return <main className="space-y-6 p-6"><Head title="Gestão de perfis" /><ProfileNavigation /><h1 className="text-2xl font-semibold">Gestão de perfis</h1>
|
||||
<p>Dupla de superutilizadores: contas {pair.first_user_id} e {pair.second_user_id}; versão {pair.version}. Substituição exige operação atómica e aprovação independente. Não há remoção isolada.</p>
|
||||
<section aria-label="Alertas de segurança"><h2 className="text-xl font-semibold">Alertas de segurança</h2>{securityAlerts.map(a => <p key={a.id}>{a.occurred_at}: {a.action} — conta {a.actor_user_id}</p>)}</section>
|
||||
<section><h2 className="text-xl font-semibold">Pedidos de Promotor</h2>{requests.map(r => <Decision key={r.id} entry={r} />)}</section>
|
||||
<Grant types={types} organizations={organizations} /><Security pair={pair} entries={securityRequests} actorId={actorId} />
|
||||
<section><h2 className="text-xl font-semibold">Atribuições e revogação</h2><label>Motivo de revogação<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
{assignments.map(a => <p key={a.id}>Conta {a.user_id}: {a.role} — {a.revoked_at ? 'revogado' : 'atribuído'} {!a.revoked_at && <button className={button} onClick={() => void revoke(a.id)}>Revogar e invalidar sessões</button>}</p>)}<p role="status">{message}</p></section>
|
||||
</main>;
|
||||
export default function Administration({
|
||||
requests,
|
||||
pair,
|
||||
assignments,
|
||||
securityAlerts,
|
||||
actorId,
|
||||
types,
|
||||
organizations,
|
||||
securityRequests,
|
||||
operatorOrganizations,
|
||||
internalTypes,
|
||||
}: {
|
||||
operatorOrganizations: OperatorOrganization[];
|
||||
internalTypes: string[];
|
||||
actorId: number;
|
||||
types: string[];
|
||||
organizations: { id: string; name: string }[];
|
||||
securityRequests: SecurityEntry[];
|
||||
securityAlerts: {
|
||||
id: string;
|
||||
action: string;
|
||||
actor_user_id: number;
|
||||
occurred_at: string;
|
||||
}[];
|
||||
requests: Entry[];
|
||||
pair: Pair;
|
||||
assignments: {
|
||||
id: string;
|
||||
user_id: number;
|
||||
role: string;
|
||||
revoked_at: string | null;
|
||||
}[];
|
||||
}) {
|
||||
const [message, setMessage] = useState('');
|
||||
const [reason, setReason] = useState('');
|
||||
async function revoke(id: string) {
|
||||
try {
|
||||
await profileJson(`/perfis/atribuicoes/${id}/revogar`, { reason });
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível.',
|
||||
);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<main className="space-y-6 p-6">
|
||||
<Head title="Gestão de perfis" />
|
||||
<ProfileNavigation />
|
||||
<h1 className="text-2xl font-semibold">Gestão de perfis</h1>
|
||||
<p>
|
||||
Dupla de superutilizadores: contas {pair.first_user_id} e{' '}
|
||||
{pair.second_user_id}; versão {pair.version}. Substituição exige
|
||||
operação atómica e aprovação independente. Não há remoção
|
||||
isolada.
|
||||
</p>
|
||||
<section aria-label="Alertas de segurança">
|
||||
<h2 className="text-xl font-semibold">Alertas de segurança</h2>
|
||||
{securityAlerts.map((a) => (
|
||||
<p key={a.id}>
|
||||
{a.occurred_at}: {a.action} — conta {a.actor_user_id}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold">Pedidos de Promotor</h2>
|
||||
{requests.map((r) => (
|
||||
<Decision key={r.id} entry={r} />
|
||||
))}
|
||||
</section>
|
||||
<OperatorOrganizationForm />
|
||||
<InternalStaffGrant types={internalTypes} organizations={organizations} operators={operatorOrganizations} />
|
||||
<Grant types={types} organizations={organizations} />
|
||||
<Security
|
||||
pair={pair}
|
||||
entries={securityRequests}
|
||||
actorId={actorId}
|
||||
/>
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Atribuições e revogação
|
||||
</h2>
|
||||
<label>
|
||||
Motivo de revogação
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{assignments.map((a) => (
|
||||
<p key={a.id}>
|
||||
Conta {a.user_id}: {a.role} —{' '}
|
||||
{a.revoked_at ? 'revogado' : 'atribuído'}{' '}
|
||||
{!a.revoked_at && (
|
||||
<button
|
||||
className={button}
|
||||
onClick={() => void revoke(a.id)}
|
||||
>
|
||||
Revogar e invalidar sessões
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
<p role="status">{message}</p>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,120 @@
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { button, control, Pagination, type Paginated } from '@/pages/management/shared';
|
||||
import {
|
||||
button,
|
||||
control,
|
||||
Pagination,
|
||||
type Paginated,
|
||||
} from '@/pages/management/shared';
|
||||
|
||||
type Event = {id: string; action: string; actor_user_id: number | null; entity_type: string; source_system: string; occurred_at: string};
|
||||
export default function Audit({records, filters}: {records: Paginated<Event>; filters: Record<string,string>}) {
|
||||
const form = useForm({actor_id: filters.actor_id ?? '', action: filters.action ?? '', record_id: filters.record_id ?? '', from: filters.from ?? '', until: filters.until ?? ''});
|
||||
const search = new URLSearchParams(Object.entries(form.data).filter(([,value]) => value !== ''));
|
||||
type Event = {
|
||||
id: string;
|
||||
action: string;
|
||||
actor_user_id: number | null;
|
||||
entity_type: string;
|
||||
source_system: string;
|
||||
occurred_at: string;
|
||||
};
|
||||
export default function Audit({
|
||||
records,
|
||||
filters,
|
||||
}: {
|
||||
records: Paginated<Event>;
|
||||
filters: Record<string, string>;
|
||||
}) {
|
||||
const form = useForm({
|
||||
actor_id: filters.actor_id ?? '',
|
||||
action: filters.action ?? '',
|
||||
record_id: filters.record_id ?? '',
|
||||
from: filters.from ?? '',
|
||||
until: filters.until ?? '',
|
||||
});
|
||||
const search = new URLSearchParams(
|
||||
Object.entries(form.data).filter(([, value]) => value !== ''),
|
||||
);
|
||||
search.set('format', 'json');
|
||||
return <main className="space-y-6 p-6"><Head title="Auditoria de acessos" /><ProfileNavigation /><h1 className="text-2xl font-semibold">Auditoria de acessos e decisões</h1>
|
||||
<p>Consulta somente de leitura. A exportação contém metadados; não inclui credenciais, documentos nem snapshots privados decifrados. Cada exportação apresenta o limite aplicado.</p>
|
||||
<form className="grid gap-3 sm:grid-cols-3" onSubmit={e => {e.preventDefault(); form.get('/perfis/auditoria');}}>
|
||||
{(['actor_id','action','record_id','from','until'] as const).map(field => <label key={field}>{field}<input className={control} type={field === 'from' || field === 'until' ? 'datetime-local' : 'text'} value={form.data[field]} onChange={e => form.setData(field,e.target.value)} /></label>)}
|
||||
<button className={button}>Filtrar</button>
|
||||
</form>
|
||||
{Object.values(form.errors).map(error => <p role="alert" key={error}>{error}</p>)}
|
||||
<a className="underline" href={`/perfis/auditoria?${search}`}>Exportar metadados JSON, até 1.000 eventos</a>
|
||||
<div className="overflow-auto"><table className="w-full"><thead><tr><th>Data UTC</th><th>Conta</th><th>Ação</th><th>Recurso</th><th>Origem</th></tr></thead><tbody>{records.data.map(e => <tr key={e.id}><td>{e.occurred_at}</td><td>{e.actor_user_id}</td><td>{e.action}</td><td>{e.entity_type}</td><td>{e.source_system}</td></tr>)}</tbody></table></div>
|
||||
{!records.data.length && <p>Nenhum evento corresponde aos filtros.</p>}<Pagination page={records} />
|
||||
</main>;
|
||||
return (
|
||||
<main className="space-y-6 p-6">
|
||||
<Head title="Auditoria de acessos" />
|
||||
<ProfileNavigation />
|
||||
<h1 className="text-2xl font-semibold">
|
||||
Auditoria de acessos e decisões
|
||||
</h1>
|
||||
<p>
|
||||
Consulta somente de leitura. A exportação contém metadados; não
|
||||
inclui credenciais, documentos nem snapshots privados
|
||||
decifrados. Cada exportação apresenta o limite aplicado.
|
||||
</p>
|
||||
<form
|
||||
className="grid gap-3 sm:grid-cols-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.get('/perfis/auditoria');
|
||||
}}
|
||||
>
|
||||
{(
|
||||
[
|
||||
'actor_id',
|
||||
'action',
|
||||
'record_id',
|
||||
'from',
|
||||
'until',
|
||||
] as const
|
||||
).map((field) => (
|
||||
<label key={field}>
|
||||
{field}
|
||||
<input
|
||||
className={control}
|
||||
type={
|
||||
field === 'from' || field === 'until'
|
||||
? 'datetime-local'
|
||||
: 'text'
|
||||
}
|
||||
value={form.data[field]}
|
||||
onChange={(e) =>
|
||||
form.setData(field, e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<button className={button}>Filtrar</button>
|
||||
</form>
|
||||
{Object.values(form.errors).map((error) => (
|
||||
<p role="alert" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
<a className="underline" href={`/perfis/auditoria?${search}`}>
|
||||
Exportar metadados JSON, até 1.000 eventos
|
||||
</a>
|
||||
<div className="overflow-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Data UTC</th>
|
||||
<th>Conta</th>
|
||||
<th>Ação</th>
|
||||
<th>Recurso</th>
|
||||
<th>Origem</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{records.data.map((e) => (
|
||||
<tr key={e.id}>
|
||||
<td>{e.occurred_at}</td>
|
||||
<td>{e.actor_user_id}</td>
|
||||
<td>{e.action}</td>
|
||||
<td>{e.entity_type}</td>
|
||||
<td>{e.source_system}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!records.data.length && (
|
||||
<p>Nenhum evento corresponde aos filtros.</p>
|
||||
)}
|
||||
<Pagination page={records} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useState } from 'react';
|
||||
import { Management, button, control } from '@/pages/management/shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
type Plan = {approval_id:string;requested_by:number;second_user_id:number;reason:string;expires_at:string;consumed:boolean;expired:boolean;code_current:boolean;can_confirm:boolean;mfa_confirmed_in_session:boolean;hash:string;target:{database:string;port:number}};
|
||||
export default function BootstrapConfirmation(plan:Plan) {
|
||||
const [key] = useState(createOperationKey);
|
||||
const [reason,setReason] = useState('');
|
||||
const [confirmed,setConfirmed] = useState(false);
|
||||
const [busy,setBusy] = useState(false);
|
||||
const [done,setDone] = useState(plan.consumed);
|
||||
const [message,setMessage] = useState('');
|
||||
async function confirm() {
|
||||
setBusy(true);setMessage('');
|
||||
try {
|
||||
await profileJson('/management/profile-install/bootstrap/'+plan.approval_id+'/confirm',{hash:plan.hash,confirm:confirmed,idempotency_key:key,reason});
|
||||
setDone(true);setMessage('Dupla inicializada por confirmação cruzada. Apenas estas duas contas foram designadas; nenhuma flag foi alterada. Inicie uma nova sessão.');
|
||||
} catch(error) {setMessage(error instanceof Error?error.message:'Resposta indisponível. Recupere este pedido antes de repetir.');}
|
||||
finally {setBusy(false);}
|
||||
}
|
||||
return <Management title="Confirmar os dois titulares">
|
||||
<p>Base {plan.target.database}:{plan.target.port}</p>
|
||||
<p>Pedido apresentado pela conta {plan.requested_by}; confirmação reservada à conta {plan.second_user_id}.</p>
|
||||
<p>Fundamento do pedido: {plan.reason}</p><p>Expira em {plan.expires_at}.</p>
|
||||
<p>O pedido não atribui privilégios. A confirmação é uma operação distinta, com MFA e auditoria. Não altera a regra de substituição posterior.</p>
|
||||
{plan.expired && <p role="alert">Pedido expirado. Prepare novo pedido autorizado.</p>}
|
||||
{!plan.code_current && <p role="alert">Revisão ou destino alterados. Este pedido não pode ser confirmado.</p>}
|
||||
{!plan.mfa_confirmed_in_session && <p role="alert">Conclua MFA nesta sessão antes de confirmar.</p>}
|
||||
{!plan.can_confirm && !done && <p>Esta conta pode consultar, mas não confirmar o pedido.</p>}
|
||||
<label className="block">Fundamento da confirmação<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e=>setReason(e.target.value)}/></label>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/> Confirmo apenas estas duas contas e esta base</label>
|
||||
<button className={button} disabled={busy||done||!plan.can_confirm||!plan.mfa_confirmed_in_session||!confirmed||reason.length<20} onClick={()=>void confirm()}>Confirmar designação cruzada</button>
|
||||
<p role="status">{done?'Pedido consumido; não reinicializar. ':''}{message}</p>
|
||||
</Management>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { useState } from 'react';
|
||||
import { Management, button, control } from '@/pages/management/shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
@@ -17,6 +18,7 @@ type Plan = {
|
||||
holders: number[];
|
||||
version: number | null;
|
||||
rule: string;
|
||||
pending: {approval_id:string;confirmation_url:string;expires_at:string} | null;
|
||||
};
|
||||
};
|
||||
export default function Installation(initial: Plan) {
|
||||
@@ -27,6 +29,9 @@ export default function Installation(initial: Plan) {
|
||||
const [second, setSecond] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [confirmationUrl, setConfirmationUrl] = useState<string | null>(null);
|
||||
const [installationKey] = useState(createOperationKey);
|
||||
const [bootstrapKey] = useState(createOperationKey);
|
||||
async function run(bootstrap = false) {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
@@ -37,7 +42,7 @@ export default function Installation(initial: Plan) {
|
||||
hash: plan.hash,
|
||||
confirm: confirmed,
|
||||
reason,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
idempotency_key: bootstrap ? bootstrapKey : installationKey,
|
||||
...(bootstrap
|
||||
? {
|
||||
first_user_id: Number(first),
|
||||
@@ -48,11 +53,12 @@ export default function Installation(initial: Plan) {
|
||||
);
|
||||
setMessage(
|
||||
bootstrap
|
||||
? 'Dupla inicializada. Inicie uma nova sessão como um dos titulares designados; MFA permanece obrigatório.'
|
||||
? 'Pedido registado, sem atribuir privilégios. O segundo titular deve autenticar-se com MFA e confirmar pelo endereço abaixo.'
|
||||
: result.changed
|
||||
? 'Schema instalado. Perfis ainda não disponibilizados; nenhuma conta ou atribuição criada.'
|
||||
: 'Schema já instalado. Nenhuma reinstalação ou duplicação.',
|
||||
);
|
||||
if (bootstrap) setConfirmationUrl(result.confirmation_url as string);
|
||||
if (!bootstrap)
|
||||
setPlan(
|
||||
(await profileJson(
|
||||
@@ -141,6 +147,7 @@ export default function Installation(initial: Plan) {
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2>Inicialização separada dos dois superutilizadores</h2>
|
||||
<p>{plan.bootstrap.rule}</p>
|
||||
{plan.bootstrap.pending && <p>Pedido pendente até {plan.bootstrap.pending.expires_at}. <a className="underline" href={plan.bootstrap.pending.confirmation_url}>Recuperar pedido de confirmação</a>. Nenhum privilégio foi atribuído pelo pedido.</p>}
|
||||
{plan.bootstrap.initialized ? (
|
||||
<p>
|
||||
Dupla já inicializada:{' '}
|
||||
@@ -176,6 +183,7 @@ export default function Installation(initial: Plan) {
|
||||
busy ||
|
||||
!confirmed ||
|
||||
!plan.installed ||
|
||||
!!plan.bootstrap.pending ||
|
||||
!first ||
|
||||
!second ||
|
||||
first === second ||
|
||||
@@ -183,12 +191,13 @@ export default function Installation(initial: Plan) {
|
||||
}
|
||||
onClick={() => void run(true)}
|
||||
>
|
||||
Inicializar apenas estas duas contas
|
||||
Pedir confirmação ao segundo titular
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
<p role="status">{message}</p>
|
||||
{confirmationUrl && <p>Endereço para o segundo titular: <a className="underline" href={confirmationUrl}>{confirmationUrl}</a>. O primeiro titular pode consultar, mas não confirmar.</p>}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,48 +1,195 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
type RequestEntry = { id: string; status: string; reason: string; decision_reason: string | null; created_at: string };
|
||||
export default function RequestProfile({ requests, types, organizations, documents }: {
|
||||
requests: RequestEntry[]; types: string[]; organizations: {id: string; name: string}[]; documents: {id: string; file_name: string}[];
|
||||
type RequestEntry = {
|
||||
id: string;
|
||||
status: string;
|
||||
reason: string;
|
||||
decision_reason: string | null;
|
||||
created_at: string;
|
||||
};
|
||||
export default function RequestProfile({
|
||||
requests,
|
||||
types,
|
||||
organizations,
|
||||
documents,
|
||||
}: {
|
||||
requests: RequestEntry[];
|
||||
types: string[];
|
||||
organizations: { id: string; name: string }[];
|
||||
documents: { id: string; file_name: string }[];
|
||||
}) {
|
||||
const [representation, setRepresentation] = useState('individual');
|
||||
const [organization, setOrganization] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [proofs, setProofs] = useState<string[]>([]);
|
||||
const [reason, setReason] = useState('');
|
||||
const [key, setKey] = useState(() => crypto.randomUUID());
|
||||
const [key, setKey] = useState(() => createOperationKey());
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function send() {
|
||||
setBusy(true); setMessage('');
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
const result = await profileJson('/perfil/promotor', { creation_key: key, representation_type: representation, organization_id: representation === 'individual' ? null : organization,
|
||||
opportunity_types: selected, document_ids: proofs, reason });
|
||||
setMessage(result.message); setKey(crypto.randomUUID()); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível. Confira o acompanhamento antes de repetir.'); }
|
||||
finally { setBusy(false); }
|
||||
const result = await profileJson('/perfil/promotor', {
|
||||
creation_key: key,
|
||||
representation_type: representation,
|
||||
organization_id:
|
||||
representation === 'individual' ? null : organization,
|
||||
opportunity_types: selected,
|
||||
document_ids: proofs,
|
||||
reason,
|
||||
});
|
||||
setMessage(result.message);
|
||||
setKey(createOperationKey());
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível. Confira o acompanhamento antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
const toggle = (values: string[], id: string) => values.includes(id) ? values.filter(v => v !== id) : [...values, id];
|
||||
return <main className="space-y-6 p-6"><Head title="Perfil de Promotor" /><ProfileNavigation />
|
||||
<h1 className="text-2xl font-semibold">Solicitar perfil de Promotor</h1>
|
||||
<p>A aprovação confirma identidade, representação e comprovativos. Só os tipos aprovados ficam disponíveis; o pedido não ativa o perfil.</p>
|
||||
<form className="max-w-2xl space-y-4" onSubmit={e => { e.preventDefault(); void send(); }}>
|
||||
<label className="block">Representação<select className={control} value={representation} onChange={e => setRepresentation(e.target.value)}>
|
||||
{['individual','company','public_entity','association','partner'].map(v => <option key={v}>{v}</option>)}
|
||||
</select></label>
|
||||
{representation !== 'individual' && <label className="block">Organização representada<select required className={control} value={organization} onChange={e => setOrganization(e.target.value)}>
|
||||
<option value="">Selecionar</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||||
</select></label>}
|
||||
<fieldset><legend>Tipos pretendidos</legend>{types.map(type => <label key={type} className="block"><input type="checkbox" checked={selected.includes(type)} onChange={() => setSelected(toggle(selected,type))} /> {type}</label>)}</fieldset>
|
||||
<fieldset><legend>Comprovativos próprios analisados</legend>{documents.map(d => <label key={d.id} className="block"><input type="checkbox" checked={proofs.includes(d.id)} onChange={() => setProofs(toggle(proofs,d.id))} /> {d.file_name}</label>)}</fieldset>
|
||||
{!documents.length && <p>Sem comprovativos próprios disponíveis. Pode anexar ao seu dossier no <Link className="underline" href="/balcao-virtual/painel">Balcão</Link>; o ficheiro precisa de análise antimalware concluída.</p>}
|
||||
<label className="block">Fundamentação<textarea required minLength={20} maxLength={1000} className={control} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button disabled={busy} className={button}>Submeter pedido de perfil</button>
|
||||
</form>
|
||||
<p role="status" aria-live="polite">{message}</p>
|
||||
<section><h2 className="text-xl font-semibold">Acompanhamento dos meus pedidos</h2>{requests.map(r => <article key={r.id} className="border-b py-3"><p>{r.id} — {r.status}</p><p>{r.decision_reason ?? 'Aguarda revisão independente.'}</p></article>)}{!requests.length && <p>Nenhum pedido recebido.</p>}</section>
|
||||
</main>;
|
||||
const toggle = (values: string[], id: string) =>
|
||||
values.includes(id) ? values.filter((v) => v !== id) : [...values, id];
|
||||
return (
|
||||
<main className="space-y-6 p-6">
|
||||
<Head title="Perfil de Promotor" />
|
||||
<ProfileNavigation />
|
||||
<h1 className="text-2xl font-semibold">
|
||||
Solicitar perfil de Promotor
|
||||
</h1>
|
||||
<p>
|
||||
A aprovação confirma identidade, representação e comprovativos.
|
||||
Só os tipos aprovados ficam disponíveis; o pedido não ativa o
|
||||
perfil.
|
||||
</p>
|
||||
<form
|
||||
className="max-w-2xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send();
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Representação
|
||||
<select
|
||||
className={control}
|
||||
value={representation}
|
||||
onChange={(e) => setRepresentation(e.target.value)}
|
||||
>
|
||||
{[
|
||||
'individual',
|
||||
'company',
|
||||
'public_entity',
|
||||
'association',
|
||||
'partner',
|
||||
].map((v) => (
|
||||
<option key={v}>{v}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{representation !== 'individual' && (
|
||||
<label className="block">
|
||||
Organização representada
|
||||
<select
|
||||
required
|
||||
className={control}
|
||||
value={organization}
|
||||
onChange={(e) => setOrganization(e.target.value)}
|
||||
>
|
||||
<option value="">Selecionar</option>
|
||||
{organizations.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<fieldset>
|
||||
<legend>Tipos pretendidos</legend>
|
||||
{types.map((type) => (
|
||||
<label key={type} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(type)}
|
||||
onChange={() =>
|
||||
setSelected(toggle(selected, type))
|
||||
}
|
||||
/>{' '}
|
||||
{type}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Comprovativos próprios analisados</legend>
|
||||
{documents.map((d) => (
|
||||
<label key={d.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={proofs.includes(d.id)}
|
||||
onChange={() => setProofs(toggle(proofs, d.id))}
|
||||
/>{' '}
|
||||
{d.file_name}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
{!documents.length && (
|
||||
<p>
|
||||
Sem comprovativos próprios disponíveis. Pode anexar ao
|
||||
seu dossier no{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href="/balcao-virtual/painel"
|
||||
>
|
||||
Balcão
|
||||
</Link>
|
||||
; o ficheiro precisa de análise antimalware concluída.
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Fundamentação
|
||||
<textarea
|
||||
required
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy} className={button}>
|
||||
Submeter pedido de perfil
|
||||
</button>
|
||||
</form>
|
||||
<p role="status" aria-live="polite">
|
||||
{message}
|
||||
</p>
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Acompanhamento dos meus pedidos
|
||||
</h2>
|
||||
{requests.map((r) => (
|
||||
<article key={r.id} className="border-b py-3">
|
||||
<p>
|
||||
{r.id} — {r.status}
|
||||
</p>
|
||||
<p>
|
||||
{r.decision_reason ??
|
||||
'Aguarda revisão independente.'}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
{!requests.length && <p>Nenhum pedido recebido.</p>}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -281,7 +281,7 @@ export default function Editor({
|
||||
</>
|
||||
)}
|
||||
{isCorridor && (
|
||||
<Field label="Descrição" error={form.errors.description}>
|
||||
<Field label="Descrição" error={form.errors.description}>
|
||||
<textarea
|
||||
className={control}
|
||||
rows={5}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export type ProfileAccess = {
|
||||
contexts: { organization_id: string | null; type: string }[];
|
||||
contexts: { organization_id: string | null; organization_name?: string; type: string }[];
|
||||
internalPromoter?: boolean;
|
||||
mine: string | null;
|
||||
create: string | null;
|
||||
request: string;
|
||||
|
||||
Reference in New Issue
Block a user