Files
Investidor-V2/resources/js/components/investment-zone-integral-details.tsx
T
nala cf003c8623
tests / ci (push) Canceled after 0s
versao nrgocios 4
2026-10-18 15:57:06 +02:00

579 lines
25 KiB
TypeScript

import { useRef } from 'react';
import { Field, input, button, card } from '@/pages/investment/shared';
type Group =
| 'titles'
| 'phases'
| 'plots'
| 'occupants'
| 'observations'
| 'chains';
type Item = {
id: string;
label: string;
knowledge: string;
disclosure: boolean;
support_document_ids?: string[];
[key: string]: string | number | boolean | string[] | null | undefined;
};
export type ParkIntegral = Partial<Record<Group, Item[]>> & {
schema_version?: number;
remove_ids?: Partial<Record<Group, string[]>>;
};
type Option = { id: string; name: string };
type Props = {
value?: ParkIntegral;
onChange: (v: ParkIntegral) => void;
organizations: Option[];
documents: { id: string; title: string }[];
geometries?: Option[];
links?: Option[];
};
const groups: Record<Group, string> = {
titles: 'Títulos e enquadramento documental',
phases: 'Fases e expansão prevista',
plots: 'Lotes e situação declarada',
occupants: 'Empresas e ocupação',
observations: 'Indicadores por período',
chains: 'Âncoras, fornecedores e necessidades',
};
const labels: Record<string, string> = {
label: 'Designação',
label_en: 'Designação em inglês',
description: 'Descrição',
description_en: 'Descrição em inglês',
code: 'Código interno',
kind: 'Tipo',
identifier: 'Identificador do título',
valid_from: 'Início de vigência / presença',
valid_until: 'Fim de vigência / presença',
starts_at: 'Início previsto ou documentado',
ends_at: 'Fim previsto ou documentado',
expansion: 'Expansão prevista segundo a fonte',
area: 'Área declarada',
area_unit: 'Unidade de área',
status: 'Situação declarada',
organization_id: 'Entidade existente',
documentary_name: 'Menção documental por corresponder (privada)',
phase_id: 'Fase deste parque',
plot_id: 'Lote deste parque',
geometry_id: 'Geometria já associada ao parque',
zone_link_id: 'Relação económica já associada ao parque',
indicator: 'Indicador',
value: 'Valor observado',
unit: 'Unidade de medida',
period_start: 'Início do período',
period_end: 'Fim do período',
population: 'Base / população abrangida',
methodology: 'Método e limitações',
source_reference: 'Fonte / citação',
source_date: 'Data da fonte',
scope: 'Âmbito da informação',
private_note: 'Nota privada',
};
const extras: Record<Group, string[]> = {
titles: ['kind', 'identifier', 'valid_from', 'valid_until'],
phases: ['code', 'status', 'starts_at', 'ends_at', 'expansion'],
plots: ['code', 'phase_id', 'area', 'area_unit', 'status', 'geometry_id'],
occupants: [
'organization_id',
'documentary_name',
'phase_id',
'plot_id',
'status',
'valid_from',
'valid_until',
],
observations: [
'indicator',
'value',
'unit',
'period_start',
'period_end',
'population',
'methodology',
'phase_id',
'plot_id',
],
chains: [
'kind',
'organization_id',
'documentary_name',
'zone_link_id',
'phase_id',
'plot_id',
],
};
const choices: Record<string, Record<string, string>> = {
knowledge: {
unknown: 'Não informado',
documented: 'Documentado pela fonte',
disputed: 'Divergente',
},
'titles.kind': {
creation: 'Criação do parque',
land_use: 'Uso do solo',
licence: 'Licença',
special_regime: 'Regime especial documentado',
other: 'Outro',
},
'chains.kind': {
anchor: 'Projecto âncora',
supplier: 'Fornecedor / cadeia de valor',
unmet_need: 'Necessidade não satisfeita',
other: 'Outra relação',
},
'phases.status': {
unknown: 'Não informado',
planned: 'Planeada',
construction: 'Em construção',
operational: 'Em operação',
suspended: 'Suspensa',
closed: 'Encerrada',
},
'plots.status': {
unknown: 'Não informado',
planned: 'Planeado',
available_declared: 'Disponível segundo a fonte e data',
reserved: 'Reservado segundo a fonte',
occupied: 'Ocupado',
construction: 'Em construção',
inactive: 'Inativo',
},
'occupants.status': {
unknown: 'Não informado',
approved: 'Aprovada segundo a fonte',
construction: 'Em construção',
installed: 'Instalada',
inactive: 'Inativa',
},
area_unit: { ha: 'Hectares', m2: 'Metros quadrados' },
indicator: {
employment: 'Emprego',
investment: 'Investimento',
production: 'Produção',
exports: 'Exportações',
local_procurement: 'Compras locais',
resource_use: 'Utilização de recursos',
waste: 'Resíduos',
emissions: 'Emissões',
other: 'Outro indicador',
},
};
const numeric = new Set(['area', 'value']);
const dates = new Set([
'source_date',
'valid_from',
'valid_until',
'starts_at',
'ends_at',
'period_start',
'period_end',
]);
export default function ParkIntegralEditor({
value = {},
onChange,
organizations,
documents,
geometries = [],
links = [],
}: Props) {
const persistedIds = useRef(
new Set(
(Object.keys(groups) as Group[]).flatMap((g) =>
(value[g] ?? []).map((i) => i.id),
),
),
);
const update = (g: Group, id: string, patch: Partial<Item>) =>
onChange({
...value,
[g]: (value[g] ?? []).map((item) =>
item.id === id ? { ...item, ...patch } : item,
),
});
function field(g: Group, item: Item, key: string) {
if (key === 'expansion')
return (
<label key={key} className="flex gap-2">
<input
type="checkbox"
checked={item.expansion === true}
onChange={(e) =>
update(g, item.id, { expansion: e.target.checked })
}
/>
{labels[key]}
</label>
);
let options = choices[`${g}.${key}`] ?? choices[key];
const referenced =
key === 'organization_id'
? organizations
: key === 'geometry_id'
? geometries
: key === 'zone_link_id'
? links
: key === 'phase_id'
? (value.phases ?? []).map((i) => ({
id: i.id,
name: String(
i.code
? `${String(i.code)} — ${i.label}`
: i.label,
),
}))
: key === 'plot_id'
? (value.plots ?? []).map((i) => ({
id: i.id,
name: String(
i.code
? `${String(i.code)} — ${i.label}`
: i.label,
),
}))
: null;
if (referenced)
options = Object.fromEntries(referenced.map((i) => [i.id, i.name]));
return (
<Field key={key} label={labels[key] ?? key}>
{options ? (
<select
className={input}
value={String(item[key] ?? '')}
onChange={(e) =>
update(g, item.id, {
[key]: e.target.value || null,
})
}
>
<option value="">Não informado / sem associação</option>
{Object.entries(options).map(([k, v]) => (
<option key={k} value={k}>
{v}
</option>
))}
</select>
) : (
<input
className={input}
type={
dates.has(key)
? 'date'
: numeric.has(key)
? 'number'
: 'text'
}
min={key === 'area' ? '0' : undefined}
step={numeric.has(key) ? 'any' : undefined}
value={String(item[key] ?? '')}
onChange={(e) =>
update(g, item.id, {
[key]:
e.target.value === ''
? null
: e.target.value,
})
}
/>
)}
</Field>
);
}
return (
<section className="space-y-4" aria-label="Ficha integral do parque">
<h2 className="font-semibold">Ficha integral do parque</h2>
<p>
Informação por parque e por versão. Pode preparar dados
incompletos em privado. Valores vazios são desconhecidos; não
significam zero, área livre ou inexistência.
</p>
<p>
As áreas não são somadas automaticamente. Títulos e regimes são
referências documentais; não atribuem DUAT, licença, benefício
fiscal ou autorização. A publicação de um detalhe não publica o
seu suporte privado.
</p>
{(Object.keys(groups) as Group[]).map((g) => (
<details key={g} className={card}>
<summary className="cursor-pointer font-semibold">
{groups[g]} · {(value[g] ?? []).length} registos
</summary>
<div className="mt-3 space-y-4">
{!(value[g] ?? []).length && (
<p>Não informado nesta versão.</p>
)}
{(value[g] ?? []).map((item, index) => (
<fieldset
key={item.id}
className="grid gap-3 rounded border p-3 md:grid-cols-2"
>
<legend>
{groups[g]} — {index + 1}
</legend>
{[
'label',
'label_en',
'description',
'description_en',
].map((k) => field(g, item, k))}
<Field label="Situação da informação">
<select
className={input}
value={item.knowledge}
onChange={(e) =>
update(g, item.id, {
knowledge: e.target.value,
...(e.target.value ===
'unknown' &&
g === 'observations'
? { value: null }
: e.target.value ===
'unknown' &&
g === 'plots'
? { area: null }
: {}),
})
}
>
{Object.entries(choices.knowledge).map(
([k, v]) => (
<option key={k} value={k}>
{v}
</option>
),
)}
</select>
</Field>
{extras[g].map((k) => field(g, item, k))}
{[
'source_reference',
'source_date',
'scope',
'private_note',
].map((k) => field(g, item, k))}
<fieldset className="space-y-2">
<legend>
Suporte privado já associado
</legend>
{documents.length === 0 && (
<p>
Nenhum documento consultável
associado.
</p>
)}
{documents.map((d) => (
<label
key={d.id}
className="flex gap-2"
>
<input
type="checkbox"
checked={(
item.support_document_ids ??
[]
).includes(d.id)}
onChange={(e) =>
update(g, item.id, {
support_document_ids: e
.target.checked
? [
...(item.support_document_ids ??
[]),
d.id,
]
: (
item.support_document_ids ??
[]
).filter(
(id) =>
id !==
d.id,
),
})
}
/>
{d.title}
</label>
))}
</fieldset>
<label className="flex gap-2">
<input
type="checkbox"
checked={item.disclosure}
onChange={(e) =>
update(g, item.id, {
disclosure: e.target.checked,
})
}
/>
Incluir este detalhe na próxima publicação
expressa
</label>
<button
type="button"
className={button}
onClick={() =>
onChange({
...value,
[g]: (value[g] ?? []).filter(
(i) => i.id !== item.id,
),
...(persistedIds.current.has(
item.id,
)
? {
remove_ids: {
...value.remove_ids,
[g]: [
...(value
.remove_ids?.[
g
] ?? []),
item.id,
],
},
}
: {}),
})
}
>
Remover detalhe {index + 1}
</button>
</fieldset>
))}
<button
type="button"
className={button}
onClick={() =>
onChange({
...value,
[g]: [
...(value[g] ?? []),
{
id: crypto.randomUUID(),
label: '',
knowledge: 'unknown',
disclosure: false,
...(g === 'observations'
? { indicator: 'employment' }
: {}),
},
],
})
}
>
Acrescentar — {groups[g]}
</button>
</div>
</details>
))}
<p>
Consulta e preparação são informativas. Disponibilidade
declarada tem fonte/data; não é disponibilidade em tempo real,
reserva, contrato ou elegibilidade automática. Não são
produzidos rankings ou cálculos fiscais.
</p>
</section>
);
}
export function ParkIntegralPublic({ value }: { value?: ParkIntegral }) {
if (!value) return null;
return (
<section className="space-y-4" aria-label="Ficha integral publicada">
<h2 className="font-semibold">Ficha integral publicada</h2>
<p>
Dados declarados por fonte e período, sem soma automática ou
disponibilidade em tempo real. Não constitui reserva,
autorização, licença ou atribuição de regime especial.
</p>
{(Object.keys(groups) as Group[]).map((g) => (
<section key={g} className={card}>
<h3 className="font-semibold">{groups[g]}</h3>
{!value[g]?.length && <p>Não informado nesta versão.</p>}
{value[g]?.map((item) => (
<article
key={item.id}
className="my-3 rounded border p-3"
>
<h4 className="font-semibold">{item.label}</h4>
{item.label_en && (
<p lang="en">{String(item.label_en)}</p>
)}
<p>{String(item.description ?? '')}</p>
{item.description_en && (
<p lang="en">{String(item.description_en)}</p>
)}
<p>
{choices.knowledge[item.knowledge] ??
'Não informado'}
</p>
<dl>
{extras[g]
.filter(
(k) =>
![
'organization_id',
'documentary_name',
'geometry_id',
'zone_link_id',
].includes(k),
)
.map((k) => (
<div key={k}>
<dt>{labels[k]}</dt>
<dd>
{k === 'phase_id' ||
k === 'plot_id'
? String(
value[
k === 'phase_id'
? 'phases'
: 'plots'
]?.find(
(i) =>
i.id ===
item[k],
)?.label ??
'Não informado',
)
: item[k] == null ||
item[k] === ''
? 'Não informado'
: k === 'expansion'
? item[k]
? 'Sim, segundo a fonte'
: 'Não declarada'
: ((choices[
`${g}.${k}`
] ?? choices[k])?.[
String(item[k])
] ?? String(item[k]))}
</dd>
</div>
))}
</dl>
{item.organization_name && (
<p>
Entidade: {String(item.organization_name)}
</p>
)}
<p>
Fonte:{' '}
{String(
item.source_reference || 'Não informada',
)}{' '}
· data:{' '}
{String(item.source_date || 'Não informada')} ·
âmbito: {String(item.scope || 'Não informado')}
</p>
</article>
))}
</section>
))}
</section>
);
}