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
+16 -7
View File
@@ -195,28 +195,37 @@ final class InvestorContext
*/
public function saveSupplyAggregate(User $actor, string $id, array $input): array
{
abort_unless(config('investor-path.aggregate_supply_qa_enabled') && \App\Support\IsolatedQaDatabase::allowsSchemaChanges(), 404);
$control = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid'])->validate();
return DB::transaction(function () use ($actor, $id, $control): array {
abort_unless(app(ProactiveSupply::class)->aggregateAvailable(), 404);
$protected = (bool) config('investor-path.protected_supply_enabled');
abort_if($protected && array_diff(array_keys($input), ['version', 'operation_key', 'activity_id']), 422, 'O território e o sector são recuperados do contexto guardado. Altere o contexto do dossier antes de consultar.');
$control = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid', 'activity_id' => 'nullable|uuid'])->validate();
$signature = hash('sha256', json_encode(\Illuminate\Support\Arr::except($control, ['version', 'operation_key']), JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $id, $control, $protected, $signature): array {
$case = $this->desk->case($actor, $id, true, true);
abort_unless((int) $case->user_id === $actor->id, 403);
$this->desk->assertOpen($case);
$payload = $this->desk->decode($case->payload);
$history = $payload['investor_path']['supply_aggregates'] ?? [];
foreach ($history as $saved) {
if ($saved['operation_key'] === $control['operation_key']) return ['version' => $case->version, 'analysis' => $saved, 'replayed' => true];
if ($saved['operation_key'] === $control['operation_key']) {
abort_if($protected && app(ProactiveSupply::class)->protectedHistory([$saved]) === [], 409, 'Esta consulta antiga não cumpre a protecção actual. Prepare uma nova consulta.');
abort_if($protected && ($saved['request_signature'] ?? null) !== $signature, 409, 'A mesma chave de consulta não pode ser usada com outra actividade. Prepare uma nova consulta.');
return ['version' => $case->version, 'analysis' => $protected ? app(ProactiveSupply::class)->protectedHistory([$saved])[0] : $saved, 'replayed' => true];
}
}
abort_unless((int) $case->version === (int) $control['version'], 409, 'O dossier mudou. Recupere-o antes de consultar.');
$context = $this->state($case);
abort_if(count($context['opportunity_choices'] ?? []) > 1, 422, 'Esta consulta agregada de QA utiliza apenas o contexto comum de uma ideia própria.');
abort_if(count($context['opportunity_choices'] ?? []) > 1, 422, 'Esta análise utiliza um único contexto de investimento. Escolha o investimento a analisar, preservando as restantes associações.');
$f = $context['fields'];
if ($protected && array_key_exists('activity_id', $control)) $f['activity_id'] = $control['activity_id'];
$territory = $f['locality_id'] ?? $f['admin_post_id'] ?? $f['district_id'] ?? $f['province_id'] ?? null;
abort_unless($territory, 422, 'Guarde primeiro a localização conhecida no dossier.');
$analysis = [...app(ProactiveSupply::class)->aggregate($actor, $territory), 'context_revision' => $context['revision'], 'recorded_at' => now()->toIso8601String(), 'operation_key' => $control['operation_key']];
$data = $protected ? app(ProactiveSupply::class)->protectedAggregate($actor, $id, $territory, $f) : app(ProactiveSupply::class)->aggregate($actor, $territory);
$analysis = [...$data, 'context_revision' => $context['revision'], 'recorded_at' => now()->toIso8601String(), 'operation_key' => $control['operation_key'], ...($protected ? ['request_signature' => $signature] : [])];
$payload['investor_path']['supply_aggregates'] = [...$history, $analysis];
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event($this->desk->case($actor, $id), $actor, 'investment_supply_aggregate_saved', ['context_revision' => $context['revision'], 'territory_id' => $territory, 'aggregate_only' => true]);
return ['version' => $case->version + 1, 'analysis' => $analysis, 'replayed' => false];
return ['version' => $case->version + 1, 'analysis' => $protected ? app(ProactiveSupply::class)->protectedHistory([$analysis])[0] : $analysis, 'replayed' => false];
});
}
+4 -2
View File
@@ -162,7 +162,7 @@ final class InvestorPath
}
$preparationTaskKeys = $opportunity !== null && ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() ? app(InvestmentPreparationWorkspace::class)->taskKeys($actor, $id, $opportunity) : null;
$supplyEnabled = (int) $case->user_id === $actor->id && config('investor-path.aggregate_supply_qa_enabled') && \App\Support\IsolatedQaDatabase::allowsSchemaChanges();
$supplyEnabled = (int) $case->user_id === $actor->id && app(ProactiveSupply::class)->aggregateAvailable();
return ['funding_selections' => ($owner || $manager) ? array_values(array_filter($path['funding_selections'] ?? [], fn ($row) => ($row['opportunity'] ?? null) === $opportunity)) : [], 'preparation_action' => ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() ? app(InvestmentPreparationWorkspace::class)->continuation($actor, $id, $opportunity, request()->query('swot_action')) : null, 'private_investment' => $preparation, 'case' => ['id' => $id, 'title' => $case->title, 'version' => $case->version, 'closed' => $case->closed_at !== null],
'journey_id' => $journey->id, 'definition_id' => $version->id, 'definition_version' => $version->version_no, 'source_sha256' => $definition['source_sha256'],
@@ -174,7 +174,9 @@ final class InvestorPath
'investment_context' => ($owner || $manager) ? [...$context, 'opportunity_choices' => $opportunity ? $context['opportunity_choices'] : $allChoices] : null,
'can_set_promoter' => (int) $case->user_id === $actor->id && $case->organization_id === null && ! $case->closed_at,
'results' => $results, 'requests' => $requests, 'documents' => $documents,
'supply_aggregate_enabled' => $supplyEnabled, 'supply_aggregates' => $supplyEnabled ? ($path['supply_aggregates'] ?? []) : [],
'supply_aggregate_enabled' => $supplyEnabled, 'supply_aggregate_protected' => $supplyEnabled && (bool) config('investor-path.protected_supply_enabled'),
'supply_activity_options' => $supplyEnabled && config('investor-path.protected_supply_enabled') ? app(ProactiveSupply::class)->aggregateActivityOptions(isset($context['fields']['sector_id']) ? (int) $context['fields']['sector_id'] : null) : [],
'supply_aggregates' => $supplyEnabled ? (config('investor-path.protected_supply_enabled') ? app(ProactiveSupply::class)->protectedHistory($path['supply_aggregates'] ?? []) : ($path['supply_aggregates'] ?? [])) : [],
'fiscal_reports' => (int) $case->user_id === $actor->id && (count($allChoices) < 2 || $opportunity !== null)
? app(SimulationFormDrafts::class)->dossierReportSources($actor, $id, $opportunity) : [],
'land_report' => $landCase ? ['id' => $landCase->id, 'version' => $landCase->version, 'updated_at' => $landCase->updated_at?->toIso8601String(),
+211 -2
View File
@@ -4,7 +4,10 @@ namespace App\Services;
use App\Models\Opportunity;
use App\Models\User;
use App\Support\IsolatedQaDatabase;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
@@ -36,14 +39,219 @@ final class ProactiveSupply
});
}
/** Aggregate access never confers the existing internal row/source permission. */
public function aggregateAvailable(): bool
{
return (bool) config('investor-path.protected_supply_enabled')
|| (config('investor-path.aggregate_supply_qa_enabled') && IsolatedQaDatabase::allowsSchemaChanges());
}
/** Fixed district/division cells; filters select released cells, never recalculate intersections.
* @param array<string,mixed> $fields
* @return array<string,mixed>
*/
public function protectedAggregate(User $actor, string $caseId, string $territory, array $fields): array
{
abort_unless(config('investor-path.protected_supply_enabled'), 404);
$case = app(VirtualDesk::class)->case($actor, $caseId, true, true);
abort_unless((int) $case->user_id === (int) $actor->id, 403);
app(VirtualDesk::class)->assertOpen($case);
$geo = app(InvestmentGeography::class);
$path = collect($geo->path($territory));
$province = $path->firstWhere('location_type', 'province');
abort_unless($province !== null, 422, 'Guarde uma localização com província conhecida no dossier.');
$scope = $path->firstWhere('location_type', 'district') ?? $province;
$nodes = $geo->publicReferences()->whereIn('id', $geo->descendants($province->id))->get(['id', 'parent_id', 'name', 'location_type'])->keyBy('id');
$mapping = [];
$scopes = [$province->id => $province];
foreach ($nodes as $node) {
$current = $node;
for ($depth = 0; $current && $depth < 5; $depth++) {
if ($current->location_type === 'district' || $current->location_type === 'province') {
break;
}
$current = $nodes->get($current->parent_id);
}
if ($current && in_array($current->location_type, ['district', 'province'], true)) {
$mapping[$node->id] = $current->id;
$scopes[$current->id] = $current;
}
}
$activities = $this->publicAggregateActivities();
$divisions = $activities->filter(fn ($a) => preg_match('/^[0-9]{2}$/D', $a->code) === 1)->groupBy('code');
$sector = isset($fields['sector_id']) ? (int) $fields['sector_id'] : null;
abort_unless($divisions->contains(fn ($references) => $references->contains(fn ($a) => ! $sector || (int) $a->effective_sector_id === $sector)), 422,
'A classificação de actividades aplicável a este sector ainda não está disponível para esta consulta. O dossier mantém-se guardado; esta limitação não significa ausência de empresas.');
$activity = ! empty($fields['activity_id']) ? $activities->firstWhere('id', $fields['activity_id']) : null;
abort_if(! empty($fields['activity_id']) && ! $activity, 422, 'A actividade guardada não está disponível nesta classificação. Reveja o contexto.');
abort_if($activity && $sector && (int) $activity->effective_sector_id !== $sector, 422, 'A actividade não corresponde ao sector guardado. Reveja o contexto.');
$rawActivityCode = $activity?->code;
abort_if($activity && ! is_string($rawActivityCode), 422, 'A referência de actividade não tem um código válido.');
$activityCode = is_string($rawActivityCode) ? str_replace('.', '', $rawActivityCode) : null;
abort_if($activityCode && ! preg_match('/^[0-9]{2,5}$/D', $activityCode), 422, 'Seleccione uma actividade com código CAE disponível.');
$division = $activityCode ? substr($activityCode, 0, 2) : null;
$previous = DB::selectOne("select current_setting('app.actor_user_id',true) as actor,current_setting('app.proactive_supply_read',true) as scope");
return $this->read($actor, function () use ($mapping, $scopes, $province, $scope, $territory, $path, $divisions, $sector, $division, $activity, $previous): array {
try {
$parts = [];
$bindings = [];
foreach ($mapping as $id => $parent) {
$parts[] = 'WHEN ? THEN ?';
$bindings[] = $id;
$bindings[] = $parent;
}
$scopeSql = 'CASE o.territory_id::text '.implode(' ', $parts).' ELSE NULL END';
$codeSql = "CASE WHEN replace(o.cae,'.','') ~ '^[0-9]{2,5}$' THEN substring(replace(o.cae,'.','') from 1 for 2) ELSE NULL END";
$rows = DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s', 's.sha256', '=', 'o.source_hash')->whereIn('o.territory_id', array_keys($mapping))
->whereRaw("s.receipt->>'candidate' = ? AND s.receipt->>'access' = 'internal'", ['a022ed9848b41ba342b4209414c2bbf2ebd0a7a3'])
->whereNull('o.duplicate_of')->where('o.identity_conflict', false)->whereRaw("trim(o.name) <> ''")
// The accepted importer uses an observation-specific key when NUIT is unresolved.
// Those keys must never masquerade as distinct documentary entities in the cohort.
->whereRaw("o.entity_key <> encode(sha256(convert_to('unresolved:' || o.source_hash || '|' || o.sheet || '|' || o.row_number::text,'UTF8')),'hex')")
->selectRaw($scopeSql.' as scope_id,'.$codeSql.' as code,count(DISTINCT o.entity_key) as entities,count(*) as observations', $bindings)
->groupByRaw('1,2')->orderByRaw('1,2')->get();
$groups = [];
foreach ($rows as $row) {
// Suppressed and absent cells have the same public representation. No marginal totals.
if ((int) $row->entities < 5 || ! $row->code || ! $divisions->has($row->code)) {
continue;
}
$references = $divisions->get($row->code);
if ($sector && ! $references->contains(fn ($a) => (int) $a->effective_sector_id === $sector)) {
continue;
}
if ($division && $row->code !== $division) {
continue;
}
if ($scope->id !== $province->id && ! in_array($row->scope_id, [$scope->id, $province->id], true)) {
continue;
}
$labels = $references->pluck('label_pt_mz')->unique();
$cellScope = $scopes[$row->scope_id];
$groups[] = ['code' => $row->code, 'label' => $labels->count() === 1 ? $labels->first() : 'Grupo CAE '.$row->code,
'total' => null, 'entities_band' => $this->countBand((int) $row->entities), 'observations_band' => $this->countBand((int) $row->observations),
'scope' => ['id' => $cellScope->id, 'name' => $cellScope->name, 'level' => $cellScope->location_type], 'first_year' => null, 'last_year' => null];
}
$years = [];
$unknownPeriod = false;
foreach (DB::table('proactive_supply_sources')->whereRaw("receipt->>'candidate' = ? AND receipt->>'access' = 'internal'", ['a022ed9848b41ba342b4209414c2bbf2ebd0a7a3'])->pluck('period') as $period) {
preg_match_all('/\b(?:19|20)[0-9]{2}\b/', $period, $matches);
if (! $matches[0]) {
$unknownPeriod = true;
}
$years = [...$years, ...$matches[0]];
}
sort($years);
$period = $years ? $years[0].($years[0] !== $years[array_key_last($years)] ? '–'.$years[array_key_last($years)] : '') : 'Por confirmar';
return ['privacy_version' => 1, 'privacy_policy' => 'fixed_district_cae_division_v1',
'requested_territory' => ['id' => $territory, 'name' => $path->last()->name],
'scope' => ['id' => $scope->id, 'name' => $scope->name, 'level' => $scope->location_type],
'broader_context' => $scope->id !== $territory, 'entities' => null, 'repeated' => null, 'uncertain' => null,
'groups' => $groups, 'truncated' => false, 'coverage_unknown' => true,
'filters' => ['sector_id' => $sector, 'activity_id' => $activity?->id, 'activity_label' => $activity?->label_pt_mz, 'division_code' => $division],
'source_summary' => ['label' => 'Base administrativa empresarial histórica incorporada no portal', 'period' => $period, 'incomplete_periods' => $unknownPeriod],
'limitations' => self::LIMITATIONS,
'interpretation' => 'Intervalos de cinco identidades documentais, nunca empresas únicas confirmadas. Observações consolidadas e identidades são medidas distintas. Uma identidade pode constar em várias actividades; não some grupos. Grupos com menos de cinco identidades, conflitos e dados sem classificação publicada não são divulgados; nenhum resultado pode significar ausência de registos ou protecção de informação.',
'privacy_notice' => 'A precisão mínima é distrital e a actividade é apresentada por divisão CAE. Não há totais marginais, contagens exactas, filtros livres ou datas por grupo. Dados apenas provinciais são contexto provincial, não implantação no distrito. Estes controlos reduzem a identificação indirecta; não constituem garantia matemática contra conhecimento externo.'];
} finally {
DB::select("select set_config('app.actor_user_id',?,true),set_config('app.proactive_supply_read',?,true)", [$previous->actor ?? '', $previous->scope ?? '']);
}
});
}
private function countBand(int $count): string
{
$lower = intdiv($count, 5) * 5;
return $lower.'–'.($lower + 4);
}
/** @return Collection<int,\stdClass> */
private function publicAggregateActivities(): Collection
{
$rows = app(EconomicReferenceCatalog::class)->activities()->keyBy('id');
return $rows->map(function ($row) use ($rows) {
$result = clone $row;
$current = $row;
$result->effective_sector_id = null;
for ($i = 0; $current && $i < 10; $i++) {
if ($current->sector_id !== null) {
$result->effective_sector_id = (int) $current->sector_id;
break;
}
$current = $current->parent_id ? $rows->get($current->parent_id) : null;
}
return $result;
})->values();
}
/** @return list<array{id:string,code:string,label:string}> */
public function aggregateActivityOptions(?int $sector): array
{
$rows = $this->publicAggregateActivities();
$divisions = $rows->filter(fn ($a) => preg_match('/^[0-9]{2}$/D', $a->code) === 1)->pluck('code')->all();
$result = [];
foreach ($rows as $a) {
if (! is_string($a->id) || ! is_string($a->code) || ! is_string($a->label_pt_mz)) {
continue;
}
if (($sector && $a->effective_sector_id !== $sector) || ! preg_match('/^[0-9]{2,5}$/D', str_replace('.', '', $a->code))
|| ! in_array(substr(str_replace('.', '', $a->code), 0, 2), $divisions, true)) {
continue;
}
$result[] = ['id' => $a->id, 'code' => $a->code, 'label' => $a->label_pt_mz];
}
return $result;
}
/** Old exact QA snapshots stay stored, but are not exposed by the protected capability.
* @param list<array<string,mixed>> $history
* @return list<array<string,mixed>>
*/
public function protectedHistory(array $history): array
{
$result = [];
foreach ($history as $row) {
if (($row['privacy_version'] ?? null) !== 1 || ($row['privacy_policy'] ?? null) !== 'fixed_district_cae_division_v1') {
continue;
}
$safe = Arr::only($row, ['privacy_version', 'privacy_policy', 'requested_territory', 'scope', 'broader_context', 'truncated', 'coverage_unknown', 'limitations', 'interpretation', 'privacy_notice', 'context_revision', 'recorded_at', 'operation_key']);
$safe['entities'] = $safe['repeated'] = $safe['uncertain'] = null;
$safe['groups'] = [];
foreach ($row['groups'] ?? [] as $group) {
if (! preg_match('/^[0-9]{2}$/D', $group['code'] ?? '') || ! $this->validBand($group['entities_band'] ?? '') || ! $this->validBand($group['observations_band'] ?? '')) {
continue;
}
$safe['groups'][] = [...Arr::only($group, ['code', 'label', 'entities_band', 'observations_band', 'scope']), 'total' => null, 'first_year' => null, 'last_year' => null];
}
$safe['filters'] = Arr::only($row['filters'] ?? [], ['sector_id', 'activity_id', 'activity_label', 'division_code']);
$safe['source_summary'] = Arr::only($row['source_summary'] ?? [], ['label', 'period', 'incomplete_periods']);
$result[] = $safe;
}
return $result;
}
private function validBand(string $band): bool
{
return preg_match('/^([0-9]{1,12})–([0-9]{1,12})$/uD', $band, $m) === 1
&& (int) $m[1] >= 5 && (int) $m[1] % 5 === 0 && (int) $m[2] - (int) $m[1] === 4;
}
/** No names, contacts, row identifiers or free-text activity descriptions leave this boundary.
* @return array<string,mixed>
*/
public function aggregate(User $actor, string $territory): array
{
abort_unless(config('investor-path.aggregate_supply_qa_enabled') && \App\Support\IsolatedQaDatabase::allowsSchemaChanges(), 404);
abort_unless(config('investor-path.aggregate_supply_qa_enabled') && IsolatedQaDatabase::allowsSchemaChanges(), 404);
$path = app(InvestmentGeography::class)->path($territory);
abort_if($path === [], 422, 'Confirme primeiro a localização do dossier.');
return $this->read($actor, function () use ($path, $territory): array {
$labels = app(EconomicReferenceCatalog::class)->activities()->groupBy('code')->map(fn ($rows) => $rows->pluck('label_pt_mz')->unique()->count() === 1 ? $rows->first()->label_pt_mz : null);
$scope = collect($path)->last();
@@ -58,10 +266,11 @@ final class ProactiveSupply
$base = $query($district->id);
}
}
$counts = (clone $base)->selectRaw("count(DISTINCT entity_key) FILTER (WHERE duplicate_of IS NULL AND NOT identity_conflict) AS entities, count(*) FILTER (WHERE duplicate_of IS NOT NULL) AS repeated, count(*) FILTER (WHERE identity_conflict) AS uncertain")->first();
$counts = (clone $base)->selectRaw('count(DISTINCT entity_key) FILTER (WHERE duplicate_of IS NULL AND NOT identity_conflict) AS entities, count(*) FILTER (WHERE duplicate_of IS NOT NULL) AS repeated, count(*) FILTER (WHERE identity_conflict) AS uncertain')->first();
$code = "CASE WHEN cae ~ '^[0-9.]{1,10}$' THEN cae ELSE '' END";
$groups = (clone $base)->whereNull('duplicate_of')->where('identity_conflict', false)->selectRaw($code." AS code, count(DISTINCT entity_key) AS total, min(substring(source_date from '(19[0-9]{2}|20[0-9]{2})')) AS first_year, max(substring(source_date from '(19[0-9]{2}|20[0-9]{2})')) AS last_year")
->groupByRaw($code)->orderByRaw($code)->limit(101)->get()->map(fn ($row) => ['code' => $row->code, 'label' => $row->code ? ($labels->get($row->code) ?? 'CAE '.$row->code.' — descrição por confirmar') : 'Actividade por classificar', 'total' => (int) $row->total, 'first_year' => $row->first_year, 'last_year' => $row->last_year])->all();
return ['requested_territory' => ['id' => $territory, 'name' => collect($path)->last()->name], 'scope' => ['id' => $scope->id, 'name' => $scope->name, 'level' => $scope->location_type],
'broader_context' => $scope->id !== $territory, 'entities' => (int) $counts->entities, 'repeated' => (int) $counts->repeated, 'uncertain' => (int) $counts->uncertain,
'groups' => array_slice($groups, 0, 100), 'truncated' => count($groups) > 100, 'coverage_unknown' => true, 'limitations' => self::LIMITATIONS,
+2
View File
@@ -6,5 +6,7 @@ return [
'enabled' => env('INVESTOR_PATH_ENABLED', false),
// Owner-authorised aggregate experiment: isolated testing database only.
'aggregate_supply_qa_enabled' => env('INVESTOR_AGGREGATE_SUPPLY_QA_ENABLED', false),
// Explicitly authorised, protected statistics in the owner's existing dossier.
'protected_supply_enabled' => env('INVESTOR_PROTECTED_SUPPLY_ENABLED', false),
'definition_id' => '61000919-0000-4000-8000-000000000001',
];
@@ -10287,3 +10287,19 @@ Instalação confirmada em `d3067050`, com backup/restauro e preservação de219
**Limite no destino:** a consulta agregada de empresas da base interna continua exclusiva do QA isolado, conforme a autorização original. Não foi activada nesta instalação e não se alargaram permissões. A consulta pública e a preparação do investimento estão disponíveis; usar os agregados internos na homologação exige decisão específica de acesso e uma alteração compatível. A demonstração completa dessa consulta permanece circunscrita ao QA, separada da pendência de tradução.
## Consulta empresarial protegida no dossier próprio — 15/11/2026
Implementada e verificada em QA, ainda sem instalação deste delta. A decisão expressa «Autorizar apenas agregados protegidos no dossier próprio» permite esta capacidade; não atribui papéis internos nem acesso às listas. A homologação de referência continua em `d3067050` até existir recibo de instalação posterior.
O proprietário encontra «Actividades existentes na localização» no dossier aberto. Recupera território, sector e intenção, pode comparar uma actividade publicada e guardar a análise no mesmo dossier. A escolha de comparação não altera a actividade do investimento. O histórico e o filtro são recuperados após recarregar; os dados de orçamento mantêm-se. O acesso a outro dossier e às linhas/documentos da base interna continua recusado.
Protecção: células fixas distrito/divisão CAE publicada, calculadas antes dos filtros; localidades recebem apenas contexto distrital. Grupos com menos de cinco identidades documentais resolvidas, conflitos, duplicações e identificadores por observação não são divulgados. Os resultados são intervalos de cinco, sem totais marginais ou datas por célula; não se recalculam intersecções arbitrárias. Dados apenas provinciais conservam esse âmbito. Não são empresas únicas certificadas; não se somam grupos. Resultados ausentes e protegidos têm a mesma representação. Fontes, períodos e cobertura desconhecida são explícitos; nomes, contactos, ficheiros e linhas originais não integram a resposta. Os controlos reduzem identificação indirecta e consultas por diferença, sem prometer anonimato matemático perante conhecimento externo ou alterações futuras das fontes.
Provas: 6 testes HTTP/218 asserções, 3 testes frontend, regressão sectorial 5/183, PHPStan dirigido sem erros, tipos, lint e compilação normal/Wayfinder aprovados. Dez execuções autenticadas, cinco sectores × computador/viewport móvel, demonstram consulta → gravação → recuperação no mesmo dossier, filtro e orçamento preservados, histórico e ausência de listas privadas. Emulação não equivale a dispositivo físico. A conferência detectou uma chave React repetida entre secções irmãs; a chave do agregado foi distinguida e os dez casos repetidos no código final, sem duplicação. Os primeiros erros de sincronização/locators do ensaio ficam nos artefactos locais, não são apresentados como provas aprovadas.
Recibo: `outputs/aggregate-supply-20261115/qa-verified.json`; capturas em `outputs/aggregate-supply-20261115/visual/`. Não há migrações, alterações RLS, novos papéis ou permissões, acesso individual/exportação, publicação de Ofertas, notificações externas ou pagamentos. A capacidade é desactivada por defeito e requer apenas a flag específica autorizada no destino; a guarda da base QA permanece inalterada. Reversão: desactivar a flag e regressar à revisão anterior, preservando os snapshots e históricos. Tradução mantém a pendência externa separada. Esta entrega não encerra requisitos globais do portal nem Ofertas.
**Bloqueante confirmado no destino:** a leitura técnica autenticada encontrou apenas cinco códigos gerais publicados (`agronegocio`, `economia-azul`, `infraestruturas`, `mercado-financeiro`, `turismo`) e nenhuma divisão CAE numérica publicada. Os quatro exemplares internos têm o contrato reconhecido e existem grupos documentados não singulares, mas a classificação não é compatível com o adaptador. As dez provas usam referências publicadas sintéticas em QA; não demonstram disponibilidade da classificação no destino. O recorte original CAE A/01/011/0112/01120 está preparado em lote existente e não cobre os cinco sectores. Não se publicou esse lote nem se presumiram correspondências CAE → sectores. O servidor devolve 422 com explicação compreensível quando falta a classificação, sem gravar um resultado falso ou alterar o dossier. O teste adicional passou sem desactivar a guarda de imutabilidade das referências. Instalação suspensa, homologação/main em d3067050, sem reserva, migração, alteração de configuração ou escrita de dados. É necessário reconciliar as referências originais CAE e as correspondências sectoriais no catálogo existente e obter a respectiva validação/publicação editorial, antes de habilitar o delta. A autorização de consulta agregada não publica automaticamente outro lote de referências (AGENTS.md: «Nunca publicar automaticamente um lote»). Isto não exige nem autoriza acesso a empresas individuais. Não existe neste momento um pacote apto para instalação útil nos cinco sectores.
@@ -326,3 +326,19 @@ Recibo final: `outputs/sector-context-20261115/installation-verified.json`. Conc
**Limitação preexistente de acesso que o resumo QA não explicitava:** a consulta agregada da base interna de empresas permanece exclusiva de QA. `InvestorContext::saveSupplyAggregate` exige a flag QA e `IsolatedQaDatabase::allowsSchemaChanges()`; esta última exige ambiente de testes, base `_test` e porta55441. O destino é `teste_investidor:5432`, pelo que essa consulta não foi activada. A guarda, a configuração e as permissões são iguais às de `44c3436b`. A autorização original alargou a consulta apenas em QA; a instalação actual preserva esse limite e não substitui uma decisão de acesso no destino. Os dez percursos demonstrados em QA não constituem prova de consulta agregada real na homologação. As fontes, preparação e restantes ferramentas foram instaladas; o acesso aos agregados internos permanece pendente de decisão expressa e de delta compatível. Isto é distinto da consulta pública de anúncios e da tradução. Não se declara o percurso integral da base interna concluído no activo.
## Consulta empresarial protegida no dossier próprio — 15/11/2026
Implementada e verificada em QA, ainda sem instalação deste delta. A decisão expressa «Autorizar apenas agregados protegidos no dossier próprio» permite esta capacidade; não atribui papéis internos nem acesso às listas. A homologação de referência continua em `d3067050` até existir recibo de instalação posterior.
O proprietário encontra «Actividades existentes na localização» no dossier aberto. Recupera território, sector e intenção, pode comparar uma actividade publicada e guardar a análise no mesmo dossier. A escolha de comparação não altera a actividade do investimento. O histórico e o filtro são recuperados após recarregar; os dados de orçamento mantêm-se. O acesso a outro dossier e às linhas/documentos da base interna continua recusado.
Protecção: células fixas distrito/divisão CAE publicada, calculadas antes dos filtros; localidades recebem apenas contexto distrital. Grupos com menos de cinco identidades documentais resolvidas, conflitos, duplicações e identificadores por observação não são divulgados. Os resultados são intervalos de cinco, sem totais marginais ou datas por célula; não se recalculam intersecções arbitrárias. Dados apenas provinciais conservam esse âmbito. Não são empresas únicas certificadas; não se somam grupos. Resultados ausentes e protegidos têm a mesma representação. Fontes, períodos e cobertura desconhecida são explícitos; nomes, contactos, ficheiros e linhas originais não integram a resposta. Os controlos reduzem identificação indirecta e consultas por diferença, sem prometer anonimato matemático perante conhecimento externo ou alterações futuras das fontes.
Provas: 6 testes HTTP/218 asserções, 3 testes frontend, regressão sectorial 5/183, PHPStan dirigido sem erros, tipos, lint e compilação normal/Wayfinder aprovados. Dez execuções autenticadas, cinco sectores × computador/viewport móvel, demonstram consulta → gravação → recuperação no mesmo dossier, filtro e orçamento preservados, histórico e ausência de listas privadas. Emulação não equivale a dispositivo físico. A conferência detectou uma chave React repetida entre secções irmãs; a chave do agregado foi distinguida e os dez casos repetidos no código final, sem duplicação. Os primeiros erros de sincronização/locators do ensaio ficam nos artefactos locais, não são apresentados como provas aprovadas.
Recibo: `outputs/aggregate-supply-20261115/qa-verified.json`; capturas em `outputs/aggregate-supply-20261115/visual/`. Não há migrações, alterações RLS, novos papéis ou permissões, acesso individual/exportação, publicação de Ofertas, notificações externas ou pagamentos. A capacidade é desactivada por defeito e requer apenas a flag específica autorizada no destino; a guarda da base QA permanece inalterada. Reversão: desactivar a flag e regressar à revisão anterior, preservando os snapshots e históricos. Tradução mantém a pendência externa separada. Esta entrega não encerra requisitos globais do portal nem Ofertas.
**Bloqueante confirmado no destino:** a leitura técnica autenticada encontrou apenas cinco códigos gerais publicados (`agronegocio`, `economia-azul`, `infraestruturas`, `mercado-financeiro`, `turismo`) e nenhuma divisão CAE numérica publicada. Os quatro exemplares internos têm o contrato reconhecido e existem grupos documentados não singulares, mas a classificação não é compatível com o adaptador. As dez provas usam referências publicadas sintéticas em QA; não demonstram disponibilidade da classificação no destino. O recorte original CAE A/01/011/0112/01120 está preparado em lote existente e não cobre os cinco sectores. Não se publicou esse lote nem se presumiram correspondências CAE → sectores. O servidor devolve 422 com explicação compreensível quando falta a classificação, sem gravar um resultado falso ou alterar o dossier. O teste adicional passou sem desactivar a guarda de imutabilidade das referências. Instalação suspensa, homologação/main em d3067050, sem reserva, migração, alteração de configuração ou escrita de dados. É necessário reconciliar as referências originais CAE e as correspondências sectoriais no catálogo existente e obter a respectiva validação/publicação editorial, antes de habilitar o delta. A autorização de consulta agregada não publica automaticamente outro lote de referências (AGENTS.md: «Nunca publicar automaticamente um lote»). Isto não exige nem autoriza acesso a empresas individuais. Não existe neste momento um pacote apto para instalação útil nos cinco sectores.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,212 @@
{
"state": "QA_VERIFIED_TARGET_CLASSIFICATION_BLOCKED",
"baseline": "d3067050278f176e3bdc6c6bb59205c71330744d",
"authorisation": "Autorizar apenas agregados protegidos no dossier próprio",
"tests": {
"http": 6,
"assertions": 218,
"frontend": 3,
"sector_regression_tests": 5,
"sector_regression_assertions": 183,
"phpstan_errors": 0,
"types": "passed",
"build": "passed",
"lint": "passed"
},
"browser": [
{
"sector": "agronegocio",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "78286e97-1759-4cc4-a4d8-8b4786dc5dcc",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "agronegocio",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "78286e97-1759-4cc4-a4d8-8b4786dc5dcc",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
},
{
"sector": "turismo",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "29615b64-2438-4821-a1b5-d6ee6d59ce85",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "turismo",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "29615b64-2438-4821-a1b5-d6ee6d59ce85",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
},
{
"sector": "infraestruturas",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "e9bb7872-0f0f-4bec-b8ca-3c574dec6e49",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "infraestruturas",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "e9bb7872-0f0f-4bec-b8ca-3c574dec6e49",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
},
{
"sector": "mineracao",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "bddd0fa6-9afe-4bdb-a3f9-55e7f53986fa",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "mineracao",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "bddd0fa6-9afe-4bdb-a3f9-55e7f53986fa",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
},
{
"sector": "energia-especifica",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "814433bf-21bc-473b-af48-829f51ade3a7",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "energia-especifica",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "814433bf-21bc-473b-af48-829f51ade3a7",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
}
],
"physical_phone": "not tested; mobile viewport emulation only",
"privacy": {
"minimum_resolved_documentary_identities": 5,
"cell": "fixed district / published CAE division",
"locality": "district scope only",
"counts": "bands of five; no marginal totals",
"source_contract": "a022ed9848b41ba342b4209414c2bbf2ebd0a7a3",
"unresolved_observation_keys": "excluded",
"names_contacts_individual_exports": false,
"role_grants": false,
"limitations": "No mathematical anonymity guarantee against external knowledge; documentary identifiers are not certified unique companies; absent and suppressed results indistinguishable; unknown coverage explicit"
},
"required_activation": "INVESTOR_PROTECTED_SUPPLY_ENABLED=true only in authorised homologation",
"migrations": [],
"translation": "separate pending external dependency",
"timestamp_utc": "2026-11-15T21:09:16.804612+00:00",
"destination_blocker": {
"installed": "d3067050",
"published_activity_codes": [
"agronegocio",
"economia-azul",
"infraestruturas",
"mercado-financeiro",
"turismo"
],
"published_numeric_cae_divisions": 0,
"catalogue_lot_01": "draft / not automatically published",
"installation": "blocked; no reservation, push, migration or config activation executed",
"required_resolution": "Reconcile original CAE references and sector correspondences in existing catalogue; editorial confirmation before exposing new references; do not invent mappings",
"approval_rule": "AGENTS.md: Nunca publicar automaticamente um lote"
},
"sha256": {
"app/Services/ProactiveSupply.php": "9fdb39dc0ac5576653ba83ada16ffba26c22c9294cd9f129648244fa2e7ad7d8",
"app/Services/InvestorContext.php": "548393db063d8537083781085f0631c45398a9c214d942043d846268a4a3dba5",
"app/Services/InvestorPath.php": "eae30cb00f1c476b5ebd79909a1a338a70775337cf7016f15d5ecbe6e13b9bd3",
"config/investor-path.php": "571862669a02421bbeea3b95e05737d393ed6c8d3afb507f0d0aa74d037f89ca",
"resources/js/components/investment-supply-aggregate.tsx": "3259e42e5365f8a92f99a42b920d03e11b0fd3fcbbc7e124b2f9f682eb50fd21",
"resources/js/lib/investor-context.ts": "efd43cd36adfed2c95b3ed53a7d71e7a4bf2a3822576114bda1d4c734fd0e344",
"resources/js/pages/investor-path/show.tsx": "66b9a2e86843a93d5b52f73a198de4a2f4e576ca9f699fa9a0f61eb023f51604",
"tests/Feature/ProtectedSupplyAggregateTest.php": "dee530a28dcb856825dd817e6cdf6ebc5b6fd80441db4a31e6e9011550aa4272",
"tests/frontend/protected-supply-aggregate.test.mjs": "9fe058ddcb479bd1a8370887acc75ba9799fc8af4050109867b8c7bb4be76682"
},
"mobile_table_checks": [
{
"sector": "agronegocio",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
},
{
"sector": "turismo",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
},
{
"sector": "infraestruturas",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
},
{
"sector": "mineracao",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
},
{
"sector": "energia-especifica",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
}
]
}
@@ -0,0 +1,32 @@
[
{
"sector": "agronegocio",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
},
{
"sector": "turismo",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
},
{
"sector": "infraestruturas",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
},
{
"sector": "mineracao",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
},
{
"sector": "energia-especifica",
"width": 390,
"horizontalTableAccessible": true,
"emulationOnly": true
}
]
@@ -0,0 +1,122 @@
[
{
"sector": "agronegocio",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "78286e97-1759-4cc4-a4d8-8b4786dc5dcc",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "agronegocio",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "78286e97-1759-4cc4-a4d8-8b4786dc5dcc",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
},
{
"sector": "turismo",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "29615b64-2438-4821-a1b5-d6ee6d59ce85",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "turismo",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "29615b64-2438-4821-a1b5-d6ee6d59ce85",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
},
{
"sector": "infraestruturas",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "e9bb7872-0f0f-4bec-b8ca-3c574dec6e49",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "infraestruturas",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "e9bb7872-0f0f-4bec-b8ca-3c574dec6e49",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
},
{
"sector": "mineracao",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "bddd0fa6-9afe-4bdb-a3f9-55e7f53986fa",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "mineracao",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "bddd0fa6-9afe-4bdb-a3f9-55e7f53986fa",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
},
{
"sector": "energia-especifica",
"width": 1440,
"status": "APROVADO",
"viewportEmulation": false,
"sameDossier": "814433bf-21bc-473b-af48-829f51ade3a7",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": false
},
{
"sector": "energia-especifica",
"width": 390,
"status": "APROVADO",
"viewportEmulation": true,
"sameDossier": "814433bf-21bc-473b-af48-829f51ade3a7",
"filterRecovered": true,
"budgetContextPreserved": true,
"smallCellsProtected": true,
"noRawData": true,
"historyRecovered": true
}
]
@@ -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}
/>
)}
@@ -0,0 +1,241 @@
<?php
namespace Tests\Feature;
use App\Models\Sector;
use App\Models\User;
use App\Services\ProactiveSupply;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
final class ProtectedSupplyAggregateTest extends TestCase
{
use DatabaseTransactions;
private User $owner;
private array $geo = [];
private array $sectors = [];
private array $activities = [];
private int $observationSequence = 0;
private string $sourceHash;
protected function setUp(): void
{
parent::setUp();
$db = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('sector_context_20261115_test', $db->name);
$this->assertSame(55441, (int) $db->port);
$this->withoutVite();
config(['portal.profile_access_enabled' => true, 'investor-path.enabled' => true, 'investor-path.protected_supply_enabled' => true, 'investor-path.aggregate_supply_qa_enabled' => false]);
$this->owner = User::factory()->create();
foreach (['country' => [null, 'country'], 'province' => ['country', 'province'], 'other_province' => ['country', 'province'], 'small' => ['province', 'district'], 'large' => ['province', 'district'], 'post' => ['large', 'admin_post'], 'locality_a' => ['post', 'locality'], 'locality_b' => ['post', 'locality']] as $key => [$parent, $type]) {
$id = (string) Str::uuid();
$this->geo[$key] = $id;
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent ? $this->geo[$parent] : null, 'name' => 'SYNTHETIC '.$key, 'code' => $id,
'location_type' => $type, 'source_system' => 'cartografia-workbook', 'data_classification' => 'public',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
}
$catalog = (string) Str::uuid();
DB::table('reference_catalog_versions')->insert(['id' => $catalog, 'catalog_code' => 'qa-'.Str::random(16), 'version_no' => 1, 'source_system' => 'SYNTHETIC', 'source_version' => 'SYNTHETIC', 'source_reference' => 'SYNTHETIC', 'status' => 'published']);
foreach (['agro' => ['A', '01'], 'hotel' => ['I', '55'], 'infrastructure' => ['F', '41'], 'mining' => ['B', '07'], 'energy' => ['D', '35']] as $key => [$section, $division]) {
$sector = Sector::create(['name' => 'SYNTHETIC '.$key, 'slug' => 'qa-'.Str::lower(Str::random(16)), 'is_active' => true]);
$this->sectors[$key] = $sector->id;
$parent = null;
foreach ([$section, $division, $division.'110'] as $index => $code) {
$id = (string) Str::uuid();
DB::table('economic_activities')->insert(['id' => $id, 'parent_id' => $parent, 'sector_id' => $index === 0 ? $sector->id : null,
'catalog_version_id' => $catalog, 'code' => $code, 'label_pt_mz' => 'SYNTHETIC public '.$key.' '.$code,
'status' => 'published', 'valid_from' => '2020-01-01']);
$parent = $id;
}
$this->activities[$key] = $parent;
}
$source = hash('sha256', Str::uuid());
$this->sourceHash = $source;
DB::table('proactive_supply_sources')->insert(['sha256' => $source, 'name' => 'PRIVATE-ORIGINAL.xlsx', 'period' => '2020', 'limitations' => 'SYNTHETIC', 'receipt' => json_encode(['candidate' => 'a022ed9848b41ba342b4209414c2bbf2ebd0a7a3', 'access' => 'internal', 'synthetic' => true], JSON_THROW_ON_ERROR), 'imported_at' => now()]);
foreach (['01', '55', '41', '07', '35'] as $division) {
for ($i = 0; $i < 6; $i++) {
$this->observation($source, $division, 'large-'.$i, $this->geo[$i < 3 ? 'locality_a' : 'locality_b']);
}
for ($i = 0; $i < 4; $i++) {
$this->observation($source, $division, 'small-'.$i, $this->geo['small']);
}
for ($i = 0; $i < 5; $i++) {
$this->observation($source, $division, 'other-'.$i, $this->geo['other_province']);
}
for ($i = 0; $i < 6; $i++) {
$this->observation($source, $division, 'large-0', $this->geo['locality_a']);
}
}
}
private function observation(string $source, string $division, string $entity, string $territory): string
{
$id = hash('sha256', Str::uuid());
DB::table('proactive_supply_observations')->insert(['id' => $id, 'source_hash' => $source, 'sheet' => 'PRIVATE-SHEET', 'row_number' => ++$this->observationSequence,
'entity_key' => hash('sha256', $division.$entity), 'name' => 'PRIVATE-COMPANY-'.$entity, 'province' => 'PRIVATE', 'district' => 'PRIVATE',
'cae' => $division.'110', 'activity' => 'PRIVATE-CONTACT +258000000000', 'sector' => 'PRIVATE-RAW-SECTOR', 'source_date' => '2020', 'fingerprint' => $id,
'duplicate_of' => null, 'identity_conflict' => false, 'territory_id' => $territory, 'territory_resolution' => 'SYNTHETIC']);
return $id;
}
private function dossier(string $sector = 'agro', string $territory = 'locality_a'): string
{
$id = $this->actingAs($this->owner)->postJson('/investimentos', ['title' => 'SYNTHETIC deliberate '.$sector, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$v = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json('case.version');
$body = ['version' => $v, 'selection' => ['sector' => 'sector:'.$this->sectors[$sector], 'territory' => 'territory:'.$this->geo[$territory]],
'opportunity_choices' => [], 'declarations' => ['project_title' => 'SYNTHETIC deliberate '.$sector, 'products_services' => 'SYNTHETIC deliberate activity', 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
$hash = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json('preview_hash');
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $hash, 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
return $id;
}
private function aggregateSnapshot(string $id, array $extra = []): array
{
$version = $this->getJson('/investimentos/'.$id)->assertOk()->json('case.version');
return $this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid(), ...$extra])->assertOk()->json('analysis');
}
public function test_five_sector_dossiers_save_recover_and_filter_only_protected_statistics(): void
{
$assignments = DB::table('portal_role_assignments')->count();
foreach (array_keys($this->sectors) as $sector) {
$id = $this->dossier($sector);
$a = $this->aggregateSnapshot($id, ['activity_id' => $this->activities[$sector]]);
$this->assertSame(1, $a['privacy_version']);
$this->assertNull($a['entities']);
$this->assertNull($a['repeated']);
$this->assertNull($a['uncertain']);
$this->assertCount(1, $a['groups']);
$this->assertSame('5–9', $a['groups'][0]['entities_band']);
$this->assertSame('10–14', $a['groups'][0]['observations_band']);
$this->assertNull($a['groups'][0]['total']);
$this->assertSame($this->geo['large'], $a['groups'][0]['scope']['id']);
$this->assertTrue($a['broader_context']);
$this->assertSame('2020', $a['source_summary']['period']);
$this->assertSame($this->activities[$sector], $a['filters']['activity_id']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($a, JSON_THROW_ON_ERROR));
$v = $this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'supply_aggregates')->assertJsonPath('supply_aggregates.0.privacy_version', 1)->json('case.version');
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $v - 1, 'operation_key' => $a['operation_key'], 'activity_id' => $this->activities[$sector]])->assertOk()->assertJsonPath('replayed', true);
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.investment_budget_min', '1000000')->assertJsonPath('prefill.simulator.investment_budget_max', '5000000')->assertJsonPath('prefill.simulator.project_title', 'SYNTHETIC deliberate '.$sector);
}
$this->assertSame($assignments, DB::table('portal_role_assignments')->count());
}
public function test_small_cells_and_differencing_do_not_reveal_exact_counts(): void
{
$id = $this->dossier();
$service = app(ProactiveSupply::class);
$fields = ['sector_id' => $this->sectors['agro']];
$before = DB::selectOne("select NULLIF(current_setting('app.actor_user_id',true),'') as actor,NULLIF(current_setting('app.proactive_supply_read',true),'') as scope");
$local = $service->protectedAggregate($this->owner, $id, $this->geo['locality_a'], $fields);
$otherLocal = $service->protectedAggregate($this->owner, $id, $this->geo['locality_b'], $fields);
$district = $service->protectedAggregate($this->owner, $id, $this->geo['large'], $fields);
$province = $service->protectedAggregate($this->owner, $id, $this->geo['province'], $fields);
$small = $service->protectedAggregate($this->owner, $id, $this->geo['small'], $fields);
$this->assertSame($local['groups'], $otherLocal['groups']);
$this->assertSame($local['groups'], $district['groups']);
$this->assertSame($district['groups'], $province['groups']);
$this->assertSame([], $small['groups']);
$this->assertNull($province['entities']);
$this->assertNull($district['groups'][0]['total']);
$this->assertSame((array) $before, (array) DB::selectOne("select NULLIF(current_setting('app.actor_user_id',true),'') as actor,NULLIF(current_setting('app.proactive_supply_read',true),'') as scope"));
}
public function test_owner_isolation_no_raw_access_unknown_filter_rejection_and_disabled_guard(): void
{
$id = $this->dossier();
$version = $this->getJson('/investimentos/'.$id)->json('case.version');
$body = ['version' => $version, 'operation_key' => (string) Str::uuid()];
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', [...$body, 'territory_id' => $this->geo['other_province']])->assertUnprocessable();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', [...$body, 'activity_id' => $this->activities['hotel']])->assertUnprocessable();
$this->getJson('/minhas-oportunidades/oferta-interna')->assertForbidden();
try {
app(ProactiveSupply::class)->authorize($this->owner);
$this->fail('Aggregate capability must not grant internal source access.');
} catch (HttpException $error) {
$this->assertSame(403, $error->getStatusCode());
}
$this->actingAs(User::factory()->create())->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', $body)->assertForbidden();
$this->getJson('/investimentos/'.$id)->assertForbidden();
$this->actingAs($this->owner);
$a = $this->aggregateSnapshot($id);
config(['investor-path.protected_supply_enabled' => false]);
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', $body)->assertNotFound();
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('supply_aggregates', [])->assertJsonPath('supply_aggregate_enabled', false);
config(['investor-path.protected_supply_enabled' => true]);
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('supply_aggregates.0.operation_key', $a['operation_key']);
}
public function test_no_raw_export_no_guest_access_and_no_legacy_exact_history_disclosure(): void
{
$id = $this->dossier();
$a = $this->aggregateSnapshot($id, ['activity_id' => $this->activities['agro']]);
$version = $this->getJson('/investimentos/'.$id)->json('case.version');
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => $a['operation_key'], 'activity_id' => null])->assertConflict();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid(), 'export' => 'csv'])->assertUnprocessable();
$this->getJson('/investimentos/'.$id.'/contexto/oferta-agregada?export=csv')->assertStatus(405);
$row = [...$a, 'PRIVATE-RAW' => 'PRIVATE-COMPANY', 'entities' => 1];
$row['groups'][0]['total'] = 1;
$row['groups'][0]['PRIVATE-CONTACT'] = 'PRIVATE-CONTACT';
$safe = app(ProactiveSupply::class)->protectedHistory([[...$a, 'privacy_version' => 0], $row]);
$this->assertCount(1, $safe);
$this->assertNull($safe[0]['entities']);
$this->assertNull($safe[0]['groups'][0]['total']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($safe, JSON_THROW_ON_ERROR));
$row['groups'][0]['entities_band'] = '1–1';
$this->assertSame([], app(ProactiveSupply::class)->protectedHistory([$row])[0]['groups']);
$this->app['auth']->forgetGuards();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid()])->assertUnauthorized();
}
public function test_unpublished_classification_is_not_presented_as_an_empty_business_result(): void
{
$sector = Sector::create(['name' => 'SYNTHETIC without public CAE', 'slug' => 'qa-'.Str::lower(Str::random(16)), 'is_active' => true]);
$this->sectors['without_cae'] = $sector->id;
$catalog = (string) Str::uuid();
DB::table('reference_catalog_versions')->insert(['id' => $catalog, 'catalog_code' => 'qa-'.Str::random(16), 'version_no' => 1, 'source_system' => 'SYNTHETIC', 'source_version' => 'SYNTHETIC', 'source_reference' => 'SYNTHETIC', 'status' => 'draft']);
DB::table('economic_activities')->insert(['id' => (string) Str::uuid(), 'sector_id' => $sector->id, 'catalog_version_id' => $catalog, 'code' => '01', 'label_pt_mz' => 'SYNTHETIC unpublished division', 'status' => 'draft', 'valid_from' => '2020-01-01']);
$id = $this->dossier('without_cae', 'locality_a');
$before = $this->actingAs($this->owner)->getJson('/investimentos/'.$id)->assertOk()->json();
$response = $this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $before['case']['version'], 'operation_key' => (string) Str::uuid(), 'activity_id' => null])->assertUnprocessable();
$this->assertStringContainsString('não significa ausência de empresas', $response->json('message'));
$after = $this->getJson('/investimentos/'.$id)->assertOk()->json();
$this->assertSame($before['case']['version'], $after['case']['version']);
$this->assertSame([], $after['supply_aggregates']);
$this->assertSame([], $after['supply_activity_options']);
}
public function test_unresolved_observation_keys_conflicts_duplicates_and_unknown_import_contracts_do_not_form_a_publishable_cohort(): void
{
$unknown = hash('sha256', Str::uuid());
DB::table('proactive_supply_sources')->insert(['sha256' => $unknown, 'name' => 'PRIVATE-FUTURE-SOURCE', 'period' => '2025', 'limitations' => 'SYNTHETIC', 'receipt' => json_encode(['candidate' => 'UNKNOWN', 'access' => 'internal'], JSON_THROW_ON_ERROR), 'imported_at' => now()]);
for ($i = 0; $i < 6; $i++) {
$id = $this->observation($this->sourceHash, '01', 'unresolved-'.$i, $this->geo['small']);
$unresolved = hash('sha256', 'unresolved:'.$this->sourceHash.'|PRIVATE-SHEET|'.$this->observationSequence);
DB::table('proactive_supply_observations')->where('id', $id)->update(['entity_key' => $unresolved]);
$conflict = $this->observation($this->sourceHash, '01', 'conflict-'.$i, $this->geo['small']);
DB::table('proactive_supply_observations')->where('id', $conflict)->update(['identity_conflict' => true]);
$duplicate = $this->observation($this->sourceHash, '01', 'duplicate-'.$i, $this->geo['small']);
DB::table('proactive_supply_observations')->where('id', $duplicate)->update(['duplicate_of' => $id]);
$this->observation($unknown, '01', 'unknown-'.$i, $this->geo['small']);
}
$id = $this->dossier('agro', 'small');
$a = $this->aggregateSnapshot($id);
$this->assertSame([], $a['groups']);
$this->assertNull($a['entities']);
$this->assertSame('2020', $a['source_summary']['period']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($a, JSON_THROW_ON_ERROR));
}
}
@@ -0,0 +1,152 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const file = new URL(
'../../resources/js/components/investment-supply-aggregate.tsx',
import.meta.url,
);
const code = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: {
jsx: ts.JsxEmit.ReactJSX,
module: ts.ModuleKind.CommonJS,
},
}).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => {
if (name === '@inertiajs/react') return { router: { reload() {} } };
if (name === '@/lib/investor-context') return { contextApi() {} };
if (name === '@/lib/operation-key')
return { createOperationKey: () => 'SYNTHETIC' };
if (name === './catalogue-choice-select')
return {
default: ({ label, options }) =>
React.createElement(
'label',
null,
label,
React.createElement(
'select',
null,
options.map((o) =>
React.createElement(
'option',
{ key: o.value },
o.label,
),
),
),
),
};
return require(name);
},
module,
module.exports,
);
const Component = module.exports.default;
const fixture = () => ({
privacy_version: 1,
privacy_policy: 'fixed_district_cae_division_v1',
context_revision: 1,
recorded_at: '2026-11-15',
requested_territory: { id: 'local', name: 'Local conhecido' },
scope: { id: 'district', name: 'Distrito conhecido', level: 'district' },
broader_context: true,
entities: 987654321,
repeated: 987654321,
uncertain: 987654321,
source_summary: {
label: 'Originais reservados à equipa',
period: '2020',
incomplete_periods: true,
},
filters: {
sector_id: 1,
activity_id: 'published-activity',
activity_label: 'Agricultura',
division_code: '01',
},
groups: [
{
code: '01',
label: 'Agricultura',
total: 987654321,
entities_band: '5–9',
observations_band: '10–14',
scope: {
id: 'district',
name: 'Distrito conhecido',
level: 'district',
},
first_year: 'PRIVATE-DATE',
last_year: null,
},
],
interpretation: 'Não somar grupos nem inferir procura.',
limitations: 'Cobertura desconhecida.',
privacy_notice: 'Grupos pequenos não divulgados.',
});
const render = (history) =>
renderToStaticMarkup(
React.createElement(Component, {
caseId: 'synthetic',
version: 1,
revision: 2,
history,
protectedMode: true,
activityOptions: [
{
id: 'published-activity',
code: '01110',
label: 'Agricultura',
},
],
}),
);
void test('protected presentation shows documentary identities and observations as separate bands, not raw marginal totals or dates', () => {
const html = render([fixture()]);
assert.match(html, /5–9/);
assert.match(html, /10–14/);
assert.match(html, /Identidades documentais/);
assert.match(html, /Observações consolidadas/);
assert.match(html, /Contexto distrital/);
assert.match(html, /Local conhecido/);
assert.match(html, /2020/);
assert.match(html, /períodos não indicados/);
assert.match(html, /O contexto mudou/);
assert.match(html, /Actividade a comparar/);
assert.ok(!html.includes('987654321'));
assert.ok(!html.includes('PRIVATE-DATE'));
});
void test('suppressed and absent results use the same non-inference message, never zero businesses', () => {
const row = fixture();
row.groups = [];
const html = render([row]);
assert.match(html, /podem faltar registos ou existir grupos protegidos/);
assert.match(html, /não significa ausência de empresas/);
assert.ok(!html.includes('987654321'));
});
void test('legacy exact QA snapshots are not displayed in protected mode and current protected history is recoverable', () => {
const legacy = {
...fixture(),
privacy_version: undefined,
entities: 987654321,
};
const html = render([
legacy,
fixture(),
{ ...fixture(), recorded_at: '2026-11-16' },
]);
assert.match(html, /Análise guardada/);
assert.match(html, /2026-11-16/);
assert.ok(!html.includes('987654321'));
assert.ok(!render([legacy]).includes('Identidades documentais'));
});