@@ -1,61 +1,256 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { Link } from "@inertiajs/react";
|
||||
import type { FormEvent } from "react";
|
||||
import { newSubmissionKey } from "@/lib/portal-api";
|
||||
import { Frame, Field, button, card, input } from "./shared";
|
||||
import { useRef, useState } from 'react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import type { FormEvent } from 'react';
|
||||
import { newSubmissionKey } from '@/lib/portal-api';
|
||||
import { Frame, Field, button, card, input } from './shared';
|
||||
|
||||
type Opportunity = { id: string; slug: string; title: string; sector?: { name: string } | null };
|
||||
type Opportunity = {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
sector?: { name: string } | null;
|
||||
};
|
||||
type Props = { record: Opportunity; modalities: string[]; returnUrl?: string };
|
||||
type Form = {
|
||||
fullName: string; email: string; phone: string; investorType: string; country: string;
|
||||
sectorInterest: string; modality: string; investmentRange: string; message: string; privacyConsent: boolean; shareWithProponent: boolean;
|
||||
fullName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
investorType: string;
|
||||
country: string;
|
||||
sectorInterest: string;
|
||||
modality: string;
|
||||
investmentRange: string;
|
||||
message: string;
|
||||
privacyConsent: boolean;
|
||||
shareWithProponent: boolean;
|
||||
};
|
||||
|
||||
export default function BusinessInterest({ record, modalities, returnUrl = "/negocios" }: Props) {
|
||||
const [form, setForm] = useState<Form>({ fullName: "", email: "", phone: "", investorType: "empresa", country: "MZ", sectorInterest: record.sector?.name ?? "", modality: modalities[0] ?? "", investmentRange: "", message: "", privacyConsent: false, shareWithProponent: false });
|
||||
export default function BusinessInterest({
|
||||
record,
|
||||
modalities,
|
||||
returnUrl = '/negocios',
|
||||
}: Props) {
|
||||
const [form, setForm] = useState<Form>({
|
||||
fullName: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
investorType: 'empresa',
|
||||
country: 'MZ',
|
||||
sectorInterest: record.sector?.name ?? '',
|
||||
modality: modalities[0] ?? '',
|
||||
investmentRange: '',
|
||||
message: '',
|
||||
privacyConsent: false,
|
||||
shareWithProponent: false,
|
||||
});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [receipt, setReceipt] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [receipt, setReceipt] = useState('');
|
||||
const key = useRef(newSubmissionKey());
|
||||
const update = <K extends keyof Form>(field: K, value: Form[K]) => setForm((current) => ({ ...current, [field]: value }));
|
||||
const update = <K extends keyof Form>(field: K, value: Form[K]) =>
|
||||
setForm((current) => ({ ...current, [field]: value }));
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!form.privacyConsent) { setError("Aceite o tratamento de dados para enviar o pedido."); return; }
|
||||
setBusy(true); setError("");
|
||||
const xsrf = decodeURIComponent(document.cookie.split("; ").find((cookie) => cookie.startsWith("XSRF-TOKEN="))?.slice(11) ?? "");
|
||||
if (!form.privacyConsent) {
|
||||
setError('Aceite o tratamento de dados para enviar o pedido.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const xsrf = decodeURIComponent(
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((cookie) => cookie.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11) ?? '',
|
||||
);
|
||||
try {
|
||||
const response = await fetch("/api/v1/interest-requests", {
|
||||
method: "POST", credentials: "same-origin",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", "X-XSRF-TOKEN": xsrf, "Idempotency-Key": key.current },
|
||||
body: JSON.stringify({ ...form, existingBusinessId: record.id }),
|
||||
const response = await fetch('/api/v1/interest-requests', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': xsrf,
|
||||
'Idempotency-Key': key.current,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...form,
|
||||
existingBusinessId: record.id,
|
||||
}),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.message ?? "Não foi possível enviar a manifestação.");
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
data.message ?? 'Não foi possível enviar a manifestação.',
|
||||
);
|
||||
setReceipt(data.data.reference);
|
||||
key.current = newSubmissionKey();
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Não foi possível enviar a manifestação.");
|
||||
} finally { setBusy(false); }
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Não foi possível enviar a manifestação.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Frame title="Manifestar interesse">
|
||||
<Link href={returnUrl} className="underline">Voltar à oportunidade</Link>
|
||||
<p>Oportunidade: <strong>{record.title}</strong></p>
|
||||
{receipt ? <section className={card} role="status"><h2 className="text-xl font-bold">Pedido recebido</h2><p>Referência: {receipt}</p><p>A equipa fará a triagem antes de qualquer partilha com o proponente.</p></section> : (
|
||||
<Link href={returnUrl} className="underline">
|
||||
Voltar à oportunidade
|
||||
</Link>
|
||||
<p>
|
||||
Oportunidade: <strong>{record.title}</strong>
|
||||
</p>
|
||||
{receipt ? (
|
||||
<section className={card} role="status">
|
||||
<h2 className="text-xl font-bold">Pedido recebido</h2>
|
||||
<p>Referência: {receipt}</p>
|
||||
<p>
|
||||
A equipa fará a triagem antes de qualquer partilha com o
|
||||
proponente.
|
||||
</p>
|
||||
</section>
|
||||
) : (
|
||||
<form className={`${card} space-y-4`} onSubmit={submit}>
|
||||
<Field label="Nome ou denominação"><input className={input} required minLength={3} maxLength={150} value={form.fullName} onChange={(e) => update("fullName", e.target.value)} /></Field>
|
||||
<Field label="Email"><input className={input} type="email" required maxLength={150} value={form.email} onChange={(e) => update("email", e.target.value)} /></Field>
|
||||
<Field label="Telefone"><input className={input} type="tel" maxLength={30} value={form.phone} onChange={(e) => update("phone", e.target.value)} /></Field>
|
||||
<Field label="Tipo de investidor"><select className={input} value={form.investorType} onChange={(e) => update("investorType", e.target.value)}><option value="empresa">Empresa</option><option value="individual">Pessoa singular</option><option value="fundo">Fundo</option><option value="entidade_publica">Entidade pública</option><option value="outro">Outro</option></select></Field>
|
||||
<Field label="País"><input className={input} required maxLength={100} value={form.country} onChange={(e) => update("country", e.target.value)} /></Field>
|
||||
<Field label="Sector de interesse"><input className={input} required maxLength={150} value={form.sectorInterest} onChange={(e) => update("sectorInterest", e.target.value)} /></Field>
|
||||
<Field label="Modalidade pretendida"><select className={input} required value={form.modality} onChange={(e) => update("modality", e.target.value)}>{modalities.map((modality) => <option key={modality} value={modality}>{modality.replaceAll("_", " ")}</option>)}</select></Field>
|
||||
<Field label="Intervalo de investimento"><input className={input} maxLength={80} value={form.investmentRange} onChange={(e) => update("investmentRange", e.target.value)} /></Field>
|
||||
<Field label="Motivação e pedido"><textarea className={input} required minLength={20} maxLength={2000} rows={5} value={form.message} onChange={(e) => update("message", e.target.value)} /></Field>
|
||||
<label className="flex items-start gap-3"><input type="checkbox" required checked={form.privacyConsent} onChange={(e) => update("privacyConsent", e.target.checked)} /><span>Autorizo o tratamento destes dados para responder a esta manifestação. O envio não confirma elegibilidade nem permite partilha automática com o proponente.</span></label>
|
||||
<label className="flex items-start gap-3"><input type="checkbox" checked={form.shareWithProponent} onChange={(e) => update("shareWithProponent", e.target.checked)} /><span>Autorizo, se necessário para avaliar esta manifestação, a partilha do meu nome, email, telefone e mensagem com o proponente. Esta autorização é opcional e pode ser retirada junto da equipa.</span></label>
|
||||
<Field label="Nome ou denominação">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={150}
|
||||
value={form.fullName}
|
||||
onChange={(e) => update('fullName', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Email">
|
||||
<input
|
||||
className={input}
|
||||
type="email"
|
||||
required
|
||||
maxLength={150}
|
||||
value={form.email}
|
||||
onChange={(e) => update('email', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Telefone">
|
||||
<input
|
||||
className={input}
|
||||
type="tel"
|
||||
maxLength={30}
|
||||
value={form.phone}
|
||||
onChange={(e) => update('phone', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Tipo de investidor">
|
||||
<select
|
||||
className={input}
|
||||
value={form.investorType}
|
||||
onChange={(e) =>
|
||||
update('investorType', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="empresa">Empresa</option>
|
||||
<option value="individual">Pessoa singular</option>
|
||||
<option value="fundo">Fundo</option>
|
||||
<option value="entidade_publica">
|
||||
Entidade pública
|
||||
</option>
|
||||
<option value="outro">Outro</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="País">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
maxLength={100}
|
||||
value={form.country}
|
||||
onChange={(e) => update('country', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Sector de interesse">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
maxLength={150}
|
||||
value={form.sectorInterest}
|
||||
onChange={(e) =>
|
||||
update('sectorInterest', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Modalidade pretendida">
|
||||
<select
|
||||
className={input}
|
||||
required
|
||||
value={form.modality}
|
||||
onChange={(e) => update('modality', e.target.value)}
|
||||
>
|
||||
{modalities.map((modality) => (
|
||||
<option key={modality} value={modality}>
|
||||
{modality.replaceAll('_', ' ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Intervalo de investimento">
|
||||
<input
|
||||
className={input}
|
||||
maxLength={80}
|
||||
value={form.investmentRange}
|
||||
onChange={(e) =>
|
||||
update('investmentRange', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Motivação e pedido">
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={20}
|
||||
maxLength={2000}
|
||||
rows={5}
|
||||
value={form.message}
|
||||
onChange={(e) => update('message', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<label className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
required
|
||||
checked={form.privacyConsent}
|
||||
onChange={(e) =>
|
||||
update('privacyConsent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
<span>
|
||||
Autorizo o tratamento destes dados para responder a
|
||||
esta manifestação. O envio não confirma
|
||||
elegibilidade nem permite partilha automática com o
|
||||
proponente.
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.shareWithProponent}
|
||||
onChange={(e) =>
|
||||
update('shareWithProponent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
<span>
|
||||
Autorizo, se necessário para avaliar esta
|
||||
manifestação, a partilha do meu nome, email,
|
||||
telefone e mensagem com o proponente. Esta
|
||||
autorização é opcional e pode ser retirada junto da
|
||||
equipa.
|
||||
</span>
|
||||
</label>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<button className={button} disabled={busy}>{busy ? "A enviar…" : "Enviar manifestação"}</button>
|
||||
<button className={button} disabled={busy}>
|
||||
{busy ? 'A enviar…' : 'Enviar manifestação'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</Frame>
|
||||
|
||||
@@ -1,57 +1,197 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Frame, button, card, input } from "./shared";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { businessModalities } from "./business-types";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, button, card, input } from './shared';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { businessModalities } from './business-types';
|
||||
|
||||
type PublicBusiness = {
|
||||
id: string; slug: string; title: string; modality: string; objective?: string | null; stage?: string | null;
|
||||
amount_min?: string | null; amount_max?: string | null; currency?: string | null;
|
||||
sector?: { name: string; slug: string } | null; province?: string | null;
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
modality: string;
|
||||
objective?: string | null;
|
||||
stage?: string | null;
|
||||
amount_min?: string | null;
|
||||
amount_max?: string | null;
|
||||
currency?: string | null;
|
||||
sector?: { name: string; slug: string } | null;
|
||||
province?: string | null;
|
||||
};
|
||||
type PaginationLink = { url: string | null; label: string; active: boolean };
|
||||
type Props = { results: { data: PublicBusiness[]; links?: PaginationLink[] | { first: string | null; last: string | null; prev: string | null; next: string | null }; meta?: { links?: PaginationLink[]; total?: number } }; filters: { q?: string; modality?: string; province_id?: string; district_id?: string; admin_post_id?: string; locality_id?: string }; territorySelection?: TerritoryOption[] };
|
||||
type Props = {
|
||||
results: {
|
||||
data: PublicBusiness[];
|
||||
links?:
|
||||
| PaginationLink[]
|
||||
| {
|
||||
first: string | null;
|
||||
last: string | null;
|
||||
prev: string | null;
|
||||
next: string | null;
|
||||
};
|
||||
meta?: { links?: PaginationLink[]; total?: number };
|
||||
};
|
||||
filters: {
|
||||
q?: string;
|
||||
modality?: string;
|
||||
province_id?: string;
|
||||
district_id?: string;
|
||||
admin_post_id?: string;
|
||||
locality_id?: string;
|
||||
};
|
||||
territorySelection?: TerritoryOption[];
|
||||
};
|
||||
|
||||
export default function BusinessMarketplace({ results, filters, territorySelection = [] }: Props) {
|
||||
const [query, setQuery] = useState(filters.q ?? "");
|
||||
const [modality, setModality] = useState(filters.modality ?? "");
|
||||
const [territory, setTerritory] = useState<Record<string, string>>({ province_id: filters.province_id ?? "", district_id: filters.district_id ?? "", admin_post_id: filters.admin_post_id ?? "", locality_id: filters.locality_id ?? "" });
|
||||
const returnQuery = new URLSearchParams({ ...(query ? { q: query } : {}), ...(modality ? { modality } : {}), ...territory }).toString();
|
||||
const paginationLinks = results.meta?.links ?? (Array.isArray(results.links) ? results.links : []);
|
||||
export default function BusinessMarketplace({
|
||||
results,
|
||||
filters,
|
||||
territorySelection = [],
|
||||
}: Props) {
|
||||
const [query, setQuery] = useState(filters.q ?? '');
|
||||
const [modality, setModality] = useState(filters.modality ?? '');
|
||||
const [territory, setTerritory] = useState<Record<string, string>>({
|
||||
province_id: filters.province_id ?? '',
|
||||
district_id: filters.district_id ?? '',
|
||||
admin_post_id: filters.admin_post_id ?? '',
|
||||
locality_id: filters.locality_id ?? '',
|
||||
});
|
||||
const returnQuery = new URLSearchParams({
|
||||
...(query ? { q: query } : {}),
|
||||
...(modality ? { modality } : {}),
|
||||
...territory,
|
||||
}).toString();
|
||||
const paginationLinks =
|
||||
results.meta?.links ??
|
||||
(Array.isArray(results.links) ? results.links : []);
|
||||
return (
|
||||
<Frame title="Oportunidades de negócio">
|
||||
<p>Explore oportunidades aprovadas para publicação. A informação está sujeita a diligência independente.</p>
|
||||
<form className="flex flex-wrap gap-3" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
router.get("/negocios", { q: query || undefined, modality: modality || undefined, ...territory }, { preserveState: true, preserveScroll: true });
|
||||
}}>
|
||||
<label className="sr-only" htmlFor="business-search">Pesquisar negócios</label>
|
||||
<input id="business-search" className={input} value={query} maxLength={120} onChange={(event) => setQuery(event.target.value)} />
|
||||
<p>
|
||||
Explore oportunidades aprovadas para publicação. A informação
|
||||
está sujeita a diligência independente.
|
||||
</p>
|
||||
<form
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
router.get(
|
||||
'/negocios',
|
||||
{
|
||||
q: query || undefined,
|
||||
modality: modality || undefined,
|
||||
...territory,
|
||||
},
|
||||
{ preserveState: true, preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label className="sr-only" htmlFor="business-search">
|
||||
Pesquisar negócios
|
||||
</label>
|
||||
<input
|
||||
id="business-search"
|
||||
className={input}
|
||||
value={query}
|
||||
maxLength={120}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
/>
|
||||
<label className="grid gap-1">
|
||||
<span>Tipo de oportunidade</span>
|
||||
<select className={input} value={modality} onChange={(event) => setModality(event.target.value)}>
|
||||
<select
|
||||
className={input}
|
||||
value={modality}
|
||||
onChange={(event) => setModality(event.target.value)}
|
||||
>
|
||||
<option value="">Todos os tipos</option>
|
||||
{Object.entries(businessModalities).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
|
||||
{Object.entries(businessModalities).map(
|
||||
([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<TerritoryFields initial={territorySelection} onChange={(path) => setTerritory({ province_id: path[0]?.id ?? "", district_id: path[1]?.id ?? "", admin_post_id: path[2]?.id ?? "", locality_id: path[3]?.id ?? "" })} />
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
onChange={(path) =>
|
||||
setTerritory({
|
||||
province_id: path[0]?.id ?? '',
|
||||
district_id: path[1]?.id ?? '',
|
||||
admin_post_id: path[2]?.id ?? '',
|
||||
locality_id: path[3]?.id ?? '',
|
||||
})
|
||||
}
|
||||
/>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
<p role="status">{results.meta?.total ?? results.data.length} anúncios de negócios publicados</p>
|
||||
{!results.data.length && <p role="status">Não existem oportunidades publicadas com estes critérios.</p>}
|
||||
<p role="status">
|
||||
{results.meta?.total ?? results.data.length} anúncios de
|
||||
negócios publicados
|
||||
</p>
|
||||
{!results.data.length && (
|
||||
<p role="status">
|
||||
Não existem oportunidades publicadas com estes critérios.
|
||||
</p>
|
||||
)}
|
||||
<ul className="grid gap-4 md:grid-cols-2">
|
||||
{results.data.map((record) => (
|
||||
<li className={card} key={record.id}>
|
||||
<p>{businessModalities[record.modality] ?? record.modality}</p>
|
||||
<h2 className="text-xl font-bold"><Link className="underline" href={`/negocios/${record.slug}${returnQuery ? `?${returnQuery}` : ""}`}>{record.title}</Link></h2>
|
||||
<p>{[record.sector?.name, record.province, record.stage].filter(Boolean).join(" · ")}</p>
|
||||
{(record.amount_min || record.amount_max) && <p>{record.amount_min ?? "—"} – {record.amount_max ?? "—"} {record.currency}</p>}
|
||||
{record.objective && <p className="mt-3 line-clamp-3">{record.objective}</p>}
|
||||
<p>
|
||||
{businessModalities[record.modality] ??
|
||||
record.modality}
|
||||
</p>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/negocios/${record.slug}${returnQuery ? `?${returnQuery}` : ''}`}
|
||||
>
|
||||
{record.title}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{[
|
||||
record.sector?.name,
|
||||
record.province,
|
||||
record.stage,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
{(record.amount_min || record.amount_max) && (
|
||||
<p>
|
||||
{record.amount_min ?? '—'} –{' '}
|
||||
{record.amount_max ?? '—'} {record.currency}
|
||||
</p>
|
||||
)}
|
||||
{record.objective && (
|
||||
<p className="mt-3 line-clamp-3">
|
||||
{record.objective}
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<nav aria-label="Paginação das oportunidades" className="flex flex-wrap gap-3">
|
||||
{paginationLinks.map((link) => link.url ? <Link key={link.label} href={link.url} className={link.active ? "font-bold underline" : "underline"} dangerouslySetInnerHTML={{ __html: link.label }} /> : null)}
|
||||
<nav
|
||||
aria-label="Paginação das oportunidades"
|
||||
className="flex flex-wrap gap-3"
|
||||
>
|
||||
{paginationLinks.map((link) =>
|
||||
link.url ? (
|
||||
<Link
|
||||
key={link.label}
|
||||
href={link.url}
|
||||
className={
|
||||
link.active
|
||||
? 'font-bold underline'
|
||||
: 'underline'
|
||||
}
|
||||
dangerouslySetInnerHTML={{ __html: link.label }}
|
||||
/>
|
||||
) : null,
|
||||
)}
|
||||
</nav>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
@@ -1,28 +1,79 @@
|
||||
import { Link } from "@inertiajs/react";
|
||||
import { Frame, button, card } from "./shared";
|
||||
import { businessModalities } from "./business-types";
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, button, card } from './shared';
|
||||
import { businessModalities } from './business-types';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
|
||||
type Business = {
|
||||
id: string; slug: string; title: string; modality: string; objective?: string | null; stage?: string | null; activity_code?: string | null;
|
||||
amount_min?: string | null; amount_max?: string | null; available_percentage?: string | null; currency?: string | null;
|
||||
province?: string | null; district?: string | null; locality?: string | null; sector?: { name: string; slug: string } | null;
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
modality: string;
|
||||
objective?: string | null;
|
||||
stage?: string | null;
|
||||
activity_code?: string | null;
|
||||
amount_min?: string | null;
|
||||
amount_max?: string | null;
|
||||
available_percentage?: string | null;
|
||||
currency?: string | null;
|
||||
province?: string | null;
|
||||
district?: string | null;
|
||||
locality?: string | null;
|
||||
sector?: { name: string; slug: string } | null;
|
||||
};
|
||||
|
||||
export default function BusinessOpportunity({ record, returnUrl = "/negocios", interestUrl = `/negocios/${record.slug}/manifestar-interesse` }: { record: Business; returnUrl?: string; interestUrl?: string }) {
|
||||
export default function BusinessOpportunity({
|
||||
record,
|
||||
returnUrl = '/negocios',
|
||||
interestUrl = `/negocios/${record.slug}/manifestar-interesse`,
|
||||
}: {
|
||||
record: Business;
|
||||
returnUrl?: string;
|
||||
interestUrl?: string;
|
||||
}) {
|
||||
return (
|
||||
<Frame title={record.title}>
|
||||
<PartnershipSourceLinks type="business" id={record.id}/>
|
||||
<Link href={returnUrl} className="underline">Voltar às oportunidades</Link>
|
||||
<PartnershipSourceLinks type="business" id={record.id} />
|
||||
<Link href={returnUrl} className="underline">
|
||||
Voltar às oportunidades
|
||||
</Link>
|
||||
<section className={`${card} space-y-4`}>
|
||||
<p>{businessModalities[record.modality] ?? record.modality}</p>
|
||||
<p>{[record.sector?.name, record.stage, record.activity_code].filter(Boolean).join(" · ")}</p>
|
||||
{(record.province || record.district || record.locality) && <p>{[record.locality, record.district, record.province].filter(Boolean).join(", ")}</p>}
|
||||
{(record.amount_min || record.amount_max) && <p>Montante indicativo: {record.amount_min ?? "—"} – {record.amount_max ?? "—"} {record.currency}</p>}
|
||||
{record.available_percentage && <p>Participação indicada: {record.available_percentage}%</p>}
|
||||
{record.objective && <div><h2 className="font-bold">Objectivo</h2><p className="whitespace-pre-wrap">{record.objective}</p></div>}
|
||||
<p className="text-sm">A publicação não constitui garantia de titularidade, avaliação, transmissibilidade ou retorno.</p>
|
||||
<Link className={button} href={interestUrl}>Manifestar interesse</Link>
|
||||
<p>
|
||||
{[record.sector?.name, record.stage, record.activity_code]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
{(record.province || record.district || record.locality) && (
|
||||
<p>
|
||||
{[record.locality, record.district, record.province]
|
||||
.filter(Boolean)
|
||||
.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
{(record.amount_min || record.amount_max) && (
|
||||
<p>
|
||||
Montante indicativo: {record.amount_min ?? '—'} –{' '}
|
||||
{record.amount_max ?? '—'} {record.currency}
|
||||
</p>
|
||||
)}
|
||||
{record.available_percentage && (
|
||||
<p>Participação indicada: {record.available_percentage}%</p>
|
||||
)}
|
||||
{record.objective && (
|
||||
<div>
|
||||
<h2 className="font-bold">Objectivo</h2>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{record.objective}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
A publicação não constitui garantia de titularidade,
|
||||
avaliação, transmissibilidade ou retorno.
|
||||
</p>
|
||||
<Link className={button} href={interestUrl}>
|
||||
Manifestar interesse
|
||||
</Link>
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { api, button, card, Field, input } from "./shared";
|
||||
import type { BusinessObject } from "./business-objects";
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { api, button, card, Field, input } from './shared';
|
||||
import type { BusinessObject } from './business-objects';
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
identity: "Identidade",
|
||||
representation: "Representação",
|
||||
declared_ownership: "Titularidade declarada",
|
||||
documentary_ownership: "Titularidade documental",
|
||||
document_received: "Documento recebido",
|
||||
document_validated: "Documento validado",
|
||||
independent_valuation: "Avaliação independente",
|
||||
land_right_documented: "Direito fundiário documentado",
|
||||
license_confirmed: "Licença confirmada",
|
||||
validity: "Validade",
|
||||
legal_transfer: "Transmissibilidade jurídica",
|
||||
prior_authorization: "Autorização prévia",
|
||||
confirmed: "Confirmado pelo revisor",
|
||||
rejected: "Não confirmado",
|
||||
inconclusive: "Inconclusivo",
|
||||
revoked: "Revogado",
|
||||
stale: "Rever após alteração dos dados",
|
||||
expired: "Expirado",
|
||||
identity: 'Identidade',
|
||||
representation: 'Representação',
|
||||
declared_ownership: 'Titularidade declarada',
|
||||
documentary_ownership: 'Titularidade documental',
|
||||
document_received: 'Documento recebido',
|
||||
document_validated: 'Documento validado',
|
||||
independent_valuation: 'Avaliação independente',
|
||||
land_right_documented: 'Direito fundiário documentado',
|
||||
license_confirmed: 'Licença confirmada',
|
||||
validity: 'Validade',
|
||||
legal_transfer: 'Transmissibilidade jurídica',
|
||||
prior_authorization: 'Autorização prévia',
|
||||
confirmed: 'Confirmado pelo revisor',
|
||||
rejected: 'Não confirmado',
|
||||
inconclusive: 'Inconclusivo',
|
||||
revoked: 'Revogado',
|
||||
stale: 'Rever após alteração dos dados',
|
||||
expired: 'Expirado',
|
||||
};
|
||||
export type BusinessVerification = {
|
||||
check: string;
|
||||
@@ -49,31 +49,38 @@ export default function BusinessVerifications({
|
||||
objects: BusinessObject[];
|
||||
}) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [outcome, setOutcome] = useState("inconclusive");
|
||||
const [error, setError] = useState('');
|
||||
const [outcome, setOutcome] = useState('inconclusive');
|
||||
return (
|
||||
<section className={`${card} space-y-4`}>
|
||||
<h2 className="text-xl font-bold">Verificações e evidências</h2>
|
||||
<p>
|
||||
Cada conclusão corresponde apenas ao aspecto e à versão analisados. Não constitui
|
||||
certificação global, autorização de publicação ou garantia de transmissão.
|
||||
Alterações aos dados exigem nova revisão.
|
||||
Cada conclusão corresponde apenas ao aspecto e à versão
|
||||
analisados. Não constitui certificação global, autorização de
|
||||
publicação ou garantia de transmissão. Alterações aos dados
|
||||
exigem nova revisão.
|
||||
</p>
|
||||
{findings.length === 0 && <p>Ainda não existem verificações registadas.</p>}
|
||||
{findings.length === 0 && (
|
||||
<p>Ainda não existem verificações registadas.</p>
|
||||
)}
|
||||
<ul className="space-y-4">
|
||||
{findings.map((finding) => (
|
||||
<li key={finding.version_no} className="break-words">
|
||||
<strong>
|
||||
{labels[finding.check]} · {labels[finding.effective_outcome]}
|
||||
{labels[finding.check]} ·{' '}
|
||||
{labels[finding.effective_outcome]}
|
||||
</strong>
|
||||
<p>
|
||||
{objects.find((object) => object.id === finding.object_id)?.payload
|
||||
.label ?? "Negócio"}{" "}
|
||||
{objects.find(
|
||||
(object) => object.id === finding.object_id,
|
||||
)?.payload.label ?? 'Negócio'}{' '}
|
||||
· versão {finding.version_no}
|
||||
</p>
|
||||
<p>Evidência: {finding.evidence_reference}</p>
|
||||
<p>{finding.note}</p>
|
||||
{finding.valid_until && <p>Válido até {finding.valid_until}</p>}
|
||||
{finding.valid_until && (
|
||||
<p>Válido até {finding.valid_until}</p>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -82,20 +89,25 @@ export default function BusinessVerifications({
|
||||
className="space-y-4"
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.currentTarget));
|
||||
const data = Object.fromEntries(
|
||||
new FormData(event.currentTarget),
|
||||
);
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api(`/api/v1/existing-business/listings/${id}/verifications`, {
|
||||
...data,
|
||||
version_no: version,
|
||||
});
|
||||
await api(
|
||||
`/api/v1/existing-business/listings/${id}/verifications`,
|
||||
{
|
||||
...data,
|
||||
version_no: version,
|
||||
},
|
||||
);
|
||||
router.reload();
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: "Não foi possível registar a verificação.",
|
||||
: 'Não foi possível registar a verificação.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -127,15 +139,20 @@ export default function BusinessVerifications({
|
||||
className={input}
|
||||
name="outcome"
|
||||
value={outcome}
|
||||
onChange={(event) => setOutcome(event.target.value)}
|
||||
onChange={(event) =>
|
||||
setOutcome(event.target.value)
|
||||
}
|
||||
>
|
||||
{["inconclusive", "confirmed", "rejected", "revoked"].map(
|
||||
(value) => (
|
||||
<option key={value} value={value}>
|
||||
{labels[value]}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
{[
|
||||
'inconclusive',
|
||||
'confirmed',
|
||||
'rejected',
|
||||
'revoked',
|
||||
].map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{labels[value]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Referência da evidência consultada">
|
||||
@@ -161,7 +178,7 @@ export default function BusinessVerifications({
|
||||
className={input}
|
||||
type="date"
|
||||
name="valid_until"
|
||||
required={outcome === "confirmed"}
|
||||
required={outcome === 'confirmed'}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button} disabled={busy}>
|
||||
|
||||
@@ -239,8 +239,12 @@ export default function BusinessWizard({
|
||||
const [sectorId, setSectorId] = useState(record.sector_id ?? null);
|
||||
const [sectorSearch, setSectorSearch] = useState('');
|
||||
const [publicTitle, setPublicTitle] = useState(record.public_title ?? '');
|
||||
const [territoryPaths, setTerritoryPaths] = useState(record.territory_paths ?? []);
|
||||
const [resolvedLocationJson, setResolvedLocationJson] = useState(record.payload.locations_json ?? '');
|
||||
const [territoryPaths, setTerritoryPaths] = useState(
|
||||
record.territory_paths ?? [],
|
||||
);
|
||||
const [resolvedLocationJson, setResolvedLocationJson] = useState(
|
||||
record.payload.locations_json ?? '',
|
||||
);
|
||||
const [version, setVersion] = useState(record.version_no);
|
||||
const versionRef = useRef(record.version_no);
|
||||
const saved = useRef(
|
||||
@@ -358,7 +362,9 @@ export default function BusinessWizard({
|
||||
next.locations_json = encodeBusinessLocations(rows);
|
||||
}
|
||||
if (key === 'geography_scope' && value === 'specific') {
|
||||
const first = decodeBusinessLocations(current.locations_json)[0];
|
||||
const first = decodeBusinessLocations(
|
||||
current.locations_json,
|
||||
)[0];
|
||||
if (first?.province_id) {
|
||||
next.province_id = first.province_id;
|
||||
next.district_id = first.district_id;
|
||||
@@ -396,23 +402,33 @@ export default function BusinessWizard({
|
||||
});
|
||||
};
|
||||
const locationRows = decodeBusinessLocations(payload.locations_json);
|
||||
const saveLocationRows = (rows: ReturnType<typeof decodeBusinessLocations>) => {
|
||||
const saveLocationRows = (
|
||||
rows: ReturnType<typeof decodeBusinessLocations>,
|
||||
) => {
|
||||
update('locations_json', encodeBusinessLocations(rows));
|
||||
};
|
||||
const setLocation = (
|
||||
index: number,
|
||||
key: keyof ReturnType<typeof emptyBusinessLocation>,
|
||||
value: string,
|
||||
) => saveLocationRows(updateBusinessLocation(locationRows, index, key, value));
|
||||
) =>
|
||||
saveLocationRows(
|
||||
updateBusinessLocation(locationRows, index, key, value),
|
||||
);
|
||||
const addLocation = () => {
|
||||
if (locationRows.length >= 20) return;
|
||||
saveLocationRows([...locationRows, emptyBusinessLocation()]);
|
||||
};
|
||||
const removeLocation = (index: number) => {
|
||||
const remaining = locationRows.filter((_, rowIndex) => rowIndex !== index);
|
||||
saveLocationRows(remaining.length ? remaining : [emptyBusinessLocation()]);
|
||||
const remaining = locationRows.filter(
|
||||
(_, rowIndex) => rowIndex !== index,
|
||||
);
|
||||
saveLocationRows(
|
||||
remaining.length ? remaining : [emptyBusinessLocation()],
|
||||
);
|
||||
};
|
||||
const duplicateLocationPath = hasDuplicateBusinessLocationPath(locationRows);
|
||||
const duplicateLocationPath =
|
||||
hasDuplicateBusinessLocationPath(locationRows);
|
||||
const fundingNeedsReconciliation = fundingReconciliationWarning(payload);
|
||||
const submit = async () => {
|
||||
if (
|
||||
@@ -635,8 +651,14 @@ export default function BusinessWizard({
|
||||
field.step === step &&
|
||||
key !== 'locations_json' &&
|
||||
!(
|
||||
payload.geography_scope === 'multiple' &&
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id'].includes(key)
|
||||
payload.geography_scope ===
|
||||
'multiple' &&
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
].includes(key)
|
||||
) &&
|
||||
Object.entries(field.when ?? {}).every(
|
||||
([dependency, values]) =>
|
||||
@@ -758,61 +780,146 @@ export default function BusinessWizard({
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
{step === 5 && payload.geography_scope === 'multiple' && (
|
||||
<section className="space-y-4" aria-labelledby="multiple-locations-heading">
|
||||
<h3 id="multiple-locations-heading" className="font-medium">
|
||||
{t('Localizações administrativas (várias) *', 'Administrative locations (multiple) *')}
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
{t('Indique pelo menos duas localizações distintas. Não são recolhidas coordenadas neste formulário.', 'Enter at least two distinct locations. This form does not collect coordinates.')}
|
||||
</p>
|
||||
{locationRows.map((row, index) => (
|
||||
<fieldset key={index} className="space-y-3 rounded border p-4">
|
||||
<legend className="px-1 font-medium">
|
||||
{t('Localização', 'Location')} {index + 1}
|
||||
</legend>
|
||||
{(['province_id', 'district_id', 'admin_post_id', 'locality_id'] as const).map((key) => {
|
||||
const configuration = territoryField[key];
|
||||
const parentId = configuration.parent
|
||||
? row[configuration.parent as keyof typeof row]
|
||||
: '';
|
||||
const name = t(
|
||||
key === 'province_id' ? 'Província ou Cidade de Maputo' : key === 'district_id' ? 'Distrito' : key === 'admin_post_id' ? 'Posto administrativo' : 'Localidade',
|
||||
key === 'province_id' ? 'Province or Maputo City' : key === 'district_id' ? 'District' : key === 'admin_post_id' ? 'Administrative post' : 'Locality',
|
||||
);
|
||||
return (
|
||||
<Field key={key} label={`${name}${key === 'province_id' ? ' *' : ''}`}>
|
||||
<TerritoryField
|
||||
name={`${name}, ${t('localização', 'location')} ${index + 1}`}
|
||||
type={configuration.type}
|
||||
parentId={parentId}
|
||||
value={row[key]}
|
||||
required={key === 'province_id'}
|
||||
onChange={(value) => setLocation(index, key, value)}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
<button type="button" className="underline" disabled={locationRows.length <= 1} onClick={() => removeLocation(index)}>
|
||||
{t('Remover esta localização', 'Remove this location')}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button type="button" className={button} disabled={locationRows.length >= 20} onClick={addLocation}>
|
||||
{t('Adicionar localização', 'Add location')}
|
||||
</button>
|
||||
{locationRows.length < 2 && (
|
||||
<p role="status">
|
||||
{t('Adicione pelo menos mais uma localização antes de submeter.', 'Add at least one more location before submitting.')}
|
||||
{step === 5 &&
|
||||
payload.geography_scope === 'multiple' && (
|
||||
<section
|
||||
className="space-y-4"
|
||||
aria-labelledby="multiple-locations-heading"
|
||||
>
|
||||
<h3
|
||||
id="multiple-locations-heading"
|
||||
className="font-medium"
|
||||
>
|
||||
{t(
|
||||
'Localizações administrativas (várias) *',
|
||||
'Administrative locations (multiple) *',
|
||||
)}
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
{t(
|
||||
'Indique pelo menos duas localizações distintas. Não são recolhidas coordenadas neste formulário.',
|
||||
'Enter at least two distinct locations. This form does not collect coordinates.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{duplicateLocationPath && (
|
||||
<p role="alert" className="text-red-700">
|
||||
{t('Remova percursos administrativos repetidos ou sobrepostos.', 'Remove repeated or overlapping administrative paths.')}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{locationRows.map((row, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<legend className="px-1 font-medium">
|
||||
{t('Localização', 'Location')}{' '}
|
||||
{index + 1}
|
||||
</legend>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key) => {
|
||||
const configuration =
|
||||
territoryField[key];
|
||||
const parentId =
|
||||
configuration.parent
|
||||
? row[
|
||||
configuration.parent as keyof typeof row
|
||||
]
|
||||
: '';
|
||||
const name = t(
|
||||
key === 'province_id'
|
||||
? 'Província ou Cidade de Maputo'
|
||||
: key === 'district_id'
|
||||
? 'Distrito'
|
||||
: key ===
|
||||
'admin_post_id'
|
||||
? 'Posto administrativo'
|
||||
: 'Localidade',
|
||||
key === 'province_id'
|
||||
? 'Province or Maputo City'
|
||||
: key === 'district_id'
|
||||
? 'District'
|
||||
: key ===
|
||||
'admin_post_id'
|
||||
? 'Administrative post'
|
||||
: 'Locality',
|
||||
);
|
||||
return (
|
||||
<Field
|
||||
key={key}
|
||||
label={`${name}${key === 'province_id' ? ' *' : ''}`}
|
||||
>
|
||||
<TerritoryField
|
||||
name={`${name}, ${t('localização', 'location')} ${index + 1}`}
|
||||
type={
|
||||
configuration.type
|
||||
}
|
||||
parentId={parentId}
|
||||
value={row[key]}
|
||||
required={
|
||||
key ===
|
||||
'province_id'
|
||||
}
|
||||
onChange={(value) =>
|
||||
setLocation(
|
||||
index,
|
||||
key,
|
||||
value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={
|
||||
locationRows.length <= 1
|
||||
}
|
||||
onClick={() =>
|
||||
removeLocation(index)
|
||||
}
|
||||
>
|
||||
{t(
|
||||
'Remover esta localização',
|
||||
'Remove this location',
|
||||
)}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={locationRows.length >= 20}
|
||||
onClick={addLocation}
|
||||
>
|
||||
{t(
|
||||
'Adicionar localização',
|
||||
'Add location',
|
||||
)}
|
||||
</button>
|
||||
{locationRows.length < 2 && (
|
||||
<p role="status">
|
||||
{t(
|
||||
'Adicione pelo menos mais uma localização antes de submeter.',
|
||||
'Add at least one more location before submitting.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{duplicateLocationPath && (
|
||||
<p
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{t(
|
||||
'Remova percursos administrativos repetidos ou sobrepostos.',
|
||||
'Remove repeated or overlapping administrative paths.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{step === 7 && (
|
||||
<p role="note">
|
||||
{t(
|
||||
@@ -868,15 +975,20 @@ export default function BusinessWizard({
|
||||
</dd>
|
||||
</div>
|
||||
{Object.entries(formSchema)
|
||||
.filter(([, field]) =>
|
||||
field.type !== 'location_list' &&
|
||||
Object.entries(
|
||||
field.when ?? {},
|
||||
).every(([dependency, values]) =>
|
||||
values.includes(
|
||||
payload[dependency] ?? '',
|
||||
.filter(
|
||||
([, field]) =>
|
||||
field.type !==
|
||||
'location_list' &&
|
||||
Object.entries(
|
||||
field.when ?? {},
|
||||
).every(
|
||||
([dependency, values]) =>
|
||||
values.includes(
|
||||
payload[
|
||||
dependency
|
||||
] ?? '',
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.map(([key, field]) => (
|
||||
<div key={key}>
|
||||
@@ -893,10 +1005,17 @@ export default function BusinessWizard({
|
||||
{payload.geography_scope === 'multiple' && (
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
{t('Localizações administrativas', 'Administrative locations')}
|
||||
{t(
|
||||
'Localizações administrativas',
|
||||
'Administrative locations',
|
||||
)}
|
||||
</dt>
|
||||
<dd>
|
||||
{locationRows.length} {t('localizações indicadas', 'locations entered')}
|
||||
{locationRows.length}{' '}
|
||||
{t(
|
||||
'localizações indicadas',
|
||||
'locations entered',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
@@ -905,11 +1024,22 @@ export default function BusinessWizard({
|
||||
<ul className="list-disc space-y-1 pl-6">
|
||||
{locationRows.map((_, index) => (
|
||||
<li key={index}>
|
||||
{payload.locations_json === resolvedLocationJson && territoryPaths[index]?.length
|
||||
? territoryPaths[index].join(' → ')
|
||||
: payload.locations_json !== resolvedLocationJson
|
||||
? t('Os nomes serão apresentados depois de guardar este rascunho.', 'Names will appear after this draft is saved.')
|
||||
: t('Percurso territorial indisponível na referência pública actual.', 'Territorial path unavailable in the current public reference data.')}
|
||||
{payload.locations_json ===
|
||||
resolvedLocationJson &&
|
||||
territoryPaths[index]?.length
|
||||
? territoryPaths[
|
||||
index
|
||||
].join(' → ')
|
||||
: payload.locations_json !==
|
||||
resolvedLocationJson
|
||||
? t(
|
||||
'Os nomes serão apresentados depois de guardar este rascunho.',
|
||||
'Names will appear after this draft is saved.',
|
||||
)
|
||||
: t(
|
||||
'Percurso territorial indisponível na referência pública actual.',
|
||||
'Territorial path unavailable in the current public reference data.',
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
import { businessModalities, businessStates } from "./business-types";
|
||||
import type { Business } from "./business-types";
|
||||
import BusinessObjects from "./business-objects";
|
||||
import type { BusinessObject } from "./business-objects";
|
||||
import BusinessVerifications from "./business-verifications";
|
||||
import type { BusinessVerification } from "./business-verifications";
|
||||
import BusinessWizard from "./business-wizard";
|
||||
import type { FormSchema } from "./business-wizard";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, Field, input, button, card, api } from './shared';
|
||||
import { businessModalities, businessStates } from './business-types';
|
||||
import type { Business } from './business-types';
|
||||
import BusinessObjects from './business-objects';
|
||||
import type { BusinessObject } from './business-objects';
|
||||
import BusinessVerifications from './business-verifications';
|
||||
import type { BusinessVerification } from './business-verifications';
|
||||
import BusinessWizard from './business-wizard';
|
||||
import type { FormSchema } from './business-wizard';
|
||||
|
||||
type Props = {
|
||||
formSchema: FormSchema;
|
||||
@@ -26,12 +26,27 @@ type Props = {
|
||||
objectKinds: string[];
|
||||
verificationChecks: string[];
|
||||
verifications: BusinessVerification[];
|
||||
history: { version_no: number; action: string; created_at: string; note: string }[];
|
||||
history: {
|
||||
version_no: number;
|
||||
action: string;
|
||||
created_at: string;
|
||||
note: string;
|
||||
}[];
|
||||
};
|
||||
export default function BusinessPage(props: Props) {
|
||||
if (props.canEdit)
|
||||
return <BusinessWizard key={props.record.id + ":" + props.record.version_no} {...props} />;
|
||||
return <Editor key={`${props.record.id}:${props.record.version_no}`} {...props} />;
|
||||
return (
|
||||
<BusinessWizard
|
||||
key={props.record.id + ':' + props.record.version_no}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Editor
|
||||
key={`${props.record.id}:${props.record.version_no}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function Editor({
|
||||
record,
|
||||
@@ -53,22 +68,28 @@ function Editor({
|
||||
}: Props) {
|
||||
const [payload, setPayload] = useState(record.payload);
|
||||
const [modality, setModality] = useState(record.modality);
|
||||
const [note, setNote] = useState("");
|
||||
const [note, setNote] = useState('');
|
||||
const [consent, setConsent] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const dirty =
|
||||
JSON.stringify(payload) !== JSON.stringify(record.payload) || modality !== record.modality;
|
||||
JSON.stringify(payload) !== JSON.stringify(record.payload) ||
|
||||
modality !== record.modality;
|
||||
const run = async (action?: string) => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api(
|
||||
`/api/v1/existing-business/listings/${record.id}${action ? "/transitions" : ""}`,
|
||||
`/api/v1/existing-business/listings/${record.id}${action ? '/transitions' : ''}`,
|
||||
action
|
||||
? { action, version_no: record.version_no, note, review_consent: consent }
|
||||
? {
|
||||
action,
|
||||
version_no: record.version_no,
|
||||
note,
|
||||
review_consent: consent,
|
||||
}
|
||||
: {
|
||||
_method: "PUT",
|
||||
_method: 'PUT',
|
||||
modality,
|
||||
classification: record.classification,
|
||||
payload,
|
||||
@@ -81,7 +102,7 @@ function Editor({
|
||||
setError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Não foi possível guardar. Recarregue se a versão mudou.",
|
||||
: 'Não foi possível guardar. Recarregue se a versão mudou.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -91,41 +112,45 @@ function Editor({
|
||||
<Frame title={record.payload.title}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={owner ? "/investidor/negocios" : "/management/negocios"}
|
||||
href={owner ? '/investidor/negocios' : '/management/negocios'}
|
||||
>
|
||||
Voltar à lista
|
||||
</Link>
|
||||
<p>
|
||||
{businessStates[record.status]} · versão {record.version_no} · informação reservada
|
||||
{businessStates[record.status]} · versão {record.version_no} ·
|
||||
informação reservada
|
||||
</p>
|
||||
<p>
|
||||
Informação declarada, pendente de validação. Não constitui anúncio público,
|
||||
certificação, avaliação ou autorização de transmissão.
|
||||
Informação declarada, pendente de validação. Não constitui
|
||||
anúncio público, certificação, avaliação ou autorização de
|
||||
transmissão.
|
||||
</p>
|
||||
{!canEdit && (
|
||||
<dl className={`${card} space-y-3 break-words`}>
|
||||
<div>
|
||||
<dt className="font-bold">Sector</dt>
|
||||
<dd>
|
||||
{sectors.find((sector) => sector.id === record.sector_id)?.name ?? "—"}
|
||||
{sectors.find(
|
||||
(sector) => sector.id === record.sector_id,
|
||||
)?.name ?? '—'}
|
||||
</dd>
|
||||
</div>
|
||||
{Object.entries(formSchema)
|
||||
.filter(
|
||||
([key]) =>
|
||||
![
|
||||
"title",
|
||||
"description",
|
||||
"declared_reason",
|
||||
"source_reference",
|
||||
"valid_until",
|
||||
'title',
|
||||
'description',
|
||||
'declared_reason',
|
||||
'source_reference',
|
||||
'valid_until',
|
||||
].includes(key),
|
||||
)
|
||||
.map(([key, field]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-bold">{field.pt}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{record.payload[key] || "—"}
|
||||
{record.payload[key] || '—'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
@@ -154,32 +179,40 @@ function Editor({
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
["title", "Título privado"],
|
||||
["description", "Descrição reservada"],
|
||||
["declared_reason", "Motivo declarado"],
|
||||
["source_reference", "Referência da fonte"],
|
||||
["valid_until", "Validade declarada"],
|
||||
['title', 'Título privado'],
|
||||
['description', 'Descrição reservada'],
|
||||
['declared_reason', 'Motivo declarado'],
|
||||
['source_reference', 'Referência da fonte'],
|
||||
['valid_until', 'Validade declarada'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<Field key={key} label={label}>
|
||||
{key === "description" ? (
|
||||
{key === 'description' ? (
|
||||
<textarea
|
||||
className={input}
|
||||
rows={5}
|
||||
maxLength={10000}
|
||||
value={payload[key] ?? ""}
|
||||
value={payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
setPayload({ ...payload, [key]: e.target.value })
|
||||
setPayload({
|
||||
...payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={input}
|
||||
type={key === "valid_until" ? "date" : "text"}
|
||||
maxLength={key === "title" ? 200 : 2000}
|
||||
value={payload[key] ?? ""}
|
||||
type={
|
||||
key === 'valid_until' ? 'date' : 'text'
|
||||
}
|
||||
maxLength={key === 'title' ? 200 : 2000}
|
||||
value={payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
setPayload({ ...payload, [key]: e.target.value })
|
||||
setPayload({
|
||||
...payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
@@ -198,11 +231,18 @@ function Editor({
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{canEdit && (
|
||||
<button className={button} disabled={busy || note.trim().length < 10}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
)}
|
||||
{dirty && <p role="status">Guarde as alterações antes de mudar de estado.</p>}
|
||||
{dirty && (
|
||||
<p role="status">
|
||||
Guarde as alterações antes de mudar de estado.
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
{owner && canEdit && (
|
||||
<label className="flex gap-3">
|
||||
@@ -211,88 +251,126 @@ function Editor({
|
||||
checked={consent}
|
||||
onChange={(e) => setConsent(e.target.checked)}
|
||||
/>
|
||||
Autorizo a análise interna desta submissão pelos revisores designados. Esta
|
||||
autorização não permite publicação.
|
||||
Autorizo a análise interna desta submissão pelos revisores
|
||||
designados. Esta autorização não permite publicação.
|
||||
</label>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{owner && canEdit && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || dirty || !consent || note.trim().length < 10}
|
||||
onClick={() => void run("submitted")}
|
||||
disabled={
|
||||
busy || dirty || !consent || note.trim().length < 10
|
||||
}
|
||||
onClick={() => void run('submitted')}
|
||||
>
|
||||
Submeter para análise
|
||||
</button>
|
||||
)}
|
||||
{canReview && record.status === "submitted" && (
|
||||
{canReview && record.status === 'submitted' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run("in_review")}
|
||||
onClick={() => void run('in_review')}
|
||||
>
|
||||
Iniciar revisão
|
||||
</button>
|
||||
)}
|
||||
{canReview && record.status === "in_review" && (
|
||||
{canReview && record.status === 'in_review' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run("needs_information")}
|
||||
onClick={() => void run('needs_information')}
|
||||
>
|
||||
Pedir informação
|
||||
</button>
|
||||
)}
|
||||
{canTriage && record.status === "submitted" && (
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("triage")}>
|
||||
{canTriage && record.status === 'submitted' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('triage')}
|
||||
>
|
||||
Iniciar triagem
|
||||
</button>
|
||||
)}
|
||||
{canReview && record.status === "triage" && (
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("in_review")}>
|
||||
{canReview && record.status === 'triage' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('in_review')}
|
||||
>
|
||||
Encaminhar para revisão
|
||||
</button>
|
||||
)}
|
||||
{canReview && record.status === "in_review" && (
|
||||
{canReview && record.status === 'in_review' && (
|
||||
<>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approval_l1")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('approval_l1')}
|
||||
>
|
||||
Enviar para aprovação nÃvel 1
|
||||
</button>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('rejected')}
|
||||
>
|
||||
Rejeitar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{canApproveLevelOne && record.status === "approval_l1" && (
|
||||
{canApproveLevelOne && record.status === 'approval_l1' && (
|
||||
<>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approval_l2")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('approval_l2')}
|
||||
>
|
||||
Aprovar nÃvel 1 e enviar ao nÃvel 2
|
||||
</button>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('rejected')}
|
||||
>
|
||||
Rejeitar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{canApproveLevelTwo && record.status === "approval_l2" && (
|
||||
{canApproveLevelTwo && record.status === 'approval_l2' && (
|
||||
<>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approved")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('approved')}
|
||||
>
|
||||
Aprovar nÃvel 2
|
||||
</button>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('rejected')}
|
||||
>
|
||||
Rejeitar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{canPublish && record.status === "approved" && (
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("published")}>
|
||||
{canPublish && record.status === 'approved' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('published')}
|
||||
>
|
||||
Publicar
|
||||
</button>
|
||||
)}
|
||||
{owner && record.status !== "withdrawn" && (
|
||||
{owner && record.status !== 'withdrawn' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || dirty || note.trim().length < 10}
|
||||
onClick={() => void run("withdrawn")}
|
||||
onClick={() => void run('withdrawn')}
|
||||
>
|
||||
Retirar submissão
|
||||
</button>
|
||||
@@ -308,7 +386,7 @@ function Editor({
|
||||
<BusinessVerifications
|
||||
id={record.id}
|
||||
version={record.version_no}
|
||||
editable={canReview && record.status === "in_review" && !busy}
|
||||
editable={canReview && record.status === 'in_review' && !busy}
|
||||
checks={verificationChecks}
|
||||
findings={verifications}
|
||||
objects={objects}
|
||||
@@ -318,20 +396,22 @@ function Editor({
|
||||
<ol>
|
||||
{history.map((h) => (
|
||||
<li key={h.version_no}>
|
||||
Versão {h.version_no} ·{" "}
|
||||
Versão {h.version_no} ·{' '}
|
||||
{businessStates[h.action] ??
|
||||
(
|
||||
{
|
||||
created: "Criado",
|
||||
updated: "Alterado",
|
||||
archived: "Arquivado",
|
||||
object_added: "Elemento declarado acrescentado",
|
||||
object_updated: "Elemento declarado alterado",
|
||||
verification: "Verificação registada",
|
||||
created: 'Criado',
|
||||
updated: 'Alterado',
|
||||
archived: 'Arquivado',
|
||||
object_added:
|
||||
'Elemento declarado acrescentado',
|
||||
object_updated:
|
||||
'Elemento declarado alterado',
|
||||
verification: 'Verificação registada',
|
||||
} as Record<string, string>
|
||||
)[h.action] ??
|
||||
h.action}{" "}
|
||||
· {new Date(h.created_at).toLocaleString("pt-MZ")}
|
||||
h.action}{' '}
|
||||
· {new Date(h.created_at).toLocaleString('pt-MZ')}
|
||||
<p>{h.note}</p>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
import { businessModalities, businessStates } from "./business-types";
|
||||
import type { Business } from "./business-types";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, Field, input, button, card, api } from './shared';
|
||||
import { businessModalities, businessStates } from './business-types';
|
||||
import type { Business } from './business-types';
|
||||
|
||||
export default function Businesses({
|
||||
records,
|
||||
management,
|
||||
modalities,
|
||||
}: {
|
||||
records: { data: Business[]; prev_page_url: string | null; next_page_url: string | null };
|
||||
records: {
|
||||
data: Business[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
management: boolean;
|
||||
modalities: string[];
|
||||
}) {
|
||||
const [title, setTitle] = useState("");
|
||||
const [title, setTitle] = useState('');
|
||||
const [modality, setModality] = useState(modalities[0]);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Frame title={management ? "Revisão de negócios" : "Os meus negócios"}>
|
||||
<Frame title={management ? 'Revisão de negócios' : 'Os meus negócios'}>
|
||||
<p>
|
||||
Área privada de preparação e revisão. A submissão não confirma titularidade,
|
||||
validade ou transmissibilidade do negócio, activo ou direito.
|
||||
Área privada de preparação e revisão. A submissão não confirma
|
||||
titularidade, validade ou transmissibilidade do negócio, activo
|
||||
ou direito.
|
||||
</p>
|
||||
{!management && (
|
||||
<form
|
||||
@@ -29,20 +34,27 @@ export default function Businesses({
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
const result = await api("/api/v1/existing-business/listings", {
|
||||
modality,
|
||||
classification: "confidential",
|
||||
reason: "Criação de rascunho pelo proprietário",
|
||||
payload: { title, wizard_version: "1", wizard_step: "1" },
|
||||
});
|
||||
const result = await api(
|
||||
'/api/v1/existing-business/listings',
|
||||
{
|
||||
modality,
|
||||
classification: 'confidential',
|
||||
reason: 'Criação de rascunho pelo proprietário',
|
||||
payload: {
|
||||
title,
|
||||
wizard_version: '1',
|
||||
wizard_step: '1',
|
||||
},
|
||||
},
|
||||
);
|
||||
router.visit(`/investidor/negocios/${result.id}`);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Não foi possível criar o rascunho.",
|
||||
: 'Não foi possível criar o rascunho.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -74,25 +86,34 @@ export default function Businesses({
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<button className={button} disabled={busy}>
|
||||
{busy ? "A criar…" : "Criar rascunho privado"}
|
||||
{busy ? 'A criar…' : 'Criar rascunho privado'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{!records.data.length && <p role="status">Não existem negócios nesta lista.</p>}
|
||||
{!records.data.length && (
|
||||
<p role="status">Não existem negócios nesta lista.</p>
|
||||
)}
|
||||
{records.data.map((r) => (
|
||||
<article className={card} key={r.id}>
|
||||
<Link className="font-bold underline" href={`/investidor/negocios/${r.id}`}>
|
||||
<Link
|
||||
className="font-bold underline"
|
||||
href={`/investidor/negocios/${r.id}`}
|
||||
>
|
||||
{r.payload.title}
|
||||
</Link>
|
||||
<p>
|
||||
{businessModalities[r.modality]} · {businessStates[r.status]} · versão{" "}
|
||||
{r.version_no}
|
||||
{businessModalities[r.modality]} ·{' '}
|
||||
{businessStates[r.status]} · versão {r.version_no}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
<nav aria-label="Paginação dos negócios" className="flex gap-4">
|
||||
{records.prev_page_url && <Link href={records.prev_page_url}>Anterior</Link>}
|
||||
{records.next_page_url && <Link href={records.next_page_url}>Seguinte</Link>}
|
||||
{records.prev_page_url && (
|
||||
<Link href={records.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
{records.next_page_url && (
|
||||
<Link href={records.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { Management } from "../management/shared";
|
||||
import { Field, input, button, card, groupLabels } from "./shared";
|
||||
import type { Opportunity, Context, References } from "./shared";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Management } from '../management/shared';
|
||||
import { Field, input, button, card, groupLabels } from './shared';
|
||||
import type { Opportunity, Context, References } from './shared';
|
||||
export default function EditContext({
|
||||
record,
|
||||
context,
|
||||
@@ -14,11 +14,11 @@ export default function EditContext({
|
||||
const form = useForm({
|
||||
version: context.profile?.version ?? 0,
|
||||
is_education: context.profile?.is_education ?? false,
|
||||
business_model: context.profile?.business_model ?? "",
|
||||
requirements: context.profile?.requirements ?? "",
|
||||
risks: context.profile?.risks ?? "",
|
||||
target_date: context.profile?.target_date ?? "",
|
||||
source_reference: context.profile?.source_reference ?? "",
|
||||
business_model: context.profile?.business_model ?? '',
|
||||
requirements: context.profile?.requirements ?? '',
|
||||
risks: context.profile?.risks ?? '',
|
||||
target_date: context.profile?.target_date ?? '',
|
||||
source_reference: context.profile?.source_reference ?? '',
|
||||
clusters: context.clusters.map((r) => r.id),
|
||||
corridors: context.corridors.map((r) => r.id),
|
||||
projects: context.projects.map((r) => r.id),
|
||||
@@ -26,12 +26,15 @@ export default function EditContext({
|
||||
facets: context.facets.map((r) => r.id),
|
||||
});
|
||||
return (
|
||||
<Management title={"Contexto: " + record.title}>
|
||||
<Management title={'Contexto: ' + record.title}>
|
||||
<p>
|
||||
As relações e características são parte da ficha publicada. Guardar devolve-a a
|
||||
rascunho para revisão.
|
||||
As relações e características são parte da ficha publicada.
|
||||
Guardar devolve-a a rascunho para revisão.
|
||||
</p>
|
||||
<Link href={`/management/opportunities/${record.id}/edit`} className="underline">
|
||||
<Link
|
||||
href={`/management/opportunities/${record.id}/edit`}
|
||||
className="underline"
|
||||
>
|
||||
Editar e publicar a ficha principal
|
||||
</Link>
|
||||
<form
|
||||
@@ -39,7 +42,8 @@ export default function EditContext({
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.put(`/management/opportunities/${record.id}/context`, {
|
||||
onSuccess: () => form.setData("version", form.data.version + 1),
|
||||
onSuccess: () =>
|
||||
form.setData('version', form.data.version + 1),
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -47,15 +51,36 @@ export default function EditContext({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.is_education}
|
||||
onChange={(e) => form.setData("is_education", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
form.setData('is_education', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Oportunidade na educação
|
||||
</label>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(["clusters", "corridors", "projects", "locations"] as const).map((key, i) => (
|
||||
<fieldset className={card + " max-h-72 space-y-2 overflow-auto"} key={key}>
|
||||
{(
|
||||
[
|
||||
'clusters',
|
||||
'corridors',
|
||||
'projects',
|
||||
'locations',
|
||||
] as const
|
||||
).map((key, i) => (
|
||||
<fieldset
|
||||
className={
|
||||
card + ' max-h-72 space-y-2 overflow-auto'
|
||||
}
|
||||
key={key}
|
||||
>
|
||||
<legend className="font-bold">
|
||||
{["Clusters", "Corredores", "Projectos âncora", "Localizações"][i]}
|
||||
{
|
||||
[
|
||||
'Clusters',
|
||||
'Corredores',
|
||||
'Projectos âncora',
|
||||
'Localizações',
|
||||
][i]
|
||||
}
|
||||
</legend>
|
||||
{references[key].map((r) => (
|
||||
<label key={r.id} className="flex gap-2">
|
||||
@@ -67,7 +92,9 @@ export default function EditContext({
|
||||
key,
|
||||
e.target.checked
|
||||
? [...form.data[key], r.id]
|
||||
: form.data[key].filter((id) => id !== r.id),
|
||||
: form.data[key].filter(
|
||||
(id) => id !== r.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
@@ -79,18 +106,20 @@ export default function EditContext({
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{[
|
||||
"subsector",
|
||||
"education",
|
||||
"infrastructure",
|
||||
"labour",
|
||||
"qualification",
|
||||
"support",
|
||||
"impact",
|
||||
"partnership",
|
||||
'subsector',
|
||||
'education',
|
||||
'infrastructure',
|
||||
'labour',
|
||||
'qualification',
|
||||
'support',
|
||||
'impact',
|
||||
'partnership',
|
||||
].map((group) => (
|
||||
<fieldset
|
||||
key={group}
|
||||
className={card + " max-h-64 space-y-2 overflow-auto"}
|
||||
className={
|
||||
card + ' max-h-64 space-y-2 overflow-auto'
|
||||
}
|
||||
>
|
||||
<legend>{groupLabels[group]}</legend>
|
||||
{references.options
|
||||
@@ -99,14 +128,21 @@ export default function EditContext({
|
||||
<label key={o.id} className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.facets.includes(o.id)}
|
||||
checked={form.data.facets.includes(
|
||||
o.id,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
"facets",
|
||||
'facets',
|
||||
e.target.checked
|
||||
? [...form.data.facets, o.id]
|
||||
? [
|
||||
...form.data
|
||||
.facets,
|
||||
o.id,
|
||||
]
|
||||
: form.data.facets.filter(
|
||||
(id) => id !== o.id,
|
||||
(id) =>
|
||||
id !== o.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -117,35 +153,43 @@ export default function EditContext({
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
{(["business_model", "requirements", "risks", "source_reference"] as const).map(
|
||||
(key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
business_model: "Modelo de negócio",
|
||||
requirements: "Requisitos e necessidades",
|
||||
risks: "Riscos",
|
||||
source_reference: "Fonte e referência de autorização",
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
className={input}
|
||||
required={key === "source_reference"}
|
||||
rows={3}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
),
|
||||
)}
|
||||
{(
|
||||
[
|
||||
'business_model',
|
||||
'requirements',
|
||||
'risks',
|
||||
'source_reference',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
business_model: 'Modelo de negócio',
|
||||
requirements: 'Requisitos e necessidades',
|
||||
risks: 'Riscos',
|
||||
source_reference:
|
||||
'Fonte e referência de autorização',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
className={input}
|
||||
required={key === 'source_reference'}
|
||||
rows={3}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Data-alvo">
|
||||
<input
|
||||
type="date"
|
||||
className={input}
|
||||
value={form.data.target_date}
|
||||
onChange={(e) => form.setData("target_date", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('target_date', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { useForm } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { newSubmissionKey } from "@/lib/portal-api";
|
||||
import { Field, card, input, button, api } from "./shared";
|
||||
export type Message = { id: string; sender_role: string; body: string; created_at: string };
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { newSubmissionKey } from '@/lib/portal-api';
|
||||
import { Field, card, input, button, api } from './shared';
|
||||
export type Message = {
|
||||
id: string;
|
||||
sender_role: string;
|
||||
body: string;
|
||||
created_at: string;
|
||||
};
|
||||
export function Conversation({
|
||||
id,
|
||||
messages,
|
||||
@@ -14,7 +19,7 @@ export function Conversation({
|
||||
submitted: boolean;
|
||||
revisions: { version: number; created_at: string }[];
|
||||
}) {
|
||||
const form = useForm({ client_key: newSubmissionKey(), body: "" });
|
||||
const form = useForm({ client_key: newSubmissionKey(), body: '' });
|
||||
const [revision, setRevision] = useState<{
|
||||
version: number;
|
||||
snapshot: {
|
||||
@@ -28,31 +33,37 @@ export function Conversation({
|
||||
attachment_ids: string[];
|
||||
};
|
||||
} | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
return (
|
||||
<>
|
||||
<section className={card + " space-y-4"}>
|
||||
<section className={card + ' space-y-4'}>
|
||||
<h2 className="text-xl font-bold">Versões guardadas</h2>
|
||||
<Field label="Consultar versão">
|
||||
<select
|
||||
className={input}
|
||||
defaultValue=""
|
||||
onChange={(e) => {
|
||||
setError("");
|
||||
setError('');
|
||||
if (!e.target.value) {
|
||||
setRevision(null);
|
||||
return;
|
||||
}
|
||||
api(`/api/v1/investment/submissions/${id}/revisions/${e.target.value}`)
|
||||
api(
|
||||
`/api/v1/investment/submissions/${id}/revisions/${e.target.value}`,
|
||||
)
|
||||
.then(setRevision)
|
||||
.catch(() => setError("Não foi possível consultar esta versão."));
|
||||
.catch(() =>
|
||||
setError(
|
||||
'Não foi possível consultar esta versão.',
|
||||
),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccionar versão</option>
|
||||
{revisions.map((r) => (
|
||||
<option value={r.version} key={r.version}>
|
||||
Versão {r.version} —{" "}
|
||||
{new Date(r.created_at).toLocaleString("pt-MZ")}
|
||||
Versão {r.version} —{' '}
|
||||
{new Date(r.created_at).toLocaleString('pt-MZ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -62,49 +73,70 @@ export function Conversation({
|
||||
<div className="space-y-2">
|
||||
<h3 className="font-bold">Versão {revision.version}</h3>
|
||||
<p>Investidor: {revision.snapshot.payload.full_name}</p>
|
||||
<p>Empresa: {revision.snapshot.payload.organisation || "Não indicada"}</p>
|
||||
<p className="whitespace-pre-line">
|
||||
Objectivo: {revision.snapshot.payload.objective || "Não indicado"}
|
||||
<p>
|
||||
Empresa:{' '}
|
||||
{revision.snapshot.payload.organisation ||
|
||||
'Não indicada'}
|
||||
</p>
|
||||
<p className="whitespace-pre-line">
|
||||
Objectivo:{' '}
|
||||
{revision.snapshot.payload.objective ||
|
||||
'Não indicado'}
|
||||
</p>
|
||||
<p>
|
||||
Prazo:{' '}
|
||||
{revision.snapshot.payload.horizon ||
|
||||
'Não indicado'}
|
||||
</p>
|
||||
<p>Prazo: {revision.snapshot.payload.horizon || "Não indicado"}</p>
|
||||
<ul>
|
||||
{revision.snapshot.needs.map((n, i) => (
|
||||
<li key={i}>{n.details.description}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
{revision.snapshot.attachment_ids.length} anexos associados nessa
|
||||
versão.
|
||||
{revision.snapshot.attachment_ids.length} anexos
|
||||
associados nessa versão.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
{submitted && (
|
||||
<section className={card + " space-y-4"}>
|
||||
<section className={card + ' space-y-4'}>
|
||||
<h2 className="text-xl font-bold">Conversa com o apoio</h2>
|
||||
<p>
|
||||
As mensagens ficam registadas neste pedido e são visíveis ao investidor e à
|
||||
equipa autorizada.
|
||||
As mensagens ficam registadas neste pedido e são
|
||||
visíveis ao investidor e à equipa autorizada.
|
||||
</p>
|
||||
{messages.map((m) => (
|
||||
<article key={m.id} className="rounded-lg border p-4">
|
||||
<p className="font-semibold">
|
||||
{m.sender_role === "support" ? "Apoio ao Investidor" : "Investidor"}{" "}
|
||||
· {new Date(m.created_at).toLocaleString("pt-MZ")}
|
||||
{m.sender_role === 'support'
|
||||
? 'Apoio ao Investidor'
|
||||
: 'Investidor'}{' '}
|
||||
·{' '}
|
||||
{new Date(m.created_at).toLocaleString('pt-MZ')}
|
||||
</p>
|
||||
<p className="mt-2 whitespace-pre-line">{m.body}</p>
|
||||
</article>
|
||||
))}
|
||||
{!messages.length && <p>Ainda não existem mensagens neste pedido.</p>}
|
||||
{!messages.length && (
|
||||
<p>Ainda não existem mensagens neste pedido.</p>
|
||||
)}
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(`/investidor/manifestacoes/${id}/messages`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () =>
|
||||
form.setData({ client_key: newSubmissionKey(), body: "" }),
|
||||
});
|
||||
form.post(
|
||||
`/investidor/manifestacoes/${id}/messages`,
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: () =>
|
||||
form.setData({
|
||||
client_key: newSubmissionKey(),
|
||||
body: '',
|
||||
}),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field label="Mensagem para acompanhamento">
|
||||
@@ -115,7 +147,9 @@ export function Conversation({
|
||||
minLength={3}
|
||||
maxLength={5000}
|
||||
value={form.data.body}
|
||||
onChange={(e) => form.setData("body", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('body', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
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 from '@/components/structure-geography';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
import { Frame, card, button, money, groupLabels } from "./shared";
|
||||
import type { Opportunity, Context } from "./shared";
|
||||
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;
|
||||
@@ -19,34 +19,57 @@ 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}/>
|
||||
<Link href={returnUrl} className="underline">Voltar à pesquisa</Link>
|
||||
{dossierOrigin && <p><Link className="underline" href={`/carteira/${dossierOrigin.id}`}>Voltar ao dossier: {dossierOrigin.title}</Link></p>}
|
||||
<PartnershipSourceLinks type="investment" id={r.id} />
|
||||
<Link href={returnUrl} className="underline">
|
||||
Voltar à pesquisa
|
||||
</Link>
|
||||
{dossierOrigin && (
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/carteira/${dossierOrigin.id}`}
|
||||
>
|
||||
Voltar ao dossier: {dossierOrigin.title}
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
{r.reference} · {r.sector?.name} · {r.province} {r.district}
|
||||
</p>
|
||||
{!r.last_validated_at && (
|
||||
<p className="rounded border border-amber-700 bg-amber-50 p-4">
|
||||
Esta ficha não regista data de validação documental. Confirme a origem e as condições antes de agir. Preparar uma manifestação expressa interesse; não confirma a oferta nem representa aprovação.
|
||||
Esta ficha não regista data de validação documental.
|
||||
Confirme a origem e as condições antes de agir. Preparar uma
|
||||
manifestação expressa interesse; não confirma a oferta nem
|
||||
representa aprovação.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xl">{r.summary}</p>
|
||||
<InvestmentMapPanel filters={{ opportunity_id: r.id }} />
|
||||
{c.primary_territory_path && c.primary_territory_path.length > 0 && (
|
||||
<p>Localização: {c.primary_territory_path.map((node) => node.name).join(" → ")}</p>
|
||||
)}
|
||||
{c.primary_territory_path &&
|
||||
c.primary_territory_path.length > 0 && (
|
||||
<p>
|
||||
Localização:{' '}
|
||||
{c.primary_territory_path
|
||||
.map((node) => node.name)
|
||||
.join(' → ')}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{auth.user ? (
|
||||
<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" }
|
||||
? {
|
||||
zone_id: zone_origin.id,
|
||||
intent: 'interest',
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
@@ -58,21 +81,28 @@ export default function Detail({
|
||||
Entrar para preparar manifestação
|
||||
</Link>
|
||||
)}
|
||||
<Link className="underline" href={`/manifestar-interesse/${r.slug}`}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/manifestar-interesse/${r.slug}`}
|
||||
>
|
||||
Contacto rápido sem rascunho
|
||||
</Link>
|
||||
<button
|
||||
className="underline"
|
||||
onClick={() => {
|
||||
if (!navigator.clipboard) {
|
||||
setSharing("Copie a ligação na barra de endereço do navegador.");
|
||||
setSharing(
|
||||
'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."),
|
||||
setSharing(
|
||||
'Copie a ligação na barra de endereço do navegador.',
|
||||
),
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -82,7 +112,9 @@ export default function Detail({
|
||||
{sharing && <p role="status">{sharing}</p>}
|
||||
{!!c.zones?.length && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">ZEE, ZFI e parques associados</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
ZEE, ZFI e parques associados
|
||||
</h2>
|
||||
{c.zones.map((z) => (
|
||||
<p key={z.id}>
|
||||
<Link
|
||||
@@ -90,50 +122,59 @@ 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>
|
||||
))}
|
||||
<p>A associação não atribui automaticamente benefícios ou licenças.</p>
|
||||
<p>
|
||||
A associação não atribui automaticamente benefícios ou
|
||||
licenças.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<section className={card + " whitespace-pre-line lg:col-span-2"}>
|
||||
<section
|
||||
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"}>
|
||||
<h2 className="text-xl font-bold">Viabilidade e preparação</h2>
|
||||
<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"}</p>
|
||||
<p className="whitespace-pre-line">
|
||||
{text || 'Não indicado'}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
{c.profile.is_education && (
|
||||
@@ -144,25 +185,44 @@ export default function Detail({
|
||||
</section>
|
||||
)}
|
||||
<section className="grid gap-4 md:grid-cols-4">
|
||||
{(["clusters", "corridors", "projects", "locations"] as const).map((key, i) => (
|
||||
{(
|
||||
['clusters', 'corridors', 'projects', 'locations'] as const
|
||||
).map((key, i) => (
|
||||
<div className={card} key={key}>
|
||||
<h2 className="font-bold">
|
||||
{["Clusters", "Corredores", "Projectos âncora", "Territórios"][i]}
|
||||
{
|
||||
[
|
||||
'Clusters',
|
||||
'Corredores',
|
||||
'Projectos âncora',
|
||||
'Territórios',
|
||||
][i]
|
||||
}
|
||||
</h2>
|
||||
{c[key].map((entity) => (
|
||||
<p key={entity.id}>
|
||||
{entity.dossiers?.map(dossier => <span key={dossier.id}><Link className="underline" href={`/carteira/${dossier.id}`}>Consultar dossier: {dossier.title}</Link><br /></span>)}
|
||||
{entity.dossiers?.map((dossier) => (
|
||||
<span key={dossier.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/carteira/${dossier.id}`}
|
||||
>
|
||||
Consultar dossier: {dossier.title}
|
||||
</Link>
|
||||
<br />
|
||||
</span>
|
||||
))}
|
||||
<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
|
||||
}
|
||||
>
|
||||
@@ -174,7 +234,20 @@ export default function Detail({
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
{(['projects','clusters'] as const).flatMap(key => c[key].filter(entity => entity.geography && entity.dossiers?.length).map(entity => <StructureGeographyPanel key={`${key}-${entity.id}`} geography={entity.geography!} cluster={key === 'clusters'} dossierId={entity.dossiers![0].id} />))}
|
||||
{(['projects', 'clusters'] as const).flatMap((key) =>
|
||||
c[key]
|
||||
.filter(
|
||||
(entity) => entity.geography && entity.dossiers?.length,
|
||||
)
|
||||
.map((entity) => (
|
||||
<StructureGeographyPanel
|
||||
key={`${key}-${entity.id}`}
|
||||
geography={entity.geography!}
|
||||
cluster={key === 'clusters'}
|
||||
dossierId={entity.dossiers![0].id}
|
||||
/>
|
||||
)),
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Infraestruturas, competências, educação e apoios
|
||||
@@ -186,8 +259,9 @@ export default function Detail({
|
||||
))}
|
||||
{!c.facets.length && (
|
||||
<p>
|
||||
Sem características estruturadas publicadas. Pode declarar as suas
|
||||
necessidades na manifestação de interesse.
|
||||
Sem características estruturadas publicadas. Pode
|
||||
declarar as suas necessidades na manifestação de
|
||||
interesse.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { Frame, card, button } from "./shared";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, card, button } from './shared';
|
||||
export default function Notifications({
|
||||
unread,
|
||||
notifications,
|
||||
@@ -19,10 +19,10 @@ export default function Notifications({
|
||||
};
|
||||
}) {
|
||||
const states: Record<string, string> = {
|
||||
received: "Recebido",
|
||||
in_review: "Em análise",
|
||||
contacted: "Contactado",
|
||||
closed: "Encerrado",
|
||||
received: 'Recebido',
|
||||
in_review: 'Em análise',
|
||||
contacted: 'Contactado',
|
||||
closed: 'Encerrado',
|
||||
};
|
||||
return (
|
||||
<Frame title="Notificações e acompanhamento">
|
||||
@@ -31,24 +31,28 @@ export default function Notifications({
|
||||
</Link>
|
||||
<p role="status">{unread} notificações por ler</p>
|
||||
{notifications.data.map((n) => (
|
||||
<article key={n.id} className={card + " space-y-3"}>
|
||||
<article key={n.id} className={card + ' space-y-3'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
{n.kind === "received"
|
||||
? "Manifestação recebida"
|
||||
: n.kind === "status"
|
||||
? "Estado actualizado"
|
||||
: "Nova mensagem na conversa"}
|
||||
{n.kind === 'received'
|
||||
? 'Manifestação recebida'
|
||||
: n.kind === 'status'
|
||||
? 'Estado actualizado'
|
||||
: 'Nova mensagem na conversa'}
|
||||
</h2>
|
||||
<p>
|
||||
{n.payload.reference ??
|
||||
(n.payload.status
|
||||
? (states[n.payload.status] ?? n.payload.status)
|
||||
: "Consulte o pedido para ler a mensagem.")}
|
||||
: 'Consulte o pedido para ler a mensagem.')}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
{new Date(n.created_at).toLocaleString('pt-MZ')}
|
||||
</p>
|
||||
<p className="text-sm">{new Date(n.created_at).toLocaleString("pt-MZ")}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link
|
||||
href={"/investidor/manifestacoes/" + n.submission_id}
|
||||
href={
|
||||
'/investidor/manifestacoes/' + n.submission_id
|
||||
}
|
||||
className="underline"
|
||||
>
|
||||
Abrir manifestação
|
||||
@@ -58,7 +62,9 @@ export default function Notifications({
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post(
|
||||
"/investidor/notifications/" + n.id + "/read",
|
||||
'/investidor/notifications/' +
|
||||
n.id +
|
||||
'/read',
|
||||
{},
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
@@ -70,7 +76,9 @@ export default function Notifications({
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
{!notifications.data.length && <p>Ainda não existem notificações.</p>}
|
||||
{!notifications.data.length && (
|
||||
<p>Ainda não existem notificações.</p>
|
||||
)}
|
||||
<nav aria-label="Paginação" className="flex gap-4">
|
||||
{notifications.prev_page_url && (
|
||||
<Link href={notifications.prev_page_url}>Anterior</Link>
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { Link, router, useForm } from "@inertiajs/react";
|
||||
import { Frame, Field, input, button, card } from "./shared";
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { Frame, Field, input, button, card } from './shared';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
|
||||
type RecordData = { version: number; payload: Record<string, string> };
|
||||
type Company = RecordData & { id: string };
|
||||
const labels: Record<string, string> = {
|
||||
phone: "Telefone",
|
||||
country: "País",
|
||||
sector: "Sector de interesse",
|
||||
experience: "Experiência relevante",
|
||||
investment_capacity: "Capacidade de investimento declarada",
|
||||
name: "Nome da empresa",
|
||||
registration: "Referência de registo / NUIT",
|
||||
role: "Função ou relação com a empresa",
|
||||
description: "Actividade e observações",
|
||||
phone: 'Telefone',
|
||||
country: 'País',
|
||||
sector: 'Sector de interesse',
|
||||
experience: 'Experiência relevante',
|
||||
investment_capacity: 'Capacidade de investimento declarada',
|
||||
name: 'Nome da empresa',
|
||||
registration: 'Referência de registo / NUIT',
|
||||
role: 'Função ou relação com a empresa',
|
||||
description: 'Actividade e observações',
|
||||
};
|
||||
|
||||
export default function Profile({
|
||||
@@ -29,43 +29,54 @@ export default function Profile({
|
||||
Voltar à área do investidor
|
||||
</Link>
|
||||
<p>
|
||||
Estes dados são privados e servem para preencher novas manifestações. Nome e email
|
||||
são mantidos nas{" "}
|
||||
Estes dados são privados e servem para preencher novas
|
||||
manifestações. Nome e email são mantidos nas{' '}
|
||||
<Link className="underline" href="/settings/profile">
|
||||
definições da conta
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
<Editor
|
||||
key={"account-" + account.version}
|
||||
key={'account-' + account.version}
|
||||
record={account}
|
||||
fields={["phone", "country", "sector", "experience", "investment_capacity"]}
|
||||
fields={[
|
||||
'phone',
|
||||
'country',
|
||||
'sector',
|
||||
'experience',
|
||||
'investment_capacity',
|
||||
]}
|
||||
/>
|
||||
<h2 className="text-2xl font-bold">Empresas declaradas</h2>
|
||||
<p>
|
||||
Declarar uma empresa não comprova representação legal nem concede acesso aos
|
||||
registos de outras pessoas. A equipa pode pedir evidência durante o atendimento.
|
||||
Declarar uma empresa não comprova representação legal nem
|
||||
concede acesso aos registos de outras pessoas. A equipa pode
|
||||
pedir evidência durante o atendimento.
|
||||
</p>
|
||||
{companies.map((company) => (
|
||||
<section key={company.id} className={card}>
|
||||
<PartnershipSourceLinks type="company" id={company.id}/>
|
||||
<h3 className="text-xl font-bold">{company.payload.name}</h3>
|
||||
<PartnershipSourceLinks type="company" id={company.id} />
|
||||
<h3 className="text-xl font-bold">
|
||||
{company.payload.name}
|
||||
</h3>
|
||||
<Editor
|
||||
key={company.version}
|
||||
record={company}
|
||||
fields={[
|
||||
"name",
|
||||
"country",
|
||||
"registration",
|
||||
"sector",
|
||||
"role",
|
||||
"description",
|
||||
'name',
|
||||
'country',
|
||||
'registration',
|
||||
'sector',
|
||||
'role',
|
||||
'description',
|
||||
]}
|
||||
/>
|
||||
<button
|
||||
className={button + " mt-4"}
|
||||
className={button + ' mt-4'}
|
||||
onClick={() =>
|
||||
router.post("/investidor/manifestacoes", { company_id: company.id })
|
||||
router.post('/investidor/manifestacoes', {
|
||||
company_id: company.id,
|
||||
})
|
||||
}
|
||||
>
|
||||
Preparar manifestação desta empresa
|
||||
@@ -76,16 +87,16 @@ export default function Profile({
|
||||
<section className={card}>
|
||||
<h3 className="text-xl font-bold">Acrescentar empresa</h3>
|
||||
<Editor
|
||||
key={"new-" + companies.length}
|
||||
key={'new-' + companies.length}
|
||||
record={{ version: 0, payload: {} }}
|
||||
company
|
||||
fields={[
|
||||
"name",
|
||||
"country",
|
||||
"registration",
|
||||
"sector",
|
||||
"role",
|
||||
"description",
|
||||
'name',
|
||||
'country',
|
||||
'registration',
|
||||
'sector',
|
||||
'role',
|
||||
'description',
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
@@ -105,7 +116,9 @@ function Editor({
|
||||
const isCompany = company || !!record.id;
|
||||
const form = useForm({
|
||||
version: record.version,
|
||||
payload: Object.fromEntries(fields.map((key) => [key, record.payload[key] ?? ""])),
|
||||
payload: Object.fromEntries(
|
||||
fields.map((key) => [key, record.payload[key] ?? '']),
|
||||
),
|
||||
});
|
||||
return (
|
||||
<form
|
||||
@@ -115,10 +128,11 @@ function Editor({
|
||||
const options = { preserveScroll: true };
|
||||
if (isCompany)
|
||||
form.post(
|
||||
"/investidor/companies" + (record.id ? "/" + record.id : ""),
|
||||
'/investidor/companies' +
|
||||
(record.id ? '/' + record.id : ''),
|
||||
options,
|
||||
);
|
||||
else form.put("/investidor/profile", options);
|
||||
else form.put('/investidor/profile', options);
|
||||
}}
|
||||
>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
@@ -127,16 +141,19 @@ function Editor({
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.payload[key]}
|
||||
required={isCompany && ["name", "country", "role"].includes(key)}
|
||||
required={
|
||||
isCompany &&
|
||||
['name', 'country', 'role'].includes(key)
|
||||
}
|
||||
maxLength={
|
||||
key === "description" || key === "experience"
|
||||
key === 'description' || key === 'experience'
|
||||
? 2000
|
||||
: key === "investment_capacity"
|
||||
: key === 'investment_capacity'
|
||||
? 1000
|
||||
: 200
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
@@ -151,7 +168,9 @@ function Editor({
|
||||
</p>
|
||||
))}
|
||||
<button className={button} disabled={form.processing}>
|
||||
{isCompany ? "Guardar declaração da empresa" : "Guardar perfil de investimento"}
|
||||
{isCompany
|
||||
? 'Guardar declaração da empresa'
|
||||
: 'Guardar perfil de investimento'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { useForm } from "@inertiajs/react";
|
||||
import { Management } from "../management/shared";
|
||||
import { Field, input, button, card, groupLabels } from "./shared";
|
||||
import type { Option } from "./shared";
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { Management } from '../management/shared';
|
||||
import { Field, input, button, card, groupLabels } from './shared';
|
||||
import type { Option } from './shared';
|
||||
export default function References({ options }: { options: Option[] }) {
|
||||
const groups = [...new Set(options.map((o) => o.group))];
|
||||
return (
|
||||
<Management title="Opções dos formulários e filtros">
|
||||
<p>
|
||||
Os códigos são estáveis; pode corrigir etiquetas ou desactivar opções sem eliminar
|
||||
referências históricas. Cada grupo conserva Outro — especificar.
|
||||
Os códigos são estáveis; pode corrigir etiquetas ou desactivar
|
||||
opções sem eliminar referências históricas. Cada grupo conserva
|
||||
Outro — especificar.
|
||||
</p>
|
||||
<OptionForm groups={groups} />
|
||||
<div className="space-y-4">
|
||||
@@ -21,7 +22,11 @@ export default function References({ options }: { options: Option[] }) {
|
||||
{options
|
||||
.filter((o) => o.group === group)
|
||||
.map((o) => (
|
||||
<OptionForm key={o.id} option={o} groups={groups} />
|
||||
<OptionForm
|
||||
key={o.id}
|
||||
option={o}
|
||||
groups={groups}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
@@ -33,8 +38,8 @@ export default function References({ options }: { options: Option[] }) {
|
||||
function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
const form = useForm({
|
||||
group: option?.group ?? groups[0],
|
||||
code: option?.code ?? "",
|
||||
label: option?.label ?? "",
|
||||
code: option?.code ?? '',
|
||||
label: option?.label ?? '',
|
||||
active: option?.active ?? true,
|
||||
requires_description: option?.requires_description ?? false,
|
||||
sort_order: option?.sort_order ?? 0,
|
||||
@@ -44,19 +49,25 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
className="space-y-3 rounded border p-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post("/management/investment/references" + (option ? "/" + option.id : ""), {
|
||||
preserveScroll: true,
|
||||
});
|
||||
form.post(
|
||||
'/management/investment/references' +
|
||||
(option ? '/' + option.id : ''),
|
||||
{
|
||||
preserveScroll: true,
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h2 className="font-semibold">{option ? "Editar opção" : "Criar opção"}</h2>
|
||||
<h2 className="font-semibold">
|
||||
{option ? 'Editar opção' : 'Criar opção'}
|
||||
</h2>
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
<Field label="Grupo">
|
||||
<select
|
||||
disabled={!!option}
|
||||
className={input}
|
||||
value={form.data.group}
|
||||
onChange={(e) => form.setData("group", e.target.value)}
|
||||
onChange={(e) => form.setData('group', e.target.value)}
|
||||
>
|
||||
{groups.map((g) => (
|
||||
<option key={g} value={g}>
|
||||
@@ -71,7 +82,7 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
required
|
||||
readOnly={!!option}
|
||||
value={form.data.code}
|
||||
onChange={(e) => form.setData("code", e.target.value)}
|
||||
onChange={(e) => form.setData('code', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Etiqueta">
|
||||
@@ -79,7 +90,7 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
className={input}
|
||||
required
|
||||
value={form.data.label}
|
||||
onChange={(e) => form.setData("label", e.target.value)}
|
||||
onChange={(e) => form.setData('label', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
@@ -87,7 +98,7 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.active}
|
||||
onChange={(e) => form.setData("active", e.target.checked)}
|
||||
onChange={(e) => form.setData('active', e.target.checked)}
|
||||
/>
|
||||
Activa
|
||||
</label>
|
||||
@@ -95,7 +106,9 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.requires_description}
|
||||
onChange={(e) => form.setData("requires_description", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
form.setData('requires_description', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Exige especificação
|
||||
</label>
|
||||
@@ -106,7 +119,9 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
max="10000"
|
||||
className={input}
|
||||
value={form.data.sort_order}
|
||||
onChange={(e) => form.setData("sort_order", Number(e.target.value))}
|
||||
onChange={(e) =>
|
||||
form.setData('sort_order', Number(e.target.value))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Head, Link, usePage } from "@inertiajs/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { PortalMenu } from "@/layouts/portal-navigation";
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import type { StructureGeography } from '@/components/structure-geography';
|
||||
|
||||
export type Option = {
|
||||
@@ -12,7 +12,12 @@ export type Option = {
|
||||
requires_description: boolean;
|
||||
sort_order: number;
|
||||
};
|
||||
export type Entity = { id: string; name: string; dossiers?: { id: string; title: string; source: string }[]; geography?: StructureGeography | null };
|
||||
export type Entity = {
|
||||
id: string;
|
||||
name: string;
|
||||
dossiers?: { id: string; title: string; source: string }[];
|
||||
geography?: StructureGeography | null;
|
||||
};
|
||||
export type References = {
|
||||
zones?: { id: string; name: string; category: string }[];
|
||||
options: Option[];
|
||||
@@ -42,7 +47,11 @@ export type Opportunity = {
|
||||
last_validated_at?: string | null;
|
||||
};
|
||||
export type Context = {
|
||||
primary_territory_path?: { id: string; name: string; location_type: string }[];
|
||||
primary_territory_path?: {
|
||||
id: string;
|
||||
name: string;
|
||||
location_type: string;
|
||||
}[];
|
||||
zones?: {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -66,18 +75,34 @@ export type Context = {
|
||||
locations: Entity[];
|
||||
};
|
||||
export const input =
|
||||
"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700";
|
||||
'w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700';
|
||||
export const button =
|
||||
"inline-flex items-center justify-center rounded-lg bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700";
|
||||
export const card = "rounded-xl border border-slate-200 bg-white p-5 shadow-sm";
|
||||
export function Frame({ title, children }: { title: string; children: ReactNode }) {
|
||||
const { flash } = usePage<{ flash?: { success?: string } }>().props;
|
||||
'inline-flex items-center justify-center rounded-lg bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700';
|
||||
export const card = 'rounded-xl border border-slate-200 bg-white p-5 shadow-sm';
|
||||
export function Frame({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { flash } = usePage<{
|
||||
flash?: { success?: string; warning?: string };
|
||||
}>().props;
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 text-slate-900">
|
||||
<Head title={title} />
|
||||
<PortalMenu />
|
||||
<main className="mx-auto max-w-7xl space-y-6 px-5 py-9">
|
||||
<h1 className="text-3xl font-bold">{title}</h1>
|
||||
{flash?.warning && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded border border-amber-600 bg-amber-50 p-4 text-amber-950"
|
||||
>
|
||||
{flash.warning}
|
||||
</p>
|
||||
)}
|
||||
{flash?.success && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -91,8 +116,8 @@ export function Frame({ title, children }: { title: string; children: ReactNode
|
||||
<footer className="border-t p-6 text-center">
|
||||
<Link href="/apoio" className="underline">
|
||||
Apoio ao Investidor
|
||||
</Link>{" "}
|
||||
·{" "}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
<Link href="/documentos" className="underline">
|
||||
Documentos
|
||||
</Link>
|
||||
@@ -100,7 +125,13 @@ export function Frame({ title, children }: { title: string; children: ReactNode
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function Field({ label, children }: { label: string; children: ReactNode }) {
|
||||
export function Field({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<label className="block space-y-1 text-sm font-medium">
|
||||
<span>{label}</span>
|
||||
@@ -110,44 +141,50 @@ export function Field({ label, children }: { label: string; children: ReactNode
|
||||
}
|
||||
export function money(r: Opportunity) {
|
||||
return r.estimated_investment_amount === null
|
||||
? "Montante não indicado"
|
||||
: `${new Intl.NumberFormat("pt-MZ", { maximumFractionDigits: 2 }).format(Number(r.estimated_investment_amount))} ${r.estimated_investment_currency}`;
|
||||
? 'Montante não indicado'
|
||||
: `${new Intl.NumberFormat('pt-MZ', { maximumFractionDigits: 2 }).format(Number(r.estimated_investment_amount))} ${r.estimated_investment_currency}`;
|
||||
}
|
||||
export async function api(url: string, body?: unknown) {
|
||||
const token = decodeURIComponent(
|
||||
document.cookie
|
||||
.split("; ")
|
||||
.find((c) => c.startsWith("XSRF-TOKEN="))
|
||||
?.slice(11) ?? "",
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11) ?? '',
|
||||
);
|
||||
const formData = typeof FormData !== "undefined" && body instanceof FormData;
|
||||
const formData =
|
||||
typeof FormData !== 'undefined' && body instanceof FormData;
|
||||
const response = await fetch(url, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
credentials: "same-origin",
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
...(formData ? {} : { "Content-Type": "application/json" }),
|
||||
"X-XSRF-TOKEN": token,
|
||||
Accept: 'application/json',
|
||||
...(formData ? {} : { 'Content-Type': 'application/json' }),
|
||||
'X-XSRF-TOKEN': token,
|
||||
},
|
||||
...(body === undefined ? {} : { body: formData ? body : JSON.stringify(body) }),
|
||||
...(body === undefined
|
||||
? {}
|
||||
: { body: formData ? body : JSON.stringify(body) }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.message ?? "Não foi possível concluir a operação.");
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
data.message ?? 'Não foi possível concluir a operação.',
|
||||
);
|
||||
return data;
|
||||
}
|
||||
export const groupLabels: Record<string, string> = {
|
||||
education: "Educação",
|
||||
infrastructure: "Infraestruturas",
|
||||
labour: "Mão de obra",
|
||||
qualification: "Qualificações",
|
||||
support: "Apoios",
|
||||
impact: "Impacto",
|
||||
partnership: "Modelo de parceria",
|
||||
subsector: "Subsector",
|
||||
need_category: "Categoria da necessidade",
|
||||
priority: "Prioridade",
|
||||
unit: "Unidade",
|
||||
participation: "Participação",
|
||||
investor_profile: "Perfil do investidor",
|
||||
need_status: "Estado da necessidade",
|
||||
education: 'Educação',
|
||||
infrastructure: 'Infraestruturas',
|
||||
labour: 'Mão de obra',
|
||||
qualification: 'Qualificações',
|
||||
support: 'Apoios',
|
||||
impact: 'Impacto',
|
||||
partnership: 'Modelo de parceria',
|
||||
subsector: 'Subsector',
|
||||
need_category: 'Categoria da necessidade',
|
||||
priority: 'Prioridade',
|
||||
unit: 'Unidade',
|
||||
participation: 'Participação',
|
||||
investor_profile: 'Perfil do investidor',
|
||||
need_status: 'Estado da necessidade',
|
||||
};
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Frame, Field, input, button, card } from "./shared";
|
||||
import type { References } from "./shared";
|
||||
import { Conversation } from "./conversation";
|
||||
import type { Message } from "./conversation";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, Field, input, button, card } from './shared';
|
||||
import type { References } from './shared';
|
||||
import { Conversation } from './conversation';
|
||||
import type { Message } from './conversation';
|
||||
type Payload = {
|
||||
full_name: string;
|
||||
email: string;
|
||||
@@ -54,9 +54,14 @@ type Props = {
|
||||
zone_origin?: {
|
||||
zone_id: string;
|
||||
zone_version: number;
|
||||
intent: "interest" | "dossier" | "meeting";
|
||||
intent: 'interest' | 'dossier' | 'meeting';
|
||||
} | null;
|
||||
submission: { id: string; version: number; payload: Partial<Payload>; status: string };
|
||||
submission: {
|
||||
id: string;
|
||||
version: number;
|
||||
payload: Partial<Payload>;
|
||||
status: string;
|
||||
};
|
||||
references: References;
|
||||
needs: Need[];
|
||||
attachments: { id: string; file_name: string }[];
|
||||
@@ -68,30 +73,37 @@ type Props = {
|
||||
revisions: { version: number; created_at: string }[];
|
||||
};
|
||||
const emptyNeed = (): Need => ({
|
||||
category_id: "",
|
||||
option_id: "",
|
||||
unit_id: "",
|
||||
priority_id: "",
|
||||
quantity: "",
|
||||
deadline: "",
|
||||
category_id: '',
|
||||
option_id: '',
|
||||
unit_id: '',
|
||||
priority_id: '',
|
||||
quantity: '',
|
||||
deadline: '',
|
||||
details: {
|
||||
description: "",
|
||||
location: "",
|
||||
observations: "",
|
||||
qualification: "",
|
||||
specialty: "",
|
||||
experience: "",
|
||||
certifications: "",
|
||||
availability: "",
|
||||
institution: "",
|
||||
training_mode: "",
|
||||
duration: "",
|
||||
status: "",
|
||||
description: '',
|
||||
location: '',
|
||||
observations: '',
|
||||
qualification: '',
|
||||
specialty: '',
|
||||
experience: '',
|
||||
certifications: '',
|
||||
availability: '',
|
||||
institution: '',
|
||||
training_mode: '',
|
||||
duration: '',
|
||||
status: '',
|
||||
},
|
||||
});
|
||||
export default function Submission(props: Props) {
|
||||
const [step, setStep] = useState(0);
|
||||
return <Editor key={props.submission.version} {...props} step={step} setStep={setStep} />;
|
||||
return (
|
||||
<Editor
|
||||
key={props.submission.version}
|
||||
{...props}
|
||||
step={step}
|
||||
setStep={setStep}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function Editor({
|
||||
zone_origin,
|
||||
@@ -109,24 +121,24 @@ function Editor({
|
||||
setStep,
|
||||
}: Props & { step: number; setStep: (step: number) => void }) {
|
||||
const initial: Payload = {
|
||||
full_name: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
country: "",
|
||||
organisation: "",
|
||||
representative_role: "",
|
||||
experience: "",
|
||||
investment_capacity: "",
|
||||
other_details: "",
|
||||
profile_id: "",
|
||||
sector: "",
|
||||
objective: "",
|
||||
participation_id: "",
|
||||
partnership_id: "",
|
||||
estimated_amount: "",
|
||||
currency: "",
|
||||
horizon: "",
|
||||
location: "",
|
||||
full_name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
country: '',
|
||||
organisation: '',
|
||||
representative_role: '',
|
||||
experience: '',
|
||||
investment_capacity: '',
|
||||
other_details: '',
|
||||
profile_id: '',
|
||||
sector: '',
|
||||
objective: '',
|
||||
participation_id: '',
|
||||
partnership_id: '',
|
||||
estimated_amount: '',
|
||||
currency: '',
|
||||
horizon: '',
|
||||
location: '',
|
||||
cluster_ids: [],
|
||||
corridor_ids: [],
|
||||
project_ids: [],
|
||||
@@ -141,13 +153,13 @@ function Editor({
|
||||
...Object.fromEntries(
|
||||
Object.entries(n).filter(([k]) =>
|
||||
[
|
||||
"category_id",
|
||||
"option_id",
|
||||
"unit_id",
|
||||
"priority_id",
|
||||
"quantity",
|
||||
"deadline",
|
||||
"details",
|
||||
'category_id',
|
||||
'option_id',
|
||||
'unit_id',
|
||||
'priority_id',
|
||||
'quantity',
|
||||
'deadline',
|
||||
'details',
|
||||
].includes(k),
|
||||
),
|
||||
),
|
||||
@@ -158,12 +170,17 @@ function Editor({
|
||||
version: s.version,
|
||||
file: null,
|
||||
});
|
||||
const [note, setNote] = useState("");
|
||||
const readonly = s.status !== "draft" || management;
|
||||
const base = "/investidor/manifestacoes/" + s.id;
|
||||
const [note, setNote] = useState('');
|
||||
const readonly = s.status !== 'draft' || management;
|
||||
const base = '/investidor/manifestacoes/' + s.id;
|
||||
const update = <K extends keyof Payload>(key: K, value: Payload[K]) =>
|
||||
form.setData("payload", { ...form.data.payload, [key]: value });
|
||||
const text = (key: keyof Payload, label: string, required = false, type = "text") => (
|
||||
form.setData('payload', { ...form.data.payload, [key]: value });
|
||||
const text = (
|
||||
key: keyof Payload,
|
||||
label: string,
|
||||
required = false,
|
||||
type = 'text',
|
||||
) => (
|
||||
<Field label={label}>
|
||||
<input
|
||||
className={input}
|
||||
@@ -171,21 +188,29 @@ function Editor({
|
||||
required={required}
|
||||
disabled={readonly}
|
||||
name={key}
|
||||
min={type === "number" ? 0 : undefined}
|
||||
minLength={key === "objective" ? 20 : key === "full_name" ? 3 : undefined}
|
||||
min={type === 'number' ? 0 : undefined}
|
||||
minLength={
|
||||
key === 'objective'
|
||||
? 20
|
||||
: key === 'full_name'
|
||||
? 3
|
||||
: undefined
|
||||
}
|
||||
onBlur={(e) => {
|
||||
if (!e.target.validity.valid)
|
||||
setNote(`Verifique o campo ${label}: ${e.target.validationMessage}`);
|
||||
else setNote("");
|
||||
setNote(
|
||||
`Verifique o campo ${label}: ${e.target.validationMessage}`,
|
||||
);
|
||||
else setNote('');
|
||||
}}
|
||||
value={String(form.data.payload[key] ?? "")}
|
||||
value={String(form.data.payload[key] ?? '')}
|
||||
onChange={(e) => update(key, e.target.value as never)}
|
||||
maxLength={key === "objective" ? 5000 : 2000}
|
||||
maxLength={key === 'objective' ? 5000 : 2000}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
const option = (
|
||||
key: "profile_id" | "participation_id" | "partnership_id",
|
||||
key: 'profile_id' | 'participation_id' | 'partnership_id',
|
||||
group: string,
|
||||
label: string,
|
||||
) => (
|
||||
@@ -193,7 +218,7 @@ function Editor({
|
||||
<select
|
||||
className={input}
|
||||
disabled={readonly}
|
||||
value={form.data.payload[key] ?? ""}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) => update(key, e.target.value)}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
@@ -201,12 +226,14 @@ function Editor({
|
||||
.filter(
|
||||
(o) =>
|
||||
o.group === group &&
|
||||
(o.active || String(o.id) === String(form.data.payload[key])),
|
||||
(o.active ||
|
||||
String(o.id) ===
|
||||
String(form.data.payload[key])),
|
||||
)
|
||||
.map((o) => (
|
||||
<option value={o.id} key={o.id} disabled={!o.active}>
|
||||
{o.label}
|
||||
{!o.active ? " (inactiva)" : ""}
|
||||
{!o.active ? ' (inactiva)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -214,81 +241,104 @@ function Editor({
|
||||
);
|
||||
const updateNeed = (index: number, value: Need) =>
|
||||
form.setData(
|
||||
"needs",
|
||||
'needs',
|
||||
form.data.needs.map((n, i) => (i === index ? value : n)),
|
||||
);
|
||||
const errorStep = (key: string) =>
|
||||
key.startsWith("needs.")
|
||||
key.startsWith('needs.')
|
||||
? 2
|
||||
: /payload\.(full_name|email|phone|country|profile_id|organisation|representative_role|sector|experience|investment_capacity)/.test(
|
||||
key,
|
||||
)
|
||||
? 0
|
||||
: key === "payload.contact_consent"
|
||||
: key === 'payload.contact_consent'
|
||||
? 4
|
||||
: 1;
|
||||
return (
|
||||
<Frame
|
||||
title={
|
||||
receipt ? "Manifestação " + receipt.reference : "Preparar manifestação de interesse"
|
||||
receipt
|
||||
? 'Manifestação ' + receipt.reference
|
||||
: 'Preparar manifestação de interesse'
|
||||
}
|
||||
>
|
||||
<p>
|
||||
{target ??
|
||||
(zone_origin
|
||||
? "Pedido relativo a zona de investimento"
|
||||
: "Interesse geral")}{" "}
|
||||
· Versão {s.version} · {s.status === "draft" ? "Rascunho privado" : "Submetido"}
|
||||
? 'Pedido relativo a zona de investimento'
|
||||
: 'Interesse geral')}{' '}
|
||||
· Versão {s.version} ·{' '}
|
||||
{s.status === 'draft' ? 'Rascunho privado' : 'Submetido'}
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/painel?submission_id=${s.id}`}
|
||||
>
|
||||
Preparar apoio e acompanhamento deste projecto no Balcão Virtual
|
||||
</Link>
|
||||
{zone_origin && (
|
||||
<p className={card}>
|
||||
<Link className="underline" href={`/zonas/${zone_origin.zone_id}`}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/zonas/${zone_origin.zone_id}`}
|
||||
>
|
||||
Consultar zona de origem
|
||||
</Link>{" "}
|
||||
· Versão da ficha {zone_origin.zone_version} ·{" "}
|
||||
</Link>{' '}
|
||||
· Versão da ficha {zone_origin.zone_version} ·{' '}
|
||||
{
|
||||
{
|
||||
interest: "Manifestação de interesse",
|
||||
dossier: "Pedido de dossier",
|
||||
meeting: "Pedido de reunião",
|
||||
interest: 'Manifestação de interesse',
|
||||
dossier: 'Pedido de dossier',
|
||||
meeting: 'Pedido de reunião',
|
||||
}[zone_origin.intent]
|
||||
}
|
||||
. Atendimento assistido, sem decisão administrativa automática.
|
||||
. Atendimento assistido, sem decisão administrativa
|
||||
automática.
|
||||
</p>
|
||||
)}
|
||||
{receipt && (
|
||||
<p role="status" className={card}>
|
||||
Protocolo: <strong>{receipt.reference}</strong> · Estado:{" "}
|
||||
Protocolo: <strong>{receipt.reference}</strong> · Estado:{' '}
|
||||
{(
|
||||
{
|
||||
received: "Recebido",
|
||||
in_review: "Em análise",
|
||||
contacted: "Contactado",
|
||||
closed: "Encerrado",
|
||||
received: 'Recebido',
|
||||
in_review: 'Em análise',
|
||||
contacted: 'Contactado',
|
||||
closed: 'Encerrado',
|
||||
} as Record<string, string>
|
||||
)[receipt.status] ?? receipt.status}
|
||||
</p>
|
||||
)}
|
||||
<nav aria-label="Etapas da manifestação" className="flex flex-wrap gap-2">
|
||||
{["Identificação", "Investimento", "Necessidades", "Anexos", "Rever e enviar"].map(
|
||||
(label, i) => (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
aria-current={step === i ? "step" : undefined}
|
||||
className={step === i ? button : "rounded border px-4 py-2"}
|
||||
onClick={() => setStep(i)}
|
||||
>
|
||||
{i + 1}. {label}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
<nav
|
||||
aria-label="Etapas da manifestação"
|
||||
className="flex flex-wrap gap-2"
|
||||
>
|
||||
{[
|
||||
'Identificação',
|
||||
'Investimento',
|
||||
'Necessidades',
|
||||
'Anexos',
|
||||
'Rever e enviar',
|
||||
].map((label, i) => (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
aria-current={step === i ? 'step' : undefined}
|
||||
className={
|
||||
step === i ? button : 'rounded border px-4 py-2'
|
||||
}
|
||||
onClick={() => setStep(i)}
|
||||
>
|
||||
{i + 1}. {label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<p className="text-sm">
|
||||
Etapa {step + 1} de 5. Guarde antes de sair. A informação declarada não é publicada.
|
||||
Etapa {step + 1} de 5. Guarde antes de sair. A informação
|
||||
declarada não é publicada.
|
||||
</p>
|
||||
<form
|
||||
className={card + " space-y-5"}
|
||||
className={card + ' space-y-5'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.put(base, { preserveScroll: true });
|
||||
@@ -296,44 +346,63 @@ function Editor({
|
||||
>
|
||||
{step === 0 && (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{text("full_name", "Nome completo", true)}
|
||||
{text("email", "Email", true, "email")}
|
||||
{text("phone", "Telefone")}
|
||||
{text("country", "País", true)}
|
||||
{option("profile_id", "investor_profile", "Perfil do investidor")}
|
||||
{text("organisation", "Organização / empresa")}
|
||||
{text("representative_role", "Função do representante")}
|
||||
{text("sector", "Sector de interesse", true)}
|
||||
{text("experience", "Experiência relevante")}
|
||||
{text('full_name', 'Nome completo', true)}
|
||||
{text('email', 'Email', true, 'email')}
|
||||
{text('phone', 'Telefone')}
|
||||
{text('country', 'País', true)}
|
||||
{option(
|
||||
'profile_id',
|
||||
'investor_profile',
|
||||
'Perfil do investidor',
|
||||
)}
|
||||
{text('organisation', 'Organização / empresa')}
|
||||
{text('representative_role', 'Função do representante')}
|
||||
{text('sector', 'Sector de interesse', true)}
|
||||
{text('experience', 'Experiência relevante')}
|
||||
{text(
|
||||
"investment_capacity",
|
||||
"Capacidade de investimento / especificação do perfil",
|
||||
'investment_capacity',
|
||||
'Capacidade de investimento / especificação do perfil',
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{step === 1 && (
|
||||
<div className="space-y-5">
|
||||
{text(
|
||||
"objective",
|
||||
"Objectivo do investimento (mínimo 20 caracteres)",
|
||||
'objective',
|
||||
'Objectivo do investimento (mínimo 20 caracteres)',
|
||||
true,
|
||||
)}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{option(
|
||||
"participation_id",
|
||||
"participation",
|
||||
"Modalidade de participação",
|
||||
'participation_id',
|
||||
'participation',
|
||||
'Modalidade de participação',
|
||||
)}
|
||||
{option("partnership_id", "partnership", "Modelo de parceria")}
|
||||
{text("estimated_amount", "Investimento estimado", false, "number")}
|
||||
{text("currency", "Moeda (código de três letras)")}
|
||||
{text("horizon", "Prazo / horizonte", true)}
|
||||
{text("location", "Localização pretendida")}
|
||||
{option(
|
||||
'partnership_id',
|
||||
'partnership',
|
||||
'Modelo de parceria',
|
||||
)}
|
||||
{text(
|
||||
'estimated_amount',
|
||||
'Investimento estimado',
|
||||
false,
|
||||
'number',
|
||||
)}
|
||||
{text('currency', 'Moeda (código de três letras)')}
|
||||
{text('horizon', 'Prazo / horizonte', true)}
|
||||
{text('location', 'Localização pretendida')}
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{(["clusters", "corridors", "projects"] as const).map((group, i) => {
|
||||
{(
|
||||
['clusters', 'corridors', 'projects'] as const
|
||||
).map((group, i) => {
|
||||
const key = (
|
||||
["cluster_ids", "corridor_ids", "project_ids"] as const
|
||||
[
|
||||
'cluster_ids',
|
||||
'corridor_ids',
|
||||
'project_ids',
|
||||
] as const
|
||||
)[i];
|
||||
return (
|
||||
<fieldset
|
||||
@@ -341,27 +410,45 @@ function Editor({
|
||||
key={group}
|
||||
>
|
||||
<legend>
|
||||
{["Clusters", "Corredores", "Projectos âncora"][i]}
|
||||
{
|
||||
[
|
||||
'Clusters',
|
||||
'Corredores',
|
||||
'Projectos âncora',
|
||||
][i]
|
||||
}
|
||||
</legend>
|
||||
{r[group].map((entity) => (
|
||||
<label key={entity.id} className="flex gap-2">
|
||||
<label
|
||||
key={entity.id}
|
||||
className="flex gap-2"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={readonly}
|
||||
checked={(
|
||||
form.data.payload[key] ?? []
|
||||
form.data.payload[
|
||||
key
|
||||
] ?? []
|
||||
).includes(entity.id)}
|
||||
onChange={(e) =>
|
||||
update(
|
||||
key,
|
||||
e.target.checked
|
||||
? [
|
||||
...(form.data.payload[key] ??
|
||||
[]),
|
||||
...(form
|
||||
.data
|
||||
.payload[
|
||||
key
|
||||
] ?? []),
|
||||
entity.id,
|
||||
]
|
||||
: form.data.payload[key].filter(
|
||||
(id) => id !== entity.id,
|
||||
: form.data.payload[
|
||||
key
|
||||
].filter(
|
||||
(id) =>
|
||||
id !==
|
||||
entity.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -381,22 +468,30 @@ function Editor({
|
||||
Mão de obra, infraestruturas, formação e apoios
|
||||
</h2>
|
||||
<p>
|
||||
Acrescente o que existe no local e o que necessita. As opções são
|
||||
mantidas pela gestão; use Outro para especificar casos adicionais.
|
||||
Acrescente o que existe no local e o que necessita.
|
||||
As opções são mantidas pela gestão; use Outro para
|
||||
especificar casos adicionais.
|
||||
</p>
|
||||
{form.data.needs.map((need, index) => {
|
||||
const category =
|
||||
r.options.find((o) => String(o.id) === String(need.category_id))
|
||||
?.code ?? "";
|
||||
const group = category.startsWith("labour")
|
||||
? "labour"
|
||||
: category.startsWith("infrastructure")
|
||||
? "infrastructure"
|
||||
: category === "education"
|
||||
? "education"
|
||||
: "support";
|
||||
r.options.find(
|
||||
(o) =>
|
||||
String(o.id) ===
|
||||
String(need.category_id),
|
||||
)?.code ?? '';
|
||||
const group = category.startsWith('labour')
|
||||
? 'labour'
|
||||
: category.startsWith('infrastructure')
|
||||
? 'infrastructure'
|
||||
: category === 'education'
|
||||
? 'education'
|
||||
: 'support';
|
||||
const needSelect = (
|
||||
field: "category_id" | "option_id" | "unit_id" | "priority_id",
|
||||
field:
|
||||
| 'category_id'
|
||||
| 'option_id'
|
||||
| 'unit_id'
|
||||
| 'priority_id',
|
||||
optionGroup: string,
|
||||
label: string,
|
||||
) => (
|
||||
@@ -404,13 +499,13 @@ function Editor({
|
||||
<select
|
||||
className={input}
|
||||
disabled={readonly}
|
||||
value={need[field] ?? ""}
|
||||
value={need[field] ?? ''}
|
||||
onChange={(e) =>
|
||||
updateNeed(index, {
|
||||
...need,
|
||||
[field]: e.target.value,
|
||||
...(field === "category_id"
|
||||
? { option_id: "" }
|
||||
...(field === 'category_id'
|
||||
? { option_id: '' }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
@@ -421,7 +516,10 @@ function Editor({
|
||||
(o) =>
|
||||
o.group === optionGroup &&
|
||||
(o.active ||
|
||||
String(o.id) === String(need[field])),
|
||||
String(o.id) ===
|
||||
String(
|
||||
need[field],
|
||||
)),
|
||||
)
|
||||
.map((o) => (
|
||||
<option value={o.id} key={o.id}>
|
||||
@@ -432,13 +530,30 @@ function Editor({
|
||||
</Field>
|
||||
);
|
||||
return (
|
||||
<fieldset key={index} className="space-y-4 rounded-lg border p-4">
|
||||
<legend className="font-bold">Necessidade {index + 1}</legend>
|
||||
<fieldset
|
||||
key={index}
|
||||
className="space-y-4 rounded-lg border p-4"
|
||||
>
|
||||
<legend className="font-bold">
|
||||
Necessidade {index + 1}
|
||||
</legend>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{needSelect("category_id", "need_category", "Categoria")}
|
||||
{needSelect("option_id", group, "Tipo")}
|
||||
{needSelect("unit_id", "unit", "Unidade")}
|
||||
{needSelect("priority_id", "priority", "Prioridade")}
|
||||
{needSelect(
|
||||
'category_id',
|
||||
'need_category',
|
||||
'Categoria',
|
||||
)}
|
||||
{needSelect('option_id', group, 'Tipo')}
|
||||
{needSelect(
|
||||
'unit_id',
|
||||
'unit',
|
||||
'Unidade',
|
||||
)}
|
||||
{needSelect(
|
||||
'priority_id',
|
||||
'priority',
|
||||
'Prioridade',
|
||||
)}
|
||||
<Field label="Quantidade">
|
||||
<input
|
||||
className={input}
|
||||
@@ -446,11 +561,12 @@ function Editor({
|
||||
min="0"
|
||||
step="0.01"
|
||||
disabled={readonly}
|
||||
value={need.quantity ?? ""}
|
||||
value={need.quantity ?? ''}
|
||||
onChange={(e) =>
|
||||
updateNeed(index, {
|
||||
...need,
|
||||
quantity: e.target.value,
|
||||
quantity:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -460,11 +576,12 @@ function Editor({
|
||||
className={input}
|
||||
type="date"
|
||||
disabled={readonly}
|
||||
value={need.deadline ?? ""}
|
||||
value={need.deadline ?? ''}
|
||||
onChange={(e) =>
|
||||
updateNeed(index, {
|
||||
...need,
|
||||
deadline: e.target.value,
|
||||
deadline:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -472,48 +589,54 @@ function Editor({
|
||||
</div>
|
||||
{(
|
||||
[
|
||||
"description",
|
||||
"location",
|
||||
"observations",
|
||||
...(group === "labour"
|
||||
'description',
|
||||
'location',
|
||||
'observations',
|
||||
...(group === 'labour'
|
||||
? [
|
||||
"qualification",
|
||||
"specialty",
|
||||
"experience",
|
||||
"certifications",
|
||||
"availability",
|
||||
"institution",
|
||||
'qualification',
|
||||
'specialty',
|
||||
'experience',
|
||||
'certifications',
|
||||
'availability',
|
||||
'institution',
|
||||
]
|
||||
: []),
|
||||
...(group === "education"
|
||||
...(group === 'education'
|
||||
? [
|
||||
"qualification",
|
||||
"institution",
|
||||
"training_mode",
|
||||
"duration",
|
||||
"certifications",
|
||||
'qualification',
|
||||
'institution',
|
||||
'training_mode',
|
||||
'duration',
|
||||
'certifications',
|
||||
]
|
||||
: []),
|
||||
] as (keyof Need["details"])[]
|
||||
] as (keyof Need['details'])[]
|
||||
).map((field) => (
|
||||
<Field
|
||||
key={field}
|
||||
label={
|
||||
{
|
||||
description: "Descrição / especificação",
|
||||
location: "Localização",
|
||||
description:
|
||||
'Descrição / especificação',
|
||||
location: 'Localização',
|
||||
observations:
|
||||
"Observações e referência dos anexos de suporte",
|
||||
qualification: "Nível de qualificação",
|
||||
specialty: "Profissão / especialidade",
|
||||
experience: "Experiência",
|
||||
certifications: "Certificações",
|
||||
availability: "Disponibilidade",
|
||||
'Observações e referência dos anexos de suporte',
|
||||
qualification:
|
||||
'Nível de qualificação',
|
||||
specialty:
|
||||
'Profissão / especialidade',
|
||||
experience: 'Experiência',
|
||||
certifications:
|
||||
'Certificações',
|
||||
availability:
|
||||
'Disponibilidade',
|
||||
institution:
|
||||
"Instituições ou centros de formação",
|
||||
training_mode: "Modalidade de formação",
|
||||
duration: "Duração",
|
||||
status: "Estado",
|
||||
'Instituições ou centros de formação',
|
||||
training_mode:
|
||||
'Modalidade de formação',
|
||||
duration: 'Duração',
|
||||
status: 'Estado',
|
||||
}[field]
|
||||
}
|
||||
>
|
||||
@@ -521,13 +644,16 @@ function Editor({
|
||||
className={input}
|
||||
rows={2}
|
||||
disabled={readonly}
|
||||
value={need.details[field] ?? ""}
|
||||
value={
|
||||
need.details[field] ?? ''
|
||||
}
|
||||
onChange={(e) =>
|
||||
updateNeed(index, {
|
||||
...need,
|
||||
details: {
|
||||
...need.details,
|
||||
[field]: e.target.value,
|
||||
[field]:
|
||||
e.target.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -540,8 +666,10 @@ function Editor({
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
"needs",
|
||||
form.data.needs.filter((_, i) => i !== index),
|
||||
'needs',
|
||||
form.data.needs.filter(
|
||||
(_, i) => i !== index,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
@@ -557,7 +685,10 @@ function Editor({
|
||||
className={button}
|
||||
disabled={form.data.needs.length >= 40}
|
||||
onClick={() =>
|
||||
form.setData("needs", [...form.data.needs, emptyNeed()])
|
||||
form.setData('needs', [
|
||||
...form.data.needs,
|
||||
emptyNeed(),
|
||||
])
|
||||
}
|
||||
>
|
||||
Acrescentar necessidade
|
||||
@@ -567,28 +698,33 @@ function Editor({
|
||||
)}
|
||||
{step === 3 && (
|
||||
<p>
|
||||
Guarde primeiro o rascunho e carregue os anexos no formulário abaixo.
|
||||
Identifique o nome do ficheiro nas observações da necessidade a que
|
||||
corresponde.
|
||||
Guarde primeiro o rascunho e carregue os anexos no
|
||||
formulário abaixo. Identifique o nome do ficheiro nas
|
||||
observações da necessidade a que corresponde.
|
||||
</p>
|
||||
)}
|
||||
{step === 4 && (
|
||||
<section className="space-y-5">
|
||||
<h2 className="text-xl font-bold">Rever antes de enviar</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
Rever antes de enviar
|
||||
</h2>
|
||||
<dl className="space-y-3">
|
||||
{[
|
||||
["Investidor", form.data.payload.full_name],
|
||||
["Email", form.data.payload.email],
|
||||
["Organização", form.data.payload.organisation],
|
||||
["Objectivo", form.data.payload.objective],
|
||||
["Prazo", form.data.payload.horizon],
|
||||
["Necessidades", String(form.data.needs.length)],
|
||||
["Anexos", String(attachments.length)],
|
||||
['Investidor', form.data.payload.full_name],
|
||||
['Email', form.data.payload.email],
|
||||
['Organização', form.data.payload.organisation],
|
||||
['Objectivo', form.data.payload.objective],
|
||||
['Prazo', form.data.payload.horizon],
|
||||
[
|
||||
'Necessidades',
|
||||
String(form.data.needs.length),
|
||||
],
|
||||
['Anexos', String(attachments.length)],
|
||||
].map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="whitespace-pre-line">
|
||||
{value || "Não indicado"}
|
||||
{value || 'Não indicado'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
@@ -598,11 +734,14 @@ function Editor({
|
||||
type="checkbox"
|
||||
disabled={readonly}
|
||||
checked={form.data.payload.contact_consent}
|
||||
onChange={(e) => update("contact_consent", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
update('contact_consent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Autorizo o tratamento destes dados e o contacto pela equipa para
|
||||
analisar e acompanhar esta manifestação. Os anexos são privados. Não
|
||||
constitui consentimento para utilização em IA.
|
||||
Autorizo o tratamento destes dados e o contacto pela
|
||||
equipa para analisar e acompanhar esta manifestação.
|
||||
Os anexos são privados. Não constitui consentimento
|
||||
para utilização em IA.
|
||||
</label>
|
||||
</section>
|
||||
)}
|
||||
@@ -618,8 +757,8 @@ function Editor({
|
||||
.includes(String(o.id)),
|
||||
) &&
|
||||
text(
|
||||
"other_details",
|
||||
"Outro — especifique o perfil, participação ou parceria seleccionados",
|
||||
'other_details',
|
||||
'Outro — especifique o perfil, participação ou parceria seleccionados',
|
||||
true,
|
||||
)}
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
@@ -650,7 +789,7 @@ function Editor({
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
setNote("");
|
||||
setNote('');
|
||||
setStep(step + 1);
|
||||
}}
|
||||
>
|
||||
@@ -670,12 +809,19 @@ function Editor({
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.payload.contact_consent}
|
||||
disabled={
|
||||
form.processing ||
|
||||
!form.data.payload.contact_consent
|
||||
}
|
||||
onClick={() =>
|
||||
form.post(base + "/submit", {
|
||||
form.post(base + '/submit', {
|
||||
preserveScroll: true,
|
||||
onError: (errors) =>
|
||||
setStep(errorStep(Object.keys(errors)[0] ?? "")),
|
||||
setStep(
|
||||
errorStep(
|
||||
Object.keys(errors)[0] ?? '',
|
||||
),
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
@@ -685,15 +831,18 @@ function Editor({
|
||||
</div>
|
||||
</form>
|
||||
{step === 3 && (
|
||||
<section className={card + " space-y-4"}>
|
||||
<section className={card + ' space-y-4'}>
|
||||
<h2 className="text-xl font-bold">Anexos privados</h2>
|
||||
<p>
|
||||
PDF ou TXT, até 10 MiB cada, máximo de dez anexos. Guardar um anexo
|
||||
actualiza a versão do rascunho.
|
||||
PDF ou TXT, até 10 MiB cada, máximo de dez anexos.
|
||||
Guardar um anexo actualiza a versão do rascunho.
|
||||
</p>
|
||||
{attachments.map((a) => (
|
||||
<p key={a.id}>
|
||||
<a className="underline" href={base + "/attachments/" + a.id}>
|
||||
<a
|
||||
className="underline"
|
||||
href={base + '/attachments/' + a.id}
|
||||
>
|
||||
{a.file_name}
|
||||
</a>
|
||||
</p>
|
||||
@@ -705,11 +854,11 @@ function Editor({
|
||||
e.preventDefault();
|
||||
if (form.isDirty) {
|
||||
setNote(
|
||||
"Guarde as alterações do formulário antes de carregar o anexo.",
|
||||
'Guarde as alterações do formulário antes de carregar o anexo.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
upload.post(base + "/attachments", {
|
||||
upload.post(base + '/attachments', {
|
||||
forceFormData: true,
|
||||
preserveScroll: true,
|
||||
});
|
||||
@@ -721,16 +870,24 @@ function Editor({
|
||||
accept="application/pdf,text/plain"
|
||||
required
|
||||
onChange={(e) =>
|
||||
upload.setData("file", e.target.files?.[0] ?? null)
|
||||
upload.setData(
|
||||
'file',
|
||||
e.target.files?.[0] ?? null,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(upload.errors).map(([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
<button className={button} disabled={upload.processing}>
|
||||
{Object.entries(upload.errors).map(
|
||||
([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{value}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={upload.processing}
|
||||
>
|
||||
Carregar anexo
|
||||
</button>
|
||||
</form>
|
||||
@@ -738,19 +895,21 @@ function Editor({
|
||||
</section>
|
||||
)}
|
||||
<details className={card}>
|
||||
<summary className="cursor-pointer font-bold">Histórico do pedido</summary>
|
||||
<summary className="cursor-pointer font-bold">
|
||||
Histórico do pedido
|
||||
</summary>
|
||||
<ol className="mt-3 space-y-2">
|
||||
{events.map((e, i) => (
|
||||
<li key={i}>
|
||||
{new Date(e.created_at).toLocaleString("pt-MZ")} —{" "}
|
||||
{new Date(e.created_at).toLocaleString('pt-MZ')} —{' '}
|
||||
{(
|
||||
{
|
||||
draft_created: "Rascunho criado",
|
||||
draft_saved: "Rascunho guardado",
|
||||
attachment_added: "Anexo acrescentado",
|
||||
submitted: "Submetido",
|
||||
draft_created: 'Rascunho criado',
|
||||
draft_saved: 'Rascunho guardado',
|
||||
attachment_added: 'Anexo acrescentado',
|
||||
submitted: 'Submetido',
|
||||
} as Record<string, string>
|
||||
)[e.action] ?? e.action}{" "}
|
||||
)[e.action] ?? e.action}{' '}
|
||||
· versão {e.version}
|
||||
</li>
|
||||
))}
|
||||
@@ -760,7 +919,7 @@ function Editor({
|
||||
id={s.id}
|
||||
messages={messages}
|
||||
revisions={revisions}
|
||||
submitted={s.status === "submitted"}
|
||||
submitted={s.status === 'submitted'}
|
||||
/>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { Frame, card, button } from "./shared";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, card, button } from './shared';
|
||||
export default function Workspace({
|
||||
submissions,
|
||||
favourites,
|
||||
@@ -18,10 +18,10 @@ export default function Workspace({
|
||||
favourites: { id: number; title: string; slug: string }[];
|
||||
}) {
|
||||
const states: Record<string, string> = {
|
||||
received: "Recebido",
|
||||
in_review: "Em análise",
|
||||
contacted: "Contactado",
|
||||
closed: "Encerrado",
|
||||
received: 'Recebido',
|
||||
in_review: 'Em análise',
|
||||
contacted: 'Contactado',
|
||||
closed: 'Encerrado',
|
||||
};
|
||||
return (
|
||||
<Frame title="Área do investidor">
|
||||
@@ -39,28 +39,38 @@ export default function Workspace({
|
||||
Apoio e parcerias
|
||||
</Link>
|
||||
</nav>
|
||||
<button className={button} onClick={() => router.post("/investidor/manifestacoes")}>
|
||||
<button
|
||||
className={button}
|
||||
onClick={() => router.post('/investidor/manifestacoes')}
|
||||
>
|
||||
Preparar nova manifestação
|
||||
</button>
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-2xl font-bold">Rascunhos e manifestações</h2>
|
||||
<h2 className="text-2xl font-bold">
|
||||
Rascunhos e manifestações
|
||||
</h2>
|
||||
{submissions.data.map((s) => (
|
||||
<article className={card} key={s.id}>
|
||||
<Link
|
||||
href={`/investidor/manifestacoes/${s.id}`}
|
||||
className="font-semibold underline"
|
||||
>
|
||||
{s.reference ?? "Continuar rascunho"}
|
||||
{s.reference ?? 'Continuar rascunho'}
|
||||
</Link>
|
||||
<p>
|
||||
{s.status === "draft"
|
||||
? "Rascunho privado"
|
||||
: (states[s.request_status ?? ""] ?? s.request_status)}
|
||||
{s.status === 'draft'
|
||||
? 'Rascunho privado'
|
||||
: (states[s.request_status ?? ''] ??
|
||||
s.request_status)}
|
||||
</p>
|
||||
<p>
|
||||
{new Date(s.created_at).toLocaleDateString('pt-MZ')}
|
||||
</p>
|
||||
<p>{new Date(s.created_at).toLocaleDateString("pt-MZ")}</p>
|
||||
</article>
|
||||
))}
|
||||
{!submissions.data.length && <p>Ainda não existem manifestações neste percurso.</p>}
|
||||
{!submissions.data.length && (
|
||||
<p>Ainda não existem manifestações neste percurso.</p>
|
||||
)}
|
||||
<nav aria-label="Paginação" className="flex gap-4">
|
||||
{submissions.prev_page_url && (
|
||||
<Link href={submissions.prev_page_url}>Anterior</Link>
|
||||
@@ -73,12 +83,19 @@ export default function Workspace({
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-2xl font-bold">Oportunidades favoritas</h2>
|
||||
{favourites.map((f) => (
|
||||
<Link href={`/oportunidades/${f.slug}`} className={card + " block"} key={f.id}>
|
||||
<Link
|
||||
href={`/oportunidades/${f.slug}`}
|
||||
className={card + ' block'}
|
||||
key={f.id}
|
||||
>
|
||||
{f.title}
|
||||
</Link>
|
||||
))}
|
||||
{!favourites.length && (
|
||||
<p>Explore o catálogo e guarde as oportunidades que pretende acompanhar.</p>
|
||||
<p>
|
||||
Explore o catálogo e guarde as oportunidades que
|
||||
pretende acompanhar.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
</Frame>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { api, button, card, Field, input } from "./shared";
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { api, button, card, Field, input } from './shared';
|
||||
|
||||
export type ZoneAttachment = {
|
||||
id: string;
|
||||
@@ -18,7 +18,13 @@ export type ZoneAttachment = {
|
||||
file_name?: string;
|
||||
file_status?: string;
|
||||
document_id?: string;
|
||||
malware_scan_status?: 'pending' | 'scanning' | 'clean' | 'infected' | 'inconclusive' | 'failed';
|
||||
malware_scan_status?:
|
||||
| 'pending'
|
||||
| 'scanning'
|
||||
| 'clean'
|
||||
| 'infected'
|
||||
| 'inconclusive'
|
||||
| 'failed';
|
||||
malware_failure_reason?: string | null;
|
||||
media_type: string;
|
||||
size_bytes: number | null;
|
||||
@@ -37,86 +43,438 @@ export default function ZoneAttachments({
|
||||
zonePublished: boolean;
|
||||
}) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [kind, setKind] = useState("legal_instrument");
|
||||
const [caption, setCaption] = useState("");
|
||||
const [source, setSource] = useState("");
|
||||
const [sourceDate, setSourceDate] = useState("");
|
||||
const [rights, setRights] = useState("pending");
|
||||
const [rightsBasis, setRightsBasis] = useState("");
|
||||
const [reviewChoices, setReviewChoices] = useState<Record<string, { rights: string; personal: string }>>({});
|
||||
const [reviewRightsBasis, setReviewRightsBasis] = useState<Record<string, string>>({});
|
||||
const [error, setError] = useState("");
|
||||
const [kind, setKind] = useState('legal_instrument');
|
||||
const [caption, setCaption] = useState('');
|
||||
const [source, setSource] = useState('');
|
||||
const [sourceDate, setSourceDate] = useState('');
|
||||
const [rights, setRights] = useState('pending');
|
||||
const [rightsBasis, setRightsBasis] = useState('');
|
||||
const [reviewChoices, setReviewChoices] = useState<
|
||||
Record<string, { rights: string; personal: string }>
|
||||
>({});
|
||||
const [reviewRightsBasis, setReviewRightsBasis] = useState<
|
||||
Record<string, string>
|
||||
>({});
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function send(url: string, payload: unknown) {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api(url, payload);
|
||||
router.reload();
|
||||
} catch (failure) {
|
||||
setError(failure instanceof Error ? failure.message : "Não foi possível guardar o anexo.");
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: 'Não foi possível guardar o anexo.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={card + " space-y-4"} aria-label="Anexos documentais da zona">
|
||||
<h2 className="text-xl font-bold">{management ? "Anexos documentais" : "Documentos e materiais publicados"}</h2>
|
||||
{management && <>
|
||||
<p>Os ficheiros ficam privados por defeito. A revisão é administrativa e não equivale a certificação. Só seleccione para divulgação ficheiros sem dados pessoais e com direitos de utilização esclarecidos.</p>
|
||||
<form className="grid gap-3 md:grid-cols-2" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!file) return;
|
||||
const data = new FormData();
|
||||
data.set("file", file);
|
||||
data.set("kind", kind);
|
||||
data.set("caption", caption);
|
||||
data.set("source_reference", source);
|
||||
if (sourceDate) data.set("source_date", sourceDate);
|
||||
data.set("rights_status", rights);
|
||||
if (rightsBasis) data.set("rights_basis", rightsBasis);
|
||||
void send(`/api/v2/investment/admin/zones/${zoneId}/attachments`, data).then(() => setFile(null));
|
||||
}}>
|
||||
<Field label="Ficheiro (PDF, JPEG, PNG ou WebP; máximo 20 MB)">
|
||||
<input className={input} type="file" accept="application/pdf,image/jpeg,image/png,image/webp" required onChange={(event) => setFile(event.target.files?.[0] ?? null)} />
|
||||
</Field>
|
||||
<Field label="Tipo do anexo"><select className={input} value={kind} onChange={(event) => setKind(event.target.value)}><option value="legal_instrument">Diploma</option><option value="map">Mapa</option><option value="photo">Fotografia</option><option value="study">Estudo</option><option value="other">Outro</option></select></Field>
|
||||
<Field label="Legenda ou título"><input className={input} required maxLength={255} value={caption} onChange={(event) => setCaption(event.target.value)} /></Field>
|
||||
<Field label="Origem exacta do ficheiro"><input className={input} required minLength={5} maxLength={2000} value={source} onChange={(event) => setSource(event.target.value)} /></Field>
|
||||
<Field label="Data da fonte, se conhecida"><input className={input} type="date" value={sourceDate} onChange={(event) => setSourceDate(event.target.value)} /></Field>
|
||||
<Field label="Direitos de utilização"><select className={input} value={rights} onChange={(event) => setRights(event.target.value)}><option value="pending">Por confirmar</option><option value="confirmed">Confirmados</option><option value="restricted">Restritos</option></select></Field>
|
||||
<Field label="Fundamento dos direitos (se confirmado)"><input className={input} maxLength={2000} value={rightsBasis} onChange={(event) => setRightsBasis(event.target.value)} /></Field>
|
||||
<button className={button} disabled={busy || !file || !caption.trim() || !source.trim()}>Carregar como privado</button>
|
||||
</form>
|
||||
</>}
|
||||
<section
|
||||
className={card + ' space-y-4'}
|
||||
aria-label="Anexos documentais da zona"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
{management
|
||||
? 'Anexos documentais'
|
||||
: 'Documentos e materiais publicados'}
|
||||
</h2>
|
||||
{management && (
|
||||
<>
|
||||
<p>
|
||||
Os ficheiros ficam privados por defeito. A revisão é
|
||||
administrativa e não equivale a certificação. Só
|
||||
seleccione para divulgação ficheiros sem dados pessoais
|
||||
e com direitos de utilização esclarecidos.
|
||||
</p>
|
||||
<form
|
||||
className="grid gap-3 md:grid-cols-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!file) return;
|
||||
const data = new FormData();
|
||||
data.set('file', file);
|
||||
data.set('kind', kind);
|
||||
data.set('caption', caption);
|
||||
data.set('source_reference', source);
|
||||
if (sourceDate) data.set('source_date', sourceDate);
|
||||
data.set('rights_status', rights);
|
||||
if (rightsBasis)
|
||||
data.set('rights_basis', rightsBasis);
|
||||
void send(
|
||||
`/api/v2/investment/admin/zones/${zoneId}/attachments`,
|
||||
data,
|
||||
).then(() => setFile(null));
|
||||
}}
|
||||
>
|
||||
<Field label="Ficheiro (PDF, JPEG, PNG ou WebP; máximo 20 MB)">
|
||||
<input
|
||||
className={input}
|
||||
type="file"
|
||||
accept="application/pdf,image/jpeg,image/png,image/webp"
|
||||
required
|
||||
onChange={(event) =>
|
||||
setFile(event.target.files?.[0] ?? null)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Tipo do anexo">
|
||||
<select
|
||||
className={input}
|
||||
value={kind}
|
||||
onChange={(event) =>
|
||||
setKind(event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="legal_instrument">
|
||||
Diploma
|
||||
</option>
|
||||
<option value="map">Mapa</option>
|
||||
<option value="photo">Fotografia</option>
|
||||
<option value="study">Estudo</option>
|
||||
<option value="other">Outro</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Legenda ou título">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
maxLength={255}
|
||||
value={caption}
|
||||
onChange={(event) =>
|
||||
setCaption(event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Origem exacta do ficheiro">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
minLength={5}
|
||||
maxLength={2000}
|
||||
value={source}
|
||||
onChange={(event) =>
|
||||
setSource(event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Data da fonte, se conhecida">
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
value={sourceDate}
|
||||
onChange={(event) =>
|
||||
setSourceDate(event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Direitos de utilização">
|
||||
<select
|
||||
className={input}
|
||||
value={rights}
|
||||
onChange={(event) =>
|
||||
setRights(event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="pending">Por confirmar</option>
|
||||
<option value="confirmed">Confirmados</option>
|
||||
<option value="restricted">Restritos</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Fundamento dos direitos (se confirmado)">
|
||||
<input
|
||||
className={input}
|
||||
maxLength={2000}
|
||||
value={rightsBasis}
|
||||
onChange={(event) =>
|
||||
setRightsBasis(event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!file ||
|
||||
!caption.trim() ||
|
||||
!source.trim()
|
||||
}
|
||||
>
|
||||
Carregar como privado
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{attachments.length === 0 && <p>Não existem anexos divulgados nesta zona.</p>}
|
||||
{attachments.length === 0 && (
|
||||
<p>Não existem anexos divulgados nesta zona.</p>
|
||||
)}
|
||||
{attachments.map((item) => {
|
||||
const choice = reviewChoices[item.id] ?? { rights: item.rights_status ?? "pending", personal: item.personal_data_status ?? "unknown" };
|
||||
return <article key={item.id} className="space-y-2 rounded border p-3">
|
||||
<p className="font-semibold">{item.caption} · {item.kind}{management && item.file_name ? ` · ${item.file_name}` : ""}</p>
|
||||
<p className="text-sm">Origem: {item.source_reference}{item.source_date ? ` · ${item.source_date}` : ""}{management ? ` · ${item.review_status}` : ""}</p>
|
||||
{management && item.independent_review === false && <p className="text-sm">Revisão administrativa registada; não independente e não certificadora.</p>}
|
||||
{management && item.malware_scan_status === "pending" && <p role="status">A analisar o ficheiro.</p>}
|
||||
{management && item.malware_scan_status === "scanning" && <p role="status">A analisar o ficheiro.</p>}
|
||||
{management && item.malware_scan_status === "clean" && <p role="status">Análise concluída: nenhuma ameaça detectada. O ficheiro continua privado até à divulgação explícita.</p>}
|
||||
{management && item.malware_scan_status === "infected" && <p role="alert">Ficheiro bloqueado: ameaça detectada. Mantenha-o em quarentena e carregue uma versão substituta.</p>}
|
||||
{management && ["inconclusive", "failed"].includes(item.malware_scan_status ?? "") && <p role="alert">Não foi possível concluir a análise. O ficheiro permanece privado e indisponível para divulgação.{item.malware_failure_reason ? ` Motivo: ${item.malware_failure_reason}.` : ""}</p>}
|
||||
{management && item.document_id && ["pending", "inconclusive", "failed"].includes(item.malware_scan_status ?? "") && <button type="button" className={button} disabled={busy} onClick={() => void send(`/management/documents/${item.document_id}/malware/retry`, {})}>Tentar análise novamente</button>}
|
||||
{management && item.review_status !== "reviewed" && <div className="grid gap-2 md:grid-cols-2">
|
||||
<select className={input} aria-label={`Direitos de ${item.caption}`} value={choice.rights} onChange={(event) => setReviewChoices((current) => ({ ...current, [item.id]: { ...choice, rights: event.target.value } }))}><option value="pending">Direitos por confirmar</option><option value="confirmed">Direitos confirmados</option><option value="restricted">Direitos restritos</option></select>
|
||||
<select className={input} aria-label={`Dados pessoais de ${item.caption}`} value={choice.personal} onChange={(event) => setReviewChoices((current) => ({ ...current, [item.id]: { ...choice, personal: event.target.value } }))}><option value="unknown">Dados pessoais por verificar</option><option value="none">Sem dados pessoais</option><option value="present">Contém dados pessoais</option></select>
|
||||
<input className={input} aria-label={`Fundamento dos direitos de ${item.caption}`} placeholder="Fundamento dos direitos" maxLength={2000} value={reviewRightsBasis[item.id] ?? item.rights_basis ?? ""} onChange={(event) => setReviewRightsBasis((current) => ({ ...current, [item.id]: event.target.value }))} />
|
||||
<button type="button" className={button} disabled={busy || choice.personal === "unknown" || (choice.rights === "confirmed" && !(reviewRightsBasis[item.id] ?? item.rights_basis)?.trim())} onClick={() => void send(`/api/v2/investment/admin/zone-attachments/${item.id}/review`, { version_no: item.version_no, decision: "reviewed", personal_data_status: choice.personal, rights_status: choice.rights, rights_basis: reviewRightsBasis[item.id] ?? item.rights_basis })}>Registar revisão administrativa</button>
|
||||
<button type="button" className={button} disabled={busy} onClick={() => void send(`/api/v2/investment/admin/zone-attachments/${item.id}/review`, { version_no: item.version_no, decision: "rejected", personal_data_status: choice.personal, rights_status: choice.rights, rights_basis: reviewRightsBasis[item.id] ?? item.rights_basis })}>Registar como não divulgável</button>
|
||||
</div>}
|
||||
{item.media_type.startsWith("image/") && (!management || item.malware_scan_status === "clean") && <img className="max-h-96 rounded object-contain" src={item.download_url} alt={item.caption} />}
|
||||
{(!management || item.malware_scan_status === "clean") && <a className="underline" href={item.download_url}>Abrir ficheiro</a>}
|
||||
{management && item.review_status === "reviewed" && !item.publicly_selected && <button type="button" className={button} disabled={busy || !zonePublished || item.file_status !== "active" || item.rights_status !== "confirmed" || item.personal_data_status !== "none"} onClick={() => void send(`/api/v2/investment/admin/zone-attachments/${item.id}/select-public`, { version_no: item.version_no })}>Seleccionar para divulgação</button>}
|
||||
{management && item.publicly_selected && <button type="button" className={button} disabled={busy} onClick={() => void send(`/api/v2/investment/admin/zone-attachments/${item.id}/withdraw-public`, { version_no: item.version_no })}>Retirar da divulgação</button>}
|
||||
</article>;
|
||||
const choice = reviewChoices[item.id] ?? {
|
||||
rights: item.rights_status ?? 'pending',
|
||||
personal: item.personal_data_status ?? 'unknown',
|
||||
};
|
||||
return (
|
||||
<article
|
||||
key={item.id}
|
||||
className="space-y-2 rounded border p-3"
|
||||
>
|
||||
<p className="font-semibold">
|
||||
{item.caption} · {item.kind}
|
||||
{management && item.file_name
|
||||
? ` · ${item.file_name}`
|
||||
: ''}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Origem: {item.source_reference}
|
||||
{item.source_date ? ` · ${item.source_date}` : ''}
|
||||
{management ? ` · ${item.review_status}` : ''}
|
||||
</p>
|
||||
{management && item.independent_review === false && (
|
||||
<p className="text-sm">
|
||||
Revisão administrativa registada; não
|
||||
independente e não certificadora.
|
||||
</p>
|
||||
)}
|
||||
{management &&
|
||||
item.malware_scan_status === 'pending' && (
|
||||
<p role="status">A analisar o ficheiro.</p>
|
||||
)}
|
||||
{management &&
|
||||
item.malware_scan_status === 'scanning' && (
|
||||
<p role="status">A analisar o ficheiro.</p>
|
||||
)}
|
||||
{management && item.malware_scan_status === 'clean' && (
|
||||
<p role="status">
|
||||
Análise concluída: nenhuma ameaça detectada. O
|
||||
ficheiro continua privado até à divulgação
|
||||
explícita.
|
||||
</p>
|
||||
)}
|
||||
{management &&
|
||||
item.malware_scan_status === 'infected' && (
|
||||
<p role="alert">
|
||||
Ficheiro bloqueado: ameaça detectada.
|
||||
Mantenha-o em quarentena e carregue uma
|
||||
versão substituta.
|
||||
</p>
|
||||
)}
|
||||
{management &&
|
||||
['inconclusive', 'failed'].includes(
|
||||
item.malware_scan_status ?? '',
|
||||
) && (
|
||||
<p role="alert">
|
||||
Não foi possível concluir a análise. O
|
||||
ficheiro permanece privado e indisponível
|
||||
para divulgação.
|
||||
{item.malware_failure_reason
|
||||
? ` Motivo: ${item.malware_failure_reason}.`
|
||||
: ''}
|
||||
</p>
|
||||
)}
|
||||
{management &&
|
||||
item.document_id &&
|
||||
['pending', 'inconclusive', 'failed'].includes(
|
||||
item.malware_scan_status ?? '',
|
||||
) && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/management/documents/${item.document_id}/malware/retry`,
|
||||
{},
|
||||
)
|
||||
}
|
||||
>
|
||||
Tentar análise novamente
|
||||
</button>
|
||||
)}
|
||||
{management && item.review_status !== 'reviewed' && (
|
||||
<div className="grid gap-2 md:grid-cols-2">
|
||||
<select
|
||||
className={input}
|
||||
aria-label={`Direitos de ${item.caption}`}
|
||||
value={choice.rights}
|
||||
onChange={(event) =>
|
||||
setReviewChoices((current) => ({
|
||||
...current,
|
||||
[item.id]: {
|
||||
...choice,
|
||||
rights: event.target.value,
|
||||
},
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="pending">
|
||||
Direitos por confirmar
|
||||
</option>
|
||||
<option value="confirmed">
|
||||
Direitos confirmados
|
||||
</option>
|
||||
<option value="restricted">
|
||||
Direitos restritos
|
||||
</option>
|
||||
</select>
|
||||
<select
|
||||
className={input}
|
||||
aria-label={`Dados pessoais de ${item.caption}`}
|
||||
value={choice.personal}
|
||||
onChange={(event) =>
|
||||
setReviewChoices((current) => ({
|
||||
...current,
|
||||
[item.id]: {
|
||||
...choice,
|
||||
personal: event.target.value,
|
||||
},
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Dados pessoais por verificar
|
||||
</option>
|
||||
<option value="none">
|
||||
Sem dados pessoais
|
||||
</option>
|
||||
<option value="present">
|
||||
Contém dados pessoais
|
||||
</option>
|
||||
</select>
|
||||
<input
|
||||
className={input}
|
||||
aria-label={`Fundamento dos direitos de ${item.caption}`}
|
||||
placeholder="Fundamento dos direitos"
|
||||
maxLength={2000}
|
||||
value={
|
||||
reviewRightsBasis[item.id] ??
|
||||
item.rights_basis ??
|
||||
''
|
||||
}
|
||||
onChange={(event) =>
|
||||
setReviewRightsBasis((current) => ({
|
||||
...current,
|
||||
[item.id]: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
choice.personal === 'unknown' ||
|
||||
(choice.rights === 'confirmed' &&
|
||||
!(
|
||||
reviewRightsBasis[item.id] ??
|
||||
item.rights_basis
|
||||
)?.trim())
|
||||
}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/api/v2/investment/admin/zone-attachments/${item.id}/review`,
|
||||
{
|
||||
version_no: item.version_no,
|
||||
decision: 'reviewed',
|
||||
personal_data_status:
|
||||
choice.personal,
|
||||
rights_status: choice.rights,
|
||||
rights_basis:
|
||||
reviewRightsBasis[
|
||||
item.id
|
||||
] ?? item.rights_basis,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Registar revisão administrativa
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/api/v2/investment/admin/zone-attachments/${item.id}/review`,
|
||||
{
|
||||
version_no: item.version_no,
|
||||
decision: 'rejected',
|
||||
personal_data_status:
|
||||
choice.personal,
|
||||
rights_status: choice.rights,
|
||||
rights_basis:
|
||||
reviewRightsBasis[
|
||||
item.id
|
||||
] ?? item.rights_basis,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Registar como não divulgável
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{item.media_type.startsWith('image/') &&
|
||||
(!management ||
|
||||
item.malware_scan_status === 'clean') && (
|
||||
<img
|
||||
className="max-h-96 rounded object-contain"
|
||||
src={item.download_url}
|
||||
alt={item.caption}
|
||||
/>
|
||||
)}
|
||||
{(!management ||
|
||||
item.malware_scan_status === 'clean') && (
|
||||
<a className="underline" href={item.download_url}>
|
||||
Abrir ficheiro
|
||||
</a>
|
||||
)}
|
||||
{management &&
|
||||
item.review_status === 'reviewed' &&
|
||||
!item.publicly_selected && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!zonePublished ||
|
||||
item.file_status !== 'active' ||
|
||||
item.rights_status !== 'confirmed' ||
|
||||
item.personal_data_status !== 'none'
|
||||
}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/api/v2/investment/admin/zone-attachments/${item.id}/select-public`,
|
||||
{ version_no: item.version_no },
|
||||
)
|
||||
}
|
||||
>
|
||||
Seleccionar para divulgação
|
||||
</button>
|
||||
)}
|
||||
{management && item.publicly_selected && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/api/v2/investment/admin/zone-attachments/${item.id}/withdraw-public`,
|
||||
{ version_no: item.version_no },
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar da divulgação
|
||||
</button>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { api, button, card } from "./shared";
|
||||
import { useState } from 'react';
|
||||
import { api, button, card } from './shared';
|
||||
|
||||
type Feature = {
|
||||
id: string;
|
||||
@@ -8,15 +8,18 @@ type Feature = {
|
||||
};
|
||||
function rings(value: unknown): number[][][] {
|
||||
if (!Array.isArray(value) || !value.length) return [];
|
||||
if (typeof value[0] === "number") return [[value as number[]]];
|
||||
if (Array.isArray(value[0]) && typeof value[0][0] === "number") return [value as number[][]];
|
||||
if (typeof value[0] === 'number') return [[value as number[]]];
|
||||
if (Array.isArray(value[0]) && typeof value[0][0] === 'number')
|
||||
return [value as number[][]];
|
||||
return value.flatMap(rings);
|
||||
}
|
||||
export default function ZoneMap({ id }: { id: string }) {
|
||||
const [features, setFeatures] = useState<Feature[] | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const points = (features ?? []).flatMap((f) => rings(f.geometry.coordinates).flat());
|
||||
const points = (features ?? []).flatMap((f) =>
|
||||
rings(f.geometry.coordinates).flat(),
|
||||
);
|
||||
const xs = points.map((p) => p[0]),
|
||||
ys = points.map((p) => p[1]);
|
||||
const west = xs.length ? Math.min(...xs) : 0,
|
||||
@@ -29,37 +32,44 @@ export default function ZoneMap({ id }: { id: string }) {
|
||||
];
|
||||
return (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">Localização e geometrias autorizadas</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
Localização e geometrias autorizadas
|
||||
</h2>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
const data = await api(`/api/v2/investment/zone-map?zone_id=${id}`);
|
||||
const data = await api(
|
||||
`/api/v2/investment/zone-map?zone_id=${id}`,
|
||||
);
|
||||
setFeatures(data.features);
|
||||
if (data.truncated) setError("Exibidas as primeiras 100 geometrias.");
|
||||
if (data.truncated)
|
||||
setError('Exibidas as primeiras 100 geometrias.');
|
||||
} catch {
|
||||
setError(
|
||||
"Mapa indisponível. A ficha, a localização textual e as acções de apoio continuam disponíveis.",
|
||||
'Mapa indisponível. A ficha, a localização textual e as acções de apoio continuam disponíveis.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{busy ? "A carregar…" : "Consultar mapa"}
|
||||
{busy ? 'A carregar…' : 'Consultar mapa'}
|
||||
</button>
|
||||
{error && <p role="status">{error}</p>}
|
||||
{features?.length === 0 && (
|
||||
<p>Não existe geometria autorizada para divulgação nesta ficha.</p>
|
||||
<p>
|
||||
Não existe geometria autorizada para divulgação nesta ficha.
|
||||
</p>
|
||||
)}
|
||||
{!!features?.length && (
|
||||
<>
|
||||
<p>
|
||||
Esquema das geometrias cadastradas, sem mapa-base. Não serve para demarcação
|
||||
ou atribuição de estatuto.
|
||||
Esquema das geometrias cadastradas, sem mapa-base. Não
|
||||
serve para demarcação ou atribuição de estatuto.
|
||||
</p>
|
||||
<svg
|
||||
viewBox="0 0 640 320"
|
||||
@@ -70,7 +80,8 @@ export default function ZoneMap({ id }: { id: string }) {
|
||||
{features.map((f) => (
|
||||
<g key={f.id}>
|
||||
<title>
|
||||
{f.properties.purpose} · {f.properties.source}
|
||||
{f.properties.purpose} ·{' '}
|
||||
{f.properties.source}
|
||||
</title>
|
||||
{rings(f.geometry.coordinates).map((ring, i) =>
|
||||
ring.length === 1 ? (
|
||||
@@ -84,7 +95,11 @@ export default function ZoneMap({ id }: { id: string }) {
|
||||
) : (
|
||||
<polyline
|
||||
key={i}
|
||||
points={ring.map((p) => project(p).join(",")).join(" ")}
|
||||
points={ring
|
||||
.map((p) =>
|
||||
project(p).join(','),
|
||||
)
|
||||
.join(' ')}
|
||||
fill="none"
|
||||
stroke="#065f46"
|
||||
strokeWidth="2"
|
||||
@@ -97,7 +112,8 @@ export default function ZoneMap({ id }: { id: string }) {
|
||||
<ul>
|
||||
{features.map((f) => (
|
||||
<li key={f.id}>
|
||||
{f.properties.purpose} · Fonte: {f.properties.source} · Data:{" "}
|
||||
{f.properties.purpose} · Fonte:{' '}
|
||||
{f.properties.source} · Data:{' '}
|
||||
{f.properties.observed_at}
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Field, input, button, card } from "./shared";
|
||||
import { Field, input, button, card } from './shared';
|
||||
|
||||
export type ZoneTargets = {
|
||||
opportunities: { id: number; title: string }[];
|
||||
@@ -38,15 +38,17 @@ export default function ZoneRelations({
|
||||
return (
|
||||
<>
|
||||
<form
|
||||
className={card + " grid gap-4 md:grid-cols-2"}
|
||||
className={card + ' grid gap-4 md:grid-cols-2'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(e.currentTarget));
|
||||
if (typeof data.target !== "string") return;
|
||||
const [kind, target] = data.target.split(":");
|
||||
const data = Object.fromEntries(
|
||||
new FormData(e.currentTarget),
|
||||
);
|
||||
if (typeof data.target !== 'string') return;
|
||||
const [kind, target] = data.target.split(':');
|
||||
delete data.target;
|
||||
void action(
|
||||
`/api/v2/investment/admin/zones/${id}/${kind === "opportunity_id" ? "links" : "relations"}`,
|
||||
`/api/v2/investment/admin/zones/${id}/${kind === 'opportunity_id' ? 'links' : 'relations'}`,
|
||||
{ ...data, [kind]: target },
|
||||
);
|
||||
}}
|
||||
@@ -64,12 +66,15 @@ export default function ZoneRelations({
|
||||
))}
|
||||
{targets.dossiers.map((d) => {
|
||||
const field = d.project_id
|
||||
? "project_id"
|
||||
? 'project_id'
|
||||
: d.cluster_id
|
||||
? "cluster_id"
|
||||
: "corridor_id";
|
||||
? 'cluster_id'
|
||||
: 'corridor_id';
|
||||
return (
|
||||
<option key={d.id} value={`${field}:${d[field]}`}>
|
||||
<option
|
||||
key={d.id}
|
||||
value={`${field}:${d[field]}`}
|
||||
>
|
||||
{d.title} · ficha territorial
|
||||
</option>
|
||||
);
|
||||
@@ -79,9 +84,13 @@ export default function ZoneRelations({
|
||||
<Field label="Tipo de associação">
|
||||
<select className={input} name="association_type">
|
||||
<option value="potential">Potencial</option>
|
||||
<option value="official">Oficial, com título próprio</option>
|
||||
<option value="official">
|
||||
Oficial, com título próprio
|
||||
</option>
|
||||
<option value="influence">Área de influência</option>
|
||||
<option value="proximity">Proximidade geográfica</option>
|
||||
<option value="proximity">
|
||||
Proximidade geográfica
|
||||
</option>
|
||||
<option value="historical">Histórica</option>
|
||||
</select>
|
||||
</Field>
|
||||
@@ -99,7 +108,9 @@ export default function ZoneRelations({
|
||||
</Field>
|
||||
<Field label="Fonte jurídica, obrigatória para associação oficial">
|
||||
<select name="legal_source_id" className={input}>
|
||||
<option value="">Não aplicável à relação proposta</option>
|
||||
<option value="">
|
||||
Não aplicável à relação proposta
|
||||
</option>
|
||||
{sources.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.title}
|
||||
@@ -126,7 +137,12 @@ export default function ZoneRelations({
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Válida desde">
|
||||
<input name="valid_from" type="date" className={input} required />
|
||||
<input
|
||||
name="valid_from"
|
||||
type="date"
|
||||
className={input}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Válida até">
|
||||
<input name="valid_until" type="date" className={input} />
|
||||
@@ -139,51 +155,61 @@ export default function ZoneRelations({
|
||||
<h2 className="text-xl font-bold">Relações territoriais</h2>
|
||||
{relations.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.association_type} · {r.validation_status}{" "}
|
||||
{r.association_type} · {r.validation_status}{' '}
|
||||
<button
|
||||
disabled={busy || r.validation_status === "revoked"}
|
||||
disabled={busy || r.validation_status === 'revoked'}
|
||||
className={button}
|
||||
onClick={() =>
|
||||
action(
|
||||
`/api/v2/investment/admin/zone-relations/${r.id}/${r.validation_status === "pending" ? "validate" : "revoke"}`,
|
||||
`/api/v2/investment/admin/zone-relations/${r.id}/${r.validation_status === 'pending' ? 'validate' : 'revoke'}`,
|
||||
{ version_no: r.version_no },
|
||||
)
|
||||
}
|
||||
>
|
||||
{r.validation_status === "pending" ? "Validar" : "Revogar"}
|
||||
{r.validation_status === 'pending'
|
||||
? 'Validar'
|
||||
: 'Revogar'}
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<form
|
||||
className={card + " grid gap-4 md:grid-cols-2"}
|
||||
className={card + ' grid gap-4 md:grid-cols-2'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(e.currentTarget));
|
||||
if (typeof data.geometry !== "string") return;
|
||||
const data = Object.fromEntries(
|
||||
new FormData(e.currentTarget),
|
||||
);
|
||||
if (typeof data.geometry !== 'string') return;
|
||||
const raw = data.geometry;
|
||||
try {
|
||||
data.geometry = JSON.parse(raw);
|
||||
void action(`/api/v2/investment/admin/zones/${id}/geometries`, data);
|
||||
void action(
|
||||
`/api/v2/investment/admin/zones/${id}/geometries`,
|
||||
data,
|
||||
);
|
||||
} catch {
|
||||
const field = e.currentTarget.elements.namedItem(
|
||||
"geometry",
|
||||
'geometry',
|
||||
) as HTMLTextAreaElement;
|
||||
field.setCustomValidity("Introduza GeoJSON válido.");
|
||||
field.setCustomValidity('Introduza GeoJSON válido.');
|
||||
field.reportValidity();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold md:col-span-2">Geometria para revisão GIS</h2>
|
||||
<h2 className="text-xl font-bold md:col-span-2">
|
||||
Geometria para revisão GIS
|
||||
</h2>
|
||||
<p>
|
||||
GeoJSON no SRID 4326, até 200 KB. Não desenhe um perímetro sem fonte autorizada.
|
||||
GeoJSON no SRID 4326, até 200 KB. Não desenhe um perímetro
|
||||
sem fonte autorizada.
|
||||
</p>
|
||||
<Field label="GeoJSON">
|
||||
<textarea
|
||||
name="geometry"
|
||||
className={input}
|
||||
required
|
||||
onChange={(e) => e.currentTarget.setCustomValidity("")}
|
||||
onChange={(e) => e.currentTarget.setCustomValidity('')}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Finalidade">
|
||||
@@ -191,7 +217,9 @@ export default function ZoneRelations({
|
||||
<option value="site">Localização</option>
|
||||
<option value="influence">Área de influência</option>
|
||||
<option value="alternative">Alternativa</option>
|
||||
<option value="official_perimeter">Perímetro oficial</option>
|
||||
<option value="official_perimeter">
|
||||
Perímetro oficial
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Fonte jurídica do perímetro">
|
||||
@@ -205,13 +233,27 @@ export default function ZoneRelations({
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Proveniência da geometria">
|
||||
<input className={input} name="source_reference" required minLength={10} />
|
||||
<input
|
||||
className={input}
|
||||
name="source_reference"
|
||||
required
|
||||
minLength={10}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Entidade indicada para validação">
|
||||
<input className={input} name="validating_entity" required />
|
||||
<input
|
||||
className={input}
|
||||
name="validating_entity"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Data da observação">
|
||||
<input className={input} type="date" name="observed_at" required />
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
name="observed_at"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<button disabled={busy} className={button}>
|
||||
Submeter geometria
|
||||
@@ -221,20 +263,20 @@ export default function ZoneRelations({
|
||||
<h2 className="text-xl font-bold">Revisão GIS</h2>
|
||||
{geometries.map((g) => (
|
||||
<p key={g.id}>
|
||||
{g.purpose} · {g.validation_status}{" "}
|
||||
{g.purpose} · {g.validation_status}{' '}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || g.validation_status === "revoked"}
|
||||
disabled={busy || g.validation_status === 'revoked'}
|
||||
onClick={() =>
|
||||
action(
|
||||
`/api/v2/investment/admin/zone-geometries/${g.id}/${g.validation_status === "pending" ? "validate" : "revoke"}`,
|
||||
`/api/v2/investment/admin/zone-geometries/${g.id}/${g.validation_status === 'pending' ? 'validate' : 'revoke'}`,
|
||||
{ version_no: g.version_no },
|
||||
)
|
||||
}
|
||||
>
|
||||
{g.validation_status === "pending"
|
||||
? "Validar e autorizar divulgação"
|
||||
: "Retirar geometria"}
|
||||
{g.validation_status === 'pending'
|
||||
? 'Validar e autorizar divulgação'
|
||||
: 'Retirar geometria'}
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,10 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { Frame, Field, input, button, card, api } from './shared';
|
||||
|
||||
type Zone = {
|
||||
id: string;
|
||||
@@ -19,11 +22,22 @@ type Zone = {
|
||||
operational_status?: string;
|
||||
development_status?: string;
|
||||
availability_status?: string;
|
||||
source_evidence?: { title: string; url: string; source_type: string; supports: string; source_date?: string | null }[];
|
||||
source_evidence?: {
|
||||
title: string;
|
||||
url: string;
|
||||
source_type: string;
|
||||
supports: string;
|
||||
source_date?: string | null;
|
||||
}[];
|
||||
area_value?: string | null;
|
||||
area_unit?: string | null;
|
||||
activities?: { name: string; status: string }[];
|
||||
locations?: { id: string; name: string; location_type: string; scope_type: string }[];
|
||||
locations?: {
|
||||
id: string;
|
||||
name: string;
|
||||
location_type: string;
|
||||
scope_type: string;
|
||||
}[];
|
||||
};
|
||||
export default function Zones({
|
||||
records,
|
||||
@@ -38,79 +52,190 @@ export default function Zones({
|
||||
next_page_url: string | null;
|
||||
prev_page_url: string | null;
|
||||
};
|
||||
filters: { q?: string; category?: string; physical_category?: string; legal_regime?: string; development_status?: string; availability_status?: string; activity?: string };
|
||||
filters: {
|
||||
q?: string;
|
||||
category?: string;
|
||||
physical_category?: string;
|
||||
legal_regime?: string;
|
||||
development_status?: string;
|
||||
availability_status?: string;
|
||||
activity?: string;
|
||||
};
|
||||
management: boolean;
|
||||
zoneExtensionsAvailable?: boolean;
|
||||
territorySelection?: TerritoryOption[];
|
||||
}) {
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const exportParams = new URLSearchParams();
|
||||
for (const key of ["q", "category", "physical_category", "legal_regime", "development_status", "availability_status", "activity"] as const) {
|
||||
for (const key of [
|
||||
'q',
|
||||
'category',
|
||||
'physical_category',
|
||||
'legal_regime',
|
||||
'development_status',
|
||||
'availability_status',
|
||||
'activity',
|
||||
] as const) {
|
||||
const value = filters[key];
|
||||
if (value) exportParams.set(key, value);
|
||||
}
|
||||
const territoryKeys: Record<string, string> = { province: "province_id", district: "district_id", admin_post: "admin_post_id", locality: "locality_id" };
|
||||
territorySelection.forEach((item) => { const key = territoryKeys[item.location_type]; if (key) exportParams.set(key, item.id); });
|
||||
const territoryKeys: Record<string, string> = {
|
||||
province: 'province_id',
|
||||
district: 'district_id',
|
||||
admin_post: 'admin_post_id',
|
||||
locality: 'locality_id',
|
||||
};
|
||||
territorySelection.forEach((item) => {
|
||||
const key = territoryKeys[item.location_type];
|
||||
if (key) exportParams.set(key, item.id);
|
||||
});
|
||||
return (
|
||||
<Frame
|
||||
title={management ? "Gestão de ZEE, ZFI e parques" : "ZEE, ZFI e parques industriais"}
|
||||
title={
|
||||
management
|
||||
? 'Gestão de ZEE, ZFI e parques'
|
||||
: 'ZEE, ZFI e parques industriais'
|
||||
}
|
||||
>
|
||||
<p>
|
||||
A informação territorial não atribui benefícios nem substitui certificados ou
|
||||
decisões das entidades competentes.
|
||||
A informação territorial não atribui benefícios nem substitui
|
||||
certificados ou decisões das entidades competentes.
|
||||
</p>
|
||||
<nav aria-label="Dimensões de investimento" className="flex flex-wrap gap-4 underline">
|
||||
<nav
|
||||
aria-label="Dimensões de investimento"
|
||||
className="flex flex-wrap gap-4 underline"
|
||||
>
|
||||
<Link href="/clusters">Por Cluster</Link>
|
||||
<Link href="/corredores">Por Corredor</Link>
|
||||
<Link href="/zonas?category=zee">Por ZEE</Link>
|
||||
<Link href="/zonas?category=zfi">Por ZFI</Link>
|
||||
<Link href="/zonas?category=industrial_park">Parques industriais</Link>
|
||||
<Link href="/zonas?category=industrial_park">
|
||||
Parques industriais
|
||||
</Link>
|
||||
</nav>
|
||||
<form method="get" className={card + " grid gap-4 md:grid-cols-3"}>
|
||||
<form method="get" className={card + ' grid gap-4 md:grid-cols-3'}>
|
||||
<Field label="Pesquisar por nome ou código">
|
||||
<input className={input} name="q" defaultValue={filters.q} maxLength={120} />
|
||||
<input
|
||||
className={input}
|
||||
name="q"
|
||||
defaultValue={filters.q}
|
||||
maxLength={120}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Categoria">
|
||||
<select className={input} name="category" defaultValue={filters.category ?? ""}>
|
||||
<select
|
||||
className={input}
|
||||
name="category"
|
||||
defaultValue={filters.category ?? ''}
|
||||
>
|
||||
<option value="">Todas</option>
|
||||
<option value="zee">ZEE</option>
|
||||
<option value="zfi">ZFI</option>
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
<option value="industrial_park">
|
||||
Parque industrial
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Categoria física">
|
||||
<select className={input} name="physical_category" defaultValue={filters.physical_category ?? ""}>
|
||||
<option value="">Todas</option><option value="industrial_park">Parque industrial</option>{zoneExtensionsAvailable && <><option value="agro_industrial_park">Parque agro-industrial</option><option value="industrial_logistics_park">Parque industrial e logístico</option></>}<option value="industrial_free_zone">ZFI</option><option value="economic_zone">ZEE</option>
|
||||
<select
|
||||
className={input}
|
||||
name="physical_category"
|
||||
defaultValue={filters.physical_category ?? ''}
|
||||
>
|
||||
<option value="">Todas</option>
|
||||
<option value="industrial_park">
|
||||
Parque industrial
|
||||
</option>
|
||||
{zoneExtensionsAvailable && (
|
||||
<>
|
||||
<option value="agro_industrial_park">
|
||||
Parque agro-industrial
|
||||
</option>
|
||||
<option value="industrial_logistics_park">
|
||||
Parque industrial e logístico
|
||||
</option>
|
||||
</>
|
||||
)}
|
||||
<option value="industrial_free_zone">ZFI</option>
|
||||
<option value="economic_zone">ZEE</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Actividade documentada">
|
||||
<input className={input} name="activity" defaultValue={filters.activity} maxLength={120} />
|
||||
<input
|
||||
className={input}
|
||||
name="activity"
|
||||
defaultValue={filters.activity}
|
||||
maxLength={120}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Regime jurídico">
|
||||
<select className={input} name="legal_regime" defaultValue={filters.legal_regime ?? ""}>
|
||||
<option value="">Todos</option><option value="zee">ZEE</option><option value="zfi">ZFI</option><option value="general">Regime geral</option><option value="pending">Por confirmar</option>
|
||||
<select
|
||||
className={input}
|
||||
name="legal_regime"
|
||||
defaultValue={filters.legal_regime ?? ''}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="zee">ZEE</option>
|
||||
<option value="zfi">ZFI</option>
|
||||
<option value="general">Regime geral</option>
|
||||
<option value="pending">Por confirmar</option>
|
||||
</select>
|
||||
</Field>
|
||||
{zoneExtensionsAvailable && <Field label="Desenvolvimento">
|
||||
<select className={input} name="development_status" defaultValue={filters.development_status ?? ""}>
|
||||
<option value="">Todos</option><option value="announced">Anunciado</option><option value="planned">Planeado</option><option value="in_development">Em desenvolvimento</option><option value="partially_operational">Parcialmente operacional</option><option value="operational">Operacional</option><option value="unknown">Por confirmar</option>
|
||||
</select>
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && <Field label="Disponibilidade">
|
||||
<select className={input} name="availability_status" defaultValue={filters.availability_status ?? ""}>
|
||||
<option value="">Todas</option><option value="confirmed">Confirmada</option><option value="unavailable">Indisponível</option><option value="reported_unverified">Reportada, por verificar</option><option value="not_informed">Não informada</option>
|
||||
</select>
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && (
|
||||
<Field label="Desenvolvimento">
|
||||
<select
|
||||
className={input}
|
||||
name="development_status"
|
||||
defaultValue={filters.development_status ?? ''}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="announced">Anunciado</option>
|
||||
<option value="planned">Planeado</option>
|
||||
<option value="in_development">
|
||||
Em desenvolvimento
|
||||
</option>
|
||||
<option value="partially_operational">
|
||||
Parcialmente operacional
|
||||
</option>
|
||||
<option value="operational">Operacional</option>
|
||||
<option value="unknown">Por confirmar</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
{zoneExtensionsAvailable && (
|
||||
<Field label="Disponibilidade">
|
||||
<select
|
||||
className={input}
|
||||
name="availability_status"
|
||||
defaultValue={filters.availability_status ?? ''}
|
||||
>
|
||||
<option value="">Todas</option>
|
||||
<option value="confirmed">Confirmada</option>
|
||||
<option value="unavailable">Indisponível</option>
|
||||
<option value="reported_unverified">
|
||||
Reportada, por verificar
|
||||
</option>
|
||||
<option value="not_informed">Não informada</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<TerritoryFields initial={territorySelection} />
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
<p role="status">{records.total} registos disponíveis</p>
|
||||
{!management && <a className="underline" href={`/api/v2/investment/zones/export.csv?${exportParams.toString()}`}>Exportar resultados filtrados (CSV)</a>}
|
||||
{!management && (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/api/v2/investment/zones/export.csv?${exportParams.toString()}`}
|
||||
>
|
||||
Exportar resultados filtrados (CSV)
|
||||
</a>
|
||||
)}
|
||||
{!records.total && (
|
||||
<p className={card}>
|
||||
Sem registos disponíveis para estes filtros. As zonas aguardam cadastro e
|
||||
validação documental.
|
||||
Sem registos disponíveis para estes filtros. As zonas
|
||||
aguardam cadastro e validação documental.
|
||||
</p>
|
||||
)}
|
||||
{records.data.map((zone) => (
|
||||
@@ -118,22 +243,80 @@ export default function Zones({
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${management ? "/management/investment/zones" : "/zonas"}/${zone.id}`}
|
||||
href={`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`}
|
||||
>
|
||||
{zone.name}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{zone.code} · {zone.category.toUpperCase()} ·{" "}
|
||||
{[zone.district, zone.province].filter(Boolean).join(", ") || "Localização por confirmar"}
|
||||
{zone.code} · {zone.category.toUpperCase()} ·{' '}
|
||||
{[zone.district, zone.province]
|
||||
.filter(Boolean)
|
||||
.join(', ') || 'Localização por confirmar'}
|
||||
</p>
|
||||
{zone.legal_regime && <p>Regime jurídico: {zone.legal_regime.toUpperCase()}</p>}
|
||||
{zoneExtensionsAvailable && zone.development_status && <p>Desenvolvimento: {zone.development_status.replaceAll("_", " ")}</p>}
|
||||
{zoneExtensionsAvailable && zone.availability_status && <p>Disponibilidade para instalação: {zone.availability_status.replaceAll("_", " ")}</p>}
|
||||
{zone.area_value && <p>Área indicada: {zone.area_value} {zone.area_unit}</p>}
|
||||
{zone.locations?.length ? <p>Abrangência: {zone.locations.map((location) => location.name).join(" · ")}</p> : null}
|
||||
{zone.activities?.length ? <p>Actividades: {zone.activities.map((activity) => `${activity.name} (${activity.status})`).join(" · ")}</p> : null}
|
||||
{!!zone.source_evidence?.length && <p>Fonte: {zone.source_evidence.map((source, index) => <span key={source.url}>{index > 0 ? " · " : ""}<a className="underline" href={source.url} target="_blank" rel="noreferrer">{source.title}</a>{source.source_date ? ` (${source.source_date})` : " (data da fonte não informada)"} — {source.supports}</span>)}</p>}
|
||||
{zone.legal_regime && (
|
||||
<p>
|
||||
Regime jurídico: {zone.legal_regime.toUpperCase()}
|
||||
</p>
|
||||
)}
|
||||
{zoneExtensionsAvailable && zone.development_status && (
|
||||
<p>
|
||||
Desenvolvimento:{' '}
|
||||
{zone.development_status.replaceAll('_', ' ')}
|
||||
</p>
|
||||
)}
|
||||
{zoneExtensionsAvailable && zone.availability_status && (
|
||||
<p>
|
||||
Disponibilidade para instalação:{' '}
|
||||
{zone.availability_status.replaceAll('_', ' ')}
|
||||
</p>
|
||||
)}
|
||||
{zone.area_value && (
|
||||
<p>
|
||||
Área indicada: {zone.area_value} {zone.area_unit}
|
||||
</p>
|
||||
)}
|
||||
{zone.locations?.length ? (
|
||||
<p>
|
||||
Abrangência:{' '}
|
||||
{zone.locations
|
||||
.map((location) => location.name)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
) : null}
|
||||
{zone.activities?.length ? (
|
||||
<p>
|
||||
Actividades:{' '}
|
||||
{zone.activities
|
||||
.map(
|
||||
(activity) =>
|
||||
`${activity.name} (${activity.status})`,
|
||||
)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
) : null}
|
||||
{!!zone.source_evidence?.length && (
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{zone.source_evidence.map((source, index) => (
|
||||
<span key={source.url}>
|
||||
{index > 0 ? ' · ' : ''}
|
||||
<a
|
||||
className="underline"
|
||||
href={source.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{source.title}
|
||||
</a>
|
||||
{source.source_date
|
||||
? ` (${source.source_date})`
|
||||
: ' (data da fonte não informada)'}{' '}
|
||||
— {source.supports}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
<p>{zone.description}</p>
|
||||
<p>Validação: {zone.validation_status}</p>
|
||||
{management && (
|
||||
@@ -144,25 +327,31 @@ export default function Zones({
|
||||
</article>
|
||||
))}
|
||||
<nav aria-label="Paginação" className="flex gap-4 underline">
|
||||
{records.prev_page_url && <Link href={records.prev_page_url}>Anterior</Link>}
|
||||
{records.next_page_url && <Link href={records.next_page_url}>Seguinte</Link>}
|
||||
{records.prev_page_url && (
|
||||
<Link href={records.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
{records.next_page_url && (
|
||||
<Link href={records.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
{management && (
|
||||
<form
|
||||
className={card + " space-y-4"}
|
||||
className={card + ' space-y-4'}
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.currentTarget));
|
||||
const data = Object.fromEntries(
|
||||
new FormData(event.currentTarget),
|
||||
);
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api("/api/v2/investment/admin/zones", data);
|
||||
await api('/api/v2/investment/admin/zones', data);
|
||||
router.reload();
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: "Não foi possível guardar. Tente novamente.",
|
||||
: 'Não foi possível guardar. Tente novamente.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -172,76 +361,205 @@ export default function Zones({
|
||||
<h2 className="text-xl font-bold">Criar rascunho</h2>
|
||||
<TerritoryFields endpoint="/management/territory-options" />
|
||||
<Field label="Código">
|
||||
<input name="code" className={input} required maxLength={80} />
|
||||
<input
|
||||
name="code"
|
||||
className={input}
|
||||
required
|
||||
maxLength={80}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Nome">
|
||||
<input name="name" className={input} required maxLength={255} />
|
||||
<input
|
||||
name="name"
|
||||
className={input}
|
||||
required
|
||||
maxLength={255}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Categoria proposta">
|
||||
<select name="category" className={input}>
|
||||
<option value="pending">Pendente de enquadramento</option>
|
||||
<option value="pending">
|
||||
Pendente de enquadramento
|
||||
</option>
|
||||
<option value="zee">ZEE</option>
|
||||
<option value="zfi">ZFI</option>
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
<option value="industrial_park">
|
||||
Parque industrial
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Categoria física">
|
||||
<select name="physical_category" className={input} defaultValue="unknown">
|
||||
<select
|
||||
name="physical_category"
|
||||
className={input}
|
||||
defaultValue="unknown"
|
||||
>
|
||||
<option value="unknown">Por confirmar</option>
|
||||
<option value="economic_zone">Zona económica</option>
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
{zoneExtensionsAvailable && <option value="agro_industrial_park">Parque agro-industrial</option>}
|
||||
{zoneExtensionsAvailable && <option value="industrial_logistics_park">Parque industrial e logístico</option>}
|
||||
<option value="industrial_free_zone">Zona franca industrial</option>
|
||||
<option value="integrated_tourism_area">Área de turismo integrado</option>
|
||||
<option value="economic_zone">
|
||||
Zona económica
|
||||
</option>
|
||||
<option value="industrial_park">
|
||||
Parque industrial
|
||||
</option>
|
||||
{zoneExtensionsAvailable && (
|
||||
<option value="agro_industrial_park">
|
||||
Parque agro-industrial
|
||||
</option>
|
||||
)}
|
||||
{zoneExtensionsAvailable && (
|
||||
<option value="industrial_logistics_park">
|
||||
Parque industrial e logístico
|
||||
</option>
|
||||
)}
|
||||
<option value="industrial_free_zone">
|
||||
Zona franca industrial
|
||||
</option>
|
||||
<option value="integrated_tourism_area">
|
||||
Área de turismo integrado
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
{zoneExtensionsAvailable && <Field label="Estado de desenvolvimento">
|
||||
<select name="development_status" className={input} defaultValue="unknown"><option value="unknown">Por confirmar</option><option value="announced">Anunciado</option><option value="planned">Planeado</option><option value="in_development">Em desenvolvimento</option><option value="partially_operational">Parcialmente operacional</option><option value="operational">Operacional</option><option value="suspended">Suspenso</option></select>
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && <Field label="Disponibilidade para instalação">
|
||||
<select name="availability_status" className={input} defaultValue="not_informed"><option value="not_informed">Não informada</option><option value="confirmed">Confirmada por fonte</option><option value="unavailable">Indisponível</option><option value="reported_unverified">Reportada, por verificar</option></select>
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && (
|
||||
<Field label="Estado de desenvolvimento">
|
||||
<select
|
||||
name="development_status"
|
||||
className={input}
|
||||
defaultValue="unknown"
|
||||
>
|
||||
<option value="unknown">Por confirmar</option>
|
||||
<option value="announced">Anunciado</option>
|
||||
<option value="planned">Planeado</option>
|
||||
<option value="in_development">
|
||||
Em desenvolvimento
|
||||
</option>
|
||||
<option value="partially_operational">
|
||||
Parcialmente operacional
|
||||
</option>
|
||||
<option value="operational">Operacional</option>
|
||||
<option value="suspended">Suspenso</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
{zoneExtensionsAvailable && (
|
||||
<Field label="Disponibilidade para instalação">
|
||||
<select
|
||||
name="availability_status"
|
||||
className={input}
|
||||
defaultValue="not_informed"
|
||||
>
|
||||
<option value="not_informed">
|
||||
Não informada
|
||||
</option>
|
||||
<option value="confirmed">
|
||||
Confirmada por fonte
|
||||
</option>
|
||||
<option value="unavailable">
|
||||
Indisponível
|
||||
</option>
|
||||
<option value="reported_unverified">
|
||||
Reportada, por verificar
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Regime jurídico">
|
||||
<select name="legal_regime" className={input} defaultValue="pending">
|
||||
<option value="pending">Pendente de confirmação</option>
|
||||
<select
|
||||
name="legal_regime"
|
||||
className={input}
|
||||
defaultValue="pending"
|
||||
>
|
||||
<option value="pending">
|
||||
Pendente de confirmação
|
||||
</option>
|
||||
<option value="zee">ZEE</option>
|
||||
<option value="zfi">ZFI</option>
|
||||
<option value="general">Regime geral</option>
|
||||
<option value="not_applicable">Não aplicável</option>
|
||||
<option value="not_applicable">
|
||||
Não aplicável
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Área (valor) — se documentada">
|
||||
<input name="area_value" className={input} type="number" min="0" step="0.0001" />
|
||||
<input
|
||||
name="area_value"
|
||||
className={input}
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.0001"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Unidade da área">
|
||||
<select name="area_unit" className={input} defaultValue="">
|
||||
<option value="">Por confirmar</option><option value="ha">hectares (ha)</option><option value="km2">quilómetros quadrados (km²)</option>
|
||||
<select
|
||||
name="area_unit"
|
||||
className={input}
|
||||
defaultValue=""
|
||||
>
|
||||
<option value="">Por confirmar</option>
|
||||
<option value="ha">hectares (ha)</option>
|
||||
<option value="km2">
|
||||
quilómetros quadrados (km²)
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Actividade documentada (opcional)">
|
||||
<input name="activity_name" className={input} maxLength={300} />
|
||||
<input
|
||||
name="activity_name"
|
||||
className={input}
|
||||
maxLength={300}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Estado da actividade">
|
||||
<select name="activity_status" className={input} defaultValue="potential">
|
||||
<option value="potential">Potencial referido pela fonte</option><option value="proposed">Proposta</option>
|
||||
<option value="authorized">Autorizada por documento</option><option value="conditional">Condicionada</option><option value="excluded">Excluída</option>
|
||||
<select
|
||||
name="activity_status"
|
||||
className={input}
|
||||
defaultValue="potential"
|
||||
>
|
||||
<option value="potential">
|
||||
Potencial referido pela fonte
|
||||
</option>
|
||||
<option value="proposed">Proposta</option>
|
||||
<option value="authorized">
|
||||
Autorizada por documento
|
||||
</option>
|
||||
<option value="conditional">Condicionada</option>
|
||||
<option value="excluded">Excluída</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Designações alternativas">
|
||||
<textarea name="aliases_text" className={input} rows={2} placeholder="Uma por linha" />
|
||||
<textarea
|
||||
name="aliases_text"
|
||||
className={input}
|
||||
rows={2}
|
||||
placeholder="Uma por linha"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Localização histórica (se diferente da actual)">
|
||||
<input name="historical_name" className={input} maxLength={255} />
|
||||
<input
|
||||
name="historical_name"
|
||||
className={input}
|
||||
maxLength={255}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Distrito histórico">
|
||||
<input name="historical_district" className={input} maxLength={120} />
|
||||
<input
|
||||
name="historical_district"
|
||||
className={input}
|
||||
maxLength={120}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Província histórica">
|
||||
<input name="historical_province" className={input} maxLength={120} />
|
||||
<input
|
||||
name="historical_province"
|
||||
className={input}
|
||||
maxLength={120}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Fonte da localização histórica">
|
||||
<input name="historical_source_reference" className={input} maxLength={2000} />
|
||||
<input
|
||||
name="historical_source_reference"
|
||||
className={input}
|
||||
maxLength={2000}
|
||||
/>
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<button className={button} disabled={busy}>
|
||||
|
||||
Reference in New Issue
Block a user