fix: reconcile accepted source classifications for protected investor aggregates
tests / ci (push) Waiting to run
tests / ci (push) Waiting to run
This commit is contained in:
@@ -80,10 +80,11 @@ final class ProactiveSupply
|
||||
$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.');
|
||||
$sourcePlan = ! empty($fields['supply_classification_key']) ? $this->sourceClassificationPlan($fields['supply_classification_key']) : null;
|
||||
abort_unless($sourcePlan || $divisions->contains(fn ($references) => $references->contains(fn ($a) => ! $sector || (int) $a->effective_sector_id === $sector)), 422,
|
||||
'Escolha a actividade a comparar na classificação das fontes. O sector do dossier mantém-se guardado; não se presume uma equivalência. Esta limitação não significa ausência de empresas.');
|
||||
$activity = ! $sourcePlan && ! empty($fields['activity_id']) ? $activities->firstWhere('id', $fields['activity_id']) : null;
|
||||
abort_if(! $sourcePlan && ! 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.');
|
||||
@@ -92,7 +93,7 @@ final class ProactiveSupply
|
||||
$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 {
|
||||
return $this->read($actor, function () use ($mapping, $scopes, $province, $scope, $territory, $path, $divisions, $sector, $division, $activity, $previous, $sourcePlan): array {
|
||||
try {
|
||||
$parts = [];
|
||||
$bindings = [];
|
||||
@@ -103,7 +104,12 @@ final class ProactiveSupply
|
||||
}
|
||||
$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))
|
||||
$query = DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s', 's.sha256', '=', 'o.source_hash');
|
||||
if ($sourcePlan) {
|
||||
$this->joinSourceClassification($query, $sourcePlan);
|
||||
$codeSql = $this->sourceClassificationExpression();
|
||||
}
|
||||
$rows = $query->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.
|
||||
@@ -114,14 +120,14 @@ final class ProactiveSupply
|
||||
$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)) {
|
||||
if ((int) $row->entities < 5 || ! $row->code || (! $sourcePlan && ! $divisions->has($row->code))) {
|
||||
continue;
|
||||
}
|
||||
$references = $divisions->get($row->code);
|
||||
if ($sector && ! $references->contains(fn ($a) => (int) $a->effective_sector_id === $sector)) {
|
||||
$references = $divisions->get($row->code, collect());
|
||||
if (! $sourcePlan && $sector && ! $references->contains(fn ($a) => (int) $a->effective_sector_id === $sector)) {
|
||||
continue;
|
||||
}
|
||||
if ($division && $row->code !== $division) {
|
||||
if (($sourcePlan && $row->code !== $sourcePlan['selected']['group']) || (! $sourcePlan && $division && $row->code !== $division)) {
|
||||
continue;
|
||||
}
|
||||
if ($scope->id !== $province->id && ! in_array($row->scope_id, [$scope->id, $province->id], true)) {
|
||||
@@ -129,7 +135,8 @@ final class ProactiveSupply
|
||||
}
|
||||
$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,
|
||||
$groups[] = ['code' => $sourcePlan ? $sourcePlan['selected']['group_code'] : $row->code, 'label' => $sourcePlan ? $sourcePlan['selected']['group_label'] : ($labels->count() === 1 ? $labels->first() : 'Grupo CAE '.$row->code),
|
||||
...($sourcePlan ? ['classification_key' => $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];
|
||||
}
|
||||
@@ -150,7 +157,8 @@ final class ProactiveSupply
|
||||
'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],
|
||||
'filters' => ['sector_id' => $sector, 'activity_id' => $activity?->id, 'activity_label' => $activity?->label_pt_mz, 'division_code' => $sourcePlan ? $sourcePlan['selected']['group_code'] : $division,
|
||||
...($sourcePlan ? ['classification_key' => $sourcePlan['selected']['id'], 'classification_label' => $sourcePlan['selected']['label'], 'classification_basis' => 'Hierarquia e designações do exemplar eBAU já utilizado nas fontes; correspondência por código ou designação exacta, sem equivalência presumida ao sector do dossier.'] : [])],
|
||||
'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.',
|
||||
@@ -168,6 +176,47 @@ final class ProactiveSupply
|
||||
return $lower.'–'.($lower + 4);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function sourceClassificationPlan(string $key): array
|
||||
{
|
||||
$nodes = collect(app(EconomicReferenceCatalog::class)->supplyClassification()['nodes']);
|
||||
$selected = $nodes->firstWhere('id', $key);
|
||||
abort_unless($selected !== null, 422, 'A classificação seleccionada não consta do exemplar disponível.');
|
||||
$codes = $labels = [];
|
||||
foreach ($nodes->groupBy(fn ($n) => mb_strtoupper(str_replace('.', '', trim($n['code'])))) as $code => $items) {
|
||||
if ($items->pluck('group')->unique()->count() === 1) {
|
||||
$codes[] = [(string) $code, $items->first()['group']];
|
||||
}
|
||||
}
|
||||
foreach ($nodes->groupBy(fn ($n) => mb_strtolower(trim($n['label']))) as $label => $items) {
|
||||
if ($items->pluck('group')->unique()->count() === 1) {
|
||||
$labels[] = [(string) $label, $items->first()['group']];
|
||||
}
|
||||
}
|
||||
|
||||
return ['selected' => $selected, 'codes' => $codes, 'labels' => $labels];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $plan */
|
||||
private function joinSourceClassification(Builder $query, array $plan): void
|
||||
{
|
||||
foreach (['codes' => ['class_code', 'upper(replace(btrim(o.cae),\'.\',\'\'))'], 'labels' => ['class_label', "translate(lower(btrim(o.activity)),'ÁÀÂÃÉÊÍÓÔÕÚÜÇ','áàâãéêíóôõúüç')"]] as $kind => [$alias, $expression]) {
|
||||
$rows = $plan[$kind];
|
||||
$values = implode(',', array_fill(0, count($rows), '(?::text,?::text)'));
|
||||
$query->leftJoin(DB::raw('(VALUES '.$values.') AS '.$alias.'(value,group_id)'), function ($join) use ($alias, $expression) {
|
||||
$join->on(DB::raw($expression), '=', $alias.'.value');
|
||||
})->addBinding(array_merge(...$rows), 'join');
|
||||
}
|
||||
}
|
||||
|
||||
/** @return literal-string */
|
||||
private function sourceClassificationExpression(): string
|
||||
{
|
||||
// Already accepted tourism import: documentary scope is accommodation, not a certified hotel subtype.
|
||||
return "CASE WHEN o.source_hash='f02e086ed4973ef17234aa6cc54b98fbb7a6952ffb16ec4dc4f7d0c72af6400c' AND btrim(o.cae)='' AND o.activity='Alojamento (âmbito do exemplar; categoria por conferir)' THEN 'ebau:158'
|
||||
WHEN class_code.group_id IS NOT NULL THEN CASE WHEN btrim(o.activity)='' OR class_label.group_id=class_code.group_id THEN class_code.group_id ELSE NULL END ELSE class_label.group_id END";
|
||||
}
|
||||
|
||||
/** @return Collection<int,\stdClass> */
|
||||
private function publicAggregateActivities(): Collection
|
||||
{
|
||||
@@ -206,6 +255,10 @@ final class ProactiveSupply
|
||||
$result[] = ['id' => $a->id, 'code' => $a->code, 'label' => $a->label_pt_mz];
|
||||
}
|
||||
|
||||
foreach (app(EconomicReferenceCatalog::class)->supplyClassification()['nodes'] as $node) {
|
||||
$result[] = ['id' => $node['id'], 'code' => $node['code'], 'label' => $node['label']];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
@@ -227,9 +280,9 @@ final class ProactiveSupply
|
||||
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['groups'][] = [...Arr::only($group, ['code', 'label', 'entities_band', 'observations_band', 'scope', 'classification_key']), 'total' => null, 'first_year' => null, 'last_year' => null];
|
||||
}
|
||||
$safe['filters'] = Arr::only($row['filters'] ?? [], ['sector_id', 'activity_id', 'activity_label', 'division_code']);
|
||||
$safe['filters'] = Arr::only($row['filters'] ?? [], ['sector_id', 'activity_id', 'activity_label', 'division_code', 'classification_key', 'classification_label', 'classification_basis']);
|
||||
$safe['source_summary'] = Arr::only($row['source_summary'] ?? [], ['label', 'period', 'incomplete_periods']);
|
||||
$result[] = $safe;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user