Files
Investidor-V2/resources/js/components/investment-supply-aggregate.tsx
T

354 lines
16 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 { useRef, useState } from 'react';
import { router } from '@inertiajs/react';
import { contextApi, type SupplyAggregate } from '@/lib/investor-context';
import { createOperationKey } from '@/lib/operation-key';
import CatalogueChoiceSelect from './catalogue-choice-select';
export default function InvestmentSupplyAggregate({
caseId,
version,
revision,
history: storedHistory,
disabled = false,
protectedMode = false,
activityOptions = [],
defaultActivityId,
}: {
caseId: string;
version: number;
revision: number;
history: SupplyAggregate[];
disabled?: boolean;
protectedMode?: boolean;
activityOptions?: { id: string; code: string; label: string }[];
defaultActivityId?: string;
}) {
const history = protectedMode
? storedHistory.filter(
(item) =>
item.privacy_version === 1 &&
item.privacy_policy === 'fixed_district_cae_division_v1',
)
: storedHistory;
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState('');
const command = useRef<{
version: number;
operation_key: string;
activity_id?: string | null;
classification_key?: string;
} | null>(null);
const [selectedHistory, setSelectedHistory] = useState<number | null>(null);
const latest =
history[selectedHistory ?? history.length - 1] ?? history.at(-1);
const protectedView = latest?.privacy_version === 1;
const [activityId, setActivityId] = useState(
history.at(-1)?.context_revision === revision
? (history.at(-1)?.filters?.classification_key ??
history.at(-1)?.filters?.activity_id ??
'')
: (defaultActivityId ?? ''),
);
return (
<section
className="max-w-full min-w-0 space-y-3 rounded border p-4"
aria-label="Oferta empresarial agregada"
>
<h2 className="font-semibold">
Actividades existentes na localização
</h2>
<p>
Consulte uma análise agregada no seu dossier. As listas, nomes e
contactos internos permanecem reservados.
</p>
{protectedMode && (
<CatalogueChoiceSelect
label="Actividade a comparar"
value={activityId}
disabled={disabled || busy}
options={[
{
value: '',
label: 'Todas as divisões do sector guardado',
},
...activityOptions.map((item) => ({
value: item.id,
label: `${item.code} — ${item.label}`,
keywords: [item.code, item.label],
})),
]}
onChange={(value) => {
if (value !== activityId) command.current = null;
setActivityId(value);
}}
/>
)}
<button
type="button"
className="min-h-11 rounded border px-3 py-2 underline"
disabled={disabled || busy}
onClick={async () => {
if (busy) return;
setBusy(true);
setMessage('');
command.current ??= {
version,
operation_key: createOperationKey(),
...(protectedMode
? activityId.startsWith('ebau:')
? {
activity_id: null,
classification_key: activityId,
}
: { activity_id: activityId || null }
: {}),
};
try {
await contextApi(
`/investimentos/${caseId}/contexto/oferta-agregada`,
command.current,
);
command.current = null;
setSelectedHistory(null);
setMessage('Análise agregada guardada no dossier.');
router.reload({
only: [
'case',
'supply_aggregates',
'supply_aggregate_enabled',
],
});
} catch (error) {
setMessage(
error instanceof Error
? error.message
: 'Não foi possível confirmar a consulta. A repetição conserva o mesmo comando.',
);
} finally {
setBusy(false);
}
}}
>
{busy
? 'A consultar…'
: command.current
? 'Repetir a mesma consulta'
: 'Consultar e guardar análise agregada'}
</button>
{message && <p role="status">{message}</p>}
{history.length > 1 && (
<label className="grid gap-1">
Análise guardada
<select
className="min-w-0 rounded border p-3"
value={selectedHistory ?? ''}
onChange={(e) =>
setSelectedHistory(
e.target.value === ''
? null
: Number(e.target.value),
)
}
>
<option value="">Mais recente</option>
{history.map((item, index) => (
<option
key={`${item.recorded_at}:${index}`}
value={index}
>
{item.recorded_at} — contexto{' '}
{item.context_revision}
</option>
))}
</select>
</label>
)}
{latest && (
<>
<h3 className="font-semibold">
{latest.scope.level === 'district'
? 'Contexto distrital'
: latest.scope.level === 'province'
? 'Contexto provincial'
: 'Contexto local'}{' '}
— {latest.scope.name}
</h3>
{latest.broader_context && (
<p>
Local escolhido: {latest.requested_territory.name}.
Os resultados referem-se ao território mais amplo
indicado acima.
</p>
)}
{!protectedView && (
<p>
{latest.entities} entidades identificadas nos
registos administrativos; {latest.repeated}{' '}
observações repetidas e {latest.uncertain}{' '}
identificações incertas, separadas dos totais.
</p>
)}
{protectedView && (
<div className="space-y-2">
<p>
{latest.source_summary?.label}. Período das
fontes:{' '}
{latest.source_summary?.period ??
'Por confirmar'}
{latest.source_summary?.incomplete_periods
? '; existem períodos não indicados'
: ''}
. Não é o período de actividade de cada
entidade.
</p>
<p>
Filtros recuperados da análise guardada:{' '}
{(latest.filters?.classification_label ??
latest.filters?.activity_label)
? `actividade ${latest.filters.classification_label ?? latest.filters.activity_label}, apresentada no grupo ${latest.filters.division_code}`
: latest.filters?.sector_id
? 'sector escolhido e actividades documentadas na classificação publicada'
: 'todas as actividades com classificação publicada'}
. Nenhum montante, contacto ou empresa
individual é apresentado.
</p>
{latest.filters?.classification_basis && (
<p>{latest.filters.classification_basis}</p>
)}
<p>
São apresentados intervalos, sem totais exactos.
Resultados pequenos ou insuficientemente
documentados não são divulgados.
</p>
</div>
)}
{latest.context_revision !== revision && (
<p role="status">
O contexto mudou depois desta análise. Reveja-a; a
consulta anterior mantém-se no histórico.
</p>
)}
<div className="overflow-x-auto">
<table
className={
protectedView
? 'w-full min-w-[42rem]'
: 'w-full'
}
>
<caption className="text-left">
Grupos para investigar actividades similares e
complementares
</caption>
<thead>
<tr>
{protectedView && (
<th className="p-2 text-left">
Âmbito dos registos
</th>
)}
<th className="p-2 text-left">
Actividade
</th>
<th className="p-2">
{protectedView
? 'Identidades documentais'
: 'Entidades'}
</th>
{protectedView && (
<th className="p-2">
Observações consolidadas
</th>
)}
{!protectedView && (
<th className="p-2">
Período conhecido
</th>
)}
</tr>
</thead>
<tbody>
{latest.groups.map((group) => (
<tr
key={`${group.scope?.id ?? ''}:${group.code}`}
>
{protectedView && (
<td className="p-2">
{group.scope?.name}
{group.scope?.level ===
'province'
? ' — contexto provincial; distrito por determinar'
: ' — contexto distrital'}
</td>
)}
<td className="p-2">{group.label}</td>
<td className="p-2 text-center">
{protectedView
? group.entities_band
: group.total}
</td>
{protectedView && (
<td className="p-2">
{group.observations_band}
</td>
)}
{!protectedView && (
<td className="p-2">
{group.first_year ??
'Por confirmar'}
{group.last_year &&
group.last_year !==
group.first_year
? '–' + group.last_year
: ''}
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
{!latest.groups.length && (
<p>
Não há resultados divulgáveis nestes critérios:
podem faltar registos ou existir grupos protegidos.
A oferta empresarial permanece por determinar; não
significa ausência de empresas.
</p>
)}
{latest.truncated && (
<p>
Apresentação limitada aos primeiros 100 grupos; não
representa cobertura completa.
</p>
)}
{protectedView ? (
<details>
<summary>
Como interpretar estes resultados e as suas
limitações
</summary>
<p>{latest.interpretation}</p>
<p>{latest.limitations}</p>
<p>{latest.privacy_notice}</p>
</details>
) : (
<>
<p>{latest.interpretation}</p>
<p>{latest.limitations}</p>
</>
)}
<details>
<summary>Consulta e histórico</summary>
<p>
{history.length} análises preservadas. Última
consulta: {latest.recorded_at}. Cobertura
territorial e actividade actual por confirmar.
</p>
</details>
</>
)}
</section>
);
}