File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,17 @@
|
||||
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 Props = { record: Opportunity; modalities: string[] };
|
||||
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;
|
||||
};
|
||||
|
||||
export default function BusinessInterest({ record, modalities }: Props) {
|
||||
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("");
|
||||
@@ -38,6 +39,7 @@ export default function BusinessInterest({ record, modalities }: Props) {
|
||||
};
|
||||
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> : (
|
||||
<form className={`${card} space-y-4`} onSubmit={submit}>
|
||||
|
||||
@@ -1,32 +1,39 @@
|
||||
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";
|
||||
|
||||
type PublicBusiness = {
|
||||
id: string; slug: string; title: 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 Props = { results: { data: PublicBusiness[]; links: { url: string | null; label: string; active: boolean }[] }; filters: { q?: string } };
|
||||
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; province_id?: string; district_id?: string; admin_post_id?: string; locality_id?: string }; territorySelection?: TerritoryOption[] };
|
||||
|
||||
export default function BusinessMarketplace({ results, filters }: Props) {
|
||||
export default function BusinessMarketplace({ results, filters, territorySelection = [] }: Props) {
|
||||
const [query, setQuery] = useState(filters.q ?? "");
|
||||
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 } : {}), ...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 }, { preserveState: true, preserveScroll: true });
|
||||
router.get("/negocios", { q: query || 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)} />
|
||||
<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>}
|
||||
<ul className="grid gap-4 md:grid-cols-2">
|
||||
{results.data.map((record) => (
|
||||
<li className={card} key={record.id}>
|
||||
<h2 className="text-xl font-bold"><Link className="underline" href={`/negocios/${record.slug}`}>{record.title}</Link></h2>
|
||||
<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>}
|
||||
@@ -34,7 +41,7 @@ export default function BusinessMarketplace({ results, filters }: Props) {
|
||||
))}
|
||||
</ul>
|
||||
<nav aria-label="Paginação das oportunidades" className="flex flex-wrap gap-3">
|
||||
{results.links.map((link) => link.url ? <Link key={link.label} href={link.url} className={link.active ? "font-bold underline" : "underline"} dangerouslySetInnerHTML={{ __html: link.label }} /> : null)}
|
||||
{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,6 +1,6 @@
|
||||
import { router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Field, input, button, card, api } from "./shared";
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Field, input, button, card, api } from './shared';
|
||||
|
||||
export type BusinessObject = {
|
||||
id: string;
|
||||
@@ -9,42 +9,44 @@ export type BusinessObject = {
|
||||
payload: Record<string, string>;
|
||||
};
|
||||
const kinds: Record<string, string> = {
|
||||
company: "Empresa",
|
||||
participation: "Participação",
|
||||
asset: "Activo físico",
|
||||
property: "Imóvel/propriedade",
|
||||
unit: "Unidade imobiliária",
|
||||
improvement: "Benfeitoria",
|
||||
agricultural_investment: "Investimento agrícola",
|
||||
land_right: "Direito fundiário",
|
||||
contract: "Contrato",
|
||||
license: "Licença",
|
||||
authorization: "Autorização",
|
||||
encumbrance: "Ónus ou encargo",
|
||||
valuation: "Avaliação declarada",
|
||||
capital_request: "Pedido de capital",
|
||||
company: 'Empresa',
|
||||
participation: 'Participação',
|
||||
asset: 'Activo físico',
|
||||
property: 'Imóvel/propriedade',
|
||||
unit: 'Unidade imobiliária',
|
||||
improvement: 'Benfeitoria',
|
||||
agricultural_investment: 'Investimento agrícola',
|
||||
land_right: 'Direito fundiário',
|
||||
contract: 'Contrato',
|
||||
license: 'Licença',
|
||||
authorization: 'Autorização',
|
||||
encumbrance: 'Ónus ou encargo',
|
||||
valuation: 'Avaliação declarada',
|
||||
capital_request: 'Pedido de capital',
|
||||
};
|
||||
const fields: Record<string, string> = {
|
||||
label: "Designação reservada",
|
||||
declared_holder: "Titular declarado",
|
||||
document_reference: "Referência documental",
|
||||
source_reference: "Fonte da informação",
|
||||
competent_entity: "Entidade emissora/competente declarada",
|
||||
purpose: "Finalidade autorizada declarada",
|
||||
location_description: "Localização reservada",
|
||||
boundaries_description: "Limites declarados",
|
||||
occupancy: "Ocupação/utilização",
|
||||
condition: "Conservação/operação",
|
||||
encumbrances: "Ónus, garantias ou litígios declarados",
|
||||
restrictions: "Restrições declaradas",
|
||||
required_authorizations: "Autorizações necessárias declaradas",
|
||||
transfer_condition: "Condição de cessão/transmissão declarada",
|
||||
valid_from: "Início de validade",
|
||||
valid_until: "Fim de validade",
|
||||
area: "Área (decimal com ponto)",
|
||||
participation_percent: "Participação (%)",
|
||||
amount: "Valor (decimal com ponto)",
|
||||
currency: "Moeda (código de três letras)",
|
||||
label: 'Designação reservada',
|
||||
declared_holder: 'Titular declarado',
|
||||
document_reference: 'Referência documental',
|
||||
source_reference: 'Fonte da informação',
|
||||
source_date: 'Data da fonte',
|
||||
resource_status: 'Situação do recurso',
|
||||
competent_entity: 'Entidade emissora/competente declarada',
|
||||
purpose: 'Finalidade autorizada declarada',
|
||||
location_description: 'Localização reservada',
|
||||
boundaries_description: 'Limites declarados',
|
||||
occupancy: 'Ocupação/utilização',
|
||||
condition: 'Conservação/operação',
|
||||
encumbrances: 'Ónus, garantias ou litígios declarados',
|
||||
restrictions: 'Restrições declaradas',
|
||||
required_authorizations: 'Autorizações necessárias declaradas',
|
||||
transfer_condition: 'Condição de cessão/transmissão declarada',
|
||||
valid_from: 'Início de validade',
|
||||
valid_until: 'Fim de validade',
|
||||
area: 'Área (decimal com ponto)',
|
||||
participation_percent: 'Participação (%)',
|
||||
amount: 'Valor (decimal com ponto)',
|
||||
currency: 'Moeda (código de três letras)',
|
||||
};
|
||||
export default function BusinessObjects({
|
||||
businessId,
|
||||
@@ -62,16 +64,19 @@ export default function BusinessObjects({
|
||||
const [kind, setKind] = useState(objectKinds[0]);
|
||||
const [objectId, setObjectId] = useState<string | null>(null);
|
||||
const [payload, setPayload] = useState<Record<string, string>>({});
|
||||
const [reason, setReason] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [reason, setReason] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<section className={`${card} space-y-4`}>
|
||||
<h2 className="text-xl font-bold">Activos, contratos e direitos declarados</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
Activos, contratos e direitos declarados
|
||||
</h2>
|
||||
<p>
|
||||
Registe separadamente cada elemento. Todos ficam pendentes de verificação; a
|
||||
declaração não confirma titularidade, validade ou transmissibilidade. Não use este
|
||||
formulário para anexar ficheiros.
|
||||
Registe separadamente cada elemento. Todos ficam pendentes de
|
||||
verificação; a declaração não confirma titularidade, validade ou
|
||||
transmissibilidade. Não use este formulário para anexar
|
||||
ficheiros.
|
||||
</p>
|
||||
{!objects.length && <p>Nenhum elemento registado.</p>}
|
||||
{objects.map((o) => (
|
||||
@@ -82,30 +87,36 @@ export default function BusinessObjects({
|
||||
<p>Pendente de verificação</p>
|
||||
<dl>
|
||||
{Object.entries(o.payload)
|
||||
.filter(([key, value]) => key !== "label" && value)
|
||||
.filter(([key, value]) => key !== 'label' && value)
|
||||
.map(([key, value]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-semibold">
|
||||
{fields[key] ??
|
||||
(
|
||||
{
|
||||
area_unit: "Unidade da área",
|
||||
value_kind: "Natureza do valor",
|
||||
contract_type: "Tipo de contrato",
|
||||
area_unit:
|
||||
'Unidade da área',
|
||||
value_kind:
|
||||
'Natureza do valor',
|
||||
contract_type:
|
||||
'Tipo de contrato',
|
||||
} as Record<string, string>
|
||||
)[key] ??
|
||||
key}
|
||||
</dt>
|
||||
<dd className="break-words">
|
||||
{key === "value_kind"
|
||||
{key === 'value_kind'
|
||||
? ((
|
||||
{
|
||||
asking: "Pedido",
|
||||
indicative: "Indicativo",
|
||||
appraised: "Avaliado — declaração pendente",
|
||||
proposed: "Proposto",
|
||||
negotiated: "Negociado — declaração pendente",
|
||||
confirmed: "Confirmado — declaração pendente",
|
||||
asking: 'Pedido',
|
||||
indicative: 'Indicativo',
|
||||
appraised:
|
||||
'Avaliado — declaração pendente',
|
||||
proposed: 'Proposto',
|
||||
negotiated:
|
||||
'Negociado — declaração pendente',
|
||||
confirmed:
|
||||
'Confirmado — declaração pendente',
|
||||
} as Record<string, string>
|
||||
)[value] ?? value)
|
||||
: value}
|
||||
@@ -121,7 +132,7 @@ export default function BusinessObjects({
|
||||
setObjectId(o.id);
|
||||
setKind(o.kind);
|
||||
setPayload(o.payload);
|
||||
setReason("");
|
||||
setReason('');
|
||||
}}
|
||||
>
|
||||
Editar elemento
|
||||
@@ -135,12 +146,12 @@ export default function BusinessObjects({
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api(
|
||||
`/api/v1/existing-business/listings/${businessId}/objects${objectId ? `/${objectId}` : ""}`,
|
||||
`/api/v1/existing-business/listings/${businessId}/objects${objectId ? `/${objectId}` : ''}`,
|
||||
{
|
||||
...(objectId ? { _method: "PUT" } : {}),
|
||||
...(objectId ? { _method: 'PUT' } : {}),
|
||||
kind,
|
||||
payload,
|
||||
reason,
|
||||
@@ -152,7 +163,7 @@ export default function BusinessObjects({
|
||||
setError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Não foi possível guardar o elemento.",
|
||||
: 'Não foi possível guardar o elemento.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -160,7 +171,9 @@ export default function BusinessObjects({
|
||||
}}
|
||||
>
|
||||
<h3 className="font-bold">
|
||||
{objectId ? "Editar elemento reservado" : "Acrescentar elemento reservado"}
|
||||
{objectId
|
||||
? 'Editar elemento reservado'
|
||||
: 'Acrescentar elemento reservado'}
|
||||
</h3>
|
||||
<Field label="Natureza">
|
||||
<select
|
||||
@@ -177,30 +190,65 @@ export default function BusinessObjects({
|
||||
</select>
|
||||
</Field>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{Object.entries(fields).map(([key, label]) => (
|
||||
<Field key={key} label={label}>
|
||||
<input
|
||||
className={input}
|
||||
type={key.startsWith("valid_") ? "date" : "text"}
|
||||
value={payload[key] ?? ""}
|
||||
maxLength={key === "label" ? 200 : 2000}
|
||||
required={key === "label" || key === "source_reference"}
|
||||
onChange={(e) =>
|
||||
setPayload({ ...payload, [key]: e.target.value })
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
{Object.entries(fields)
|
||||
.filter(([key]) => key !== 'resource_status')
|
||||
.map(([key, label]) => (
|
||||
<Field key={key} label={label}>
|
||||
<input
|
||||
className={input}
|
||||
type={
|
||||
key.startsWith('valid_')
|
||||
? 'date'
|
||||
: 'text'
|
||||
}
|
||||
value={payload[key] ?? ''}
|
||||
maxLength={key === 'label' ? 200 : 2000}
|
||||
required={
|
||||
key === 'label' ||
|
||||
key === 'source_reference'
|
||||
}
|
||||
onChange={(e) =>
|
||||
setPayload({
|
||||
...payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<Field label={fields.resource_status}>
|
||||
<select
|
||||
className={input}
|
||||
value={payload.resource_status ?? ''}
|
||||
onChange={(e) =>
|
||||
setPayload({
|
||||
...payload,
|
||||
resource_status: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Por confirmar</option>
|
||||
<option value="available">Disponível</option>
|
||||
<option value="contracted">Contratado</option>
|
||||
<option value="planned">Previsto</option>
|
||||
<option value="unconfirmed">
|
||||
Por confirmar
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Unidade da área">
|
||||
<select
|
||||
className={input}
|
||||
value={payload.area_unit ?? ""}
|
||||
value={payload.area_unit ?? ''}
|
||||
onChange={(e) =>
|
||||
setPayload({ ...payload, area_unit: e.target.value })
|
||||
setPayload({
|
||||
...payload,
|
||||
area_unit: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Não indicada</option>
|
||||
{["m2", "ha", "km2"].map((x) => (
|
||||
{['m2', 'ha', 'km2'].map((x) => (
|
||||
<option key={x}>{x}</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -208,19 +256,25 @@ export default function BusinessObjects({
|
||||
<Field label="Natureza do valor">
|
||||
<select
|
||||
className={input}
|
||||
value={payload.value_kind ?? ""}
|
||||
value={payload.value_kind ?? ''}
|
||||
onChange={(e) =>
|
||||
setPayload({ ...payload, value_kind: e.target.value })
|
||||
setPayload({
|
||||
...payload,
|
||||
value_kind: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Não indicada</option>
|
||||
{Object.entries({
|
||||
asking: "Pedido",
|
||||
indicative: "Indicativo",
|
||||
appraised: "Avaliado (declaração por verificar)",
|
||||
proposed: "Proposto",
|
||||
negotiated: "Negociado (declaração por verificar)",
|
||||
confirmed: "Confirmado (declaração por verificar)",
|
||||
asking: 'Pedido',
|
||||
indicative: 'Indicativo',
|
||||
appraised:
|
||||
'Avaliado (declaração por verificar)',
|
||||
proposed: 'Proposto',
|
||||
negotiated:
|
||||
'Negociado (declaração por verificar)',
|
||||
confirmed:
|
||||
'Confirmado (declaração por verificar)',
|
||||
}).map(([key, label]) => (
|
||||
<option key={key} value={key}>
|
||||
{label}
|
||||
@@ -231,19 +285,22 @@ export default function BusinessObjects({
|
||||
<Field label="Tipo de contrato">
|
||||
<select
|
||||
className={input}
|
||||
value={payload.contract_type ?? ""}
|
||||
value={payload.contract_type ?? ''}
|
||||
onChange={(e) =>
|
||||
setPayload({ ...payload, contract_type: e.target.value })
|
||||
setPayload({
|
||||
...payload,
|
||||
contract_type: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Não indicado</option>
|
||||
{Object.entries({
|
||||
purchase: "Compra",
|
||||
sale: "Venda",
|
||||
lease: "Arrendamento",
|
||||
operation: "Exploração",
|
||||
management: "Gestão",
|
||||
other: "Outro",
|
||||
purchase: 'Compra',
|
||||
sale: 'Venda',
|
||||
lease: 'Arrendamento',
|
||||
operation: 'Exploração',
|
||||
management: 'Gestão',
|
||||
other: 'Outro',
|
||||
}).map(([key, label]) => (
|
||||
<option key={key} value={key}>
|
||||
{label}
|
||||
@@ -264,7 +321,7 @@ export default function BusinessObjects({
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<button className={button} disabled={busy}>
|
||||
{busy ? "A guardar…" : "Guardar elemento reservado"}
|
||||
{busy ? 'A guardar…' : 'Guardar elemento reservado'}
|
||||
</button>
|
||||
{objectId && (
|
||||
<button
|
||||
@@ -273,7 +330,7 @@ export default function BusinessObjects({
|
||||
onClick={() => {
|
||||
setObjectId(null);
|
||||
setPayload({});
|
||||
setReason("");
|
||||
setReason('');
|
||||
}}
|
||||
>
|
||||
Cancelar edição
|
||||
|
||||
@@ -7,10 +7,10 @@ type Business = {
|
||||
province?: string | null; district?: string | null; locality?: string | null; sector?: { name: string; slug: string } | null;
|
||||
};
|
||||
|
||||
export default function BusinessOpportunity({ record }: { record: Business }) {
|
||||
export default function BusinessOpportunity({ record, returnUrl = "/negocios", interestUrl = `/negocios/${record.slug}/manifestar-interesse` }: { record: Business; returnUrl?: string; interestUrl?: string }) {
|
||||
return (
|
||||
<Frame title={record.title}>
|
||||
<Link href="/negocios" className="underline">Voltar às oportunidades</Link>
|
||||
<Link href={returnUrl} className="underline">Voltar às oportunidades</Link>
|
||||
<section className={`${card} space-y-4`}>
|
||||
<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>}
|
||||
@@ -18,7 +18,7 @@ export default function BusinessOpportunity({ record }: { record: Business }) {
|
||||
{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={`/negocios/${record.slug}/manifestar-interesse`}>Manifestar interesse</Link>
|
||||
<Link className={button} href={interestUrl}>Manifestar interesse</Link>
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
@@ -15,6 +15,7 @@ export type Business = {
|
||||
amount_max?: string | null;
|
||||
available_percentage?: string | null;
|
||||
funds_use?: string | null;
|
||||
territory_paths?: string[][];
|
||||
submitted_at?: string | null;
|
||||
published_at?: string | null;
|
||||
expires_at?: string | null;
|
||||
@@ -31,43 +32,48 @@ export type Business = {
|
||||
};
|
||||
};
|
||||
export const businessStates: Record<string, string> = {
|
||||
draft: "Rascunho",
|
||||
submitted: "Submetido",
|
||||
in_review: "Em revisão",
|
||||
needs_information: "Pendente de informação",
|
||||
withdrawn: "Retirado",
|
||||
triage: "Triagem",
|
||||
information_pending: "Informação pendente",
|
||||
review: "Em revisão",
|
||||
approval_l1: "Aprovação nível 1",
|
||||
approval_l2: "Aprovação nível 2",
|
||||
approved: "Aprovado",
|
||||
published: "Publicado",
|
||||
suspended: "Suspenso",
|
||||
rejected: "Rejeitado",
|
||||
cancelled: "Cancelado",
|
||||
archived: "Arquivado",
|
||||
draft: 'Rascunho',
|
||||
submitted: 'Submetido',
|
||||
in_review: 'Em revisão',
|
||||
needs_information: 'Pendente de informação',
|
||||
withdrawn: 'Retirado',
|
||||
triage: 'Triagem',
|
||||
information_pending: 'Informação pendente',
|
||||
review: 'Em revisão',
|
||||
approval_l1: 'Aprovação nível 1',
|
||||
approval_l2: 'Aprovação nível 2',
|
||||
approved: 'Aprovado',
|
||||
published: 'Publicado',
|
||||
suspended: 'Suspenso',
|
||||
rejected: 'Rejeitado',
|
||||
cancelled: 'Cancelado',
|
||||
archived: 'Arquivado',
|
||||
};
|
||||
export const businessModalities: Record<string, string> = {
|
||||
company_sale: "Venda da empresa",
|
||||
participation_sale: "Venda de participação",
|
||||
capital_increase: "Aumento de capital",
|
||||
financial_investor: "Investidor financeiro",
|
||||
strategic_partner: "Sócio estratégico",
|
||||
buyer_search: "Procura de comprador",
|
||||
position_assignment: "Cessão de posição",
|
||||
franchise: "Franchising",
|
||||
asset_sale: "Venda de activos",
|
||||
asset_lease: "Arrendamento de activos",
|
||||
business_unit_transfer: "Transferência de unidade de negócio",
|
||||
joint_venture: "Joint venture",
|
||||
succession: "Sucessão empresarial",
|
||||
recovery: "Recuperação",
|
||||
expansion: "Expansão",
|
||||
internationalization: "Internacionalização",
|
||||
real_estate: "Imobiliário",
|
||||
agricultural_investment: "Investimento agrícola",
|
||||
land_right: "Direito fundiário",
|
||||
mining_license: "Licença mineira",
|
||||
forestry_license: "Licença florestal",
|
||||
company_sale: 'Venda da empresa',
|
||||
participation_sale: 'Venda de participação',
|
||||
capital_increase: 'Aumento de capital',
|
||||
financial_investor: 'Investidor financeiro',
|
||||
strategic_partner: 'Sócio estratégico',
|
||||
buyer_search: 'Procura de comprador',
|
||||
position_assignment: 'Cessão de posição',
|
||||
franchise: 'Franchising',
|
||||
asset_sale: 'Venda de activos',
|
||||
asset_lease: 'Arrendamento de activos',
|
||||
business_unit_transfer: 'Transferência de unidade de negócio',
|
||||
joint_venture: 'Joint venture',
|
||||
succession: 'Sucessão empresarial',
|
||||
recovery: 'Recuperação',
|
||||
expansion: 'Expansão',
|
||||
internationalization: 'Internacionalização',
|
||||
real_estate: 'Imobiliário',
|
||||
agricultural_investment: 'Investimento agrícola',
|
||||
land_right: 'Direito fundiário',
|
||||
mining_license: 'Licença mineira',
|
||||
forestry_license: 'Licença florestal',
|
||||
investment_project: 'Projecto de investimento',
|
||||
business_partnership: 'Parceria empresarial',
|
||||
financing_request: 'Procura de financiamento',
|
||||
concession_opportunity: 'Concessão',
|
||||
supply_opportunity: 'Oportunidade de fornecimento',
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -51,6 +51,7 @@ export default function Catalogue({
|
||||
district_id: String(filters.district_id ?? ""),
|
||||
admin_post_id: String(filters.admin_post_id ?? ""),
|
||||
locality_id: String(filters.locality_id ?? ""),
|
||||
include_national: Boolean(filters.include_national && filters.include_national !== "0"),
|
||||
cluster_id: String(filters.cluster_id ?? ""),
|
||||
zee_id: String(filters.zee_id ?? ""),
|
||||
zfi_id: String(filters.zfi_id ?? ""),
|
||||
@@ -90,7 +91,7 @@ export default function Catalogue({
|
||||
lastRequest.current = draftFilterKey;
|
||||
router.get(
|
||||
catalogueUrl,
|
||||
{ ...data, education: data.education ? 1 : 0 },
|
||||
{ ...data, education: data.education ? 1 : 0, include_national: data.include_national ? 1 : 0 },
|
||||
{
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
@@ -201,11 +202,19 @@ export default function Catalogue({
|
||||
<Link className={card} href={dimensionUrl("zfi")}>
|
||||
Por ZFI
|
||||
</Link>
|
||||
<Link className={card} href="/zonas?category=zee">Fichas de ZEE</Link>
|
||||
<Link className={card} href="/zonas?category=zfi">Fichas de ZFI</Link>
|
||||
<Link className={card} href="/zonas?category=industrial_park">Parques industriais</Link>
|
||||
<Link className={card} href="/carteira?kind=project">Projectos âncora documentados</Link>
|
||||
<Link className={card} href="/negocios">Negócios e participações publicados</Link>
|
||||
</nav>
|
||||
<p>
|
||||
Combine contexto territorial, dimensão e necessidades. As fichas documentais e as
|
||||
oportunidades mantêm a sua origem e natureza.
|
||||
</p>
|
||||
<p className={card}>
|
||||
Negócios existentes, participações, imóveis e activos só surgem como anúncio depois de revisão e publicação expressa. A pesquisa de negócios é um catálogo separado; ausência de resultados não confirma inexistência do activo. As referências governamentais da carteira são separadas de anúncios privados.
|
||||
</p>
|
||||
<form
|
||||
className={card + " space-y-4"}
|
||||
onSubmit={(e) => {
|
||||
@@ -213,97 +222,11 @@ export default function Catalogue({
|
||||
setPoints(null);
|
||||
setComparison([]);
|
||||
setSelected([]);
|
||||
form.transform((data) => ({ ...data, education: data.education ? 1 : 0 }));
|
||||
form.transform((data) => ({ ...data, education: data.education ? 1 : 0, include_national: data.include_national ? 1 : 0 }));
|
||||
form.get(catalogueUrl, { preserveState: true });
|
||||
}}
|
||||
>
|
||||
<Field label="Pesquisar oportunidades">
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.q}
|
||||
onChange={(e) => form.setData("q", e.target.value)}
|
||||
autoComplete="off"
|
||||
aria-describedby="search-suggestions"
|
||||
/>
|
||||
</Field>
|
||||
{suggestions.length > 0 && (
|
||||
<ul
|
||||
id="search-suggestions"
|
||||
aria-label="Sugestões de pesquisa"
|
||||
className="space-y-2"
|
||||
>
|
||||
{suggestions.map((s) => (
|
||||
<li key={s.slug}>
|
||||
<Link href={`/oportunidades/${s.slug}`} className="underline">
|
||||
{s.title}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{(
|
||||
[
|
||||
["zee_id", "zee", "ZEE"],
|
||||
["zfi_id", "zfi", "ZFI"],
|
||||
["park_id", "industrial_park", "Parque industrial"],
|
||||
] as const
|
||||
).map(([field, category, label]) => (
|
||||
<Field key={field} label={label}>
|
||||
<select
|
||||
className={input}
|
||||
value={form.data[field]}
|
||||
onChange={(e) => form.setData(field, e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{(references.zones ?? [])
|
||||
.filter((z) => z.category === category)
|
||||
.map((z) => (
|
||||
<option key={z.id} value={z.id}>
|
||||
{z.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
{(["clusters", "corridors", "projects"] as const).map((group, i) => {
|
||||
const key = (
|
||||
["cluster_id", "corridor_id", "project_id", "geo_location_id"] as const
|
||||
)[i];
|
||||
return (
|
||||
<Field
|
||||
key={group}
|
||||
label={["Cluster", "Corredor", "Projecto âncora", "Localização"][i]}
|
||||
>
|
||||
<select
|
||||
className={input}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{references[group].map((r) => (
|
||||
<option value={r.id} key={r.id}>
|
||||
{r.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
<Field label="Sector">
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.sector}
|
||||
onChange={(e) => form.setData("sector", e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{references.sectors.map((s) => (
|
||||
<option key={s.id} value={s.slug}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<section aria-label="Localização da oportunidade" className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
|
||||
(key, index) => (
|
||||
<TerritoryLevel
|
||||
@@ -313,10 +236,7 @@ export default function Catalogue({
|
||||
selected={territoryPath[index]}
|
||||
endpoint="/api/v1/catalogs/jurisdictions"
|
||||
onChange={(value) => {
|
||||
const path = [
|
||||
...territoryPath.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
const path = [...territoryPath.slice(0, index), ...(value ? [value] : [])];
|
||||
setTerritoryPath(path);
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
@@ -327,11 +247,68 @@ export default function Catalogue({
|
||||
district_id: path[1]?.id ?? "",
|
||||
admin_post_id: path[2]?.id ?? "",
|
||||
locality_id: path[3]?.id ?? "",
|
||||
zee_id: "",
|
||||
zfi_id: "",
|
||||
park_id: "",
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</section>
|
||||
<Field label="Pesquisar oportunidades">
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.q}
|
||||
onChange={(e) => form.setData("q", e.target.value)}
|
||||
autoComplete="off"
|
||||
aria-describedby="search-suggestions"
|
||||
/>
|
||||
</Field>
|
||||
{suggestions.length > 0 && (
|
||||
<ul id="search-suggestions" aria-label="Sugestões de pesquisa" className="space-y-2">
|
||||
{suggestions.map((s) => (
|
||||
<li key={s.slug}>
|
||||
<Link href={`/oportunidades/${s.slug}`} className="underline">{s.title}</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{([
|
||||
["zee_id", "zee", "ZEE"],
|
||||
["zfi_id", "zfi", "ZFI"],
|
||||
["park_id", "industrial_park", "Parque industrial"],
|
||||
] as const).map(([field, category, label]) => (
|
||||
<Field key={field} label={label}>
|
||||
<select className={input} value={form.data[field]} onChange={(e) => form.setData(field, e.target.value)}>
|
||||
<option value="">Todos</option>
|
||||
{(references.zones ?? []).filter((zone) => zone.category === category).map((zone) => (
|
||||
<option key={zone.id} value={zone.id}>{zone.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
{(["clusters", "corridors", "projects"] as const).map((group, index) => {
|
||||
const key = (["cluster_id", "corridor_id", "project_id"] as const)[index];
|
||||
const label = (["Cluster", "Corredor", "Projecto âncora"] as const)[index];
|
||||
return (
|
||||
<Field key={group} label={label}>
|
||||
<select className={input} value={form.data[key]} onChange={(e) => form.setData(key, e.target.value)}>
|
||||
<option value="">Todos</option>
|
||||
{references[group].map((item) => <option value={item.id} key={item.id}>{item.name}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
<Field label="Sector">
|
||||
<select className={input} value={form.data.sector} onChange={(e) => form.setData("sector", e.target.value)}>
|
||||
<option value="">Todos</option>
|
||||
{references.sectors.map((sector) => <option key={sector.id} value={sector.slug}>{sector.name}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
<section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Field label="Estado de preparação">
|
||||
<select
|
||||
className={input}
|
||||
@@ -387,7 +364,7 @@ export default function Catalogue({
|
||||
onChange={(e) => form.setData("before", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
</section>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -396,6 +373,11 @@ export default function Catalogue({
|
||||
/>
|
||||
Apenas oportunidades na educação
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input type="checkbox" checked={form.data.include_national}
|
||||
onChange={(e) => form.setData("include_national", e.target.checked)} />
|
||||
Incluir âmbito nacional
|
||||
</label>
|
||||
<details>
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Subsector, educação, infraestruturas, competências e apoios
|
||||
@@ -467,8 +449,50 @@ export default function Catalogue({
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
{(territoryPath.length > 0 || form.data.q || form.data.dimension || form.data.sector || form.data.cluster_id || form.data.corridor_id || form.data.project_id || form.data.geo_location_id || form.data.zee_id || form.data.zfi_id || form.data.park_id || form.data.include_national || form.data.education || form.data.maturity_level || form.data.min_amount || form.data.max_amount || form.data.currency || form.data.before || form.data.facets.length > 0) && (
|
||||
<section aria-label="Filtros activos" className="flex flex-wrap items-center gap-2">
|
||||
<strong>Filtros activos:</strong>
|
||||
{territoryPath.map((node, index) => <span key={node.id} className="rounded border px-2 py-1">{node.name} <button type="button" aria-label={`Remover localização ${node.name}`} onClick={() => {
|
||||
const path = territoryPath.slice(0, index);
|
||||
setTerritoryPath(path);
|
||||
form.setData((data) => ({ ...data, province_id: path[0]?.id ?? "", district_id: path[1]?.id ?? "", admin_post_id: path[2]?.id ?? "", locality_id: path[3]?.id ?? "", province: "", district: "", geo_location_id: "" }));
|
||||
}}>×</button></span>)}
|
||||
{form.data.sector && <span className="rounded border px-2 py-1">Sector: {references.sectors.find((s) => s.slug === form.data.sector)?.name ?? form.data.sector}</span>}
|
||||
{form.data.cluster_id && <span className="rounded border px-2 py-1">Cluster: {references.clusters.find((v) => v.id === form.data.cluster_id)?.name} <button type="button" aria-label="Remover filtro Cluster" onClick={() => form.setData("cluster_id", "")}>×</button></span>}
|
||||
{form.data.corridor_id && <span className="rounded border px-2 py-1">Corredor: {references.corridors.find((v) => v.id === form.data.corridor_id)?.name} <button type="button" aria-label="Remover filtro Corredor" onClick={() => form.setData("corridor_id", "")}>×</button></span>}
|
||||
{form.data.project_id && <span className="rounded border px-2 py-1">Projecto: {references.projects.find((v) => v.id === form.data.project_id)?.name} <button type="button" aria-label="Remover filtro Projecto" onClick={() => form.setData("project_id", "")}>×</button></span>}
|
||||
{form.data.q && <span className="rounded border px-2 py-1">Pesquisa: {form.data.q} <button type="button" aria-label="Remover pesquisa" onClick={() => form.setData("q", "")}>×</button></span>}
|
||||
{form.data.dimension && <span className="rounded border px-2 py-1">Dimensão: {form.data.dimension} <button type="button" aria-label="Remover dimensão" onClick={() => form.setData("dimension", "")}>×</button></span>}
|
||||
{form.data.geo_location_id && <span className="rounded border px-2 py-1">Localização adicional: {references.locations.find((v) => v.id === form.data.geo_location_id)?.name ?? "seleccionada"} <button type="button" aria-label="Remover localização adicional" onClick={() => form.setData("geo_location_id", "")}>×</button></span>}
|
||||
{form.data.zee_id && <span className="rounded border px-2 py-1">ZEE: {references.zones?.find((z) => z.id === form.data.zee_id)?.name ?? "seleccionada"} <button type="button" aria-label="Remover filtro ZEE" onClick={() => form.setData("zee_id", "")}>×</button></span>}
|
||||
{form.data.zfi_id && <span className="rounded border px-2 py-1">ZFI: {references.zones?.find((z) => z.id === form.data.zfi_id)?.name ?? "seleccionada"} <button type="button" aria-label="Remover filtro ZFI" onClick={() => form.setData("zfi_id", "")}>×</button></span>}
|
||||
{form.data.park_id && <span className="rounded border px-2 py-1">Parque: {references.zones?.find((z) => z.id === form.data.park_id)?.name ?? "seleccionado"} <button type="button" aria-label="Remover filtro parque" onClick={() => form.setData("park_id", "")}>×</button></span>}
|
||||
{form.data.education && <span className="rounded border px-2 py-1">Educação <button type="button" aria-label="Remover filtro de educação" onClick={() => form.setData("education", false)}>×</button></span>}
|
||||
{form.data.maturity_level && <span className="rounded border px-2 py-1">Maturidade: {form.data.maturity_level} <button type="button" aria-label="Remover maturidade" onClick={() => form.setData("maturity_level", "")}>×</button></span>}
|
||||
{(form.data.min_amount || form.data.max_amount) && <span className="rounded border px-2 py-1">Montante: {form.data.min_amount || "sem mínimo"}–{form.data.max_amount || "sem máximo"} {form.data.currency} <button type="button" aria-label="Remover intervalo de montante" onClick={() => form.setData((data) => ({ ...data, min_amount: "", max_amount: "", currency: "" }))}>×</button></span>}
|
||||
{form.data.currency && !form.data.min_amount && !form.data.max_amount && <span className="rounded border px-2 py-1">Moeda: {form.data.currency} <button type="button" aria-label="Remover moeda" onClick={() => form.setData("currency", "")}>×</button></span>}
|
||||
{form.data.before && <span className="rounded border px-2 py-1">Data até: {form.data.before} <button type="button" aria-label="Remover data-alvo" onClick={() => form.setData("before", "")}>×</button></span>}
|
||||
{form.data.facets.map((id) => {
|
||||
const option = references.options.find((item) => item.id === id);
|
||||
return <span key={id} className="rounded border px-2 py-1">{option?.label ?? `Opção ${id}`} <button type="button" aria-label={`Remover filtro ${option?.label ?? id}`} onClick={() => form.setData("facets", form.data.facets.filter((value) => value !== id))}>×</button></span>;
|
||||
})}
|
||||
{form.data.include_national && <span className="rounded border px-2 py-1">Âmbito nacional incluído</span>}
|
||||
{territoryPath.length > 0 && <button type="button" className="underline" onClick={() => {
|
||||
setTerritoryPath([]);
|
||||
form.setData((data) => ({ ...data, province_id: "", district_id: "", admin_post_id: "", locality_id: "", province: "", district: "", geo_location_id: "" }));
|
||||
}}>Remover localização</button>}
|
||||
{form.data.sector && <button type="button" className="underline" onClick={() => form.setData("sector", "")}>Remover sector</button>}
|
||||
{form.data.include_national && <button type="button" className="underline" onClick={() => form.setData("include_national", false)}>Remover âmbito nacional</button>}
|
||||
</section>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<p role="status">{results.total} oportunidades publicadas</p>
|
||||
{results.total === 0 && (form.data.province_id || form.data.district_id || form.data.admin_post_id || form.data.locality_id) && (
|
||||
<button type="button" className="underline" onClick={() => {
|
||||
setTerritoryPath([]);
|
||||
form.setData((data) => ({ ...data, province_id: "", district_id: "", admin_post_id: "", locality_id: "", province: "", district: "", geo_location_id: "" }));
|
||||
}}>Alargar pesquisa (remover localização)</button>
|
||||
)}
|
||||
{["grid", "list", "map", "combined"].map((value, i) => (
|
||||
<button
|
||||
key={value}
|
||||
@@ -531,13 +555,18 @@ export default function Catalogue({
|
||||
{r.sector?.name} · {r.province || "Localização não indicada"}
|
||||
</p>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link href={`/oportunidades/${r.slug}`}>{r.title}</Link>
|
||||
<Link href={`/oportunidades/${r.slug}${query() ? `?${query()}` : ""}`}>{r.title}</Link>
|
||||
</h2>
|
||||
{!r.last_validated_at && (
|
||||
<p className="rounded border border-amber-700 bg-amber-50 p-3 text-sm">
|
||||
Esta ficha não regista data de validação documental. Confirme a origem e as condições antes de agir.
|
||||
</p>
|
||||
)}
|
||||
<p>{r.summary}</p>
|
||||
<p className="font-semibold">{money(r)}</p>
|
||||
<p>{r.maturity_label}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link className="underline" href={`/oportunidades/${r.slug}`}>
|
||||
<Link className="underline" href={`/oportunidades/${r.slug}${query() ? `?${query()}` : ""}`}>
|
||||
Ver ficha
|
||||
</Link>
|
||||
<button
|
||||
|
||||
@@ -7,18 +7,26 @@ export default function Detail({
|
||||
record: r,
|
||||
context: c,
|
||||
zone_origin,
|
||||
returnUrl = "/oportunidades",
|
||||
}: {
|
||||
record: Opportunity;
|
||||
context: Context;
|
||||
zone_origin?: { id: string; name: string } | null;
|
||||
returnUrl?: string;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: { user: unknown } }>().props;
|
||||
const [sharing, setSharing] = useState("");
|
||||
return (
|
||||
<Frame title={r.title}>
|
||||
<Link href={returnUrl} className="underline">Voltar à pesquisa</Link>
|
||||
<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.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xl">{r.summary}</p>
|
||||
<InvestmentMapPanel filters={{ opportunity_id: r.id }} />
|
||||
{c.primary_territory_path && c.primary_territory_path.length > 0 && (
|
||||
|
||||
@@ -38,6 +38,7 @@ export type Opportunity = {
|
||||
expected_impact: string | null;
|
||||
financing_modality: string | null;
|
||||
status: string;
|
||||
last_validated_at?: string | null;
|
||||
};
|
||||
export type Context = {
|
||||
primary_territory_path?: { id: string; name: string; location_type: string }[];
|
||||
@@ -118,15 +119,16 @@ export async function api(url: string, body?: unknown) {
|
||||
.find((c) => c.startsWith("XSRF-TOKEN="))
|
||||
?.slice(11) ?? "",
|
||||
);
|
||||
const formData = typeof FormData !== "undefined" && body instanceof FormData;
|
||||
const response = await fetch(url, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
credentials: "same-origin",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
...(formData ? {} : { "Content-Type": "application/json" }),
|
||||
"X-XSRF-TOKEN": token,
|
||||
},
|
||||
...(body === undefined ? {} : { 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.");
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { api, button, card, Field, input } from "./shared";
|
||||
|
||||
export type ZoneAttachment = {
|
||||
id: string;
|
||||
kind: string;
|
||||
caption: string;
|
||||
source_reference: string;
|
||||
source_date: string | null;
|
||||
rights_status?: string;
|
||||
rights_basis?: string | null;
|
||||
personal_data_status?: string;
|
||||
review_status?: string;
|
||||
independent_review?: boolean;
|
||||
publicly_selected?: boolean;
|
||||
version_no?: number;
|
||||
file_name?: string;
|
||||
file_status?: string;
|
||||
document_id?: string;
|
||||
malware_scan_status?: 'pending' | 'scanning' | 'clean' | 'infected' | 'inconclusive' | 'failed';
|
||||
malware_failure_reason?: string | null;
|
||||
media_type: string;
|
||||
size_bytes: number | null;
|
||||
download_url: string;
|
||||
};
|
||||
|
||||
export default function ZoneAttachments({
|
||||
zoneId,
|
||||
attachments,
|
||||
management,
|
||||
zonePublished,
|
||||
}: {
|
||||
zoneId: string;
|
||||
attachments: ZoneAttachment[];
|
||||
management: boolean;
|
||||
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 [busy, setBusy] = useState(false);
|
||||
|
||||
async function send(url: string, payload: unknown) {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await api(url, payload);
|
||||
router.reload();
|
||||
} catch (failure) {
|
||||
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>
|
||||
</>}
|
||||
{error && <p role="alert">{error}</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>;
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Link, router, useForm } from "@inertiajs/react";
|
||||
import InvestmentTerritory from "@/components/investment-territory";
|
||||
import InvestmentMapPanel from "@/components/investment-map-panel";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { useState } from "react";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
import ZoneRelations from "./zone-relations";
|
||||
import ZoneMap from "./zone-map";
|
||||
import ZoneAttachments from "./zone-attachments";
|
||||
import type { ZoneTargets } from "./zone-relations";
|
||||
|
||||
type Zone = {
|
||||
@@ -22,6 +24,19 @@ type Zone = {
|
||||
legal_source_id?: string;
|
||||
publication_status?: string;
|
||||
validation_status: string;
|
||||
physical_category?: string | null;
|
||||
legal_regime?: string | null;
|
||||
operational_status?: string;
|
||||
development_status?: string;
|
||||
availability_status?: string;
|
||||
area_value?: string | null;
|
||||
area_unit?: string | null;
|
||||
area_components?: unknown[];
|
||||
source_evidence?: unknown[];
|
||||
aliases?: string[];
|
||||
activities?: { name: string; status: string; source_reference?: string | null }[];
|
||||
resources?: { name: string; status: string; source_reference?: string | null }[];
|
||||
historical_territory?: { name: string; district?: string; province?: string; source_reference?: string } | null;
|
||||
};
|
||||
type Source = {
|
||||
id: string;
|
||||
@@ -35,6 +50,33 @@ type Source = {
|
||||
version_no: number;
|
||||
validation_status: string;
|
||||
};
|
||||
type ZoneEditorForm = {
|
||||
version_no: number;
|
||||
code: string;
|
||||
category: string;
|
||||
physical_category: string;
|
||||
legal_regime: string;
|
||||
operational_status: string;
|
||||
development_status: string;
|
||||
availability_status: string;
|
||||
area_value: string;
|
||||
area_unit: string;
|
||||
area_components_json: string;
|
||||
source_evidence_json: string;
|
||||
activities: { name: string; status: string; source_reference: string | null }[];
|
||||
resources: { name: string; status: string; source_reference: string | null }[];
|
||||
aliases_text: string;
|
||||
historical_name: string;
|
||||
historical_district: string;
|
||||
historical_province: string;
|
||||
historical_source_reference: string;
|
||||
name: string;
|
||||
name_en: string;
|
||||
description: string;
|
||||
description_en: string;
|
||||
operator_id: string;
|
||||
legal_source_id: string;
|
||||
};
|
||||
type Props = {
|
||||
targets: ZoneTargets | null;
|
||||
related: { id: string; title: string }[];
|
||||
@@ -47,6 +89,7 @@ type Props = {
|
||||
geometries: { id: string; version_no: number; purpose: string; validation_status: string }[];
|
||||
record: Zone;
|
||||
management: boolean;
|
||||
zoneExtensionsAvailable?: boolean;
|
||||
source: Source | null;
|
||||
operator: string | null;
|
||||
operators: { id: string; name: string }[];
|
||||
@@ -59,6 +102,13 @@ type Props = {
|
||||
version_no: number;
|
||||
}[];
|
||||
revisions: { version_no: number; action: string; created_at: string }[];
|
||||
locations: { id: string; name: string; location_type: string; scope_type: string; source_reference: string; validation_status: string }[];
|
||||
attachments: {
|
||||
id: string; kind: string; caption: string; source_reference: string; source_date: string | null;
|
||||
rights_status?: string; rights_basis?: string | null; personal_data_status?: string; review_status?: string;
|
||||
reviewed_by?: number | null; independent_review?: boolean; publicly_selected?: boolean; uploaded_by?: number;
|
||||
version_no?: number; file_name?: string; media_type: string; size_bytes: number | null; download_url: string;
|
||||
}[];
|
||||
opportunities: {
|
||||
data: { id: number; title: string; slug: string }[];
|
||||
next_page_url: string | null;
|
||||
@@ -75,20 +125,56 @@ function Editor({
|
||||
geometries,
|
||||
record: z,
|
||||
management,
|
||||
zoneExtensionsAvailable = false,
|
||||
source,
|
||||
operator,
|
||||
operators,
|
||||
legalSources,
|
||||
links,
|
||||
revisions,
|
||||
locations,
|
||||
attachments,
|
||||
opportunities,
|
||||
}: Props) {
|
||||
const [message, setMessage] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const form = useForm({
|
||||
const [locationPath, setLocationPath] = useState<TerritoryOption[]>([]);
|
||||
const [locationSource, setLocationSource] = useState("");
|
||||
const [locationScope, setLocationScope] = useState("administrative");
|
||||
const [activityName, setActivityName] = useState("");
|
||||
const [activityStatus, setActivityStatus] = useState("potential");
|
||||
const [activitySource, setActivitySource] = useState("");
|
||||
const [resourceName, setResourceName] = useState("");
|
||||
const [resourceStatus, setResourceStatus] = useState("unconfirmed");
|
||||
const [resourceSource, setResourceSource] = useState("");
|
||||
const [attachmentFile, setAttachmentFile] = useState<File | null>(null);
|
||||
const [attachmentKind, setAttachmentKind] = useState("legal_instrument");
|
||||
const [attachmentCaption, setAttachmentCaption] = useState("");
|
||||
const [attachmentSource, setAttachmentSource] = useState("");
|
||||
const [attachmentSourceDate, setAttachmentSourceDate] = useState("");
|
||||
const [attachmentRightsBasis, setAttachmentRightsBasis] = useState("");
|
||||
const [attachmentRightsStatus, setAttachmentRightsStatus] = useState("pending");
|
||||
const [reviewChoices, setReviewChoices] = useState<Record<string, { rights: string; personal: string }>>({});
|
||||
const form = useForm<ZoneEditorForm>({
|
||||
version_no: z.version_no,
|
||||
code: z.code,
|
||||
category: z.category,
|
||||
physical_category: z.physical_category ?? "unknown",
|
||||
legal_regime: z.legal_regime ?? "pending",
|
||||
operational_status: z.operational_status ?? "unknown",
|
||||
development_status: z.development_status ?? "unknown",
|
||||
availability_status: z.availability_status ?? "not_informed",
|
||||
area_value: z.area_value ?? "",
|
||||
area_unit: z.area_unit ?? "",
|
||||
area_components_json: JSON.stringify(z.area_components ?? [], null, 2),
|
||||
source_evidence_json: JSON.stringify(z.source_evidence ?? [], null, 2),
|
||||
activities: (z.activities ?? []).map((activity) => ({ ...activity, source_reference: activity.source_reference ?? null })),
|
||||
resources: (z.resources ?? []).map((resource) => ({ ...resource, source_reference: resource.source_reference ?? null })),
|
||||
aliases_text: (z.aliases ?? []).join("\n"),
|
||||
historical_name: z.historical_territory?.name ?? "",
|
||||
historical_district: z.historical_territory?.district ?? "",
|
||||
historical_province: z.historical_territory?.province ?? "",
|
||||
historical_source_reference: z.historical_territory?.source_reference ?? "",
|
||||
name: z.name,
|
||||
name_en: z.name_en ?? "",
|
||||
description: z.description ?? "",
|
||||
@@ -132,8 +218,11 @@ function Editor({
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
try {
|
||||
const { area_components_json, source_evidence_json, ...base } = form.data;
|
||||
await api(`/api/v2/investment/admin/zones/${z.id}`, {
|
||||
...form.data,
|
||||
...base,
|
||||
area_components: JSON.parse(area_components_json),
|
||||
source_evidence: JSON.parse(source_evidence_json),
|
||||
_method: "PUT",
|
||||
});
|
||||
router.reload();
|
||||
@@ -175,6 +264,96 @@ function Editor({
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Categoria física">
|
||||
<select className={input} value={form.data.physical_category} onChange={(e) => form.setData("physical_category", e.target.value)}>
|
||||
<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><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="other">Outra</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Regime jurídico">
|
||||
<select className={input} value={form.data.legal_regime} onChange={(e) => form.setData("legal_regime", e.target.value)}>
|
||||
<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>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Estado operacional">
|
||||
<select className={input} value={form.data.operational_status} onChange={(e) => form.setData("operational_status", e.target.value)}>
|
||||
<option value="unknown">Não confirmado</option><option value="operational">Operacional</option>
|
||||
<option value="implementation">Em implementação</option><option value="planned">Planeado</option><option value="suspended">Suspenso</option>
|
||||
</select>
|
||||
</Field>
|
||||
{zoneExtensionsAvailable && <Field label="Estado de desenvolvimento">
|
||||
<select className={input} value={form.data.development_status} onChange={(e) => form.setData("development_status", e.target.value)}>
|
||||
<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 className={input} value={form.data.availability_status} onChange={(e) => form.setData("availability_status", e.target.value)}>
|
||||
<option value="not_informed">Não informada</option><option value="confirmed">Confirmada</option><option value="unavailable">Indisponível</option><option value="reported_unverified">Reportada, por verificar</option>
|
||||
</select>
|
||||
</Field>}
|
||||
<Field label="Área documentada">
|
||||
<input className={input} type="number" min="0" step="0.0001" value={form.data.area_value} onChange={(e) => form.setData("area_value", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Unidade da área">
|
||||
<select className={input} value={form.data.area_unit} onChange={(e) => form.setData("area_unit", e.target.value)}>
|
||||
<option value="">Por confirmar</option><option value="ha">hectares (ha)</option><option value="km2">quilómetros quadrados (km²)</option>
|
||||
</select>
|
||||
</Field>
|
||||
{zoneExtensionsAvailable && <Field label="Áreas por âmbito (JSON; valor, unidade, fonte, data, estado)">
|
||||
<textarea className={input} rows={6} value={form.data.area_components_json} onChange={(e) => form.setData("area_components_json", e.target.value)} />
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && <Field label="Evidência e fontes (JSON; tipo e o que comprova)">
|
||||
<textarea className={input} rows={6} value={form.data.source_evidence_json} onChange={(e) => form.setData("source_evidence_json", e.target.value)} />
|
||||
</Field>}
|
||||
<Field label="Designações alternativas (uma por linha)">
|
||||
<textarea className={input} rows={2} value={form.data.aliases_text} onChange={(e) => form.setData("aliases_text", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Localização histórica">
|
||||
<input className={input} value={form.data.historical_name} onChange={(e) => form.setData("historical_name", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Distrito histórico">
|
||||
<input className={input} value={form.data.historical_district} onChange={(e) => form.setData("historical_district", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Província histórica">
|
||||
<input className={input} value={form.data.historical_province} onChange={(e) => form.setData("historical_province", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Fonte da localização histórica">
|
||||
<input className={input} value={form.data.historical_source_reference} onChange={(e) => form.setData("historical_source_reference", e.target.value)} />
|
||||
</Field>
|
||||
<section className="space-y-3 md:col-span-2" aria-label="Actividades documentadas">
|
||||
<h2 className="font-semibold">Actividades e sectores</h2>
|
||||
{form.data.activities.map((activity, index) => <p key={`${activity.name}-${index}`}>{activity.name} · {activity.status} · {activity.source_reference ?? "fonte por registar"}</p>)}
|
||||
<div className="grid gap-2 md:grid-cols-3">
|
||||
<input className={input} aria-label="Actividade" placeholder="Actividade" value={activityName} onChange={(e) => setActivityName(e.target.value)} />
|
||||
<select className={input} aria-label="Estado da actividade" value={activityStatus} onChange={(e) => setActivityStatus(e.target.value)}>
|
||||
<option value="potential">Potencial referido pela fonte</option><option value="proposed">Proposta</option><option value="authorized">Autorizada</option><option value="conditional">Condicionada</option><option value="excluded">Excluída</option>
|
||||
</select>
|
||||
<input className={input} aria-label="Fonte da actividade" placeholder="URL ou referência" value={activitySource} onChange={(e) => setActivitySource(e.target.value)} />
|
||||
</div>
|
||||
<button type="button" className={button} disabled={!activityName.trim()} onClick={() => {
|
||||
form.setData("activities", [...form.data.activities, { name: activityName.trim(), status: activityStatus, source_reference: activitySource.trim() || null }]);
|
||||
setActivityName(""); setActivitySource("");
|
||||
}}>Adicionar actividade</button>
|
||||
</section>
|
||||
<section className="space-y-3 md:col-span-2" aria-label="Infra-estruturas e recursos">
|
||||
<h2 className="font-semibold">Infra-estruturas e recursos</h2>
|
||||
{form.data.resources.map((resource, index) => <p key={`${resource.name}-${index}`}>{resource.name} · {resource.status} · {resource.source_reference ?? "fonte por registar"}</p>)}
|
||||
<div className="grid gap-2 md:grid-cols-3">
|
||||
<input className={input} aria-label="Recurso" placeholder="Estrada, energia, água…" value={resourceName} onChange={(e) => setResourceName(e.target.value)} />
|
||||
<select className={input} aria-label="Estado do recurso" value={resourceStatus} onChange={(e) => setResourceStatus(e.target.value)}>
|
||||
<option value="existing">Existente, fonte confirmada</option><option value="planned">Planeado</option><option value="unconfirmed">Não confirmado</option>
|
||||
</select>
|
||||
<input className={input} aria-label="Fonte do recurso" placeholder="URL ou referência" value={resourceSource} onChange={(e) => setResourceSource(e.target.value)} />
|
||||
</div>
|
||||
<button type="button" className={button} disabled={!resourceName.trim()} onClick={() => {
|
||||
form.setData("resources", [...form.data.resources, { name: resourceName.trim(), status: resourceStatus, source_reference: resourceSource.trim() || null }]);
|
||||
setResourceName(""); setResourceSource("");
|
||||
}}>Adicionar recurso</button>
|
||||
</section>
|
||||
{(
|
||||
[
|
||||
["description", "Descrição PT"],
|
||||
@@ -221,6 +400,36 @@ function Editor({
|
||||
Guardar rascunho
|
||||
</button>
|
||||
</form>
|
||||
<ZoneAttachments zoneId={z.id} attachments={attachments} management={true} zonePublished={z.publication_status === "published"} />
|
||||
<section className={card + " space-y-4"} aria-label="Localizações documentadas">
|
||||
<h2 className="text-xl font-bold">Localizações documentadas</h2>
|
||||
<p>As localizações acrescentadas ficam pendentes até revisão independente. Não são inferidas pelo nome.</p>
|
||||
{locations.map((location) => (
|
||||
<div key={location.id} className="rounded border p-3">
|
||||
<p>{location.name} · {location.scope_type} · {location.validation_status}</p>
|
||||
<p className="text-sm">{location.source_reference}</p>
|
||||
{location.validation_status === "pending" && (
|
||||
<button type="button" className={button} disabled={busy} onClick={() => action(`/api/v2/investment/admin/zone-locations/${location.id}/validate`, { version_no: 1 })}>
|
||||
Rever localização
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<TerritoryFields endpoint="/management/territory-options" onChange={setLocationPath} />
|
||||
<Field label="Tipo de abrangência">
|
||||
<select className={input} value={locationScope} onChange={(event) => setLocationScope(event.target.value)}>
|
||||
<option value="legal_scope">Perímetro legal</option><option value="administrative">Unidade administrativa</option>
|
||||
<option value="site">Instalação/local</option><option value="influence">Área de influência</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Fonte e fundamento da associação">
|
||||
<input className={input} minLength={10} maxLength={2000} value={locationSource} onChange={(event) => setLocationSource(event.target.value)} />
|
||||
</Field>
|
||||
<button type="button" className={button} disabled={busy || !locationPath.length || locationSource.length < 10} onClick={() => {
|
||||
const selected = locationPath[locationPath.length - 1];
|
||||
void action(`/api/v2/investment/admin/zones/${z.id}`, { ...form.data, locations: [{ geo_location_id: selected.id, scope_type: locationScope, source_reference: locationSource }], _method: "PUT" });
|
||||
}}>Guardar outra localização</button>
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">Revisão independente</h2>
|
||||
<p>
|
||||
@@ -386,6 +595,14 @@ function Editor({
|
||||
) : (
|
||||
<>
|
||||
<p className="whitespace-pre-line">{z.description}</p>
|
||||
<p>Categoria física: {z.physical_category ?? "Por confirmar"} · Regime jurídico: {z.legal_regime ?? "Por confirmar"}{zoneExtensionsAvailable ? ` · Desenvolvimento: ${z.development_status ?? "Por confirmar"} · Disponibilidade: ${z.availability_status ?? "Não informada"}` : ""}</p>
|
||||
{z.area_value && <p>Área documentada: {z.area_value} {z.area_unit}</p>}
|
||||
{zoneExtensionsAvailable && !!z.area_components?.length && <section className={card}><h2 className="font-bold">Áreas por âmbito</h2><ul>{z.area_components.map((area, index) => <li key={index}>{JSON.stringify(area)}</li>)}</ul></section>}
|
||||
{zoneExtensionsAvailable && !!z.source_evidence?.length && <section className={card}><h2 className="font-bold">Fontes e o que comprovam</h2><ul>{z.source_evidence.map((evidence, index) => <li key={index}>{JSON.stringify(evidence)}</li>)}</ul></section>}
|
||||
{z.historical_territory?.name && <p>Localização histórica: {z.historical_territory.name}{z.historical_territory.district ? ` · ${z.historical_territory.district}` : ""}{z.historical_territory.province ? ` · ${z.historical_territory.province}` : ""}</p>}
|
||||
{z.activities?.length ? <section className={card}><h2 className="text-xl font-bold">Actividades e sectores referidos</h2><ul>{z.activities.map((activity, index) => <li key={`${activity.name}-${index}`}>{activity.name} · {activity.status === "potential" ? "potencial referido; não confirmado como autorizado" : activity.status === "proposed" ? "proposto; não confirmado como autorizado" : activity.status === "authorized" ? "autorizado segundo a fonte indicada" : activity.status === "conditional" ? "condicionado segundo a fonte indicada" : "excluído segundo a fonte indicada"}{activity.source_reference ? ` · ${activity.source_reference}` : ""}</li>)}</ul></section> : null}
|
||||
{z.resources?.length ? <section className={card}><h2 className="text-xl font-bold">Infra-estruturas e recursos</h2>{z.resources.map((resource, index) => <p key={`${resource.name}-${index}`}>{resource.name} · {resource.status}{resource.source_reference ? ` · ${resource.source_reference}` : ""}</p>)}</section> : null}
|
||||
{locations.length > 0 && <section className={card}><h2 className="text-xl font-bold">Abrangência territorial</h2><ul>{locations.map((location) => <li key={location.id}>{location.name} ({location.location_type}) · {location.scope_type}</li>)}</ul></section>}
|
||||
<ZoneMap id={z.id} />
|
||||
{z.description_en && (
|
||||
<details>
|
||||
@@ -396,6 +613,7 @@ function Editor({
|
||||
</details>
|
||||
)}
|
||||
<p>Operador: {operator ?? "Informação pública por disponibilizar"}</p>
|
||||
<ZoneAttachments zoneId={z.id} attachments={attachments} management={false} zonePublished={z.publication_status === "published"} />
|
||||
{source && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">Fonte e vigência</h2>
|
||||
|
||||
@@ -10,14 +10,26 @@ type Zone = {
|
||||
category: string;
|
||||
description: string | null;
|
||||
province: string | null;
|
||||
district: string | null;
|
||||
version_no: number;
|
||||
publication_status: string;
|
||||
validation_status: string;
|
||||
territory_path?: { id: string; name: string; location_type: string }[];
|
||||
legal_regime?: string | null;
|
||||
operational_status?: string;
|
||||
development_status?: string;
|
||||
availability_status?: string;
|
||||
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 }[];
|
||||
};
|
||||
export default function Zones({
|
||||
records,
|
||||
filters,
|
||||
management,
|
||||
zoneExtensionsAvailable = false,
|
||||
territorySelection = [],
|
||||
}: {
|
||||
records: {
|
||||
@@ -26,12 +38,20 @@ export default function Zones({
|
||||
next_page_url: string | null;
|
||||
prev_page_url: string | null;
|
||||
};
|
||||
filters: { q?: string; category?: 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 [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) {
|
||||
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); });
|
||||
return (
|
||||
<Frame
|
||||
title={management ? "Gestão de ZEE, ZFI e parques" : "ZEE, ZFI e parques industriais"}
|
||||
@@ -59,10 +79,34 @@ export default function Zones({
|
||||
<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>
|
||||
</Field>
|
||||
<Field label="Actividade documentada">
|
||||
<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>
|
||||
</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>}
|
||||
{!records.total && (
|
||||
<p className={card}>
|
||||
Sem registos disponíveis para estes filtros. As zonas aguardam cadastro e
|
||||
@@ -81,8 +125,15 @@ export default function Zones({
|
||||
</h2>
|
||||
<p>
|
||||
{zone.code} · {zone.category.toUpperCase()} ·{" "}
|
||||
{zone.province ?? "Localização por confirmar"}
|
||||
{[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>}
|
||||
<p>{zone.description}</p>
|
||||
<p>Validação: {zone.validation_status}</p>
|
||||
{management && (
|
||||
@@ -134,6 +185,64 @@ export default function Zones({
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Categoria física">
|
||||
<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>
|
||||
</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>
|
||||
<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>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Área (valor) — se documentada">
|
||||
<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>
|
||||
</Field>
|
||||
<Field label="Actividade documentada (opcional)">
|
||||
<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>
|
||||
</Field>
|
||||
<Field label="Designações alternativas">
|
||||
<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} />
|
||||
</Field>
|
||||
<Field label="Distrito histórico">
|
||||
<input name="historical_district" className={input} maxLength={120} />
|
||||
</Field>
|
||||
<Field label="Província histórica">
|
||||
<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} />
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<button className={button} disabled={busy}>
|
||||
Guardar rascunho
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export default function Blank({ disclaimer }: { disclaimer: string }) {
|
||||
return <main className="mx-auto max-w-4xl space-y-6 p-8 print:max-w-none print:p-0">
|
||||
<div className="flex justify-end print:hidden"><button className="rounded border px-4 py-2" onClick={() => window.print()}>Imprimir / guardar como PDF</button></div>
|
||||
<header className="space-y-2 border-b pb-4"><p>InvestMoz · modelo de preparação · versão land-assistance-v1</p><h1 className="text-2xl font-bold">Formulário de orientação e preparação — Terra e DUAT</h1><p>{disclaimer}</p></header>
|
||||
<p>Preencha apenas o que sabe. Use “Não sei” ou “Por confirmar”. Este modelo imprimível não é um PDF electrónico preenchível nem formulário oficial.</p>
|
||||
<Section title="A. Tipo de apoio"><Lines items={['Terra para investimento', 'Habitação', 'Exploração familiar', 'Reconhecimento ou titulação de área ocupada', 'Regularização cadastral', 'Delimitação ou demarcação', 'Alteração de uso/área', 'Transmissão/herança', 'Acompanhamento de processo', 'Conflito/restrição', 'Outro']} /><Line label="Descrição do pedido" /><Line label="Modalidade invocada, se conhecida" /><Line label="Projecto ou oportunidade no InvestMoz" /></Section>
|
||||
<Section title="B. Requerente"><Lines items={['Pessoa singular', 'Pessoa colectiva', 'Comunidade', 'Outra categoria']} /><Line label="Nome ou denominação" /><Line label="Pessoa de contacto" /><Line label="Email" /><Line label="Telefone" /><Line label="Canal preferido de resposta" /><Line label="País/nacionalidade (se aplicável)" /><Line label="Representante, qualidade e fundamento (se aplicável)" /><Line label="NUIT/identificação (apenas se necessário ao acto concreto)" /></Section>
|
||||
<Section title="C. Localização"><Lines items={['Tenho área identificada', 'Procuro localização', 'Preciso de apoio para localizar']} />{['Província','Distrito/município','Posto administrativo','Localidade/bairro/comunidade','Descrição do local','Área e unidade','Referência cadastral (se existente)','Coordenadas/planta (se disponíveis)'].map((label) => <Line key={label} label={label} />)}</Section>
|
||||
<Section title="D. Finalidade e situação conhecida"><Line label="Uso pretendido e actividade, se aplicável" />{['Ocupantes/utilizações conhecidas? Sim / Não segundo informação disponível / Não sei','Descrição','Construções, benfeitorias, machambas, servidões ou usos comunitários?','Título, autorização ou antecedentes?','Conflito, oposição ou possível sobreposição?','Descrição'].map((label) => <Line key={label} label={label} />)}<p>As respostas são declarações do requerente, não conclusões cadastrais.</p></Section>
|
||||
<Section title="E. Processo existente"><Line label="Número oficial, se já atribuído" /><Line label="Entidade receptora e data apresentada" /><Line label="Estado comunicado pela entidade" /><Line label="Pendências e comprovativo disponível" /></Section>
|
||||
<Section title="F. Plano de exploração, se aplicável"><p>Indique períodos livremente; não existe duração obrigatória presumida por este modelo.</p>{['Actividade e período','Área/unidade','Existente ou planeado','Metas e construções','Investimento previsto'].map((label) => <Line key={label} label={label} />)}</Section>
|
||||
<Section title="G. Consulta comunitária e pareceres"><p>Esta secção serve apenas para preparar/registar informação. Não declarar consulta realizada sem evidência.</p>{['Comunidade/local/data','Participantes e funções','Língua/tradução','Intervenções e divergências','Oposição','Acordos e compromissos','Acta, assinaturas e pareceres recebidos'].map((label) => <Line key={label} label={label} />)}</Section>
|
||||
<Section title="H. Documentos opcionais nesta fase"><Lines items={['Planta/esboço','Título ou antecedente','Plano de exploração','Recibo/comunicação oficial','Acta de consulta','Fotografias','Outros']} /><Line label="Informação complementar" /></Section>
|
||||
<footer className="space-y-2 border-t pt-4"><p>Confirmo que os dados correspondem à informação de que disponho e que identifiquei as dúvidas conhecidas.</p><Line label="Data, nome do requerente/representante e assinatura (só na versão impressa, quando aplicável)"/><p className="font-semibold">{disclaimer}</p></footer>
|
||||
<style>{'@media print { button { display: none } section { break-inside: avoid } }'}</style>
|
||||
</main>;
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: ReactNode }) { return <section className="space-y-3 rounded border p-4"><h2 className="text-lg font-bold">{title}</h2>{children}</section>; }
|
||||
function Line({ label }: { label: string }) { return <div className="space-y-1"><span className="text-sm">{label}</span><div className="min-h-8 border-b border-dotted border-slate-500" /></div>; }
|
||||
function Lines({ items }: { items: string[] }) { return <div className="grid gap-2 sm:grid-cols-2">{items.map((item) => <div key={item}>☐ {item}</div>)}</div>; }
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
|
||||
type Props = {
|
||||
case: { id: string; reference: string; version: number; status: string; payload: Record<string, any>; updated_at: string };
|
||||
documents: { id: string; category: string; file_name: string; status: 'active'|'quarantined' }[];
|
||||
events: { action: string; version: number; metadata: Record<string, unknown>; created_at: string }[];
|
||||
disclaimer: string;
|
||||
management: boolean;
|
||||
};
|
||||
const statusLabels: Record<string,string> = { draft:'Rascunho privado', support_requested:'Apoio solicitado ao InvestMoz', internal_review:'Análise interna', waiting_applicant:'A aguardar informação do requerente', referral_prepared:'Encaminhamento preparado (não submetido)', closed:'Encerrado no InvestMoz' };
|
||||
const actionLabels: Record<string,string> = { draft_created:'Rascunho criado', draft_updated:'Rascunho actualizado', support_requested:'Pedido de apoio registado', status_changed:'Estado interno actualizado', attachment_added:'Documento anexado', applicant_update_recorded:'Actualização comunicada pelo requerente' };
|
||||
const categoryLabels: Record<string,string> = { sketch:'Planta/esboço', prior_right:'Antecedente de direito', exploration_plan:'Plano de exploração', official_receipt:'Recibo/comunicação oficial', consultation_minutes:'Acta/minuta', photo:'Fotografia', other:'Outro' };
|
||||
|
||||
export default function LandCase({case: record, documents, events, disclaimer, management}:Props) {
|
||||
const [file,setFile]=useState<File|null>(null);
|
||||
const [category,setCategory]=useState('other');
|
||||
const [status,setStatus]=useState('internal_review');
|
||||
const upload=useForm({version:record.version,category,file:null as File|null});
|
||||
const report=useForm({version:record.version,reported_status:'',official_reference:'',receiving_entity:'',reported_at:''});
|
||||
const change=useForm({version:record.version,status:'internal_review',evidence_reference:''});
|
||||
const canEdit=['draft','waiting_applicant'].includes(record.status);
|
||||
const payload=record.payload??{};
|
||||
const supportKinds:Record<string,string>={investment:'Terra para investimento',home:'Habitação',family_exploitation:'Exploração familiar',recognition:'Reconhecimento/titulação',regularization:'Regularização cadastral',delimitation:'Delimitação/demarcação',change_of_use:'Alteração de uso/área',transfer:'Transmissão/herança',existing_process:'Processo existente',conflict_guidance:'Orientação sobre conflito/restrição',other:'Outro'};
|
||||
return <main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<header className="space-y-2"><Link href="/investidor/terra-duat" className="underline">Os meus pedidos Terra e DUAT</Link><h1 className="text-3xl font-bold">Acompanhamento {record.reference}</h1><p>Referência interna InvestMoz · versão {record.version} · {statusLabels[record.status]??record.status}</p><p className="rounded border border-amber-400 bg-amber-50 p-3">{disclaimer}</p>{record.status==='referral_prepared'&&<p className="rounded bg-amber-50 p-3">O encaminhamento foi preparado internamente. Não há confirmação de submissão nem de recepção por entidade pública.</p>}</header>
|
||||
{!management&&canEdit&&<Link className="inline-block rounded border px-4 py-2" href={`/investidor/terra-duat/${record.id}/editar`}>Continuar preenchimento</Link>}
|
||||
{!management&&<Link className="ml-3 inline-block rounded border px-4 py-2" href={`/investidor/terra-duat/${record.id}/imprimir`}>Imprimir / guardar cópia preenchida como PDF</Link>}
|
||||
<section className="grid gap-4 rounded border p-4 sm:grid-cols-2"><h2 className="sm:col-span-2 text-xl font-semibold">Resumo informado pelo requerente</h2><p><strong>Tipo:</strong> {supportKinds[payload.support_kind]??'Por indicar'}</p><p><strong>Requerente:</strong> {payload.full_name??'Por indicar'}</p><p><strong>Categoria:</strong> {payload.applicant_category??'Por indicar'}</p><p><strong>Contacto preferido:</strong> {payload.preferred_contact??'Por indicar'}</p><p className="sm:col-span-2"><strong>Descrição:</strong> {payload.request_description??'Por indicar'}</p><p className="sm:col-span-2"><strong>Uso pretendido:</strong> {payload.purpose??'Por indicar'}</p><p className="sm:col-span-2"><strong>Localização declarada:</strong> {(payload.parcels??[]).map((parcel:any)=>parcel.place_description).filter(Boolean).join('; ')||'Por localizar/confirmar'}</p><p className="sm:col-span-2 text-sm">Dados e situação geográfica aqui exibidos são declarações do requerente; não confirmam direitos ou disponibilidade cadastral.</p></section>
|
||||
{!management&&<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Comunicar actualização</h2><p className="text-sm">A informação fica identificada como comunicada por si e não é confirmada automaticamente pelo InvestMoz.</p><label className="block space-y-1"><span>Actualização do estado *</span><textarea className="w-full rounded border p-2" value={report.data.reported_status} onChange={e=>report.setData('reported_status',e.target.value)} maxLength={1000}/></label><div className="grid gap-3 sm:grid-cols-3"><label>Referência oficial (se tiver)<input className="mt-1 w-full rounded border p-2" value={report.data.official_reference} onChange={e=>report.setData('official_reference',e.target.value)}/></label><label>Entidade indicada<input className="mt-1 w-full rounded border p-2" value={report.data.receiving_entity} onChange={e=>report.setData('receiving_entity',e.target.value)}/></label><label>Data indicada<input type="date" className="mt-1 w-full rounded border p-2" value={report.data.reported_at} onChange={e=>report.setData('reported_at',e.target.value)}/></label></div><button className="rounded border px-4 py-2" disabled={!report.data.reported_status||report.processing} onClick={()=>router.post(`/investidor/terra-duat/${record.id}/actualizacoes`,report.data,{preserveScroll:true})}>Registar informação comunicada</button></section>}
|
||||
<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Documentos anexados</h2>{documents.map((document)=><p key={document.id}>{document.status==='active'?<a className="underline" href={`/investidor/terra-duat/${record.id}/documentos/${document.id}`}>{categoryLabels[document.category]??document.category}: {document.file_name}</a>:<span>{categoryLabels[document.category]??document.category}: {document.file_name} · em quarentena; leitura/descarga bloqueada até verificação</span>}</p>)}{!documents.length&&<p>Nenhum documento anexado. Anexos são opcionais nesta fase.</p>}{!management&&record.status!=='closed'&&<div className="grid gap-3 sm:grid-cols-3"><label>Categoria<select className="mt-1 w-full rounded border p-2" value={category} onChange={e=>setCategory(e.target.value)}>{Object.entries(categoryLabels).map(([key,label])=><option value={key} key={key}>{label}</option>)}</select></label><label className="sm:col-span-2">Ficheiro PDF/JPG/PNG (até 10 MB)<input className="mt-1 w-full rounded border p-2" type="file" accept=".pdf,.jpg,.jpeg,.png" onChange={e=>setFile(e.target.files?.[0]??null)}/></label><button className="rounded border px-4 py-2" disabled={!file||upload.processing} onClick={()=>router.post(`/investidor/terra-duat/${record.id}/documentos`,{version:record.version,category,file},{forceFormData:true,preserveScroll:true})}>Anexar em espaço privado</button></div>}<p className="text-sm">Os ficheiros são reservados; anexar não equivale a verificação, validação cadastral ou parecer oficial. O ambiente não tem antivírus configurado, por isso os uploads ficam em quarentena e não podem ser descarregados até verificação.</p></section>
|
||||
<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Histórico no InvestMoz</h2>{events.map((event,index)=><div className="border-l-2 pl-3" key={`${event.version}-${index}`}><p className="font-medium">{actionLabels[event.action]??event.action}</p><p className="text-sm">{new Date(event.created_at).toLocaleString('pt-MZ')} · versão {event.version}</p>{event.action==='applicant_update_recorded'&&<p className="text-xs">Actualização comunicada pelo requerente; não verificada externamente.</p>}{event.action==='status_changed'&&event.metadata?.external_submission_confirmed===false&&<p className="text-xs">Transição de estado interno; submissão oficial não confirmada.</p>}</div>)}</section>
|
||||
{management&&<section className="space-y-3 rounded border border-slate-400 p-4"><h2 className="text-xl font-semibold">Gestão interna</h2><label className="block">Estado interno<select className="mt-1 w-full rounded border p-2" value={change.data.status} onChange={e=>change.setData('status',e.target.value)}><option value="internal_review">Análise interna</option><option value="waiting_applicant">A aguardar requerente</option><option value="referral_prepared">Encaminhamento preparado (não enviado)</option><option value="closed">Encerrado no InvestMoz</option></select></label>{change.data.status==='referral_prepared'&&<label className="block">Referência interna da preparação<input className="mt-1 w-full rounded border p-2" value={change.data.evidence_reference} onChange={e=>change.setData('evidence_reference',e.target.value)}/></label>}<button className="rounded bg-slate-800 px-4 py-2 text-white" disabled={change.processing} onClick={()=>router.patch(`/management/terra-duat/${record.id}/estado`,{...change.data,version:record.version},{preserveScroll:true})}>Actualizar estado interno</button></section>}
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { TerritoryFields, type TerritoryOption } from '@/components/investment-territory';
|
||||
|
||||
type Parcel = Record<string, string>;
|
||||
type Payload = Record<string, any>;
|
||||
const emptyParcel = (): Parcel => ({ province_id: '', district_id: '', admin_post_id: '', locality_id: '', place_description: '', area: '', area_unit: '', cadastral_reference: '', coordinates: '', geometry_confidence: 'unknown' });
|
||||
const emptyPayload = (user: { name: string; email: string }): Payload => ({
|
||||
support_kind: '', request_description: '', project_reference: '', applicant_category: '', full_name: user.name ?? '', contact_person: '', email: user.email ?? '', phone: '', preferred_contact: '',
|
||||
country: '', nationality: '', representative_name: '', representative_role: '', representation_basis: '', nuit: '', constitution_or_residency_note: '', area_status: '', parcels: [emptyParcel()],
|
||||
purpose: '', activity: '', known_occupants: 'unknown', occupant_description: '', known_improvements: 'unknown', improvements_description: '', prior_right_status: 'unknown', prior_right_description: '', conflict_status: 'unknown', conflict_description: '',
|
||||
official_process: {}, attachments_to_follow: [], exploration_plan: { activity_rows: [], notes: '' },
|
||||
consultation: { status: 'not_started', participants: [] }, additional_information: '', truth_declaration: false, contact_consent: false,
|
||||
});
|
||||
|
||||
const supportKinds: Record<string, string> = {
|
||||
investment: 'Terra para projecto de investimento', home: 'Orientação para habitação', family_exploitation: 'Exploração familiar', recognition: 'Reconhecimento/titulação de área ocupada', regularization: 'Regularização cadastral', delimitation: 'Delimitação/demarcação', change_of_use: 'Alteração de uso ou área', transfer: 'Transmissão/herança', existing_process: 'Acompanhamento de processo existente', conflict_guidance: 'Esclarecimento sobre conflito/restrição', other: 'Outro',
|
||||
};
|
||||
|
||||
export default function LandForm({ case: existing, user, disclaimer, modelVersion }: { case: { id: string; reference: string; version: number; status: string; payload: Payload } | null; user: { name: string; email: string }; disclaimer: string; modelVersion: string }) {
|
||||
const [step, setStep] = useState(0);
|
||||
const initial = useMemo(() => existing?.payload ?? emptyPayload(user), [existing?.id]);
|
||||
const form = useForm({ version: existing?.version ?? 1, payload: initial });
|
||||
const update = (field: string, value: unknown) => form.setData('payload', { ...form.data.payload, [field]: value });
|
||||
const updateParcel = (index: number, key: string, value: unknown) => {
|
||||
const parcels = [...(form.data.payload.parcels ?? [emptyParcel()])];
|
||||
parcels[index] = { ...parcels[index], [key]: value };
|
||||
update('parcels', parcels);
|
||||
};
|
||||
const text = (key: string, label: string, required = false, type = 'text', help?: string) => <label className="block space-y-1" key={key}><span className="text-sm font-medium">{label}{required ? ' *' : ''}</span><input className="w-full rounded border p-2" type={type} required={required} value={form.data.payload[key] ?? ''} onChange={(event) => update(key, event.target.value)} aria-invalid={Boolean(form.errors[`payload.${key}`])} />{help && <span className="block text-xs text-slate-600">{help}</span>}{form.errors[`payload.${key}`] && <span role="alert" className="text-sm text-red-700">{form.errors[`payload.${key}`]}</span>}</label>;
|
||||
const areaStatus = form.data.payload.area_status;
|
||||
const category = form.data.payload.applicant_category;
|
||||
const current = form.data.payload;
|
||||
const saveUrl = existing ? `/investidor/terra-duat/${existing.id}` : '/investidor/terra-duat';
|
||||
const save = () => existing
|
||||
? form.put(saveUrl, { preserveScroll: true })
|
||||
: form.post(saveUrl, { preserveScroll: true });
|
||||
const support = () => existing && form.post(`/investidor/terra-duat/${existing.id}/solicitar-apoio`, { preserveScroll: true });
|
||||
const canEdit = !existing || ['draft', 'waiting_applicant'].includes(existing.status);
|
||||
|
||||
return <main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<header className="space-y-2"><Link href="/terra-duat" className="underline">Terra e DUAT</Link><h1 className="text-3xl font-bold">Formulário de orientação e preparação</h1><p className="text-sm">Modelo {modelVersion}{existing ? ` · Referência interna ${existing.reference} · versão ${existing.version}` : ''}</p><p className="rounded border border-amber-400 bg-amber-50 p-3">{disclaimer}</p><p className="text-sm">A referência é interna do InvestMoz, não é número oficial de processo. Preencha só o que sabe; documentos são opcionais para pedir orientação.</p></header>
|
||||
<ol className="grid grid-cols-2 gap-2 sm:grid-cols-4" aria-label="Etapas do formulário">{['Pedido e requerente','Localização e situação','Plano e consulta','Rever'].map((title, index) => <li key={title}><button type="button" onClick={() => setStep(index)} aria-current={step === index ? 'step' : undefined} className={`w-full rounded border p-2 text-sm ${step === index ? 'bg-emerald-800 text-white' : ''}`}>{index + 1}. {title}</button></li>)}</ol>
|
||||
{step === 0 && <section className="grid gap-4 rounded border p-4 sm:grid-cols-2"><h2 className="sm:col-span-2 text-xl font-semibold">A. Tipo de apoio e requerente</h2>
|
||||
<label className="space-y-1"><span className="text-sm font-medium">Pretende apoio para *</span><select className="w-full rounded border p-2" required value={current.support_kind ?? ''} onChange={(event) => update('support_kind', event.target.value)}><option value="">Seleccione</option>{Object.entries(supportKinds).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label>
|
||||
{text('request_description', 'Descrição do pedido', true)}{text('project_reference', 'Projecto/oportunidade já registado, se existir')}
|
||||
<label className="space-y-1"><span className="text-sm font-medium">Categoria do requerente *</span><select className="w-full rounded border p-2" required value={current.applicant_category ?? ''} onChange={(event) => update('applicant_category', event.target.value)}><option value="">Seleccione</option><option value="individual">Pessoa singular</option><option value="entity">Pessoa colectiva</option><option value="community">Comunidade</option><option value="other">Outra</option></select></label>
|
||||
{text('full_name', 'Nome ou denominação', true)}{category === 'community' && text('contact_person', 'Pessoa de contacto da comunidade')}{text('email', 'Email (facultativo)', false, 'email')}{text('phone', 'Telefone (facultativo)', false, 'tel')}
|
||||
<label className="space-y-1"><span className="text-sm font-medium">Canal preferido *</span><select className="w-full rounded border p-2" required value={current.preferred_contact ?? ''} onChange={(event) => update('preferred_contact', event.target.value)}><option value="">Seleccione</option><option value="email">Email</option><option value="phone">Telefone</option><option value="any">Qualquer um indicado</option></select></label>
|
||||
{text('country', 'País, se aplicável')}{text('nationality', 'Nacionalidade, se aplicável')}
|
||||
{category === 'entity' && <>{text('representative_name', 'Representante')}{text('representative_role', 'Função/qualidade da representação')}{text('representation_basis', 'Fundamento ou documento de representação (referência)')}{text('constitution_or_residency_note', 'Constituição/residência — detalhe apenas se relevante')}</>}
|
||||
{text('nuit', 'NUIT/identificação — facultativo e apenas se necessário')}
|
||||
</section>}
|
||||
{step === 1 && <section className="space-y-5 rounded border p-4"><h2 className="text-xl font-semibold">B. Localização, finalidade e situação conhecida</h2>
|
||||
<label className="block space-y-1"><span className="text-sm font-medium">Situação da localização *</span><select className="w-full rounded border p-2" required value={current.area_status ?? ''} onChange={(event) => update('area_status', event.target.value)}><option value="">Seleccione</option><option value="identified">Tenho uma área identificada</option><option value="seeking">Procuro uma localização</option><option value="location_support">Preciso de apoio para confirmar/localizar</option><option value="unknown">Ainda não sei</option></select></label>
|
||||
{current.area_status !== 'seeking' && current.area_status !== 'unknown' && (current.parcels ?? []).map((parcel: Parcel, index: number) => <ParcelEditor key={index} index={index} parcel={parcel} onChange={(key, value) => updateParcel(index, key, value)} onRemove={() => update('parcels', current.parcels.filter((_: Parcel, i: number) => i !== index))} />)}
|
||||
{areaStatus !== 'seeking' && <button type="button" className="rounded border px-3 py-2" onClick={() => update('parcels', [...(current.parcels ?? []), emptyParcel()])}>Adicionar outra parcela (até 10)</button>}
|
||||
{text('purpose', 'Uso pretendido *', true)}{text('activity', 'Actividade económica, se aplicável')}
|
||||
<StatusField label="Ocupantes ou utilizações conhecidas?" value={current.known_occupants} choices={['yes','no_as_far_as_known','unknown']} labels={['Sim','Não, segundo a informação disponível','Não sei']} onChange={(v) => update('known_occupants', v)} />
|
||||
{current.known_occupants === 'yes' && text('occupant_description', 'Descrição dos ocupantes/usos')}
|
||||
<StatusField label="Construções, benfeitorias, machambas, servidões ou usos comunitários?" value={current.known_improvements} choices={['yes','unknown','none_identified']} labels={['Sim','Não sei','Não identificados na informação disponível']} onChange={(v) => update('known_improvements', v)} />
|
||||
{current.known_improvements === 'yes' && text('improvements_description', 'Descrição')}
|
||||
<StatusField label="Título, autorização ou antecedentes?" value={current.prior_right_status} choices={['yes','unknown','no_documents']} labels={['Sim','Não sei','Não disponho de documentos']} onChange={(v) => update('prior_right_status', v)} />
|
||||
{current.prior_right_status === 'yes' && text('prior_right_description', 'Descrição/referência dos antecedentes')}
|
||||
<StatusField label="Conflito, oposição ou possível sobreposição conhecida?" value={current.conflict_status} choices={['yes','unknown','no_knowledge']} labels={['Sim','Não sei','Não tenho conhecimento']} onChange={(v) => update('conflict_status', v)} />
|
||||
{current.conflict_status === 'yes' && text('conflict_description', 'Descrição (não constitui resolução de litígio)')}
|
||||
{current.support_kind === 'existing_process' && <fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2"><legend className="font-medium">Processo existente — informação comunicada pelo requerente</legend>{(['official_reference','receiving_entity','presented_at','reported_status','pending_items','proof_available'] as const).map((key) => <label key={key} className="space-y-1"><span>{({official_reference:'Número oficial, se atribuído',receiving_entity:'Entidade receptora',presented_at:'Data de apresentação',reported_status:'Estado comunicado pela entidade',pending_items:'Pendências conhecidas',proof_available:'Comprovativo disponível'})[key]}</span>{key === 'proof_available' ? <select className="w-full rounded border p-2" value={current.official_process?.[key] ?? ''} onChange={(e) => update('official_process',{...current.official_process,[key]:e.target.value})}><option value="">Não sei</option><option value="yes">Sim</option><option value="no">Não</option></select> : <input className="w-full rounded border p-2" type={key === 'presented_at' ? 'date' : 'text'} value={current.official_process?.[key] ?? ''} onChange={(e) => update('official_process',{...current.official_process,[key]:e.target.value})} />}</label>)}</fieldset>}
|
||||
</section>}
|
||||
{step === 2 && <section className="space-y-5 rounded border p-4"><h2 className="text-xl font-semibold">C. Plano de exploração e consulta comunitária (quando aplicável)</h2><p>As tabelas são facultativas. Os períodos são definidos por si; o sistema não impõe cinco anos nem soma áreas repetidas como novas parcelas.</p>
|
||||
{(current.exploration_plan?.activity_rows ?? []).map((row: any, index: number) => <div key={index} className="grid gap-3 rounded border p-3 sm:grid-cols-2"><h3 className="sm:col-span-2 font-semibold">Actividade {index + 1}</h3>{(['period','activity','area','area_unit','stage','targets','structures','investment'] as const).map((key) => <label key={key} className="space-y-1"><span>{({period:'Período',activity:'Actividade',area:'Área (não somada)',area_unit:'Unidade',stage:'Existente/planeado',targets:'Metas',structures:'Construções/vedações',investment:'Investimento previsto'})[key]}</span>{key === 'area_unit' ? <select className="w-full rounded border p-2" value={row[key] ?? ''} onChange={(e) => update('exploration_plan',{...current.exploration_plan,activity_rows:current.exploration_plan.activity_rows.map((r:any,i:number)=>i===index?{...r,[key]:e.target.value}:r)})}><option value="">Por confirmar</option><option value="m2">m²</option><option value="hectares">Hectares</option><option value="other">Outra</option></select> : key === 'stage' ? <select className="w-full rounded border p-2" value={row[key] ?? ''} onChange={(e) => update('exploration_plan',{...current.exploration_plan,activity_rows:current.exploration_plan.activity_rows.map((r:any,i:number)=>i===index?{...r,[key]:e.target.value}:r)})}><option value="">Por confirmar</option><option value="existing">Existente</option><option value="planned">Planeado</option><option value="unknown">Não sei</option></select> : <input className="w-full rounded border p-2" type={['area','investment'].includes(key) ? 'number' : 'text'} min={['area','investment'].includes(key) ? 0 : undefined} value={row[key] ?? ''} onChange={(e) => update('exploration_plan',{...current.exploration_plan,activity_rows:current.exploration_plan.activity_rows.map((r:any,i:number)=>i===index?{...r,[key]:e.target.value}:r)})} />}</label>)}<button type="button" className="text-left text-sm underline" onClick={() => update('exploration_plan',{...current.exploration_plan,activity_rows:current.exploration_plan.activity_rows.filter((_:any,i:number)=>i!==index)})}>Remover linha</button></div>)}
|
||||
{(current.exploration_plan?.activity_rows?.length ?? 0) < 30 && <button type="button" className="rounded border px-3 py-2" onClick={() => update('exploration_plan',{...current.exploration_plan,activity_rows:[...(current.exploration_plan?.activity_rows ?? []),{period:'',activity:'',area:'',area_unit:'',stage:'',targets:'',structures:'',investment:''}]})}>Adicionar período/actividade</button>}
|
||||
<label className="block space-y-1"><span>Notas do plano</span><textarea className="w-full rounded border p-2" value={current.exploration_plan?.notes ?? ''} onChange={(e)=>update('exploration_plan',{...current.exploration_plan,notes:e.target.value})}/></label>
|
||||
<fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2"><legend className="font-semibold">Preparação/acompanhamento de consulta — não preencher como realizada</legend><label><span>Estado comunicado</span><select className="w-full rounded border p-2" value={current.consultation?.status ?? 'not_started'} onChange={(e)=>update('consultation',{...current.consultation,status:e.target.value})}><option value="not_started">Não iniciada</option><option value="preparing">Em preparação</option><option value="reported_completed">Requerente informa que ocorreu</option><option value="unknown">Não sei</option></select></label>{(['community','location','date','facilitators','language','interventions','opposition','agreements','minutes_reference','opinions_received'] as const).map(key=><label className="space-y-1" key={key}><span>{({community:'Comunidade',location:'Local',date:'Data',facilitators:'Responsáveis/facilitadores',language:'Língua/tradução',interventions:'Intervenções e divergências',opposition:'Oposição comunicada',agreements:'Acordos/compromissos comunicados',minutes_reference:'Referência de acta recebida',opinions_received:'Pareceres recebidos'})[key]}</span>{['interventions','opposition','agreements','opinions_received'].includes(key)?<textarea className="w-full rounded border p-2" value={current.consultation?.[key]??''} onChange={e=>update('consultation',{...current.consultation,[key]:e.target.value})}/>:<input className="w-full rounded border p-2" type={key==='date'?'date':'text'} value={current.consultation?.[key]??''} onChange={e=>update('consultation',{...current.consultation,[key]:e.target.value})}/>}</label>)}
|
||||
{(current.consultation?.participants ?? []).map((person:any,index:number)=><div key={index} className="flex gap-2"><input className="w-full rounded border p-2" aria-label="Nome de participante" placeholder="Nome, se aplicável" value={person.name??''} onChange={e=>update('consultation',{...current.consultation,participants:current.consultation.participants.map((p:any,i:number)=>i===index?{...p,name:e.target.value}:p)})}/><input className="w-full rounded border p-2" aria-label="Função de participante" placeholder="Função" value={person.role??''} onChange={e=>update('consultation',{...current.consultation,participants:current.consultation.participants.map((p:any,i:number)=>i===index?{...p,role:e.target.value}:p)})}/></div>)}
|
||||
{(current.consultation?.participants?.length ?? 0)<200 && <button type="button" className="text-sm underline" onClick={()=>update('consultation',{...current.consultation,participants:[...(current.consultation?.participants??[]),{name:'',role:''}]})}>Adicionar participante</button>}
|
||||
</fieldset>
|
||||
</section>}
|
||||
{step === 3 && <section className="space-y-4 rounded border p-4"><h2 className="text-xl font-semibold">D. Rever e pedir apoio</h2><label className="block space-y-1"><span>Informação complementar</span><textarea className="w-full rounded border p-2" value={current.additional_information ?? ''} onChange={(e)=>update('additional_information',e.target.value)} /></label><label className="flex gap-2"><input type="checkbox" checked={Boolean(current.truth_declaration)} onChange={(e)=>update('truth_declaration',e.target.checked)} />Confirmo que as respostas correspondem à informação de que disponho e assinalei dúvidas conhecidas.</label><label className="flex gap-2"><input type="checkbox" checked={Boolean(current.contact_consent)} onChange={(e)=>update('contact_consent',e.target.checked)} />Autorizo o contacto para responder a este pedido. Esta autorização não permite publicação dos documentos.</label><p className="rounded bg-amber-50 p-3 text-sm">Ainda não carregue actas, documentos de identidade ou informações sensíveis que não sejam necessárias à orientação. Os anexos são opcionais e ficam reservados quando enviados.</p><p className="text-sm">O estado da consulta e dos processos externos será sempre apresentado como informação comunicada, não como confirmação oficial.</p></section>}
|
||||
<footer className="flex flex-wrap justify-between gap-3 border-t pt-4"><button type="button" disabled={step===0} className="rounded border px-4 py-2 disabled:opacity-50" onClick={()=>setStep(step-1)}>Anterior</button><div className="flex flex-wrap gap-3"><button type="button" disabled={!canEdit || form.processing} className="rounded border px-4 py-2 disabled:opacity-50" onClick={save}>Guardar rascunho</button>{step<3 ? <button type="button" className="rounded bg-emerald-800 px-4 py-2 text-white" onClick={()=>setStep(step+1)}>Continuar</button> : existing ? <button type="button" disabled={!canEdit || form.processing} className="rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50" onClick={support}>Solicitar apoio</button> : <button type="button" disabled={form.processing} className="rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50" onClick={save}>Guardar rascunho e continuar para solicitar apoio</button>}</div></footer>
|
||||
{Object.keys(form.errors).length>0 && <div role="alert" className="rounded border border-red-500 p-3"><p>Revise os campos assinalados antes de continuar.</p><ul>{Object.entries(form.errors).map(([key,value])=><li key={key}>{String(value)}</li>)}</ul></div>}
|
||||
{existing && <Link href={`/investidor/terra-duat/${existing.id}`} className="underline">Voltar ao acompanhamento</Link>}
|
||||
</main>;
|
||||
}
|
||||
|
||||
function StatusField({label,value,choices,labels,onChange}:{label:string;value:string;choices:string[];labels:string[];onChange:(value:string)=>void}) { return <label className="block space-y-1"><span className="text-sm font-medium">{label}</span><select className="w-full rounded border p-2" value={value??'unknown'} onChange={e=>onChange(e.target.value)}>{choices.map((choice,i)=><option key={choice} value={choice}>{labels[i]}</option>)}</select></label>; }
|
||||
|
||||
function ParcelEditor({index,parcel,onChange,onRemove}:{index:number;parcel:Parcel;onChange:(key:string,value:string)=>void;onRemove:()=>void}) {
|
||||
const [path,setPath]=useState<TerritoryOption[]>([]);
|
||||
useEffect(()=>{
|
||||
const ids=['province_id','district_id','admin_post_id','locality_id'].map(k=>parcel[k]).filter(Boolean);
|
||||
if (!ids.length) { setPath([]); return; }
|
||||
const abort=new AbortController();
|
||||
void (async()=>{const result:TerritoryOption[]=[];let parent='';for(let i=0;i<ids.length;i++){const type=['province','district','admin_post','locality'][i];const params=new URLSearchParams({type,id:ids[i],...(parent?{parent_id:parent}:{})});const response=await fetch(`/api/v1/investment/territory-options?${params}`,{signal:abort.signal,headers:{Accept:'application/json'}});if(!response.ok)break;const body=await response.json();const option=body.data?.[0] as TerritoryOption|undefined;if(!option)break;result.push(option);parent=option.id;}if(!abort.signal.aborted)setPath(result);})().catch(()=>{});
|
||||
return ()=>abort.abort();
|
||||
},[]);
|
||||
const initial=useMemo(()=>path,[path]);
|
||||
return <fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2"><legend className="px-1 font-semibold">Parcela/área {index+1}</legend><div className="sm:col-span-2"><TerritoryFields initial={initial} endpoint="/api/v1/investment/territory-options" onChange={(next)=>{(['province_id','district_id','admin_post_id','locality_id'] as const).forEach((field,i)=>onChange(field,next[i]?.id??''));}} /></div>
|
||||
<label className="space-y-1"><span>Área estimada (se conhecida)</span><input type="number" min="0" className="w-full rounded border p-2" value={parcel.area??''} onChange={e=>onChange('area',e.target.value)}/></label><label className="space-y-1"><span>Unidade</span><select className="w-full rounded border p-2" value={parcel.area_unit??''} onChange={e=>onChange('area_unit',e.target.value)}><option value="">Por confirmar</option><option value="m2">m²</option><option value="hectares">Hectares</option><option value="other">Outra</option><option value="unknown">Não sei</option></select></label>
|
||||
<label className="space-y-1"><span>Referência cadastral, se existente</span><input className="w-full rounded border p-2" value={parcel.cadastral_reference??''} onChange={e=>onChange('cadastral_reference',e.target.value)}/></label><label className="space-y-1"><span>Coordenadas ou planta, se disponíveis</span><input className="w-full rounded border p-2" value={parcel.coordinates??''} onChange={e=>onChange('coordinates',e.target.value)}/></label><label className="space-y-1"><span>Precisão indicada</span><select className="w-full rounded border p-2" value={parcel.geometry_confidence??'unknown'} onChange={e=>onChange('geometry_confidence',e.target.value)}><option value="declared">Declarada pelo requerente</option><option value="approximate">Aproximada</option><option value="confirmed_by_authority">Confirmada por entidade, segundo documento referido</option><option value="unknown">Por confirmar</option></select></label><label className="space-y-1 sm:col-span-2"><span>Descrição do local</span><textarea className="w-full rounded border p-2" value={parcel.place_description??''} onChange={e=>onChange('place_description',e.target.value)}/></label><button type="button" className="text-left text-sm underline" onClick={onRemove}>Remover parcela</button><p className="text-xs text-slate-600">A selecção territorial e qualquer intersecção cartográfica não confirmam direitos, limites ou disponibilidade.</p>
|
||||
</fieldset>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
|
||||
export default function Guide({ disclaimer }: { disclaimer: string }) {
|
||||
return <main className="mx-auto max-w-5xl space-y-8 p-6 print:p-0">
|
||||
<header className="space-y-3">
|
||||
<p className="text-sm font-semibold uppercase tracking-wide">InvestMoz · orientação informativa</p>
|
||||
<h1 className="text-3xl font-bold">Terra e DUAT</h1>
|
||||
<p>Prepare informação sobre uma área, um pedido ou um processo que já acompanha. Pode indicar dúvidas e dados por confirmar.</p>
|
||||
<p className="rounded border border-amber-400 bg-amber-50 p-4 text-sm">{disclaimer}</p>
|
||||
</header>
|
||||
<section className="grid gap-4 md:grid-cols-3">
|
||||
<article className="rounded border p-4"><h2 className="font-semibold">Preparar informação</h2><p>Identifique a finalidade, o requerente, a localização conhecida e os antecedentes que tiver.</p></article>
|
||||
<article className="rounded border p-4"><h2 className="font-semibold">Organizar documentos</h2><p>Anexos são opcionais nesta fase. A lista não substitui os requisitos confirmados pela entidade competente.</p></article>
|
||||
<article className="rounded border p-4"><h2 className="font-semibold">Acompanhar</h2><p>Guarde uma referência interna e registe separadamente informações comunicadas por si e diligências internas.</p></article>
|
||||
</section>
|
||||
<p className="rounded bg-slate-50 p-4">Não inferimos que uma área está livre, que não existem direitos ou conflitos, nem que um registo ou mapa confirma titularidade. O InvestMoz não atribui DUAT nem substitui a autoridade pública.</p>
|
||||
<nav className="flex flex-wrap gap-4">
|
||||
<Link className="rounded bg-emerald-800 px-4 py-3 text-white" href="/investidor/terra-duat/novo">Preencher no portal</Link>
|
||||
<Link className="rounded border px-4 py-3" href="/terra-duat/formulario-em-branco">Descarregar formulário em branco (imprimir/guardar como PDF)</Link>
|
||||
<Link className="rounded border px-4 py-3" href="/apoio">Solicitar apoio geral</Link>
|
||||
</nav>
|
||||
<details className="rounded border p-4"><summary className="cursor-pointer font-semibold">Estado das fontes e requisitos</summary><p className="mt-3">Os modelos digitalizados estão inventariados como referências reservadas. Conteúdo, actualidade e requisitos legais aguardam OCR, conferência oficial e revisão. Não use esta orientação como checklist oficial.</p></details>
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
type Row={id:string;reference:string;status:string;version:number;applicant:string|null;updated_at:string};
|
||||
const labels:Record<string,string>={draft:'Rascunho',support_requested:'Apoio solicitado',internal_review:'Análise interna',waiting_applicant:'A aguardar requerente',referral_prepared:'Encaminhamento preparado (não enviado)',closed:'Encerrado'};
|
||||
export default function Management({cases}:{cases:{data:Row[];prev_page_url:string|null;next_page_url:string|null}}){return <main className="mx-auto max-w-6xl space-y-6 p-6"><header><h1 className="text-3xl font-bold">Gestão — Terra e DUAT</h1><p>Fila interna. Não representa protocolo com autoridade pública.</p></header><div className="overflow-x-auto"><table className="w-full border-collapse text-left"><thead><tr><th className="border p-2">Referência interna</th><th className="border p-2">Requerente</th><th className="border p-2">Estado InvestMoz</th><th className="border p-2">Versão/actualização</th><th className="border p-2">Acção</th></tr></thead><tbody>{cases.data.map(row=><tr key={row.id}><td className="border p-2">{row.reference}</td><td className="border p-2">{row.applicant??'—'}</td><td className="border p-2">{labels[row.status]??row.status}</td><td className="border p-2">{row.version} · {new Date(row.updated_at).toLocaleString('pt-MZ')}</td><td className="border p-2"><Link className="underline" href={`/management/terra-duat/${row.id}`}>Abrir</Link></td></tr>)}</tbody></table></div>{!cases.data.length&&<p>Sem pedidos registados.</p>}<nav className="flex gap-4">{cases.prev_page_url&&<Link href={cases.prev_page_url}>Anterior</Link>}{cases.next_page_url&&<Link href={cases.next_page_url}>Seguinte</Link>}</nav></main>;}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,4 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
type CaseRow={id:string;reference:string;status:string;version:number;updated_at:string};
|
||||
const labels:Record<string,string>={draft:'Rascunho privado',support_requested:'Apoio solicitado ao InvestMoz',internal_review:'Análise interna',waiting_applicant:'A aguardar informação',referral_prepared:'Encaminhamento preparado (não enviado)',closed:'Encerrado no InvestMoz'};
|
||||
export default function Workspace({cases}:{cases:{data:CaseRow[];prev_page_url:string|null;next_page_url:string|null}}){return <main className="mx-auto max-w-5xl space-y-6 p-6"><header><h1 className="text-3xl font-bold">Os meus pedidos — Terra e DUAT</h1><p>As referências e estados são internos do InvestMoz.</p></header><Link className="inline-block rounded bg-emerald-800 px-4 py-3 text-white" href="/terra-duat">Orientação Terra e DUAT</Link> <Link className="ml-2 inline-block rounded border px-4 py-3" href="/investidor/terra-duat/novo">Preparar novo pedido</Link><section className="space-y-3">{cases.data.map((record)=><article key={record.id} className="rounded border p-4"><Link href={`/investidor/terra-duat/${record.id}`} className="font-semibold underline">{record.reference}</Link><p>{labels[record.status]??record.status} · versão {record.version}</p><p className="text-sm">Actualizado {new Date(record.updated_at).toLocaleString('pt-MZ')}</p></article>)}{!cases.data.length&&<p>Ainda não tem rascunhos ou pedidos de apoio.</p>}</section><nav className="flex gap-4">{cases.prev_page_url&&<Link href={cases.prev_page_url}>Anterior</Link>}{cases.next_page_url&&<Link href={cases.next_page_url}>Seguinte</Link>}</nav></main>;}
|
||||
@@ -10,22 +10,27 @@ type Record = {
|
||||
slug: string;
|
||||
is_active?: boolean;
|
||||
status?: string;
|
||||
geography_scope?: string;
|
||||
primary_territory?: { name: string; location_type: string; source_system?: string; source_code?: string | null } | null;
|
||||
};
|
||||
export default function Catalog({
|
||||
resource,
|
||||
records,
|
||||
filters,
|
||||
sectors,
|
||||
geographyReviewCount = 0,
|
||||
}: {
|
||||
resource: 'sectors' | 'opportunities';
|
||||
records: Paginated<Record>;
|
||||
filters: { q?: string; status?: string; sector_id?: number | string };
|
||||
filters: { q?: string; status?: string; sector_id?: number | string; geography_scope?: string };
|
||||
sectors: { id: number; name: string }[];
|
||||
geographyReviewCount?: number;
|
||||
}) {
|
||||
const form = useForm({
|
||||
q: filters.q ?? '',
|
||||
status: filters.status ?? '',
|
||||
sector_id: String(filters.sector_id ?? ''),
|
||||
geography_scope: filters.geography_scope ?? '',
|
||||
});
|
||||
return (
|
||||
<Management
|
||||
@@ -34,6 +39,11 @@ export default function Catalog({
|
||||
<Link className={button} href={`/management/${resource}/create`}>
|
||||
Criar {resource === 'sectors' ? 'sector' : 'oportunidade'}
|
||||
</Link>
|
||||
{resource === 'opportunities' && (
|
||||
<p role="status" className="my-3">
|
||||
{geographyReviewCount} oportunidade(s) aguardam confirmação do âmbito geográfico. A lista não altera localizações; confirme apenas com fontes existentes.
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(event) => {
|
||||
@@ -74,6 +84,7 @@ export default function Catalog({
|
||||
))}
|
||||
</select>
|
||||
{resource === 'opportunities' && (
|
||||
<>
|
||||
<select
|
||||
aria-label="Sector"
|
||||
className={`${control} max-w-xs`}
|
||||
@@ -89,6 +100,20 @@ export default function Catalog({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="Âmbito geográfico"
|
||||
className={`${control} max-w-xs`}
|
||||
value={form.data.geography_scope}
|
||||
onChange={(event) => form.setData('geography_scope', event.target.value)}
|
||||
>
|
||||
<option value="">Todos os âmbitos</option>
|
||||
<option value="unspecified">Pendente de confirmação</option>
|
||||
<option value="specific">Localização específica</option>
|
||||
<option value="multiple">Várias localizações</option>
|
||||
<option value="national">Âmbito nacional</option>
|
||||
<option value="digital">Digital/sem instalação definida</option>
|
||||
</select>
|
||||
</>
|
||||
)}
|
||||
<button className={button} disabled={form.processing}>
|
||||
Pesquisar
|
||||
@@ -123,6 +148,11 @@ export default function Catalog({
|
||||
: 'Inactivo'
|
||||
: states[record.status ?? 'draft']}
|
||||
</p>
|
||||
{resource === 'opportunities' && record.geography_scope === 'unspecified' && (
|
||||
<p className="mt-1 text-sm">
|
||||
Pendente de confirmação; território já registado: {record.primary_territory?.name ?? 'nenhum'}. Fonte do território: {record.primary_territory?.source_system ?? 'não indicada'}{record.primary_territory?.source_code ? `, código ${record.primary_territory.source_code}` : ''}. A classificação não é alterada automaticamente.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
className="underline"
|
||||
|
||||
@@ -67,6 +67,7 @@ export default function Editor({
|
||||
initial.maturity_level = String(record?.maturity_level ?? "");
|
||||
initial.status = String(record?.status ?? "draft");
|
||||
initial.is_featured = Boolean(record?.is_featured ?? false);
|
||||
initial.geography_scope = String(record?.geography_scope ?? "unspecified");
|
||||
initial.territory_version = String(record?.territory_version ?? 0);
|
||||
["province_id", "district_id", "admin_post_id", "locality_id"].forEach((field, index) => {
|
||||
initial[field] = territoryPath[index]?.id ?? "";
|
||||
@@ -180,6 +181,22 @@ export default function Editor({
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Âmbito geográfico" error={form.errors.geography_scope}>
|
||||
<select className={control} value={String(form.data.geography_scope)} onChange={(e) => {
|
||||
form.setData("geography_scope", e.target.value);
|
||||
if (e.target.value === "national" || e.target.value === "digital") {
|
||||
setCreationPath([]);
|
||||
form.setData((data) => ({ ...data, geography_scope: e.target.value,
|
||||
province_id: "", district_id: "", admin_post_id: "", locality_id: "" }));
|
||||
}
|
||||
}}>
|
||||
<option value="unspecified">Não especificado</option>
|
||||
<option value="specific">Localização específica</option>
|
||||
<option value="multiple">Várias localizações</option>
|
||||
<option value="national">Âmbito nacional</option>
|
||||
<option value="digital">Digital/sem instalação definida</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Estado" error={form.errors.status}>
|
||||
<select
|
||||
className={control}
|
||||
|
||||
@@ -45,7 +45,8 @@ type Consent = { purpose: string; policy_version: string | null; status: string;
|
||||
|
||||
export default function InterestDetail({ interest, history = [], assignees = [], consents = [] }: { interest: Interest; history?: Transition[]; assignees?: Assignee[]; consents?: Consent[] }) {
|
||||
const form = useForm({ status: interest.status, note: "", next_action: interest.next_action ?? "", next_action_due_at: interest.next_action_due_at?.slice(0, 10) ?? "", assigned_to: interest.assigned_to?.toString() ?? "" });
|
||||
const consentForm = useForm({ reason: "" });
|
||||
const contactConsentForm = useForm({ reason: "" });
|
||||
const sharingConsentForm = useForm({ reason: "" });
|
||||
const rows: [string, string | number | null][] = [
|
||||
["Nome", interest.full_name],
|
||||
["Email", interest.email],
|
||||
@@ -111,15 +112,26 @@ export default function InterestDetail({ interest, history = [], assignees = [],
|
||||
{consent.withdrawn_at && <p className="text-sm">Revogado {dateTime(consent.withdrawn_at)}</p>}
|
||||
</article>
|
||||
))}
|
||||
{consents.some((consent) => consent.purpose === "respond_to_interest" && consent.status === "granted") && (
|
||||
<form className="max-w-sm space-y-3" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
contactConsentForm.patch(`/management/interests/${interest.id}/consent/contact`);
|
||||
}}>
|
||||
<Field label="Motivo do pedido de revogação" error={contactConsentForm.errors.reason}>
|
||||
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={contactConsentForm.data.reason} onChange={(event) => contactConsentForm.setData("reason", event.target.value)} />
|
||||
</Field>
|
||||
<button className={button} disabled={contactConsentForm.processing}>Revogar autorização de contacto</button>
|
||||
</form>
|
||||
)}
|
||||
{consents.some((consent) => consent.purpose === "share_contact_with_proponent" && consent.status === "granted") && (
|
||||
<form className="max-w-sm space-y-3" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
consentForm.patch(`/management/interests/${interest.id}/consent/proponent`);
|
||||
sharingConsentForm.patch(`/management/interests/${interest.id}/consent/proponent`);
|
||||
}}>
|
||||
<Field label="Motivo do pedido de revogação" error={consentForm.errors.reason}>
|
||||
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={consentForm.data.reason} onChange={(event) => consentForm.setData("reason", event.target.value)} />
|
||||
<Field label="Motivo do pedido de revogação" error={sharingConsentForm.errors.reason}>
|
||||
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={sharingConsentForm.data.reason} onChange={(event) => sharingConsentForm.setData("reason", event.target.value)} />
|
||||
</Field>
|
||||
<button className={button} disabled={consentForm.processing}>Revogar autorização de partilha</button>
|
||||
<button className={button} disabled={sharingConsentForm.processing}>Revogar autorização de partilha</button>
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -53,6 +53,7 @@ export function Management({ title, children }: { title: string; children: React
|
||||
<Link href="/management/crm/investors">Investidores</Link>
|
||||
<Link href="/management/projects">Projectos</Link>
|
||||
<Link href="/management/clusters">Clusters</Link>
|
||||
<Link href="/management/corridors">Corredores</Link>
|
||||
<Link href="/management/territory-associations">
|
||||
Localizações dos investimentos
|
||||
</Link>
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
|
||||
type DocumentResource = {
|
||||
title: string;
|
||||
description: string | null;
|
||||
category: string;
|
||||
topic: string;
|
||||
document_type: string;
|
||||
document_number: string | null;
|
||||
document_date: string | null;
|
||||
applicable_from: string | null;
|
||||
applicable_until: string | null;
|
||||
source_url: string | null;
|
||||
language: string;
|
||||
version_label: string | null;
|
||||
territorial_scope: string;
|
||||
territory_name: string | null;
|
||||
source_confirmation: string;
|
||||
legal_status: string;
|
||||
source_reference: string;
|
||||
issuer: string | null;
|
||||
file_name: string;
|
||||
size_bytes: number | null;
|
||||
view_url: string | null;
|
||||
links: {
|
||||
target_type: string;
|
||||
target_key: string;
|
||||
relationship: string;
|
||||
applicability: string;
|
||||
condition_text: string | null;
|
||||
basis_reference: string | null;
|
||||
review_status: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
const modulePaths: Record<string, { href: string; label: string }> = {
|
||||
simulator: { href: '/Simulador', label: 'Simulador fiscal' },
|
||||
investment: { href: '/oportunidades', label: 'Oportunidades de investimento' },
|
||||
zones: { href: '/zonas', label: 'ZEE, ZFI e parques industriais' },
|
||||
education: { href: '/educacao', label: 'Educação e competências' },
|
||||
business: { href: '/negocios', label: 'Negócios' },
|
||||
land: { href: '/investidor/terra-duat', label: 'Terra e DUAT' },
|
||||
};
|
||||
const documentTypeLabels: Record<string, string> = {
|
||||
legislation: 'Legislação', procedure: 'Procedimento oficial', official_form: 'Formulário oficial',
|
||||
digital_adaptation: 'Adaptação digital de formulário', guidance_template: 'Modelo orientativo',
|
||||
guide: 'Guia', study: 'Estudo', reference_data: 'Dados de referência', unknown: 'Tipo por classificar',
|
||||
};
|
||||
const legalStatusLabels: Record<string, string> = {
|
||||
not_applicable: 'Não aplicável', in_force: 'Vigência indicada; confirme o período', historical: 'Histórico',
|
||||
proposed: 'Proposta; não é norma vigente', repealed: 'Revogada', amended: 'Alterada; consulte alterações posteriores', unknown: 'Por confirmar',
|
||||
};
|
||||
|
||||
export default function DocumentPage({
|
||||
resource,
|
||||
backUrl,
|
||||
downloadUrl,
|
||||
}: {
|
||||
resource: DocumentResource;
|
||||
backUrl: string;
|
||||
downloadUrl: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 text-slate-900">
|
||||
<Head title={resource.title} />
|
||||
<PortalMenu />
|
||||
<main className="mx-auto max-w-4xl space-y-6 px-5 py-10">
|
||||
<Link className="underline" href={backUrl}>← Voltar à pesquisa</Link>
|
||||
<article className="space-y-5 rounded-xl border bg-white p-5 sm:p-8">
|
||||
<header className="space-y-2">
|
||||
<p className="text-sm text-slate-600">{resource.category} · {resource.topic}</p>
|
||||
<h1 className="break-words text-3xl font-bold">{resource.title}</h1>
|
||||
{resource.description && <p className="whitespace-pre-line">{resource.description}</p>}
|
||||
</header>
|
||||
<dl className="grid gap-4 sm:grid-cols-2">
|
||||
<div><dt className="font-semibold">Tipo documental</dt><dd>{documentTypeLabels[resource.document_type] ?? resource.document_type}</dd></div>
|
||||
<div><dt className="font-semibold">Entidade emitente / autor</dt><dd>{resource.issuer ?? 'Não indicada'}</dd></div>
|
||||
<div><dt className="font-semibold">Número e data</dt><dd>{[resource.document_number, resource.document_date].filter(Boolean).join(' · ') || 'Não indicados'}</dd></div>
|
||||
<div><dt className="font-semibold">Período de aplicação documentado</dt><dd>{resource.applicable_from || resource.applicable_until ? `${resource.applicable_from ?? 'Início não indicado'} — ${resource.applicable_until ?? 'Sem data final indicada'}` : 'Não registado'}</dd></div>
|
||||
<div><dt className="font-semibold">Versão e idioma</dt><dd>{resource.version_label ?? 'Versão não indicada'} · {resource.language}</dd></div>
|
||||
<div><dt className="font-semibold">Âmbito</dt><dd>{resource.territorial_scope === 'national' ? 'Nacional' : resource.territory_name ?? 'Por confirmar'}</dd></div>
|
||||
<div><dt className="font-semibold">Situação documental</dt><dd>{legalStatusLabels[resource.legal_status] ?? resource.legal_status}</dd></div>
|
||||
<div><dt className="font-semibold">Fonte</dt><dd>{resource.source_confirmation === 'official_confirmed' ? 'Fonte oficial confirmada' : resource.source_confirmation === 'identified' ? 'Origem identificada' : 'Por confirmar'}</dd></div>
|
||||
</dl>
|
||||
<p className="break-words text-sm">Referência: {resource.source_reference}</p>
|
||||
{resource.links.length > 0 && <section className="space-y-2">
|
||||
<h2 className="text-xl font-semibold">Base legal e documentos relacionados no portal</h2>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
{resource.links.map((link, index) => {
|
||||
const destination = link.target_type === 'module' ? modulePaths[link.target_key] : undefined;
|
||||
return <li key={`${link.target_type}-${link.target_key}-${index}`}>
|
||||
{destination ? <Link className="underline" href={destination.href}>{destination.label}</Link> : <span>{link.target_type === 'requirement' ? `Requisito documental: ${link.target_key}` : `${link.target_type}: ${link.target_key}`}</span>}
|
||||
{' · '}{link.applicability === 'evidence' ? 'evidência documental' : link.applicability}
|
||||
{link.condition_text && <span> · Condição: {link.condition_text}</span>}
|
||||
{link.basis_reference && <span> · Referência documental (não é regra fiscal): {link.basis_reference}</span>}
|
||||
{link.review_status === 'confirmed' ? <span> · Citação conferida no ficheiro; aplicação fiscal pendente</span> : <span> · Pendente de conferência; não constitui fundamento confirmado</span>}
|
||||
</li>;
|
||||
})}
|
||||
</ul>
|
||||
</section>}
|
||||
<div className="flex flex-wrap gap-3 border-t pt-4">
|
||||
<a className="rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white" href={downloadUrl}>Descarregar ficheiro ({resource.file_name}{resource.size_bytes ? ` · ${Math.ceil(resource.size_bytes / 1024)} KB` : ''})</a>
|
||||
{resource.view_url && <a className="rounded-lg border px-5 py-3 font-semibold underline" href={resource.view_url} target="_blank" rel="noreferrer">Consultar ficheiro</a>}
|
||||
{resource.source_url && <a className="rounded-lg border px-5 py-3 font-semibold underline" href={resource.source_url} target="_blank" rel="noreferrer">Abrir fonte identificada</a>}
|
||||
</div>
|
||||
<p className="text-sm text-slate-600">A disponibilização desta referência não certifica vigência, elegibilidade, viabilidade ou aprovação oficial. Consulte o diploma ou a entidade competente para confirmar a sua aplicação ao caso concreto.</p>
|
||||
</article>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+1031
-294
File diff suppressed because it is too large
Load Diff
@@ -3,16 +3,19 @@ import { Management } from '../management/shared';
|
||||
import type { Paginated } from '../management/shared';
|
||||
import { Layout, Field, control, button, Pagination, kind } from './shared';
|
||||
import type { Dossier } from './shared';
|
||||
import { TerritoryFields, type TerritoryOption } from '@/components/investment-territory';
|
||||
export default function Index({
|
||||
records,
|
||||
management,
|
||||
filters,
|
||||
territorySelection = [],
|
||||
}: {
|
||||
records: Paginated<Dossier>;
|
||||
management: boolean;
|
||||
filters: { q?: string; kind?: string };
|
||||
filters: { q?: string; kind?: string; province_id?: string; district_id?: string; admin_post_id?: string; locality_id?: string };
|
||||
territorySelection?: TerritoryOption[];
|
||||
}) {
|
||||
const form = useForm({ q: filters.q ?? '', kind: filters.kind ?? '' });
|
||||
const form = useForm({ q: filters.q ?? '', kind: filters.kind ?? '', province_id: filters.province_id ?? '', district_id: filters.district_id ?? '', admin_post_id: filters.admin_post_id ?? '', locality_id: filters.locality_id ?? '' });
|
||||
const base = management ? '/management/portfolio' : '/carteira';
|
||||
const Frame = management ? Management : Layout;
|
||||
return (
|
||||
@@ -54,6 +57,7 @@ export default function Index({
|
||||
<option value="project">Projectos âncora</option>
|
||||
</select>
|
||||
</Field>
|
||||
<TerritoryFields initial={territorySelection} onChange={(path) => form.setData((current) => ({ ...current, 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>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
@@ -80,6 +84,7 @@ export default function Index({
|
||||
r.content.focus ??
|
||||
r.content.anchors}
|
||||
</p>
|
||||
{(r.content.location || r.content.region) && <p>Localização: {r.content.location ?? r.content.region}</p>}
|
||||
{r.content.priority && (
|
||||
<p>
|
||||
{r.content.priority}{' '}
|
||||
@@ -95,7 +100,15 @@ export default function Index({
|
||||
))}
|
||||
</div>
|
||||
{!records.data.length && (
|
||||
<p>Ainda não existem fichas publicadas para esta pesquisa.</p>
|
||||
<div className="space-y-3 rounded-xl border p-5" role="status">
|
||||
<p>Ainda não existem fichas publicadas para esta pesquisa. Os filtros activos foram mantidos.</p>
|
||||
<p>Esta lista contém dossiers territoriais documentados; não representa concursos abertos nem confirma disponibilidade de infra-estruturas ou incentivos.</p>
|
||||
<nav aria-label="Alternativas de exploração" className="flex flex-wrap gap-4">
|
||||
<Link className="underline" href="/oportunidades">Ver oportunidades publicadas</Link>
|
||||
<Link className="underline" href="/zonas">Consultar ZEE, ZFI e parques</Link>
|
||||
<Link className="underline" href="/Simulador">Transformar uma ideia num projecto</Link>
|
||||
</nav>
|
||||
</div>
|
||||
)}
|
||||
<Pagination page={records} />
|
||||
</Frame>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Link, useForm, router } from "@inertiajs/react";
|
||||
import { Link, useForm, router, usePage } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import InvestmentMapPanel from "@/components/investment-map-panel";
|
||||
import { Management } from "../management/shared";
|
||||
import { Layout, Field, control, button, labels, kind } from "./shared";
|
||||
@@ -8,6 +9,8 @@ export default function Show(props: Props) {
|
||||
}
|
||||
|
||||
type Props = {
|
||||
existingSubmissions?: { id: string; version: number; updated_at: string }[];
|
||||
anchorProject?: { code: string; name: string; status: string; budget_amount: string | null; budget_currency: string | null; start_date: string | null; end_date: string | null } | null;
|
||||
zones?: {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -31,7 +34,11 @@ function Editor({
|
||||
opportunities = [],
|
||||
chains = [],
|
||||
zones = [],
|
||||
anchorProject = null,
|
||||
existingSubmissions = [],
|
||||
}: Props) {
|
||||
const { auth } = usePage<{ auth: { user: unknown } }>().props;
|
||||
const [creatingManifestation, setCreatingManifestation] = useState(false);
|
||||
const form = useForm({
|
||||
title: record.title,
|
||||
source: record.source,
|
||||
@@ -48,6 +55,22 @@ function Editor({
|
||||
{kind(record)} · {record.content.code}
|
||||
</p>
|
||||
<p className="text-sm">Fonte: {record.source}</p>
|
||||
{anchorProject && (
|
||||
<section className="space-y-2 rounded-xl border p-5" aria-labelledby="anchor-project-heading">
|
||||
<h2 id="anchor-project-heading" className="text-xl font-bold">Referência de projecto âncora</h2>
|
||||
<p>{anchorProject.code} · {anchorProject.name}</p>
|
||||
<p>Estado registado: {{ draft: "rascunho", planned: "previsto", active: "em execução", suspended: "suspenso", completed: "concluído", cancelled: "cancelado" }[anchorProject.status] ?? "por confirmar"}.</p>
|
||||
{anchorProject.budget_amount && <p>Investimento estimado documentado: {anchorProject.budget_amount} {anchorProject.budget_currency}</p>}
|
||||
{(anchorProject.start_date || anchorProject.end_date) && <p>Calendário registado: {anchorProject.start_date ?? "início não indicado"} – {anchorProject.end_date ?? "fim não indicado"}</p>}
|
||||
<p>Esta é uma referência de planeamento. Não significa concurso aberto, disponibilidade imediata ou convite à apresentação de propostas.</p>
|
||||
</section>
|
||||
)}
|
||||
{record.project_id && !anchorProject && (
|
||||
<section className="space-y-2 rounded-xl border p-5" aria-labelledby="anchor-status-pending-heading">
|
||||
<h2 id="anchor-status-pending-heading" className="text-xl font-bold">Referência de projecto âncora</h2>
|
||||
<p>O estado de execução e o investimento não estão confirmados num registo publicável. A referência do dossier não representa concurso aberto nem disponibilidade imediata.</p>
|
||||
</section>
|
||||
)}
|
||||
{!management && (record.cluster_id || record.corridor_id || record.project_id) && (
|
||||
<InvestmentMapPanel
|
||||
filters={
|
||||
@@ -73,16 +96,32 @@ function Editor({
|
||||
</section>
|
||||
)}
|
||||
{origin && <p>Exploração iniciada em: {origin.title}</p>}
|
||||
{!management && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post("/investidor/manifestacoes", { dossier_id: record.id })
|
||||
}
|
||||
>
|
||||
Preparar manifestação com necessidades e anexos
|
||||
</button>
|
||||
{!management && auth.user && (
|
||||
<div className="space-y-2 rounded-xl border p-4">
|
||||
<p>As manifestações ficam privadas até uma submissão separada. A referência não copia nem publica o dossier público no seu nome.</p>
|
||||
{existingSubmissions.length > 0 && (
|
||||
<section className="space-y-2" aria-label="Manifestações em rascunho para esta ficha">
|
||||
<h2 className="font-semibold">Continuar um rascunho existente</h2>
|
||||
{existingSubmissions.map((submission) => <Link key={submission.id} className="block underline" href={`/investidor/manifestacoes/${submission.id}`}>Continuar rascunho actualizado em {new Date(submission.updated_at).toLocaleDateString("pt-MZ")}</Link>)}
|
||||
<p>Ou crie outra manifestação privada. Os rascunhos não serão fundidos.</p>
|
||||
</section>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={creatingManifestation}
|
||||
onClick={() => {
|
||||
if (!window.confirm(`Criar ${existingSubmissions.length ? "outra" : "uma"} manifestação privada associada a “${record.title}”? Pode continuar a editá-la antes de submeter. Os rascunhos existentes não serão alterados.`)) return;
|
||||
setCreatingManifestation(true);
|
||||
router.post("/investidor/manifestacoes", { dossier_id: record.id }, { onFinish: () => setCreatingManifestation(false) });
|
||||
}}
|
||||
>
|
||||
{creatingManifestation ? "A preparar…" : "Preparar manifestação privada"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!management && !auth.user && (
|
||||
<p className="rounded-xl border p-4">Para associar esta referência a uma manifestação privada, entre na sua conta. Esta ficha continuará pública e não será copiada nem publicada no seu nome. <Link className="underline" href="/login">Entrar</Link></p>
|
||||
)}
|
||||
{chains.length > 0 && (
|
||||
<section>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { Link, router, useForm } from "@inertiajs/react";
|
||||
import InvestmentTerritory, { TerritoryFields } from "@/components/investment-territory";
|
||||
import { Management, Field, button, control } from "../management/shared";
|
||||
import { titles, statuses, stages, roles } from "./types";
|
||||
@@ -65,6 +65,7 @@ export default function Editor({
|
||||
structure,
|
||||
record,
|
||||
projects,
|
||||
viewerId,
|
||||
chains,
|
||||
memberships,
|
||||
chainLinks,
|
||||
@@ -73,6 +74,7 @@ export default function Editor({
|
||||
structure: Structure;
|
||||
record: StructureRecord | null;
|
||||
projects: { id: string; name: string; code: string }[];
|
||||
viewerId: number;
|
||||
chains: Chain[];
|
||||
chainLinks: ChainLink[];
|
||||
gaps: Gap[];
|
||||
@@ -81,13 +83,24 @@ export default function Editor({
|
||||
project_id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
association_type: string;
|
||||
source_reference: string | null;
|
||||
evidence_reference: string | null;
|
||||
valid_from: string | null;
|
||||
valid_until: string | null;
|
||||
validation_status: string;
|
||||
version_no: number;
|
||||
editor_id: number | null;
|
||||
}[];
|
||||
}) {
|
||||
const isProject = structure === "projects";
|
||||
const isCluster = structure === "clusters";
|
||||
const isCorridor = structure === "corridors";
|
||||
const singular = isProject ? "projecto" : isCluster ? "cluster" : "corredor";
|
||||
const form = useForm({
|
||||
code: record?.code ?? "",
|
||||
name: record?.name ?? "",
|
||||
status: record?.status ?? (isProject ? "draft" : "planned"),
|
||||
status: record?.status ?? (isProject ? "draft" : isCluster ? "planned" : "proposed"),
|
||||
sector: record?.sector ?? "",
|
||||
description: record?.description ?? "",
|
||||
budget_amount: record?.budget_amount ?? "",
|
||||
@@ -99,9 +112,9 @@ export default function Editor({
|
||||
admin_post_id: "",
|
||||
locality_id: "",
|
||||
});
|
||||
const association = useForm({ project_id: "", role: "complementary" });
|
||||
const association = useForm({ project_id: "", version_no: 0, role: "complementary", association_type: "potential", source_reference: "", evidence_reference: "", valid_from: "", valid_until: "" });
|
||||
return (
|
||||
<Management title={`${record ? "Editar" : "Criar"} ${isProject ? "projecto" : "cluster"}`}>
|
||||
<Management title={`${record ? "Editar" : "Criar"} ${singular}`}>
|
||||
<Link className="underline" href={`/management/${structure}`}>
|
||||
Voltar a {titles[structure].toLowerCase()}
|
||||
</Link>
|
||||
@@ -155,7 +168,7 @@ export default function Editor({
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{!isProject && (
|
||||
{isCluster && (
|
||||
<Field label="Sector do cluster" error={form.errors.sector}>
|
||||
<input
|
||||
className={control}
|
||||
@@ -216,11 +229,21 @@ export default function Editor({
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
{isCorridor && (
|
||||
<Field label="Descrição" error={form.errors.description}>
|
||||
<textarea
|
||||
className={control}
|
||||
rows={5}
|
||||
value={form.data.description}
|
||||
onChange={(e) => form.setData("description", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar
|
||||
</button>
|
||||
</form>
|
||||
{!isProject && record && (
|
||||
{isCluster && record && (
|
||||
<>
|
||||
<section className="max-w-3xl space-y-4">
|
||||
<h2 className="text-xl font-semibold">Projectos associados</h2>
|
||||
@@ -235,6 +258,14 @@ export default function Editor({
|
||||
· {roles[member.role]}
|
||||
</p>
|
||||
))}
|
||||
{memberships.map((member) => (
|
||||
<div key={`${member.id}-governance`} className="text-sm">
|
||||
{member.validation_status} - {member.association_type} - {member.source_reference ?? "Sem fonte"} - {member.evidence_reference ?? "Sem evidencia"} - {member.valid_from ?? "Sem inicio"} - {member.valid_until ?? "Sem termo"}
|
||||
{member.validation_status === "pending" && member.editor_id !== viewerId && (
|
||||
<button className={button} type="button" onClick={() => router.post(`/management/structure-relations/cluster-project/${member.id}/validate`, { version_no: member.version_no }, { preserveScroll: true })}>Validar associacao</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{!memberships.length && <p>Ainda não existem projectos associados.</p>}
|
||||
<form
|
||||
className="space-y-3"
|
||||
@@ -250,7 +281,8 @@ export default function Editor({
|
||||
className={control}
|
||||
value={association.data.project_id}
|
||||
onChange={(e) =>
|
||||
association.setData("project_id", e.target.value)
|
||||
association.setData((data) => ({ ...data, project_id: e.target.value,
|
||||
version_no: memberships.find((member) => member.project_id === e.target.value)?.version_no ?? 0 }))
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
@@ -274,6 +306,15 @@ export default function Editor({
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Tipo de associacao" error={association.errors.association_type}>
|
||||
<select className={control} value={association.data.association_type} onChange={(e) => association.setData("association_type", e.target.value)}>
|
||||
<option value="official">Oficial</option><option value="influence">Influencia</option><option value="proximity">Proximidade</option><option value="potential">Potencial</option><option value="historical">Historica</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Referencia da fonte" error={association.errors.source_reference}><textarea className={control} value={association.data.source_reference} onChange={(e) => association.setData("source_reference", e.target.value)} /></Field>
|
||||
<Field label="Referencia da evidencia" error={association.errors.evidence_reference}><input className={control} value={association.data.evidence_reference} onChange={(e) => association.setData("evidence_reference", e.target.value)} /></Field>
|
||||
<Field label="Vigente desde" error={association.errors.valid_from}><input className={control} type="date" value={association.data.valid_from} onChange={(e) => association.setData("valid_from", e.target.value)} /></Field>
|
||||
<Field label="Vigente ate" error={association.errors.valid_until}><input className={control} type="date" value={association.data.valid_until} onChange={(e) => association.setData("valid_until", e.target.value)} /></Field>
|
||||
<button className={button} disabled={association.processing}>
|
||||
Guardar associação
|
||||
</button>
|
||||
|
||||
@@ -23,7 +23,11 @@ export default function Index({
|
||||
return (
|
||||
<Management title={titles[structure]}>
|
||||
<Link className={button} href={`/management/${structure}/create`}>
|
||||
{structure === 'projects' ? 'Criar projecto' : 'Criar cluster'}
|
||||
{structure === 'projects'
|
||||
? 'Criar projecto'
|
||||
: structure === 'clusters'
|
||||
? 'Criar cluster'
|
||||
: 'Criar corredor'}
|
||||
</Link>
|
||||
<form
|
||||
className="flex flex-wrap items-end gap-3"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type Structure = 'projects' | 'clusters';
|
||||
export type Structure = 'projects' | 'clusters' | 'corridors';
|
||||
export type StructureRecord = {
|
||||
id: string;
|
||||
code: string;
|
||||
@@ -11,7 +11,7 @@ export type StructureRecord = {
|
||||
start_date?: string | null;
|
||||
end_date?: string | null;
|
||||
};
|
||||
export const titles = { projects: 'Projectos', clusters: 'Clusters' };
|
||||
export const titles = { projects: 'Projectos', clusters: 'Clusters', corridors: 'Corredores' };
|
||||
export const statuses: Record<Structure, Record<string, string>> = {
|
||||
projects: {
|
||||
draft: 'Rascunho',
|
||||
@@ -22,6 +22,7 @@ export const statuses: Record<Structure, Record<string, string>> = {
|
||||
cancelled: 'Cancelado',
|
||||
},
|
||||
clusters: { planned: 'Planeado', active: 'Activo', inactive: 'Inactivo' },
|
||||
corridors: { proposed: 'Proposto', active: 'Activo', closed: 'Encerrado' },
|
||||
};
|
||||
export const stages: Record<string, string> = {
|
||||
input: 'Insumos',
|
||||
|
||||
Reference in New Issue
Block a user