Criar Hotel: a CAE de hotelaria fica associada à intenção, com detalhe até ao nível 5
tests / ci (push) Waiting to run

Em «Actividades existentes na localização», um dossier cuja intenção é um
hotel passa a ficar associado à classe 551 «Estabelecimentos hoteleiros» da
CAE-Rev.2 (INE, 2008), por correspondência documentada no código, e a lista
mostra apenas as classes de hotelaria, da classe 551 até ao nível 5 (por
exemplo 55111 «Hotéis com restaurante»). O detalhe continua a ser escolha do
investidor, como fixa o aditamento 3 aprovado em 20/11/2026. Sem
correspondência documentada nada é associado e a lista completa mantém-se.

A lista deixa de pré-seleccionar um valor que não esteja nela: um
identificador guardado que não corresponda a uma opção já não aparece como
«Escolha guardada — designação por recuperar». As designações oficiais em
maiúsculas passam a texto corrente.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
Claude
2026-12-05 00:14:01 +02:00
committed by nala
parent c558960500
commit 66316f0902
5 changed files with 120 additions and 19 deletions
+8 -4
View File
@@ -175,7 +175,9 @@ final class InvestorPath
'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_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_activity_intention' => $supplyIntention = $supplyEnabled && config('investor-path.protected_supply_enabled')
? app(ProactiveSupply::class)->intentionClassification(trim(($context['fields']['project_title'] ?? '').' '.($context['fields']['project_summary'] ?? ''))) : null,
'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, $supplyIntention) : [],
'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) : [],
@@ -379,9 +381,11 @@ final class InvestorPath
return DB::transaction(function () use ($actor, $id, $data): string {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
if (!empty($data['preparation_action'])) { app(InvestmentConsumerScope::class)->key(app(InvestorContext::class)->state($case), $data['opportunity'] ?? null, true); }
$origin = !empty($data['preparation_action']) ? app(InvestmentPreparationWorkspace::class)->continuation($actor, $id, $data['opportunity'] ?? null, $data['preparation_action']) : null;
abort_if(!empty($data['preparation_action']) && (!$origin || $origin['kind'] !== 'risk'), 422, 'A acção SWOT não pertence a este dossier/oportunidade ou não é uma acção de risco.');
if (! empty($data['preparation_action'])) {
app(InvestmentConsumerScope::class)->key(app(InvestorContext::class)->state($case), $data['opportunity'] ?? null, true);
}
$origin = ! empty($data['preparation_action']) ? app(InvestmentPreparationWorkspace::class)->continuation($actor, $id, $data['opportunity'] ?? null, $data['preparation_action']) : null;
abort_if(! empty($data['preparation_action']) && (! $origin || $origin['kind'] !== 'risk'), 422, 'A acção SWOT não pertence a este dossier/oportunidade ou não é uma acção de risco.');
$key = $origin ? 'swot:'.$origin['id'] : 'path:'.$data['code'];
$existing = DB::table('tasks')->where('desk_case_id', $id)->where('guidance_key', $key)->first();
if ($existing) {
+37 -2
View File
@@ -238,9 +238,44 @@ final class ProactiveSupply
})->values();
}
/** @return list<array{id:string,code:string,label:string}> */
public function aggregateActivityOptions(?int $sector): array
/**
* Documented correspondences between the investor's stated intention and the CAE (mapa de erros, "Criar Hotel";
* aditamento 3 aprovado em 20/11/2026). Only a correspondence written here is applied; the detail within the class
* (level 4 or 5) is always the investor's choice.
*/
private const INTENTION_CLASSIFICATIONS = [
['pattern' => '/\\bhot[eé]is?\\b|\\bhotel(?:aria|eir[oa]s?)?\\b/iu', 'code' => '551',
'basis' => 'CAE-Rev.2 (INE, 2008), classe 551 «Estabelecimentos hoteleiros», correspondente à intenção «hotel» declarada no dossier.'],
];
/** @return array{id:string,code:string,label:string,basis:string}|null */
public function intentionClassification(string $intention): ?array
{
foreach (self::INTENTION_CLASSIFICATIONS as $correspondence) {
if (preg_match($correspondence['pattern'], $intention) !== 1) {
continue;
}
$node = collect(app(EconomicReferenceCatalog::class)->supplyClassification()['nodes'])->firstWhere('code', $correspondence['code']);
return $node ? ['id' => $node['id'], 'code' => $node['code'], 'label' => $node['label'], 'basis' => $correspondence['basis']] : null;
}
return null;
}
/**
* @param array{code:string}|null $intention
* @return list<array{id:string,code:string,label:string}>
*/
public function aggregateActivityOptions(?int $sector, ?array $intention = null): array
{
if ($intention) {
// Only the classes of the investor's intention, from the class down to level 5.
return collect(app(EconomicReferenceCatalog::class)->supplyClassification()['nodes'])
->filter(fn (array $node) => str_starts_with($node['code'], $intention['code']))
->sortBy('code')->map(fn (array $node) => ['id' => $node['id'], 'code' => $node['code'], 'label' => $node['label']])->values()->all();
}
$rows = $this->publicAggregateActivities();
$divisions = $rows->filter(fn ($a) => preg_match('/^[0-9]{2}$/D', $a->code) === 1)->pluck('code')->all();
$result = [];
@@ -4,6 +4,12 @@ import { contextApi, type SupplyAggregate } from '@/lib/investor-context';
import { createOperationKey } from '@/lib/operation-key';
import CatalogueChoiceSelect from './catalogue-choice-select';
/** Official CAE designations are in capitals; shown as ordinary text. */
const sentenceCase = (text: string) => {
const lower = text.toLocaleLowerCase('pt');
return lower.charAt(0).toLocaleUpperCase('pt') + lower.slice(1);
};
export default function InvestmentSupplyAggregate({
caseId,
version,
@@ -13,6 +19,7 @@ export default function InvestmentSupplyAggregate({
protectedMode = false,
activityOptions = [],
defaultActivityId,
intention = null,
}: {
caseId: string;
version: number;
@@ -22,6 +29,13 @@ export default function InvestmentSupplyAggregate({
protectedMode?: boolean;
activityOptions?: { id: string; code: string; label: string }[];
defaultActivityId?: string;
/** CAE class documented for the investor's intention (for example «Criar Hotel» → 551). */
intention?: {
id: string;
code: string;
label: string;
basis: string;
} | null;
}) {
const history = protectedMode
? storedHistory.filter(
@@ -42,12 +56,18 @@ export default function InvestmentSupplyAggregate({
const latest =
history[selectedHistory ?? history.length - 1] ?? history.at(-1);
const protectedView = latest?.privacy_version === 1;
// Only a value present in the list is preselected: never a bare identifier.
const offered = (id: string | null | undefined) =>
id && activityOptions.some((item) => item.id === id) ? id : '';
const [activityId, setActivityId] = useState(
history.at(-1)?.context_revision === revision
? (history.at(-1)?.filters?.classification_key ??
history.at(-1)?.filters?.activity_id ??
'')
: (defaultActivityId ?? ''),
(history.at(-1)?.context_revision === revision
? offered(
history.at(-1)?.filters?.classification_key ??
history.at(-1)?.filters?.activity_id,
)
: '') ||
offered(defaultActivityId) ||
offered(intention?.id),
);
return (
<section
@@ -61,19 +81,31 @@ export default function InvestmentSupplyAggregate({
Consulte uma análise agregada no seu dossier. As listas, nomes e
contactos internos permanecem reservados.
</p>
{protectedMode && intention && (
<p className="text-sm">
Associado à sua intenção: {intention.code} —{' '}
{intention.label.toLocaleLowerCase('pt')}. Pode detalhar até
ao nível 5.{' '}
<span className="text-slate-600">{intention.basis}</span>
</p>
)}
{protectedMode && (
<CatalogueChoiceSelect
label="Actividade a comparar"
value={activityId}
disabled={disabled || busy}
options={[
{
value: '',
label: 'Todas as divisões do sector guardado',
},
...(intention
? []
: [
{
value: '',
label: 'Todas as divisões do sector guardado',
},
]),
...activityOptions.map((item) => ({
value: item.id,
label: `${item.code} — ${item.label}`,
label: `${item.code} — ${sentenceCase(item.label)}`,
keywords: [item.code, item.label],
})),
]}
@@ -106,6 +106,12 @@ type Path = {
supply_aggregate_enabled?: boolean;
supply_aggregate_protected?: boolean;
supply_activity_options?: { id: string; code: string; label: string }[];
supply_activity_intention?: {
id: string;
code: string;
label: string;
basis: string;
} | null;
supply_aggregates?: SupplyAggregate[];
zone_contexts?: {
zone_id: string;
@@ -717,6 +723,7 @@ export default function InvestmentPath(path: Path) {
history={path.supply_aggregates ?? []}
protectedMode={path.supply_aggregate_protected ?? false}
activityOptions={path.supply_activity_options ?? []}
intention={path.supply_activity_intention ?? null}
defaultActivityId={
path.investment_context?.fields.activity_id
}
+26 -3
View File
@@ -88,12 +88,13 @@ final class ProtectedSupplyAggregateTest extends TestCase
return $id;
}
private function dossier(string $sector = 'agro', string $territory = 'locality_a'): string
private function dossier(string $sector = 'agro', string $territory = 'locality_a', ?string $title = null): string
{
$id = $this->actingAs($this->owner)->postJson('/investimentos', ['title' => 'SYNTHETIC deliberate '.$sector, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$title ??= 'SYNTHETIC deliberate '.$sector;
$id = $this->actingAs($this->owner)->postJson('/investimentos', ['title' => $title, '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']];
'opportunity_choices' => [], 'declarations' => ['project_title' => $title, '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();
@@ -200,6 +201,28 @@ final class ProtectedSupplyAggregateTest extends TestCase
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid()])->assertUnauthorized();
}
public function test_a_hotel_dossier_is_associated_with_hotel_classes_down_to_level_five_and_offers_nothing_else(): void
{
// Mapa de erros, "Criar Hotel" (C03; aditamento 3): documented correspondence, the detail is the investor's choice.
$hotel = $this->dossier('hotel', 'locality_a', 'Criar Hotel');
$view = $this->actingAs($this->owner)->getJson('/investimentos/'.$hotel)->assertOk()->json();
$this->assertSame('551', $view['supply_activity_intention']['code']);
$this->assertStringContainsString('CAE-Rev.2', $view['supply_activity_intention']['basis']);
$codes = array_column($view['supply_activity_options'], 'code');
$this->assertContains('551', $codes);
$this->assertContains('5511', $codes);
$this->assertNotEmpty(array_filter($codes, fn (string $code) => strlen($code) === 5), 'level 5 is offered');
$this->assertSame([], array_values(array_filter($codes, fn (string $code) => ! str_starts_with($code, '551'))), 'only hotel classes');
$this->assertContains('55111', $codes, 'hotels with restaurant, level 5');
$this->aggregateSnapshot($hotel, ['classification_key' => $view['supply_activity_intention']['id']]);
// Without a documented correspondence nothing is associated and the full choice stays available.
$agro = $this->dossier('agro');
$other = $this->getJson('/investimentos/'.$agro)->assertOk()->json();
$this->assertNull($other['supply_activity_intention']);
$this->assertNotEmpty(array_filter(array_column($other['supply_activity_options'], 'code'), fn (string $code) => ! str_starts_with($code, '551')));
}
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]);