feat: protect owner-only supply aggregates and record target CAE blocker

This commit is contained in:
2026-11-15 23:10:17 +02:00
parent e0b18413ac
commit c8957ecb9d
15 changed files with 1255 additions and 49 deletions
@@ -2,29 +2,53 @@ 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,
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 } | null>(
null,
const command = useRef<{
version: number;
operation_key: string;
activity_id?: string | null;
} | 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?.activity_id ?? '')
: (defaultActivityId ?? ''),
);
const latest = history.at(-1);
return (
<section
className="space-y-3 rounded border p-4"
className="max-w-full min-w-0 space-y-3 rounded border p-4"
aria-label="Oferta empresarial agregada"
>
<h2 className="font-semibold">
@@ -34,6 +58,28 @@ export default function InvestmentSupplyAggregate({
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"
@@ -45,6 +91,9 @@ export default function InvestmentSupplyAggregate({
command.current ??= {
version,
operation_key: createOperationKey(),
...(protectedMode
? { activity_id: activityId || null }
: {}),
};
try {
await contextApi(
@@ -52,6 +101,7 @@ export default function InvestmentSupplyAggregate({
command.current,
);
command.current = null;
setSelectedHistory(null);
setMessage('Análise agregada guardada no dossier.');
router.reload({
only: [
@@ -78,6 +128,33 @@ export default function InvestmentSupplyAggregate({
: '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">
@@ -91,16 +168,48 @@ export default function InvestmentSupplyAggregate({
{latest.broader_context && (
<p>
Local escolhido: {latest.requested_territory.name}.
Os totais referem-se ao território mais amplo
Os resultados referem-se ao território mais amplo
indicado acima.
</p>
)}
<p>
{latest.entities} entidades identificadas nos registos
administrativos; {latest.repeated} observações repetidas
e {latest.uncertain} identificações incertas, separadas
dos totais.
</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 do dossier:{' '}
{latest.filters?.activity_label
? `actividade ${latest.filters.activity_label}, apresentada ao nível da divisão CAE ${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>
<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
@@ -108,35 +217,80 @@ export default function InvestmentSupplyAggregate({
</p>
)}
<div className="overflow-x-auto">
<table className="w-full">
<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">Entidades</th>
<th className="p-2">Período conhecido</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.code}>
<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">
{group.total}
</td>
<td className="p-2">
{group.first_year ??
'Por confirmar'}
{group.last_year &&
group.last_year !== group.first_year
? '–' + group.last_year
: ''}
{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>
@@ -144,8 +298,9 @@ export default function InvestmentSupplyAggregate({
</div>
{!latest.groups.length && (
<p>
Não existem registos aplicáveis nesta consulta. A
oferta empresarial permanece por determinar; não
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>
)}
@@ -155,8 +310,22 @@ export default function InvestmentSupplyAggregate({
representa cobertura completa.
</p>
)}
<p>{latest.interpretation}</p>
<p>{latest.limitations}</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>
+21 -4
View File
@@ -33,18 +33,35 @@ export type ContextDocument = {
download_url: string;
};
export type SupplyAggregate = {
privacy_version?: number;
privacy_policy?: string;
privacy_notice?: string;
source_summary?: {
label: string;
period: string;
incomplete_periods: boolean;
};
filters?: {
sector_id: number | null;
activity_id: string | null;
activity_label: string | null;
division_code: string | null;
};
context_revision: number;
recorded_at: string;
requested_territory: { id: string; name: string };
scope: { id: string; name: string; level: string };
broader_context: boolean;
entities: number;
repeated: number;
uncertain: number;
entities: number | null;
repeated: number | null;
uncertain: number | null;
groups: {
code: string;
label: string;
total: number;
total: number | null;
entities_band?: string;
observations_band?: string;
scope?: { id: string; name: string; level: string };
first_year: string | null;
last_year: string | null;
}[];
+8 -1
View File
@@ -99,6 +99,8 @@ type Path = {
investment_context: DossierContext | null;
can_set_promoter?: boolean;
supply_aggregate_enabled?: boolean;
supply_aggregate_protected?: boolean;
supply_activity_options?: { id: string; code: string; label: string }[];
supply_aggregates?: SupplyAggregate[];
zone_contexts?: {
zone_id: string;
@@ -688,11 +690,16 @@ export default function InvestmentPath(path: Path) {
/>
{path.supply_aggregate_enabled && (
<InvestmentSupplyAggregate
key={path.case.id}
key={`supply:${path.case.id}`}
caseId={path.case.id}
version={path.case.version}
revision={path.investment_context?.revision ?? 0}
history={path.supply_aggregates ?? []}
protectedMode={path.supply_aggregate_protected ?? false}
activityOptions={path.supply_activity_options ?? []}
defaultActivityId={
path.investment_context?.fields.activity_id
}
disabled={!path.canWrite}
/>
)}