Files
Investidor-V2/resources/js/pages/management/opportunity-resources.tsx
T
nala 20971d523f
tests / ci (push) Canceled after 0s
oportunidades 6
2026-10-10 21:17:46 +02:00

709 lines
29 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 { 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: 'Natureza da relação territorial',
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 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,
}: {
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;
}) {
const { basePath = '/management/opportunities', readOnly = false, countries = [] } = usePage<{basePath?: string; readOnly?: boolean; countries?: {code:string;name:string}[]}>().props;
const [kind, setKind] = useState<Kind>('locations');
const [editing, setEditing] = useState<Resource | null>(null);
const [payload, setPayload] = useState<Payload>({country_code:'MZ'});
const [path, setPath] = useState<TerritoryOption[]>([]);
const [geometry, setGeometry] = useState('');
const [file, setFile] = useState<File | null>(null);
const [reason, setReason] = useState('');
const [confirm, setConfirm] = useState(false);
const [key, setKey] = useState(() => crypto.randomUUID());
const [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(crypto.randomUUID());
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', String(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(' ')
: String(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(crypto.randomUUID());
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">
<Link href={`${basePath}/${opportunity.id}/edit`}>
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>
)}
<section>
<h2>Conferência e pendências</h2>
<ul>
{assessment.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</section>
{existingLocations.length > 0 && (
<section>
<h2>Ligações territoriais existentes preservadas</h2>
{existingLocations.map((r) => (
<p key={r.id}>
{r.name} · {r.location_type}
</p>
))}
</section>
)}
<nav className="flex flex-wrap gap-3">
{(['locations', 'images', 'documents'] as Kind[]).map((k) => (
<button
className={button}
key={k}
disabled={busy || readOnly}
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>
{String(
r.payload.title ??
r.file?.file_name ??
'Recurso incompleto',
)}{' '}
· v{r.version} ·{' '}
{r.deleted_at
? 'eliminado logicamente'
: 'rascunho'}
</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={String(
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)}
>
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>
<Field label="País da localização" error={errors.country_code}>
<select
className={control}
disabled={readOnly}
value={String(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"
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={String(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={String(
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}>{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={String(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}>
{String(
r.payload.title ??
r.file?.file_name ??
r.id,
)}
</option>
))}
</select>
</Field>
),
)}
{kind !== 'documents' && (
<label>
<input
key={key}
type="checkbox"
checked={
!!payload[
kind === 'images'
? 'is_cover'
: 'is_primary'
]
}
onChange={(event) =>
set(
kind === 'images'
? 'is_cover'
: 'is_primary',
event.target.checked,
)
}
/>
{kind === 'images'
? 'Selecionar capa de preparação'
: 'Localização principal'}
</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>
);
}