Files
Investidor-V2/resources/js/pages/management/opportunity-resources.tsx
T

961 lines
41 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import OpportunityLibraryReuse, {
type LibrarySource,
} from '@/components/opportunity-library-reuse';
import { createOperationKey } from '@/lib/operation-key';
import OpportunityTechnicalIncidents, {
type OpportunityTechnicalIncident,
} from '@/components/opportunity-technical-incidents';
import { valueText } from '@/lib/value-text';
import { Link, router, usePage } from '@inertiajs/react';
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
import { useState } from 'react';
import {
TerritoryLevel,
type TerritoryOption,
} from '@/components/investment-territory';
import { Management, Field, button, control } from './shared';
type Payload = Record<string, string | number | boolean | null | object>;
type Resource = {
id: string;
version: number;
deleted_at: string | null;
payload: Payload;
territoryPath?: TerritoryOption[];
derivativePreviews?: {
document_id: string;
url: string;
width: number;
height: number;
}[];
file?: {
file_name: string;
malware_scan_status: string;
malware_engine: string | null;
sha256: string;
};
};
type Kind = 'locations' | 'images' | 'documents';
const fields: Record<Kind, string[]> = {
locations: [
'title',
'address',
'operational_unit',
'role_description',
'area_value',
'area_unit',
'allocation_percentage',
'multi_district_rationale',
'source_reference',
'source_date',
],
images: [
'title',
'caption',
'alt_text',
'author_source',
'captured_at',
'rights_valid_until',
'role_description',
'sort_order',
'source_reference',
],
documents: [
'title',
'category',
'issuer',
'edition',
'source_date',
'valid_until',
'source_reference',
'section',
'supported_statement',
],
};
const labels: Record<string, string> = {
role: 'Papel da localização',
imageRole: 'Tipo de imagem',
territorial_purpose: 'Finalidade deste local',
rights_status: 'Direitos de utilização',
visibility: 'Âmbito de consulta',
classification: 'Classificação documental',
location_id: 'Localização associada',
rights_document_id: 'Comprovativo de direitos',
title: 'Título',
address: 'Referência física',
operational_unit: 'Unidade operacional',
role_description: 'Descrição do papel outro',
area_value: 'Área',
area_unit: 'Unidade de área',
allocation_percentage: 'Distribuição (%)',
multi_district_rationale: 'Fundamento multidistrito/interprovincial',
source_reference: 'Fonte / referência',
source_date: 'Data da fonte',
caption: 'Legenda',
alt_text: 'Texto alternativo',
author_source: 'Autor / fonte',
captured_at: 'Data da imagem',
rights_valid_until: 'Validade dos direitos',
sort_order: 'Ordem',
category: 'Categoria documental',
issuer: 'Emissor',
edition: 'Edição / versão',
valid_until: 'Validade',
section: 'Página / secção',
supported_statement: 'Afirmação fundamentada',
};
const localLabels: Record<string, string> = {
implementation: 'Implantação',
context: 'Contexto',
impact: 'Impacto',
coverage: 'Abrangência',
headquarters: 'Sede',
production: 'Produção',
raw_material: 'Matéria-prima',
storage: 'Armazenagem',
logistics: 'Logística',
market: 'Mercado',
support: 'Apoio',
other: 'Outro',
};
const choices: Record<string, string[]> = {
role: [
'headquarters',
'production',
'raw_material',
'storage',
'logistics',
'market',
'support',
'other',
],
imageRole: [
'cover',
'gallery',
'location',
'asset',
'product',
'plan',
'rendering',
'evidence',
'other',
],
territorial_purpose: ['implementation', 'context', 'impact', 'coverage'],
rights_status: ['owned', 'licensed', 'authorized', 'public_domain'],
visibility: ['internal', 'authenticated', 'public'],
classification: ['public', 'internal', 'confidential', 'restricted'],
};
export default function OpportunityResources({
opportunity,
etag,
resources,
existingLocations,
assessment,
imageProcessingAvailable,
technicalIncidents = [],
librarySources = [],
locationReference = { path: [], differences: [] },
}: {
opportunity: {
id: number;
title: string | null;
status: string;
deleted_at: string | null;
};
etag: string;
resources: Record<Kind, Resource[]>;
existingLocations: { id: string; name: string; location_type: string }[];
assessment: string[];
imageProcessingAvailable: boolean;
technicalIncidents?: OpportunityTechnicalIncident[];
librarySources?: LibrarySource[];
locationReference?: {
path: TerritoryOption[];
differences: { resource_id: string; title: string; message: string }[];
};
}) {
const {
basePath = '/management/opportunities',
readOnly = false,
countries = [],
} = usePage<{
basePath?: string;
readOnly?: boolean;
countries?: { code: string; name: string }[];
}>().props;
const returnGroup = new URLSearchParams(
usePage().url.split('?')[1] ?? '',
).get('return_group');
const returnHash = ['territory', 'evidence'].includes(returnGroup ?? '')
? `#fill-${returnGroup}`
: '#fill-evidence';
const [kind, setKind] = useState<Kind>('locations');
const [editing, setEditing] = useState<Resource | null>(null);
const [payload, setPayload] = useState<Payload>({ country_code: 'MZ' });
const [path, setPath] = useState<TerritoryOption[]>([]);
const [geometry, setGeometry] = useState('');
const [file, setFile] = useState<File | null>(null);
const [reason, setReason] = useState('');
const [confirm, setConfirm] = useState(false);
const [key, setKey] = useState(() => createOperationKey());
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState('');
const [errors, setErrors] = useState<Record<string, string>>({});
const foreignCountry = Boolean(
payload.country_code && payload.country_code !== 'MZ',
);
const set = (name: string, value: Payload[string]) =>
setPayload((previous) => ({ ...previous, [name]: value }));
function select(nextKind: Kind, record: Resource | null = null) {
setKind(nextKind);
setEditing(record);
setPayload(
record?.payload ??
(nextKind === 'locations' ? { country_code: 'MZ' } : {}),
);
setPath(record?.territoryPath ?? []);
setGeometry(
record?.payload.geometry
? JSON.stringify(record.payload.geometry)
: '',
);
setFile(null);
setKey(createOperationKey());
setConfirm(false);
setErrors({});
}
async function execute(action: 'save' | 'delete' | 'restore' | 'prepare') {
if (busy || readOnly) return;
setBusy(true);
setErrors({});
setMessage('');
try {
const form = new FormData();
form.set('etag', etag);
form.set('reason', reason);
form.set('creation_key', key);
if (editing) form.set('version', valueText(editing.version));
if (action === 'save') {
const values = { ...payload };
if (kind === 'locations') {
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
].forEach(
(name, index) =>
(values[name] = path[index]?.id ?? null),
);
values.geometry = geometry ? JSON.parse(geometry) : null;
}
form.set('payload', JSON.stringify(values));
if (file) form.set('file', file);
} else {
form.set('action', action);
form.set('confirm', confirm ? '1' : '0');
}
const url = `${basePath}/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
const csrf =
document.cookie
.split('; ')
.find((v) => v.startsWith('XSRF-TOKEN='))
?.split('=')
.slice(1)
.join('=') ?? '';
const result = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'X-XSRF-TOKEN': decodeURIComponent(csrf),
},
body: form,
});
const data = await result.json();
if (!result.ok) {
setErrors(
Object.fromEntries(
Object.entries(data.errors ?? {}).map(
([name, value]) => [
name,
Array.isArray(value)
? value.join(' ')
: valueText(value),
],
),
),
);
throw new Error(data.message ?? `Falha HTTP ${result.status}`);
}
setMessage(data.message);
setEditing(null);
setPayload(kind === 'locations' ? { country_code: 'MZ' } : {});
setPath([]);
setGeometry('');
setFile(null);
setKey(createOperationKey());
setConfirm(false);
router.reload({
onFinish: () =>
document.getElementById('resource-result')?.focus(),
});
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Falha de ligação; preenchimento preservado.',
);
} finally {
setBusy(false);
setTimeout(
() => document.getElementById('resource-result')?.focus(),
0,
);
}
}
const unavailable =
!!opportunity.deleted_at || opportunity.status === 'archived';
return (
<Management title="Imagens, documentos e localizações">
<OpportunityTechnicalIncidents incidents={technicalIncidents} />
<Link href={`${basePath}/${opportunity.id}/edit${returnHash}`}>
Regressar ao rascunho #{opportunity.id}
</Link>
<p>
Recursos de preparação. Não alteram automaticamente a ficha
pública ou relações territoriais aceites. O estado e o motor do
scan são apresentados por ficheiro e versão; um scan simulado
nunca verifica ficheiros reais.
</p>
<div
id="resource-result"
role="status"
tabIndex={-1}
className="rounded border p-3"
>
{message ||
'Guardar é independente de validar, submeter e publicar.'}
{errors.etag && <p>{errors.etag}</p>}
</div>
{kind === 'images' && !imageProcessingAvailable && (
<p
role="status"
className="rounded border border-amber-500 p-3"
>
Processamento de imagens indisponível: GD/WebP não está
carregado no servidor. Pode guardar o original e os
metadados; miniaturas e imagens para divulgação ficam
pendentes.
</p>
)}
{kind !== 'locations' && (
<p className="rounded border p-3">
Pode guardar anexos para preparação. Cada ficheiro permanece
sem download ou pré-visualização enquanto o seu scan não
estiver concluído. Guardar metadados, locais ou rascunhos é
independente do scan e não publica ficheiros.
</p>
)}
{kind !== 'locations' && (
<section
aria-label="Privacidade dos anexos"
className="rounded border p-3"
>
<h2>Privacidade dos anexos</h2>
<p>
Os anexos pertencem à oportunidade. Podem ser
consultados pelos Promotores autorizados da organização,
pelos Validadores e Publicadores com acesso ao tipo e
âmbito e pelos Auditores autorizados. O Superutilizador
precisa também de perfil operacional no âmbito e de
elevação temporária para consulta, aprovada por outro
titular. O gestor da biblioteca, por si só, não obtém
esse acesso.
</p>
<p>
Classificação e âmbito de consulta são metadados;
escolher «public» ou «authenticated» não divulga o
ficheiro. Publicar o anúncio não publica os anexos. A
retirada lógica impede a entrega do ficheiro; a
revogação do perfil impede acessos futuros.
</p>
<p>
Partilhar um anexo com um destinatário individual ou
restringi-lo a alguns membros da organização permanece
indisponível. Não guarde neste fluxo um ficheiro que
exija essa restrição individual. Não é possível retirar
cópias já descarregadas.
</p>
</section>
)}
{kind === 'locations' && (
<section
aria-label="Onde se localiza"
className="space-y-3 rounded border p-4"
>
<h2 className="text-xl font-semibold">Onde se localiza</h2>
<p>
Registe o local principal e os locais adicionais
documentados: país, hierarquia territorial, endereço e
geometria ou parcela quando conhecidos. Indique a
finalidade de cada local: implantação, abrangência,
impacto ou contexto. Uma área de contexto não comprova
implantação.
</p>
<p>
Referência principal já guardada:{' '}
{locationReference.path.length
? locationReference.path
.map((item) => item.name)
.join(' → ')
: 'Não indicada'}
. Os níveis em falta continuam desconhecidos.
</p>
<p>
Pode guardar a preparação incompleta. No percurso de
submissão existente são conferidos distrito, papel,
indicação de principal e uma única localização principal
seleccionada; área e unidade devem ser coerentes quando
preenchidas. Não se acrescentam obrigatoriedades ao
guardar este recurso.
</p>
{locationReference.differences.map((item) => (
<p role="status" key={item.resource_id}>
{item.title}: {item.message}
</p>
))}
<p>
Corredores, clusters, ZEE, ZFI, parques e projectos
associados são descritos nas associações da ficha, com
finalidade, fonte e estado próprios. Estar num distrito
não confirma pertença a nenhum deles.
</p>
</section>
)}
<section>
<h2>Conferência e pendências</h2>
<ul>
{assessment.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</section>
{existingLocations.length > 0 && (
<section>
<h2>Referências territoriais anteriores — preservadas</h2>
<p>
Estas referências não são novas associações confirmadas
nem obrigam a repetir o preenchimento.
</p>
{existingLocations.map((r) => (
<p key={r.id}>
{r.name} · {r.location_type}
</p>
))}
</section>
)}
{!readOnly && kind === 'documents' && (
<OpportunityLibraryReuse
sources={librarySources}
action={`${basePath}/${opportunity.id}/library-support`}
etag={etag}
/>
)}
<nav className="flex flex-wrap gap-3">
{(['locations', 'images', 'documents'] as Kind[]).map((k) => (
<button
className={button}
key={k}
disabled={busy}
onClick={() => select(k)}
>
{k === 'locations'
? 'Localizações'
: k === 'images'
? 'Imagens'
: 'Documentos'}
</button>
))}
</nav>
<section>
{resources[kind].map((r) => (
<article key={r.id} className="my-3 rounded border p-3">
<p>
{valueText(
r.payload.title ??
r.file?.file_name ??
'Recurso incompleto',
)}{' '}
· v{r.version} ·{' '}
{r.deleted_at
? 'eliminado logicamente'
: 'rascunho'}
</p>
{!!r.payload.library_source && (
<p>
Original da biblioteca reutilizado; edição e
hash preservados, sem cópia dos bytes.
</p>
)}
{r.file && (
<p className="break-all">
Scan: {r.file.malware_scan_status} · motor:{' '}
{r.file.malware_engine ?? 'não executado'} ·
hash: {r.file.sha256}
</p>
)}
{kind === 'images' &&
!r.deleted_at &&
!!r.derivativePreviews?.length && (
<img
className="max-w-full"
src={r.derivativePreviews[0].url}
srcSet={r.derivativePreviews
.map((p) => `${p.url} ${p.width}w`)
.join(', ')}
alt={valueText(
r.payload.alt_text ??
'Pré-visualização interna pendente de descrição',
)}
onError={() =>
setMessage(
'Pré-visualização indisponível ou endereço expirado; recarregue. Dados preservados.',
)
}
/>
)}
<button
className={button}
onClick={() => select(kind, r)}
>
{readOnly
? 'Ver recurso'
: 'Ver / editar / restaurar'}
</button>
{r.file?.malware_scan_status === 'clean' &&
!r.deleted_at && (
<a
href={`${basePath}/${opportunity.id}/resources/${kind}/${r.id}/download`}
>
Consultar original autorizado
</a>
)}
</article>
))}
</section>
<form
onSubmit={(event) => {
event.preventDefault();
void execute('save');
}}
className="space-y-3"
>
<h2>
{editing
? 'Editar recurso / nova versão'
: 'Novo recurso incompleto'}
</h2>
{kind === 'locations' && (
<div>
{locationReference.path.length > 0 && (
<div className="my-3 rounded border p-3">
<button
type="button"
className={button}
disabled={
readOnly ||
Boolean(editing) ||
path.length > 0 ||
foreignCountry
}
onClick={() => {
setPath(locationReference.path);
setPayload((previous) => ({
...previous,
country_code: 'MZ',
}));
setMessage(
'Hierarquia principal reutilizada no preenchimento. Só foi reutilizada a hierarquia: coordenadas e parcela não foram copiadas. Papel, finalidade, fonte e indicação de principal continuam sob a sua escolha; nada foi guardado automaticamente.',
);
}}
>
Reutilizar hierarquia principal guardada
</button>
<p>
Use-a quando documentar o mesmo território.
Para um local diferente, escolha outra
hierarquia. A reutilização não substitui um
local em edição, um país estrangeiro ou uma
selecção já preenchida.
</p>
</div>
)}
<Field
label="País da localização"
error={errors.country_code}
>
<select
className={control}
disabled={readOnly}
value={valueText(payload.country_code ?? '')}
onChange={(event) => {
const country = event.target.value;
set('country_code', country || null);
if (
country &&
country !== 'MZ' &&
path.length
) {
setPath([]);
setMessage(
'A seleção territorial de Moçambique foi retirada do preenchimento ao mudar de país. Guarde para registar a alteração; a geometria própria foi preservada.',
);
}
}}
>
<option value="">Por indicar</option>
{countries.map((c) => (
<option key={c.code} value={c.code}>
{c.name}
</option>
))}
</select>
</Field>
{foreignCountry && (
<p>
A hierarquia abaixo corresponde a Moçambique e
não é aplicável ao país escolhido. Pode guardar
uma localização incompleta noutro país sem esta
hierarquia.
</p>
)}
{foreignCountry && path.length > 0 && (
<p role="alert">
Este registo conserva uma seleção territorial de
Moçambique incompatível com o país. Escolha
Moçambique ou{' '}
<button
type="button"
className="underline"
disabled={readOnly}
onClick={() => setPath([])}
>
retirar a seleção territorial deste
preenchimento
</button>
. O registo guardado só muda quando guardar.
</p>
)}
<TerritoryGeometryPreview
territoryId={
foreignCountry ? undefined : path.at(-1)?.id
}
management
endpoint={
basePath === '/minhas-oportunidades'
? '/minhas-oportunidades/territory-geometries'
: undefined
}
/>
{[0, 1, 2, 3].map((index) => (
<TerritoryLevel
key={index}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
disabled={readOnly || foreignCountry}
endpoint={
basePath === '/minhas-oportunidades'
? '/minhas-oportunidades/territory-options'
: '/management/territory-options'
}
onChange={(value) =>
setPath((previous) =>
value
? [
...previous.slice(0, index),
value,
]
: previous.slice(0, index),
)
}
fieldError={
errors[
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
][index]
]
}
/>
))}
</div>
)}
{kind !== 'locations' && (
<Field
label="Original / substituir por nova versão"
error={errors.file}
>
<input
key={key}
aria-label="Original / substituir por nova versão"
type="file"
disabled={!!editing?.payload.library_source}
accept={
kind === 'images'
? '.jpg,.jpeg,.png,.webp'
: '.pdf,.docx,.xlsx,.png,.jpg,.jpeg'
}
onChange={(event) =>
setFile(event.target.files?.[0] ?? null)
}
/>
<p>
Armazenamento privado cifrado, original e versões
preservados; sem acesso até scan limpo.
</p>
</Field>
)}
{fields[kind].map((name) => (
<Field
key={name}
label={labels[name]}
error={errors[name] ?? errors[`payload.${name}`]}
>
<input
aria-label={labels[name]}
className={control}
value={valueText(payload[name] ?? '')}
type={
name.includes('date') ||
name.endsWith('_at') ||
name.endsWith('_until')
? 'date'
: 'text'
}
onChange={(event) =>
set(name, event.target.value || null)
}
/>
</Field>
))}
{(kind === 'locations'
? ['role', 'territorial_purpose']
: kind === 'images'
? ['imageRole', 'rights_status', 'visibility']
: ['classification', 'visibility']
).map((name) => (
<Field
key={name}
label={labels[name] ?? name}
error={
errors[name === 'imageRole' ? 'role' : name] ??
errors[
`payload.${name === 'imageRole' ? 'role' : name}`
]
}
>
<select
className={control}
aria-label={labels[name] ?? name}
value={valueText(
payload[name === 'imageRole' ? 'role' : name] ??
'',
)}
onChange={(event) =>
set(
name === 'imageRole' ? 'role' : name,
event.target.value || null,
)
}
>
<option value="">Pendente</option>
{choices[name].map((option) => (
<option key={option} value={option}>
{kind === 'locations'
? (localLabels[option] ?? option)
: option}
</option>
))}
</select>
</Field>
))}
{kind === 'locations' && (
<Field
label="GeoJSON documentado (opcional)"
error={errors.geometry}
>
<textarea
className={control}
value={geometry}
onChange={(event) =>
setGeometry(event.target.value)
}
/>
<p>
Sem coordenadas continua consultável. Limite oficial
em falta aparece como pendência espacial.
</p>
</Field>
)}
{kind === 'images' &&
(['location_id', 'rights_document_id'] as const).map(
(name) => (
<Field
key={name}
label={labels[name] ?? name}
error={
errors[name] ?? errors[`payload.${name}`]
}
>
<select
className={control}
value={valueText(payload[name] ?? '')}
onChange={(event) =>
set(name, event.target.value || null)
}
>
<option value="">Pendente</option>
{resources[
name === 'location_id'
? 'locations'
: 'documents'
]
.filter((r) => !r.deleted_at)
.map((r) => (
<option value={r.id} key={r.id}>
{valueText(
r.payload.title ??
r.file?.file_name ??
r.id,
)}
</option>
))}
</select>
</Field>
),
)}
{kind === 'locations' && (
<Field
label="Local principal ou adicional"
error={errors.is_primary}
>
<select
aria-label="Local principal ou adicional"
className={control}
disabled={readOnly}
value={
typeof payload.is_primary === 'boolean'
? payload.is_primary
? 'primary'
: 'additional'
: ''
}
onChange={(event) =>
set(
'is_primary',
event.target.value === ''
? null
: event.target.value === 'primary',
)
}
>
<option value="">Por indicar</option>
<option value="primary">Principal</option>
<option value="additional">Adicional</option>
</select>
<p>
A escolha identifica o papel do local nesta ficha;
não confirma a sua implantação nem uma associação
territorial.
</p>
</Field>
)}
{kind === 'images' && (
<label>
<input
key={key}
type="checkbox"
checked={!!payload.is_cover}
onChange={(event) =>
set('is_cover', event.target.checked)
}
/>
Selecionar capa de preparação
</label>
)}
<Field
label="Motivo (20–1000 caracteres)"
error={errors.reason}
>
<textarea
className={control}
aria-label="Motivo (20–1000 caracteres)"
value={reason}
onChange={(event) => setReason(event.target.value)}
/>
</Field>
{editing && (
<label>
<input
type="checkbox"
checked={confirm}
onChange={(event) =>
setConfirm(event.target.checked)
}
/>
Confirmar exclusão lógica / restauração
</label>
)}
<div className="flex flex-wrap gap-3">
{kind === 'images' && editing && !editing.deleted_at && (
<button
type="button"
className={button}
disabled={
busy ||
readOnly ||
unavailable ||
!imageProcessingAvailable
}
onClick={() => void execute('prepare')}
>
Preparar WebP e miniaturas
</button>
)}
<button
className={button}
disabled={
busy ||
readOnly ||
unavailable ||
!!editing?.deleted_at
}
>
Guardar recurso
</button>
{editing && (
<button
type="button"
className={button}
disabled={busy || readOnly || unavailable}
onClick={() =>
void execute(
editing.deleted_at ? 'restore' : 'delete',
)
}
>
{editing.deleted_at
? 'Restaurar recurso'
: 'Excluir recurso logicamente'}
</button>
)}
</div>
</form>
</Management>
);
}