Entrega dashboard e correccoes transversais preservando Ofertas instalado
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-15 18:56:39 +02:00
parent 1349789226
commit fb076c174f
117 changed files with 10380 additions and 1905 deletions
+14 -6
View File
@@ -139,7 +139,8 @@ final class CompanyComparison
public function view(User $actor, string $id, array $input): array
{
$case = $this->desk->case($actor, $id);
$saved = $this->desk->decode($case->payload)['company_comparison'] ?? null;
$payload = $this->desk->decode($case->payload);
$saved = $payload['company_comparison'] ?? null;
$v = Validator::make($input, ['revision' => 'nullable|uuid', 'history_before' => 'nullable|integer|min:1'])->validate();
if (! empty($v['revision'])) {
if (array_key_exists('answers', $input)) {
@@ -160,7 +161,7 @@ final class CompanyComparison
return ['id' => $row->id, 'revision' => $snapshot['revision'], 'at' => $snapshot['at'], 'engine_version' => $snapshot['result']['engine_version']];
})->all();
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
return ['entity_kind' => $payload['investor_path']['context']['promoter_entity']['kind'] ?? ($case->company_id ? 'company' : 'undetermined'), 'case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
'canWrite' => ! $case->closed_at && $this->desk->owns($actor, $case), 'answers' => $answers, 'result' => $result,
'saved' => $saved, 'history' => $history, 'historyNext' => $events->count() > 25 ? $events[24]->event_order : null,
'historical' => ! empty($v['revision']), 'workingCopy' => array_key_exists('answers', $input)];
@@ -171,7 +172,7 @@ final class CompanyComparison
public function save(User $actor, string $id, array $input): array
{
$this->desk->case($actor, $id, true);
$v = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid'])->validate();
$v = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid', 'continue_preparation' => 'nullable|boolean'])->validate();
$v['version'] = (int) $v['version'];
return DB::transaction(function () use ($actor, $id, $v, $input) {
@@ -180,19 +181,23 @@ final class CompanyComparison
$data = $this->desk->decode($event->payload);
if ($data['operation_key'] === $v['operation_key']) {
$answers = $this->normalize($input, $data['snapshot']['result']['questions']);
$hash = hash('sha256', json_encode([$v['version'], $answers], JSON_THROW_ON_ERROR));
$hash = hash('sha256', json_encode(! empty($v['continue_preparation']) ? [$v['version'], $answers, 'continue_preparation'] : [$v['version'], $answers], JSON_THROW_ON_ERROR));
abort_unless(hash_equals($data['request_hash'], $hash), 409, 'Esta operação já guardou respostas diferentes. Reabra a comparação.');
return ['saved' => true, 'replayed' => true, 'revision' => $data['snapshot']['revision']];
}
}
$answers = $this->answers($input);
$hash = hash('sha256', json_encode([$v['version'], $answers], JSON_THROW_ON_ERROR));
$hash = hash('sha256', json_encode(! empty($v['continue_preparation']) ? [$v['version'], $answers, 'continue_preparation'] : [$v['version'], $answers], JSON_THROW_ON_ERROR));
abort_if($case->closed_at || (int) $case->version !== (int) $v['version'], 409, 'O dossier mudou ou foi fechado. Conserve as respostas e recupere a versão actual antes de guardar.');
$payload = $this->desk->decode($case->payload);
if (! empty($v['continue_preparation'])) {
abort_if(in_array($payload['investor_path']['context']['promoter_entity']['kind'] ?? '', ['company', 'organization'], true), 422, 'A entidade existente pode continuar a viabilidade sem preparar nova constituição.');
abort_if(($answers['preferred'] ?? 'unknown') === 'unknown', 422, 'Escolha a alternativa que pretende preparar.');
}
$result = $this->evaluate($answers);
$previous = $payload['company_comparison'] ?? null;
if ($previous !== null && $previous['answers'] === $answers && $previous['result'] === $result) {
if (empty($v['continue_preparation']) && $previous !== null && $previous['answers'] === $answers && $previous['result'] === $result) {
return ['saved' => true, 'replayed' => false, 'unchanged' => true, 'revision' => $previous['revision']];
}
$snapshot = ['revision' => (int) ($payload['company_comparison']['revision'] ?? 0) + 1, 'answers' => $answers,
@@ -201,6 +206,9 @@ final class CompanyComparison
$case->version++;
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version, 'updated_at' => now()]);
$this->desk->event($case, $actor, self::EVENT, ['operation_key' => $v['operation_key'], 'request_hash' => $hash, 'snapshot' => $snapshot]);
if (! empty($v['continue_preparation'])) {
app(InvestorContext::class)->setPromoter($actor, $id, ['version' => $case->version, 'operation_key' => (string) \Illuminate\Support\Str::uuid(), 'kind' => 'being_formed']);
}
return ['saved' => true, 'replayed' => false, 'revision' => $snapshot['revision']];
});
+21 -5
View File
@@ -23,7 +23,7 @@ final class CompanyPreparation
return ['version' => self::VERSION, 'forms' => config('company-comparison.forms'),
'roles' => ['subscriber' => 'Titular, sócio ou accionista', 'administrator' => 'Administrador ou gerente', 'representative' => 'Representante', 'beneficial_owner' => 'Beneficiário efectivo declarado'],
'source' => config('company-comparison.source'),
'template_status' => 'source_pending', 'template_notice' => 'Os sete exemplares referidos no complemento ainda não foram fornecidos. Esta ficha prepara dados para revisão; não é uma minuta contratual, assinatura, registo ou licença.'];
'template_status' => 'source_pending', 'template_notice' => 'Os modelos contratuais não estão disponíveis nesta preparação. Prepare os dados para revisão; esta preparação não é uma minuta contratual, assinatura, registo ou licença.'];
}
/** Reuse only the already-authorized, frozen dossier values, never a fresh master lookup.
@@ -36,8 +36,8 @@ final class CompanyPreparation
$sources['case_proponent'] = ['name' => $payload['name'], 'kind' => 'person', 'reference' => $case->id,
'version' => $payload['reuse_consent']['date'] ?? 'creation', 'origin' => 'Proponente conservado na criação do dossier'];
}
if ($case->company_id && ! empty($payload['company']['name'])) {
$sources['case_company'] = ['name' => $payload['company']['name'], 'kind' => 'entity', 'reference' => $case->company_id,
if (($case->company_id || ! empty($payload['investor_path']['context']['promoter_entity']['id'])) && ! empty($payload['company']['name'])) {
$sources['case_company'] = ['name' => $payload['company']['name'], 'kind' => 'entity', 'reference' => $case->company_id ?? $payload['investor_path']['context']['promoter_entity']['id'],
'version' => $payload['company_version'] ?? null, 'origin' => 'Declaração de empresa conservada no dossier'];
}
@@ -220,7 +220,7 @@ final class CompanyPreparation
{
$case = $this->desk->case($actor, $id);
$payload = $this->desk->decode($case->payload);
$v = Validator::make($input, ['revision' => 'nullable|uuid', 'history_before' => 'nullable|integer|min:1'])->validate();
$v = Validator::make($input, ['revision' => 'nullable|uuid', 'history_before' => 'nullable|integer|min:1', 'form' => ['nullable', Rule::in(array_keys(config('company-comparison.forms')))]])->validate();
$saved = $payload['company_preparation'] ?? null;
if (! empty($v['revision'])) {
$event = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->where('id', $v['revision'])->first();
@@ -228,11 +228,22 @@ final class CompanyPreparation
$saved = $this->desk->decode($event->payload)['snapshot'];
}
$facts = $saved['facts'] ?? $this->facts(['facts' => []]);
$entity = $payload['investor_path']['context']['promoter_entity'] ?? null;
$context = app(InvestorContext::class)->state($case)['fields'];
$existingEntity = in_array($entity['kind'] ?? '', ['company', 'organization'], true);
if (! $saved && empty($v['revision'])) {
foreach (['currency' => 'currency', 'activities' => 'products_services', 'seat' => 'location'] as $target => $source) {
if (empty($facts[$target]) && ! empty($context[$source])) $facts[$target] = $context[$source];
}
$facts['proposed_name'] = $entity['snapshot']['name'] ?? $facts['proposed_name'];
$knownForm = $entity['snapshot']['legal_form'] ?? null;
$facts['form'] = $existingEntity ? $knownForm : ($v['form'] ?? $facts['form']);
}
$events = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)
->when(! empty($v['history_before']), fn ($q) => $q->where('event_order', '<', $v['history_before']))
->orderByDesc('event_order')->limit(26)->get(['id', 'payload', 'event_order']);
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
return ['entity' => $entity, 'proposedForm' => ! $existingEntity ? ($v['form'] ?? null) : null, 'case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
'canWrite' => ! $case->closed_at && $this->desk->owns($actor, $case), 'historical' => ! empty($v['revision']),
'definition' => $saved['definition'] ?? $this->definition(), 'facts' => $facts, 'review' => $saved['review'] ?? $this->review($facts), 'saved' => $saved,
'sources' => $this->sources($case), 'history' => $events->take(25)->map(function ($e) {
@@ -265,6 +276,11 @@ final class CompanyPreparation
$hash = hash('sha256', json_encode([(int) $v['version'], $facts], JSON_THROW_ON_ERROR));
abort_if($case->closed_at || (int) $case->version !== (int) $v['version'], 409, 'O dossier mudou ou foi fechado. Os dados continuam no formulário; recupere a versão antes de guardar.');
$payload = $this->desk->decode($case->payload);
$entity = $payload['investor_path']['context']['promoter_entity'] ?? null;
$registeredForm = $entity['snapshot']['legal_form'] ?? null;
if (in_array($entity['kind'] ?? '', ['company', 'organization'], true) && $registeredForm) {
abort_unless($facts['form'] === $registeredForm, 422, 'A forma jurídica da entidade existente não é alterada nesta preparação. Use o percurso próprio de alteração do cadastro.');
}
$previous = $payload['company_preparation'] ?? null;
$resolved = $this->resolve($facts, $this->sources($case), $previous);
$definition = $this->definition();
+23
View File
@@ -34,6 +34,29 @@ final class DemographicEvidence
return ['commerce' => 'Comércio e serviços', 'industry' => 'Indústria', 'agriculture' => 'Agricultura e agro-indústria', 'education' => 'Educação', 'health' => 'Saúde', 'general' => 'Contexto geral'];
}
/** Broader administrative evidence stays labelled as context, never local data.
* @return array<string,mixed>
*/
public function investmentContext(string $territory, int $start, int $end, string $sector = 'general', ?string $edition = null): array
{
$path = app(InvestmentGeography::class)->path($territory);
$requested = collect($path)->last();
$result = $this->analyse([], $start, $end, $sector, $edition);
foreach (array_reverse($path) as $node) {
if (! in_array($node->location_type, ['district', 'province'], true)) {
continue;
}
$result = $this->analyse([$node->id], $start, $end, $sector, $edition);
if ($result['state'] === 'available') {
break;
}
}
$result['requested_territory'] = $requested ? ['id' => $requested->id, 'name' => $requested->name, 'level' => $requested->location_type] : null;
$result['broader_context'] = $requested && count($result['territories']) && $requested->id !== $result['territories'][0]['id'];
return $result;
}
/** @param list<string> $territories
* @return array<string,mixed> */
public function analyse(array $territories, int $start, int $end, string $sector = 'general', ?string $edition = null): array
@@ -13,6 +13,29 @@ final class FundingInstitutionClassification
public const TYPES = ['commercial_bank' => 'Banco comercial', 'investment_bank' => 'Banco de investimento', 'bank' => 'Banco (tipo não especificado)', 'microbank' => 'Microbanco', 'cooperative' => 'Cooperativa de crédito', 'savings' => 'Organização de poupança e empréstimo', 'investment_manager' => 'Gestora de fundos de investimento', 'investment_company' => 'Sociedade de investimento', 'pension_manager' => 'Gestora de fundos de pensões', 'insurer' => 'Seguradora', 'reinsurer' => 'Resseguradora', 'microinsurer' => 'Micro-seguradora', 'broker' => 'Corretora de seguros', 'agent' => 'Agente de seguros', 'reinsurance_broker' => 'Corretor de resseguro', 'exchange_house' => 'Casa de câmbio', 'electronic_money' => 'Instituição de moeda electrónica', 'interbank' => 'Serviços interbancários', 'supervisor' => 'Supervisor', 'other' => 'Outro tipo documentado'];
// Category/type semantics in the supplied, accepted institutional reference.
public const CATEGORY_TYPES = ['banking' => ['commercial_bank', 'investment_bank', 'bank'], 'credit' => ['microbank', 'cooperative', 'savings'],
'investment' => ['investment_manager', 'investment_company'], 'pensions' => ['pension_manager', 'insurer'], 'insurance' => ['insurer', 'reinsurer', 'microinsurer', 'pension_manager'],
'intermediation' => ['broker', 'agent', 'reinsurance_broker'], 'exchange' => ['exchange_house'], 'payments' => ['electronic_money', 'interbank'], 'supervision' => ['supervisor'], 'other' => ['other']];
/** Structural validity is independent of whether matching records exist.
* @param array<string,mixed> $filters
*/
public function validateFilters(array $filters): void
{
$v = Validator::make($filters, ['category' => ['nullable', Rule::in(array_keys(self::CATEGORIES))], 'institution_type' => ['nullable', Rule::in(array_keys(self::TYPES))],
'kind' => ['nullable', Rule::in(array_keys(FundingProgrammes::KINDS))], 'location_mode' => 'nullable|in:physical,coverage'])->validate();
$errors = [];
if (! empty($v['category']) && $v['category'] !== 'other' && ! empty($v['institution_type']) && $v['institution_type'] !== 'other' && ! in_array($v['institution_type'], self::CATEGORY_TYPES[$v['category']], true)) {
$errors['institution_type'] = 'O tipo de instituição não pertence à categoria escolhida. Reveja esse critério; isto não é uma pesquisa sem resultados.';
}
if (! empty($v['kind']) && $v['kind'] !== 'institution') {
if (! empty($v['category']) || ! empty($v['institution_type'])) $errors['kind'] = 'Categoria e tipo de instituição aplicam-se à consulta de instituições. Um fundo ou programa é um registo distinto.';
if (($v['location_mode'] ?? '') === 'physical') $errors['location_mode'] = 'Sede e balcões aplicam-se a instituições. Para fundos e programas, escolha a cobertura do financiamento.';
}
if ($errors) throw \Illuminate\Validation\ValidationException::withMessages($errors);
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function normalize(array $input): array
@@ -31,6 +54,7 @@ final class FundingInstitutionClassification
/** @param array<string,mixed> $filters */
public function filter(Builder $query, array $filters): void
{
$this->validateFilters($filters);
foreach (['category' => 'institution_categories', 'institution_type' => 'institution_types'] as $key => $field) {
if (! empty($filters[$key])) {
$query->whereRaw('v.payload->? @> ?::jsonb', [$field, json_encode([$filters[$key]], JSON_THROW_ON_ERROR)]);
+3 -3
View File
@@ -113,7 +113,7 @@ final class FundingInstitutionDetails
public function match(array $product, array $filters): bool
{
$unknown = ($filters['certainty'] ?? 'include_unknown') === 'include_unknown';
if ($product['availability'] === 'closed') {
if ($product['availability'] === 'closed' && ($filters['state'] ?? '') !== 'closed') {
return false;
}
if (! $unknown && $product['availability'] === 'unknown') {
@@ -122,7 +122,7 @@ final class FundingInstitutionDetails
if (! empty($filters['need']) && ! in_array($filters['need'], $product['needs'], true) && ! ($unknown && $product['needs'] === [])) {
return false;
}
if (empty($filters['territory'])) {
if (empty($filters['territory']) || ($filters['location_mode'] ?? '') === 'physical') {
return true;
}
if ($product['coverage'] === 'national') {
@@ -150,7 +150,7 @@ final class FundingInstitutionDetails
return;
}
$unknown = ($filters['certainty'] ?? 'include_unknown') === 'include_unknown';
$conditions = ["p->>'availability' <> 'closed'"];
$conditions = [($filters['state'] ?? '') === 'closed' ? "p->>'availability' IN ('documented','closed','unknown')" : "p->>'availability' <> 'closed'"];
$bindings = [];
if (! $unknown) {
$conditions[] = "p->>'availability' <> 'unknown'";
+42 -11
View File
@@ -68,7 +68,17 @@ final class FundingProgrammes
/** @param array<string,mixed> $filters */
public function catalogueQuery(array $filters): Builder
{
Validator::make($filters, ['q' => 'nullable|string|max:150', 'state' => 'nullable|in:open,closed,upcoming,unknown', 'certainty' => 'nullable|in:include_unknown,documented',
'sector' => ['nullable', 'integer', Rule::in(Sector::choices()->whereNotNull('published_at')->pluck('id')->all())], 'need' => ['nullable', Rule::in(array_keys(FundingInstitutionDetails::NEEDS))], 'include_historical' => 'nullable|boolean'])->validate();
$filters = app(InvestmentGeography::class)->interestSelection($filters);
$query = $this->publicQuery();
if (! empty($filters['q'])) {
$term = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['q']).'%';
$query->where(fn ($q) => $q->whereRaw("v.payload->>'title' ilike ?", [$term])->orWhereRaw("v.payload->>'summary' ilike ?", [$term])->orWhereRaw("(v.payload->'aliases')::text ilike ?", [$term])->orWhereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'locations','[]'::jsonb)) l WHERE l->>'label' ilike ? OR l->>'address' ilike ? OR l->>'location_text' ilike ?)", [$term, $term, $term]));
}
if (! empty($filters['kind'])) {
$query->whereRaw("v.payload->>'kind' = ?", [$filters['kind']]);
}
app(FundingInstitutionDetails::class)->applyFilters($query, $filters);
$includeUnknown = ($filters['certainty'] ?? 'include_unknown') === 'include_unknown';
if (! empty($filters['sector'])) {
@@ -94,22 +104,43 @@ final class FundingProgrammes
});
}
if (! empty($filters['state'])) {
$today = today()->toDateString();
$state = $filters['state'];
if ($state === 'unknown') {
$query->whereRaw("(jsonb_array_length(v.payload->'windows') = 0 OR EXISTS (SELECT 1 FROM jsonb_array_elements(v.payload->'windows') w WHERE w->>'mode' = 'unknown'))");
} elseif ($state === 'closed') {
$query->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(v.payload->'windows') w WHERE w->>'mode' = 'closed' OR (w->>'mode' = 'dated' AND w->>'end_on' < ?))", [$today]);
} elseif ($state === 'upcoming') {
$query->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(v.payload->'windows') w WHERE w->>'mode' = 'dated' AND w->>'start_on' > ?)", [$today]);
} else {
$query->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(v.payload->'windows') w WHERE w->>'mode' IN ('dated','rolling') AND COALESCE(NULLIF(w->>'start_on',''),?) <= ? AND COALESCE(NULLIF(w->>'end_on',''),?) >= ?)", [$today, $today, $today, $today]);
}
[$windowSql, $windowBindings] = $this->windowFilter($filters);
$query->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'windows','[]'::jsonb)) w WHERE ".$windowSql.')', $windowBindings);
}
return $query;
}
/** Window dates and geographical scope concern the same documented window.
* @param array<string,mixed> $filters
* @return array{literal-string,list<mixed>}
*/
private function windowFilter(array $filters): array
{
$today = today()->toDateString();
$state = $filters['state'];
$bindings = [];
if ($state === 'unknown') $sql = "w->>'mode' = 'unknown'";
elseif ($state === 'closed') { $sql = "(w->>'mode' = 'closed' OR (w->>'mode' = 'dated' AND w->>'end_on' < ?))"; $bindings = [$today]; }
elseif ($state === 'upcoming') { $sql = "w->>'mode' = 'dated' AND w->>'start_on' > ?"; $bindings = [$today]; }
else { $sql = "w->>'mode' IN ('dated','rolling') AND COALESCE(NULLIF(w->>'start_on',''),?) <= ? AND COALESCE(NULLIF(w->>'end_on',''),?) >= ?"; $bindings = [$today, $today, $today, $today]; }
if (! empty($filters['territory']) && ($filters['location_mode'] ?? '') !== 'physical') {
$path = array_column(app(InvestmentGeography::class)->path($filters['territory']), 'id');
$window = ["EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(w->'territory_paths','[]'::jsonb)) t WHERE t @> ?::jsonb)"];
$scopeBindings = [json_encode([['id' => $filters['territory']]], JSON_THROW_ON_ERROR)];
foreach ($path as $id) { $window[] = "w->'territory_ids' @> ?::jsonb"; $scopeBindings[] = json_encode([$id], JSON_THROW_ON_ERROR); }
$parent = ["v.payload->>'coverage'='national'", "v.payload->'territory_ancestor_ids' @> ?::jsonb"];
$scopeBindings[] = json_encode([$filters['territory']], JSON_THROW_ON_ERROR);
foreach ($path as $id) { $parent[] = "v.payload->'territory_ids' @> ?::jsonb"; $scopeBindings[] = json_encode([$id], JSON_THROW_ON_ERROR); }
if (($filters['certainty'] ?? 'include_unknown') === 'include_unknown') $parent[] = "v.payload->>'coverage'='unknown'";
$scope = "(w->>'coverage'='national' OR (w->>'coverage'='territorial' AND (".implode(' OR ', $window).")) OR (w->>'coverage'='programme' AND (".implode(' OR ', $parent).')))';
if (($filters['certainty'] ?? 'include_unknown') === 'include_unknown') $scope = '('.$scope." OR w->>'coverage'='unknown')";
$sql = '('.$sql.') AND '.$scope;
$bindings = [...$bindings, ...$scopeBindings];
}
return [$sql, $bindings];
}
/** @param array<string,mixed> $record
* @param array<string,mixed> $filters
* @return array<string,string> */
+8 -3
View File
@@ -66,11 +66,16 @@ final class InvestmentCorridorContext
*/
public function parks(?string $key, ?string $territory): array
{
if (! $key || ! $territory) {
if (! $territory) {
return [];
}
abort_unless($this->compatible($key, $territory), 422, 'A localização não pertence ao corredor escolhido.');
if ($key) {
abort_unless($this->compatible($key, $territory), 422, 'A localização não pertence ao corredor escolhido.');
}
$selectedPath = array_column(app(InvestmentGeography::class)->path($territory), 'id');
if ($selectedPath === []) {
return [];
}
$candidates = app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->orderBy('name')->get();
$result = [];
foreach ($candidates as $zone) {
@@ -83,7 +88,7 @@ final class InvestmentCorridorContext
}
foreach ($ids as $link) {
$id = $link->geo_location_id;
if (! $this->compatible($key, $id)) {
if ($key && ! $this->compatible($key, $id)) {
continue;
}
$path = array_column(app(InvestmentGeography::class)->path($id), 'id');
+24
View File
@@ -245,6 +245,30 @@ final class InvestmentGeography
return $path;
}
/** Canonical selection for a place-of-interest filter, including legacy links.
* @param array<string,mixed> $filters
* @return array<string,mixed>
*/
public function interestSelection(array $filters): array
{
$location = \Illuminate\Support\Facades\Validator::make($filters, ['territory' => 'nullable|uuid', 'province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid'])->validate();
if (array_intersect(array_keys(self::FIELDS), array_keys($location))) {
$path = $this->selection($location);
$territory = $path ? $path[array_key_last($path)]->id : null;
if (! empty($location['territory']) && $location['territory'] !== $territory) {
throw ValidationException::withMessages(['territory' => 'O local de interesse não corresponde à hierarquia seleccionada.']);
}
if ($territory) $filters['territory'] = $territory;
else unset($filters['territory']);
}
if (! empty($filters['territory'])) {
$path = $this->path($filters['territory']);
if (! $path) throw ValidationException::withMessages(['territory' => 'Seleccione um local disponível no cadastro.']);
foreach ($path as $node) $filters[$node->location_type.'_id'] = $node->id;
}
return $filters;
}
/** @return list<string> */
public function descendants(string $id, bool $includeNonPublic = false): array
{
@@ -74,7 +74,7 @@ final class InvestmentOpportunityChoices
$old = collect($previous)->first(fn ($row) => $row['opportunity']['key'] === $ref['key']);
$origins = $this->portfolioOrigins($choice['portfolio_origins'] ?? array_column($old['portfolio_origins'] ?? [], 'id'), (int) $record->id);
$corridors = app(InvestmentCorridorContext::class);
$corridor = $choice['corridor_key'] ?? $old['corridor_key'] ?? $corridors->key($record);
$corridor = array_key_exists('corridor_key', $choice) ? $choice['corridor_key'] : ($old['corridor_key'] ?? $corridors->key($record));
$provinces = $corridor ? $corridors->provinces($corridor) : [];
$documented = $record->primary_territory_id;
$territory = array_key_exists('territory', $choice) ? $choice['territory'] : ($documented ? 'territory:'.$documented : null);
+132 -17
View File
@@ -24,7 +24,7 @@ final class InvestorContext
public const SOURCE = 'investor-context';
public const FIELDS = ['project_title', 'project_summary', 'sector_id', 'sector', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'currency', 'expected_start_date', 'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'investor_origin', 'person_type', 'entity_stage', 'tax_residency_country', 'fiscal_residency_country', 'activity_id', 'project_type', 'maturity_stage', 'special_zone_id', 'investment_regime', ...PrivateInvestmentPreparation::FIELDS];
public const FIELDS = ['promoter_entity_key', 'legal_name', 'legal_form', 'registration_number', 'products_services', 'investment_budget_min', 'investment_budget_max', 'project_title', 'project_summary', 'sector_id', 'sector', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'currency', 'expected_start_date', 'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'investor_origin', 'person_type', 'entity_stage', 'tax_residency_country', 'fiscal_residency_country', 'activity_id', 'project_type', 'maturity_stage', 'special_zone_id', 'investment_regime', ...PrivateInvestmentPreparation::FIELDS];
public function __construct(private readonly VirtualDesk $desk) {}
@@ -51,7 +51,7 @@ final class InvestorContext
$entrySources = Validator::make($input, ['entry_sources' => 'sometimes|array|max:200', 'entry_sources.*' => 'string|max:100'])->validate()['entry_sources'] ?? [];
unset($input['draft_sequence'],$input['entry_sources']);
abort_unless($sequence > 0, 422);
$data = $this->input($input);
$data = $this->input($input, true);
if (isset($data['complements'])) {
app(InvestmentComplements::class)->resolve($data['complements'], $this->state($case)['complements'] ?? []);
}
@@ -69,7 +69,7 @@ final class InvestorContext
abort_unless($ref['kind'] === 'opportunity', 422);
$record = Opportunity::whereKey($ref['id'])->firstOrFail();
app(InvestmentOpportunityChoices::class)->portfolioOrigins($choice['portfolio_origins'] ?? [], (int) $record->id);
$key = $choice['corridor_key'] ?? app(InvestmentCorridorContext::class)->key($record);
$key = array_key_exists('corridor_key', $choice) ? $choice['corridor_key'] : app(InvestmentCorridorContext::class)->key($record);
if (! empty($choice['territory'])) {
$location = $this->reference($choice['territory']);
abort_unless($location['kind'] === 'territory', 422);
@@ -114,6 +114,112 @@ final class InvestorContext
return Schema::hasTable('investor_navigation_preferences');
}
/** Existing identity records only; these choices never change dossier ownership.
* @return array<string,mixed>
*/
public function promoter(User $actor, string $id): array
{
$case = $this->desk->case($actor, $id);
abort_unless((int) $case->user_id === $actor->id, 403);
$payload = $this->desk->decode($case->payload);
$companies = DB::table('investment_company_declarations')->where('user_id', $actor->id)->orderByDesc('created_at')->get(['id', 'version', 'payload'])->map(function ($row) {
$f = $this->desk->decode($row->payload);
return ['id' => $row->id, 'version' => $row->version, 'name' => $f['name'] ?? 'Empresa declarada', 'legal_form' => $f['legal_form'] ?? null];
})->all();
return ['version' => $case->version, 'selected' => $payload['investor_path']['context']['promoter_entity'] ?? ($case->company_id ? ['kind' => 'company', 'id' => $case->company_id, 'snapshot' => $payload['company'] ?? []] : ['kind' => 'undetermined']),
'companies' => $companies, 'organizations' => $this->desk->representedOrganizations($actor), 'can_write' => $case->organization_id === null && ! $case->closed_at];
}
/** Attach an authorised identity snapshot while retaining the case owner and ACL.
* @param array<string,mixed> $input
* @return array<string,mixed>
*/
public function setPromoter(User $actor, string $id, array $input): array
{
$v = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid', 'kind' => 'required|in:company,organization,being_formed,undetermined', 'id' => 'nullable|uuid', 'source_version' => 'nullable|integer|min:1'])->validate();
return DB::transaction(function () use ($actor, $id, $v): array {
$case = $this->desk->case($actor, $id, true, true);
abort_unless((int) $case->user_id === $actor->id && $case->organization_id === null, 403);
$this->desk->assertOpen($case);
$payload = $this->desk->decode($case->payload);
$hash = hash('sha256', json_encode($v, JSON_THROW_ON_ERROR));
foreach ($payload['investor_path']['promoter_history'] ?? [] as $entry) {
if (($entry['operation_key'] ?? null) === $v['operation_key']) {
abort_unless(hash_equals($entry['request_hash'], $hash), 409);
return ['saved' => true, 'replayed' => true, 'continue' => '/investimentos/'.$id];
}
}
abort_unless((int) $case->version === (int) $v['version'], 409, 'O dossier mudou; recupere os dados antes de alterar a entidade.');
$snapshot = [];
$sourceVersion = null;
if ($v['kind'] === 'company') {
$company = DB::table('investment_company_declarations')->where('id', $v['id'] ?? null)->where('user_id', $actor->id)->lockForUpdate()->first();
abort_unless($company !== null, 404);
$snapshot = $this->desk->decode($company->payload);
$sourceVersion = $company->version;
} elseif ($v['kind'] === 'organization') {
DB::table('memberships')->where('organization_id', $v['id'] ?? null)->where('user_id', $actor->id)->whereNull('deleted_at')->lockForUpdate()->get();
abort_unless($this->desk->represents($actor, $v['id'] ?? '', false), 403);
$organization = collect($this->desk->representedOrganizations($actor))->firstWhere('id', $v['id']);
abort_unless($organization !== null, 403);
$snapshot = ['name' => $organization['name'], 'incorporation_country_code' => $organization['country']];
$sourceVersion = $organization['version'];
}
abort_if(isset($v['source_version']) && (int) $v['source_version'] !== (int) $sourceVersion, 409, 'O cadastro da entidade mudou. Recupere a associação antes de continuar.');
$entity = ['kind' => $v['kind'], 'id' => in_array($v['kind'], ['company', 'organization'], true) ? $v['id'] : null, 'source_version' => $sourceVersion, 'snapshot' => $snapshot, 'recorded_at' => now()->toIso8601String()];
$stage = in_array($v['kind'], ['company', 'organization'], true) ? 'existing' : ($v['kind'] === 'being_formed' ? 'being_formed' : '');
$declarations = ['entity_stage' => $stage, 'promoter_entity_key' => $v['kind'].':'.($entity['id'] ?? '').'@'.($sourceVersion ?? '')];
$existingFields = $this->state($case)['fields'];
foreach (['legal_name' => 'name', 'legal_form' => 'legal_form', 'registration_number' => 'registration'] as $field => $key) {
if (empty($existingFields[$field]) && ! empty($snapshot[$key])) $declarations[$field] = $snapshot[$key];
}
$body = ['version' => $case->version, 'selection' => [], 'declarations' => $declarations];
$plan = $this->preview($actor, $id, $body);
$this->commit($actor, $id, [...$body, 'preview_hash' => $plan['preview_hash'], 'confirm' => true, 'operation_key' => $v['operation_key']]);
$current = $this->desk->case($actor, $id, true, true);
$next = $this->desk->decode($current->payload);
$previous = $payload['investor_path']['context']['promoter_entity'] ?? ($case->company_id ? ['kind' => 'company', 'id' => $case->company_id, 'snapshot' => $payload['company'] ?? []] : ['kind' => 'undetermined']);
$next['investor_path']['context']['promoter_entity'] = $entity;
$next['investor_path']['promoter_history'][] = ['before' => $previous, 'after' => $entity, 'operation_key' => $v['operation_key'], 'request_hash' => $hash];
$next['company'] = $snapshot;
$next['company_version'] = $sourceVersion;
DB::table('desk_cases')->where('id', $id)->update(['company_id' => $v['kind'] === 'company' ? $v['id'] : null, 'payload' => $this->desk->encode($next)]);
$this->desk->event($current, $actor, 'investment_promoter_associated', ['before' => $previous, 'after' => $entity, 'ownership_unchanged' => true]);
return ['saved' => true, 'replayed' => false, 'continue' => $v['kind'] === 'being_formed' ? '/investimentos/'.$id.'/preparar-empresa' : '/investimentos/'.$id];
});
}
/** Explicit consultation saved in the existing encrypted dossier, with optimistic locking.
* @param array<string,mixed> $input
* @return array<string,mixed>
*/
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 {
$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];
}
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.');
$f = $context['fields'];
$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']];
$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 array<array-key, mixed>
*/
@@ -327,17 +433,18 @@ final class InvestorContext
return $fields;
}
/**
* @return array<array-key, mixed>
/** @param array<string,mixed> $filters
* @return array<array-key,mixed>
*/
public function options(string $query = ''): array
public function options(string $query = '', array $filters = []): array
{
$query = mb_substr(trim($query), 0, 120);
$items = [];
foreach (Opportunity::published()->when($query, fn ($q) => $q->where('title', 'ilike', '%'.$query.'%'))->orderBy('title')->limit(51)->get(['id', 'title']) as $o) {
$items[] = ['key' => 'opportunity:'.$o->id, 'title' => $o->title, 'kind' => 'opportunity'];
$public = $filters ? app(InvestmentCatalogue::class)->query([...$filters, 'q' => $query]) : Opportunity::published()->when($query, fn ($q) => $q->where('title', 'ilike', '%'.$query.'%'));
foreach ($public->orderBy('title')->limit(51)->get(['opportunities.id', 'opportunities.title']) as $o) {
$items[] = ['key' => 'opportunity:'.$o->id, 'title' => $o->title, 'kind' => 'opportunity', 'relevance' => $filters ? 'Corresponde aos critérios explicitamente seleccionados.' : 'Correspondência com a pesquisa; confirme a pertinência antes de associar.'];
}
if (request()->user()) {
if (request()->user() && (! $filters || $query !== '')) {
$private = app(PortalProfileAccess::class)->scope(Opportunity::query(), request()->user())->where('status', '!=', 'published')->where('status', '!=', 'archived')->when($query, fn ($q) => $q->where('title', 'ilike', '%'.$query.'%'))->orderBy('title')->limit(51)->get();
foreach ($private as $o) {
if (app(PortalProfileAccess::class)->canView(request()->user(), $o)) {
@@ -345,13 +452,13 @@ final class InvestorContext
}
}
}
if (config('existing-business.enabled')) {
if (config('existing-business.enabled') && (! $filters || $query !== '')) {
foreach (ExistingBusiness::published()->when($query, fn ($q) => $q->where('public_title', 'ilike', '%'.$query.'%'))->orderBy('public_title')->limit(51)->get(['id', 'public_title']) as $o) {
$items[] = ['key' => 'business:'.$o->id, 'title' => $o->public_title, 'kind' => 'business'];
}
}
return ['opportunities' => $items, 'search_limited' => count($items) > 50, 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']),
return ['opportunities' => $items, 'countries' => app(CountryCatalogue::class)->all(), 'search_limited' => count($items) > 50, 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']),
'parks' => app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->orderBy('name')->get(['id', 'name', 'category', 'version_no'])];
}
@@ -414,7 +521,7 @@ final class InvestorContext
* @param array<array-key, mixed> $input
* @return array<array-key, mixed>
*/
private function input(array $input): array
private function input(array $input, bool $draft = false): array
{
abort_if(array_diff(array_keys($input), ['complements', 'opportunity_choices', 'version', 'selection', 'declarations', 'replace_fields', 'preview_hash', 'operation_key', 'confirm', 'document_links', '_token']) !== [], 422, 'Campo de controlo desconhecido.');
@@ -440,8 +547,10 @@ final class InvestorContext
'opportunity_choices.*.source' => 'required|string|distinct|max:100', 'opportunity_choices.*.territory' => 'nullable|string|max:100',
'opportunity_choices.*.location_reason' => 'nullable|string|max:2000', 'opportunity_choices.*.confirm_location_change' => 'sometimes|boolean',
'version' => 'required|integer|min:1', 'selection' => 'present|array:portfolio,opportunity,sector,territory,park',
'selection.*' => 'nullable|string|max:100', 'declarations' => 'nullable|array:project_title,project_summary,currency,expected_start_date,investor_origin,person_type,entity_stage,tax_residency_country,fiscal_residency_country,project_type,maturity_stage,'.implode(',', PrivateInvestmentPreparation::FIELDS), 'declarations.project_title' => 'nullable|string|max:200', 'declarations.project_summary' => 'nullable|string|max:5000',
'declarations.currency' => 'nullable|regex:/^[A-Z]{3}$/', 'declarations.expected_start_date' => 'nullable|date_format:Y-m-d', 'declarations.investor_origin' => 'nullable|in:national,foreign,mixed', 'declarations.person_type' => 'nullable|in:singular,collective,sole_trader,consortium', 'declarations.entity_stage' => 'nullable|in:existing,being_formed', 'declarations.tax_residency_country' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'declarations.fiscal_residency_country' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'declarations.project_type' => 'nullable|string|max:100', 'declarations.maturity_stage' => 'nullable|string|max:100',
'selection.*' => 'nullable|string|max:100', 'declarations' => 'nullable|array:promoter_entity_key,legal_name,legal_form,registration_number,products_services,investment_budget_min,investment_budget_max,project_title,project_summary,currency,expected_start_date,investor_origin,person_type,entity_stage,tax_residency_country,fiscal_residency_country,project_type,maturity_stage,'.implode(',', PrivateInvestmentPreparation::FIELDS), 'declarations.promoter_entity_key' => 'nullable|string|max:160', 'declarations.legal_name' => 'nullable|string|max:250', 'declarations.legal_form' => 'nullable|string|max:100', 'declarations.registration_number' => 'nullable|string|max:100',
'declarations.products_services' => 'nullable|string|max:2000', 'declarations.project_title' => 'nullable|string|max:200', 'declarations.project_summary' => 'nullable|string|max:5000',
'declarations.investment_budget_min' => 'nullable|numeric|min:0', 'declarations.investment_budget_max' => ['nullable', 'numeric', 'min:0', ...(! empty($input['declarations']['investment_budget_min']) ? ['gte:declarations.investment_budget_min'] : [])],
'declarations.currency' => $draft ? 'nullable|regex:/^[A-Za-z]{0,3}$/D' : 'nullable|regex:/^[A-Z]{3}$/D', 'declarations.expected_start_date' => 'nullable|date_format:Y-m-d', 'declarations.investor_origin' => 'nullable|in:national,foreign,mixed', 'declarations.person_type' => 'nullable|in:singular,collective,sole_trader,consortium', 'declarations.entity_stage' => 'nullable|in:existing,being_formed', 'declarations.tax_residency_country' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'declarations.fiscal_residency_country' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'declarations.project_type' => 'nullable|string|max:100', 'declarations.maturity_stage' => 'nullable|string|max:100',
'replace_fields' => 'nullable|array', 'replace_fields.*' => 'string|in:'.implode(',', self::FIELDS)])->validate();
}
@@ -480,7 +589,9 @@ final class InvestorContext
$choices = app(InvestmentOpportunityChoices::class)->resolve($data['opportunity_choices'], $choices);
$data['selection']['opportunity'] = $choices[0]['opportunity']['key'] ?? null;
// Shared fields concern the first identified opportunity; other sites remain separate.
if ($choices !== []) {
$data['selection']['territory'] = $choices[0]['territory']['key'] ?? null;
}
if (array_key_exists('park', $data['opportunity_choices'][0] ?? [])) {
$data['selection']['park'] = $choices[0]['park']['key'] ?? null;
}
@@ -511,7 +622,7 @@ final class InvestorContext
}
$selection[$slot] = $ref;
}
$corridor = $choices[0]['corridor_key'] ?? (isset($selection['opportunity']) && $selection['opportunity']['kind'] === 'opportunity'
$corridor = array_key_exists('corridor_key', $choices[0] ?? []) ? $choices[0]['corridor_key'] : (isset($selection['opportunity']) && $selection['opportunity']['kind'] === 'opportunity'
? app(InvestmentCorridorContext::class)->key(Opportunity::whereKey($selection['opportunity']['id'])->firstOrFail()) : null);
if ($corridor && isset($selection['territory'])) {
abort_unless(app(InvestmentCorridorContext::class)->compatible($corridor, $selection['territory']['id']), 422, 'A localização não pertence ao corredor escolhido.');
@@ -579,9 +690,12 @@ final class InvestorContext
$fields['special_zone_id'] = $selection['park']['id'] ?? '';
$fields['investment_regime'] = $selection['park']['fields']['investment_regime'] ?? 'general';
}
if (isset($fields['investment_budget_min'], $fields['investment_budget_max']) && $fields['investment_budget_min'] !== '' && $fields['investment_budget_max'] !== '') {
Validator::make(['declarations' => $fields], ['declarations.investment_budget_max' => 'numeric|gte:declarations.investment_budget_min'])->validate();
}
$replaced = [];
foreach (array_unique([...array_keys($old['fields']), ...array_keys($fields)]) as $key) {
if (($old['fields'][$key] ?? null) !== ($fields[$key] ?? null)) {
if (($old['fields'][$key] ?? '') !== ($fields[$key] ?? '')) {
$replaced[] = ['field' => $key, 'before' => $old['fields'][$key] ?? null, 'after' => $fields[$key] ?? null];
}
}
@@ -764,7 +878,7 @@ final class InvestorContext
$original = $ctx;
$ctx = app(InvestmentConsumerScope::class)->context($ctx, $opportunity);
$f = $ctx['fields'];
$sim = Arr::except(Arr::only($f, self::FIELDS), ['sector', 'province', 'district', 'location', ...array_diff(PrivateInvestmentPreparation::FIELDS, ['total_investment', 'area_required', 'area_unit'])]);
$sim = Arr::except(Arr::only($f, self::FIELDS), ['promoter_entity_key', 'sector', 'province', 'district', 'location', ...array_diff(PrivateInvestmentPreparation::FIELDS, ['total_investment', 'area_required', 'area_unit'])]);
// Entering this tool from an investment dossier selects the existing investment-analysis route.
// The reconciliation preserves any purpose deliberately chosen in an existing simulator draft.
$sim += ['journey_type' => 'investor', 'journey_type_label' => 'Avaliar o meu investimento', 'purpose' => 'simulate_only', 'purpose_label' => 'Apenas simular'];
@@ -790,6 +904,7 @@ final class InvestorContext
'version' => 1, 'context_revision' => $ctx['revision'],
'consumer_opportunity' => $ctx['consumer_opportunity']['opportunity']['key'] ?? null,
'portfolio_origin' => $ctx['selection']['portfolio'] ?? null,
'promoter_entity' => $ctx['promoter_entity'] ?? null,
'zone' => $zone ? Arr::only($zone, ['id', 'title', 'href', 'version', 'sha256', 'fields', 'analysis']) : null,
'provenance' => $ctx['provenance'],
// Retain dossier options as provenance when no consumer is selected; scoped fields remain empty.
+4
View File
@@ -162,6 +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();
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'],
@@ -171,7 +172,9 @@ final class InvestorPath
'canWrite' => $owner && ! $case->closed_at, 'canReview' => $manager && (int) $case->user_id !== $actor->id && ! $case->closed_at,
'next' => $next ? ['code' => $next['code'], 'title' => $next['title'], 'action' => 'Preparar', 'href' => $next['href'] ?? '#'.$next['code']] : null,
'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'] ?? []) : [],
'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(),
@@ -324,6 +327,7 @@ final class InvestorPath
'snapshot_sha256' => $draft->snapshot_sha256, 'financial_snapshot' => $snapshot,
'context_opportunity' => $opportunity,
'currency' => $economic['currency'] ?? null, 'engine' => 'financial-calculators:v1',
'preparation_snapshot' => Arr::only($economic, ['total_investment', 'secured_amount', 'planned_funding', 'requested_funding', 'approved_funding', 'planning_loan', 'annual_revenue', 'annual_operating_costs', 'investment_budget_min', 'investment_budget_max', 'initial_budget_snapshot', 'planning_assumptions_snapshot']),
'kind' => 'local_calculation_inputs', 'context_state' => 'current', 'context_revision' => $context['revision'], 'context_dependency_hash' => $context['dependency_hash'] ?? app(InvestorContext::class)->dependencyHash([]), 'recorded_at' => now()->toIso8601String()];
$payload['investor_path']['results'][] = $result;
abort_unless(count($payload['investor_path']['results']) <= 100, 422, 'Limite de evidências financeiras deste dossier atingido.');
+33
View File
@@ -36,6 +36,39 @@ final class ProactiveSupply
});
}
/** 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);
$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();
$query = function (string $id): Builder {
return DB::table('proactive_supply_observations as o')->whereIn('o.territory_id', app(InvestmentGeography::class)->descendants($id));
};
$base = $query($territory);
if (! (clone $base)->exists() && in_array($scope->location_type, ['locality', 'admin_post'], true)) {
$district = collect($path)->firstWhere('location_type', 'district');
if ($district && $query($district->id)->exists()) {
$scope = $district;
$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();
$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,
'interpretation' => 'Os grupos ajudam a investigar actividades similares e complementares. A relação deve ser fundamentada; não demonstra concorrência efectiva, clientes, capacidade ou receitas. Uma entidade pode constar em vários grupos; não some os grupos.'];
});
}
/**
* @param array<array-key, mixed> $input
* @return array<array-key, mixed>
+10
View File
@@ -47,6 +47,16 @@ class VirtualDesk
return $case->organization_id ? $this->represents($actor, $case->organization_id, $write) : (int) $case->user_id === $actor->id;
}
/** The same effective membership used by dossier access; identity does not depend on country configuration.
* @return list<array<string,mixed>>
*/
public function representedOrganizations(User $actor): array
{
return array_values(DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')->where('m.user_id', $actor->id)
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->get(['o.id', 'o.name', 'o.version_no', ...(Schema::hasColumn('organizations', 'incorporation_country_code') ? ['o.incorporation_country_code'] : [])])
->unique('id')->map(fn ($row) => ['id' => $row->id, 'name' => $row->name, 'version' => $row->version_no, 'country' => $row->incorporation_country_code ?? null])->values()->all());
}
public function case(User $actor, string $id, bool $write = false, bool $lock = false): \stdClass
{
$case = DB::table('desk_cases')->where('id', $id)->when($lock, fn ($q) => $q->lockForUpdate())->first();