fix: complete InvesteMoz validation and error corrections
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
@@ -27,63 +28,83 @@ final class InvestorContext
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
public function draft(User $actor, string $id): ?array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id, true);
|
||||
$draft = $this->desk->decode($case->payload)['investor_path']['context_drafts'][(string)$actor->id] ?? null;
|
||||
return $draft ? [...$draft, 'needs_review' => (int)$draft['version'] !== (int)$case->version] : null;
|
||||
$draft = $this->desk->decode($case->payload)['investor_path']['context_drafts'][(string) $actor->id] ?? null;
|
||||
|
||||
return $draft ? [...$draft, 'needs_review' => (int) $draft['version'] !== (int) $case->version] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function saveDraft(User $actor, string $id, array $input): array
|
||||
{
|
||||
$case=$this->desk->case($actor,$id,true);
|
||||
abort_if($case->closed_at,409);
|
||||
$sequence = (int)($input['draft_sequence'] ?? 0);
|
||||
$entrySources=Validator::make($input,['entry_sources'=>'sometimes|array|max:200','entry_sources.*'=>'string|max:100'])->validate()['entry_sources']??[];
|
||||
$case = $this->desk->case($actor, $id, true);
|
||||
abort_if($case->closed_at, 409);
|
||||
$sequence = (int) ($input['draft_sequence'] ?? 0);
|
||||
$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);
|
||||
if (isset($data['complements'])) app(InvestmentComplements::class)->resolve($data['complements'], $this->state($case)['complements'] ?? []);
|
||||
foreach ($data['selection'] as $slot=>$key) {
|
||||
if (!$key) continue;
|
||||
$ref=$this->reference($key);
|
||||
abort_unless(in_array($ref['kind'],$slot==='opportunity'?['opportunity','business']:[$slot],true),422,'Referência incompatível com a escolha.');
|
||||
if (isset($data['complements'])) {
|
||||
app(InvestmentComplements::class)->resolve($data['complements'], $this->state($case)['complements'] ?? []);
|
||||
}
|
||||
foreach ($data['selection'] as $slot => $key) {
|
||||
if (! $key) {
|
||||
continue;
|
||||
}
|
||||
$ref = $this->reference($key);
|
||||
if (! (in_array($ref['kind'], $slot === 'opportunity' ? ['opportunity', 'business'] : [$slot], true))) {
|
||||
abort(422, 'Referência incompatível com a escolha.');
|
||||
}
|
||||
}
|
||||
foreach ($data['opportunity_choices'] ?? [] as $choice) {
|
||||
$ref = $this->reference($choice['source']);
|
||||
abort_unless($ref['kind'] === 'opportunity', 422);
|
||||
$record = Opportunity::findOrFail($ref['id']);
|
||||
$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);
|
||||
if (!empty($choice['territory'])) {
|
||||
if (! empty($choice['territory'])) {
|
||||
$location = $this->reference($choice['territory']);
|
||||
abort_unless($location['kind'] === 'territory', 422);
|
||||
if ($key) abort_unless(app(InvestmentCorridorContext::class)->compatible($key, $location['id']), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
}
|
||||
}
|
||||
if (isset($data['opportunity_choices'])) app(InvestmentOpportunityChoices::class)->resolve($data['opportunity_choices'], $this->state($case)['opportunity_choices'] ?? [], true);
|
||||
if (!empty($data['selection']['park'])) {
|
||||
$first=$data['opportunity_choices'][0] ?? null;
|
||||
$source=$first['source'] ?? $data['selection']['opportunity'] ?? null;
|
||||
if ($source && str_starts_with($source,'opportunity:')) {
|
||||
$key=$first['corridor_key'] ?? app(InvestmentCorridorContext::class)->key(Opportunity::findOrFail(substr($source,12)));
|
||||
if ($key) {
|
||||
$territory=$first['territory'] ?? $data['selection']['territory'] ?? null;
|
||||
$ids=app(InvestmentCorridorContext::class)->provinces($key);
|
||||
$territory=$territory ? substr($territory,10) : (count($ids)===1?$ids[0]->id:null);
|
||||
$park=$this->reference($data['selection']['park']);
|
||||
abort_unless($park['kind']==='park' && in_array($park['id'],array_column(app(InvestmentCorridorContext::class)->parks($key,$territory),'id'),true),422,'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
abort_unless(app(InvestmentCorridorContext::class)->compatible($key, $location['id']), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($data['opportunity_choices'])) {
|
||||
app(InvestmentOpportunityChoices::class)->resolve($data['opportunity_choices'], $this->state($case)['opportunity_choices'] ?? [], true);
|
||||
}
|
||||
if (! empty($data['selection']['park'])) {
|
||||
$first = $data['opportunity_choices'][0] ?? null;
|
||||
$source = $first['source'] ?? $data['selection']['opportunity'] ?? null;
|
||||
if ($source && str_starts_with($source, 'opportunity:')) {
|
||||
$key = $first['corridor_key'] ?? app(InvestmentCorridorContext::class)->key(Opportunity::whereKey(substr($source, 12))->firstOrFail());
|
||||
if ($key) {
|
||||
$territory = $first['territory'] ?? $data['selection']['territory'] ?? null;
|
||||
$ids = app(InvestmentCorridorContext::class)->provinces($key);
|
||||
$territory = $territory ? substr($territory, 10) : (count($ids) === 1 ? $ids[0]->id : null);
|
||||
$park = $this->reference($data['selection']['park']);
|
||||
abort_unless($park['kind'] === 'park' && in_array($park['id'], array_column(app(InvestmentCorridorContext::class)->parks($key, $territory), 'id'), true), 422, 'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data, $sequence, $entrySources) {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at || (int)$case->version !== (int)$data['version'], 409, 'O dossier mudou. Recupere os dados antes de continuar.');
|
||||
abort_if($case->closed_at || (int) $case->version !== (int) $data['version'], 409, 'O dossier mudou. Recupere os dados antes de continuar.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$previous = $payload['investor_path']['context_drafts'][(string)$actor->id] ?? [];
|
||||
$previous = $payload['investor_path']['context_drafts'][(string) $actor->id] ?? [];
|
||||
abort_if(($previous['draft_sequence'] ?? 0) > $sequence, 409, 'Existe um rascunho mais recente. Recupere o dossier antes de continuar.');
|
||||
$payload['investor_path']['context_drafts'][(string)$actor->id] = [...$data, 'draft_sequence' => $sequence, 'entry_sources'=>array_values(array_unique([...($previous['entry_sources']??[]),...$entrySources]))];
|
||||
$payload['investor_path']['context_drafts'][(string) $actor->id] = [...$data, 'draft_sequence' => $sequence, 'entry_sources' => array_values(array_unique([...($previous['entry_sources'] ?? []), ...$entrySources]))];
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload)]);
|
||||
|
||||
return ['saved' => true];
|
||||
});
|
||||
}
|
||||
@@ -93,6 +114,9 @@ final class InvestorContext
|
||||
return Schema::hasTable('investor_navigation_preferences');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function state(\stdClass $case): array
|
||||
{
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
@@ -112,7 +136,9 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!empty($context['opportunity_choices']) && !array_key_exists('park', $context['opportunity_choices'][0])) $context['opportunity_choices'][0]['park'] = $context['selection']['park'] ?? null;
|
||||
if (! empty($context['opportunity_choices']) && ! array_key_exists('park', $context['opportunity_choices'][0])) {
|
||||
$context['opportunity_choices'][0]['park'] = $context['selection']['park'] ?? null;
|
||||
}
|
||||
$zone = $context['selection']['park'] ?? null;
|
||||
$context['fields']['investment_regime'] = $zone['fields']['investment_regime'] ?? 'general';
|
||||
$context['fields']['special_zone_id'] = $zone['id'] ?? '';
|
||||
@@ -120,13 +146,22 @@ final class InvestorContext
|
||||
return $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $selection
|
||||
*/
|
||||
public function dependencyHash(array $selection): string
|
||||
{
|
||||
unset($selection['portfolio'], $selection['selection']['portfolio']);
|
||||
if (isset($selection['opportunity_choices'])) $selection['opportunity_choices'] = array_map(fn($choice)=>Arr::except($choice,['portfolio_origins']),$selection['opportunity_choices']);
|
||||
if (isset($selection['opportunity_choices'])) {
|
||||
$selection['opportunity_choices'] = array_map(fn ($choice) => Arr::except($choice, ['portfolio_origins']), $selection['opportunity_choices']);
|
||||
}
|
||||
|
||||
return hash('sha256', json_encode(Arr::sortRecursive($selection), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function reference(string $key): array
|
||||
{
|
||||
[$kind,$id] = array_pad(explode(':', $key, 2), 2, '');
|
||||
@@ -140,7 +175,7 @@ final class InvestorContext
|
||||
$zoneAnalysis = null;
|
||||
if ($kind === 'opportunity') {
|
||||
abort_unless(ctype_digit($id), 422, 'Identificador de oportunidade inválido.');
|
||||
$o = Opportunity::with('sector')->findOrFail((int) $id);
|
||||
$o = Opportunity::with('sector')->whereKey((int) $id)->firstOrFail();
|
||||
$published = Opportunity::published()->whereKey($o->id)->exists();
|
||||
if (! $published) {
|
||||
abort_unless(request()->user() && $o->status !== 'archived' && app(PortalProfileAccess::class)->canView(request()->user(), $o), 404, 'Ficha privada indisponível neste âmbito.');
|
||||
@@ -160,7 +195,9 @@ final class InvestorContext
|
||||
$fields['sector'] = $o->sector->name;
|
||||
}
|
||||
$proactive = $published ? app(ProactiveInvestment::class)->publicData($o) : ($draft['proactive'] ?? null);
|
||||
if ($proactive) $zoneAnalysis = ['proactive' => $proactive, 'source_key' => $key, 'source_version' => $version, 'private_source' => !$published];
|
||||
if ($proactive) {
|
||||
$zoneAnalysis = ['proactive' => $proactive, 'source_key' => $key, 'source_version' => $version, 'private_source' => ! $published];
|
||||
}
|
||||
// Text labels do not establish a canonical territorial correspondence.
|
||||
if ($o->province) {
|
||||
$fields['province'] = $o->province;
|
||||
@@ -173,7 +210,7 @@ final class InvestorContext
|
||||
}
|
||||
} elseif ($kind === 'portfolio') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$dossier = \App\Http\Controllers\InvestmentPortfolioController::visible()->findOrFail($id);
|
||||
$dossier = InvestmentPortfolioController::visible()->whereKey($id)->firstOrFail();
|
||||
$title = $dossier->title;
|
||||
$href = '/carteira/'.$id;
|
||||
// Documentary coverage is not the investor's chosen implantation.
|
||||
@@ -185,7 +222,7 @@ final class InvestorContext
|
||||
'geography' => app(InvestmentRelations::class)->dossier($dossier), 'available_opportunity' => false];
|
||||
} elseif ($kind === 'business') {
|
||||
abort_unless(config('existing-business.enabled') && Str::isUuid($id), 404);
|
||||
$o = ExistingBusiness::published()->with('sector')->findOrFail($id);
|
||||
$o = ExistingBusiness::published()->with('sector')->whereKey($id)->firstOrFail();
|
||||
$title = $o->public_title;
|
||||
$href = '/negocios/'.$o->public_slug;
|
||||
$version = $o->version_no;
|
||||
@@ -198,7 +235,9 @@ final class InvestorContext
|
||||
if ($location) {
|
||||
$leaf = $location->province_id;
|
||||
foreach (['district', 'admin_post', 'locality'] as $level) {
|
||||
if (in_array($location->precision_level, array_slice(['province', 'district', 'admin_post', 'locality', 'exact'], array_search($level, ['province', 'district', 'admin_post', 'locality', 'exact'])), true) && $location->{$level.'_id'}) {
|
||||
if (in_array($location->precision_level, match ($level) {
|
||||
'district' => ['district', 'admin_post', 'locality', 'exact'], 'admin_post' => ['admin_post', 'locality', 'exact'], 'locality' => ['locality', 'exact']
|
||||
}, true) && $location->{$level.'_id'}) {
|
||||
$leaf = $location->{$level.'_id'};
|
||||
}
|
||||
}
|
||||
@@ -208,7 +247,7 @@ final class InvestorContext
|
||||
}
|
||||
} elseif ($kind === 'sector') {
|
||||
abort_unless(ctype_digit($id), 422);
|
||||
$s = Sector::where('is_active', true)->findOrFail((int) $id);
|
||||
$s = Sector::where('is_active', true)->whereKey((int) $id)->firstOrFail();
|
||||
$title = $s->name;
|
||||
$href = SectorOrganization::href($s->slug);
|
||||
$version = $s->updated_at?->toIso8601String();
|
||||
@@ -216,14 +255,14 @@ final class InvestorContext
|
||||
} elseif ($kind === 'territory') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$t = app(InvestmentGeography::class)->publicReferences()->whereIn('location_type', array_values(InvestmentGeography::FIELDS))->where('id', $id)->first();
|
||||
abort_unless($t, 404, 'Território público indisponível.');
|
||||
abort_unless($t !== null, 404, 'Território público indisponível.');
|
||||
$title = $t->name;
|
||||
$version = $t->version_no;
|
||||
$href = '/oportunidades?'.$t->location_type.'_id='.$id;
|
||||
$fields = $this->territoryFields($id);
|
||||
} elseif ($kind === 'park') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$p = app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->findOrFail($id);
|
||||
$p = app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->whereKey($id)->firstOrFail();
|
||||
$title = $p->name;
|
||||
$fields = ['special_zone_id' => (string) $p->id, 'investment_regime' => (string) $p->category];
|
||||
$version = $p->version_no;
|
||||
@@ -249,6 +288,9 @@ final class InvestorContext
|
||||
return [...$record, 'sha256' => hash('sha256', json_encode($record, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function territoryFields(string $id): array
|
||||
{
|
||||
$path = app(InvestmentGeography::class)->path($id);
|
||||
@@ -271,6 +313,9 @@ final class InvestorContext
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function options(string $query = ''): array
|
||||
{
|
||||
$query = mb_substr(trim($query), 0, 120);
|
||||
@@ -296,6 +341,9 @@ final class InvestorContext
|
||||
'parks' => app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->orderBy('name')->get(['id', 'name', 'category', 'version_no'])];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function current(User $actor): array
|
||||
{
|
||||
if (! $this->installed()) {
|
||||
@@ -322,6 +370,10 @@ final class InvestorContext
|
||||
return ['installed' => true, 'focus' => ['case_id' => $case->id, 'step_code' => $p->step_code, 'version' => (int) $p->version]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function focus(User $actor, array $input): array
|
||||
{
|
||||
abort_unless($this->installed(), 409, 'Instalação do contexto ainda pendente.');
|
||||
@@ -344,9 +396,13 @@ final class InvestorContext
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function input(array $input): 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.');
|
||||
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.');
|
||||
|
||||
abort_if(! app(PrivateInvestmentPreparation::class)->available() && (! empty($input['document_links']) || array_intersect(array_keys(is_array($input['declarations'] ?? null) ? $input['declarations'] : []), PrivateInvestmentPreparation::FIELDS)), 409, 'Esta preparação ainda não está disponível neste ambiente. As respostas foram preservadas.');
|
||||
|
||||
@@ -375,6 +431,10 @@ final class InvestorContext
|
||||
'replace_fields' => 'nullable|array', 'replace_fields.*' => 'string|in:'.implode(',', self::FIELDS)])->validate();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor, string $id, array $input): array
|
||||
{
|
||||
$data = $this->input($input);
|
||||
@@ -397,7 +457,7 @@ final class InvestorContext
|
||||
if (! array_key_exists('opportunity_choices', $data) && array_key_exists('territory', $data['selection'])) {
|
||||
$source = $data['selection']['opportunity'] ?? ($old['selection']['opportunity']['key'] ?? null);
|
||||
if ($source && str_starts_with($source, 'opportunity:')) {
|
||||
$documented = Opportunity::findOrFail(substr($source, 12))->primary_territory_id;
|
||||
$documented = Opportunity::whereKey(substr($source, 12))->firstOrFail()->primary_territory_id;
|
||||
abort_if($documented && $data['selection']['territory'] !== 'territory:'.$documented, 422,
|
||||
'Confirme a alternativa territorial por ficha e indique o motivo; a localização documentada foi preservada.');
|
||||
}
|
||||
@@ -407,15 +467,21 @@ final class InvestorContext
|
||||
$data['selection']['opportunity'] = $choices[0]['opportunity']['key'] ?? null;
|
||||
// Shared fields concern the first identified opportunity; other sites remain separate.
|
||||
$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;
|
||||
if (array_key_exists('park', $data['opportunity_choices'][0] ?? [])) {
|
||||
$data['selection']['park'] = $choices[0]['park']['key'] ?? null;
|
||||
}
|
||||
} elseif (array_key_exists('opportunity', $data['selection']) && $choices !== []) {
|
||||
abort(422, 'Actualize a selecção identificada de oportunidades; não substitua silenciosamente o conjunto por uma ficha.');
|
||||
}
|
||||
$selection = $old['selection'];
|
||||
foreach ($complements as $complement) {
|
||||
if (($complement['availability'] ?? '') === 'review_required') continue;
|
||||
if (($complement['availability'] ?? '') === 'review_required') {
|
||||
continue;
|
||||
}
|
||||
foreach ([$complement['origin']['key'], $complement['target']['key'] ?? ''] as $key) {
|
||||
if (str_starts_with($key, 'opportunity:')) abort_unless(in_array($key, array_column(array_column($choices, 'opportunity'), 'key'), true), 422, 'Conserve a oportunidade escolhida ou retire explicitamente a sua relação complementar.');
|
||||
if (str_starts_with($key, 'opportunity:')) {
|
||||
abort_unless(in_array($key, array_column(array_column($choices, 'opportunity'), 'key'), true), 422, 'Conserve a oportunidade escolhida ou retire explicitamente a sua relação complementar.');
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($data['selection'] as $slot => $key) {
|
||||
@@ -426,16 +492,20 @@ final class InvestorContext
|
||||
}
|
||||
$ref = $this->reference($key);
|
||||
$expected = $slot === 'opportunity' ? ['opportunity', 'business'] : [$slot];
|
||||
abort_unless(in_array($ref['kind'], $expected, true), 422, 'Referência incompatível com a dimensão.');
|
||||
if (! (in_array($ref['kind'], $expected, true))) {
|
||||
abort(422, 'Referência incompatível com a dimensão.');
|
||||
}
|
||||
$selection[$slot] = $ref;
|
||||
}
|
||||
$corridor = $choices[0]['corridor_key'] ?? (isset($selection['opportunity']) && $selection['opportunity']['kind'] === 'opportunity'
|
||||
? app(InvestmentCorridorContext::class)->key(Opportunity::findOrFail($selection['opportunity']['id'])) : 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.');
|
||||
? 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.');
|
||||
}
|
||||
if ($corridor && isset($selection['park'])) {
|
||||
$eligible = array_column(app(InvestmentCorridorContext::class)->parks($corridor, $selection['territory']['id'] ?? null), 'id');
|
||||
if (!in_array($selection['park']['id'], $eligible, true)) {
|
||||
abort_if(!empty($data['selection']['park']), 422, 'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
if (! in_array($selection['park']['id'], $eligible, true)) {
|
||||
abort_if(! empty($data['selection']['park']), 422, 'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
unset($selection['park']);
|
||||
}
|
||||
}
|
||||
@@ -484,14 +554,16 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
if ($corridor) {
|
||||
foreach (['province_id','district_id','admin_post_id','locality_id','province','district','location'] as $key) {
|
||||
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location'] as $key) {
|
||||
if (isset($selection['territory']['fields'][$key])) {
|
||||
$fields[$key]=(string)$selection['territory']['fields'][$key];
|
||||
$provenance[$key]=Arr::except($selection['territory'],['fields']);
|
||||
} else unset($fields[$key],$provenance[$key]);
|
||||
$fields[$key] = (string) $selection['territory']['fields'][$key];
|
||||
$provenance[$key] = Arr::except($selection['territory'], ['fields']);
|
||||
} else {
|
||||
unset($fields[$key],$provenance[$key]);
|
||||
}
|
||||
}
|
||||
$fields['special_zone_id']=$selection['park']['id']??'';
|
||||
$fields['investment_regime']=$selection['park']['fields']['investment_regime']??'general';
|
||||
$fields['special_zone_id'] = $selection['park']['id'] ?? '';
|
||||
$fields['investment_regime'] = $selection['park']['fields']['investment_regime'] ?? 'general';
|
||||
}
|
||||
$replaced = [];
|
||||
foreach (array_unique([...array_keys($old['fields']), ...array_keys($fields)]) as $key) {
|
||||
@@ -505,11 +577,16 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
$changedFields = array_column($replaced, 'field');
|
||||
if ($complements !== ($old['complements'] ?? [])) $changed[] = 'complements';
|
||||
if ($complements !== ($old['complements'] ?? [])) {
|
||||
$changed[] = 'complements';
|
||||
}
|
||||
$choicesChanged = $choices !== ($old['opportunity_choices'] ?? []);
|
||||
$choiceInputsChanged = array_map(fn($c)=>Arr::except($c,['portfolio_origins']),$choices) !== array_map(fn($c)=>Arr::except($c,['portfolio_origins']),$old['opportunity_choices']??[]);
|
||||
if ($choiceInputsChanged) $changed = array_values(array_unique([...$changed, 'opportunity', 'territory']));
|
||||
elseif ($choicesChanged) $changed[] = 'portfolio_origins';
|
||||
$choiceInputsChanged = array_map(fn ($c) => Arr::except($c, ['portfolio_origins']), $choices) !== array_map(fn ($c) => Arr::except($c, ['portfolio_origins']), $old['opportunity_choices'] ?? []);
|
||||
if ($choiceInputsChanged) {
|
||||
$changed = array_values(array_unique([...$changed, 'opportunity', 'territory']));
|
||||
} elseif ($choicesChanged) {
|
||||
$changed[] = 'portfolio_origins';
|
||||
}
|
||||
$conditionsChanged = (bool) array_intersect($changedFields, array_diff(self::FIELDS, ['project_title', 'project_summary']));
|
||||
$dependencyChanged = $choiceInputsChanged || in_array('complements', $changed, true) || $this->dependencyHash($old['selection']) !== $this->dependencyHash($selection) || $conditionsChanged;
|
||||
$privateConditionsChanged = (bool) array_intersect($changedFields, PrivateInvestmentPreparation::FIELDS);
|
||||
@@ -524,7 +601,9 @@ final class InvestorContext
|
||||
if ($privateConditionsChanged) {
|
||||
$steps = array_values(array_unique([...$steps, 'S02', 'S05', 'S06', 'S07']));
|
||||
}
|
||||
if (in_array('complements', $changed, true)) $steps = array_values(array_unique([...$steps, 'S02', 'S08']));
|
||||
if (in_array('complements', $changed, true)) {
|
||||
$steps = array_values(array_unique([...$steps, 'S02', 'S08']));
|
||||
}
|
||||
$privatePreparation = null;
|
||||
if (app(PrivateInvestmentPreparation::class)->available()) {
|
||||
$docs = $this->preparationDocuments($id);
|
||||
@@ -543,6 +622,10 @@ final class InvestorContext
|
||||
return [...$plan, 'preview_hash' => $hash];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function commit(User $actor, string $id, array $input): array
|
||||
{
|
||||
abort_unless($this->installed(), 409, 'Instalação do contexto ainda pendente.');
|
||||
@@ -586,7 +669,7 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
$payload['investor_path']['context'] = $context;
|
||||
unset($payload['investor_path']['context_drafts'][(string)$actor->id]);
|
||||
unset($payload['investor_path']['context_drafts'][(string) $actor->id]);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'title' => $context['fields']['project_title'] ?? $case->title, 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'investment_context_changed', ['before' => $before, 'after' => $context, 'affected_result_ids' => array_column($plan['dependent_results'], 'id'), 'preserved_request_ids' => array_column($plan['requests'], 'id')]);
|
||||
$result = ['case_id' => $id, 'version' => (int) $case->version + 1, 'revision' => $revision, 'replayed' => false];
|
||||
@@ -596,6 +679,9 @@ final class InvestorContext
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function view(User $actor, string $id, ?string $opportunity = null): array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id);
|
||||
@@ -622,21 +708,28 @@ final class InvestorContext
|
||||
|
||||
$prefill = $this->prefill($ctx, $opportunity);
|
||||
$saved = $this->desk->decode($case->payload);
|
||||
if (!empty($saved['reuse_consent'])) {
|
||||
$contacts = array_filter(['email' => $saved['email'] ?? null, 'phone' => $saved['profile']['phone'] ?? null], fn($v) => is_string($v) && $v !== '');
|
||||
if (! empty($saved['reuse_consent'])) {
|
||||
$contacts = array_filter(['email' => $saved['email'] ?? null, 'phone' => $saved['profile']['phone'] ?? null], fn ($v) => is_string($v) && $v !== '');
|
||||
$prefill['simulator'] = [...$contacts, ...$prefill['simulator']];
|
||||
$prefill['land'] = [...$contacts, ...(!empty($saved['name']) ? ['full_name' => $saved['name']] : []), ...$prefill['land']];
|
||||
$prefill['land'] = [...$contacts, ...(! empty($saved['name']) ? ['full_name' => $saved['name']] : []), ...$prefill['land']];
|
||||
}
|
||||
|
||||
return ['private_investment' => $preparation, 'preparation_documents' => $this->preparationDocuments($id), 'simulator_context_revision' => $simulatorRevision, 'case' => $path['case'], 'context' => $ctx, 'steps' => array_map(fn ($s) => Arr::only($s, ['code', 'title', 'state', 'context_review_required']), $path['steps']),
|
||||
'can_write' => $path['canWrite'], 'next' => $path['next'], 'results' => $path['results'], 'requests' => $path['requests'],
|
||||
'prefill' => $prefill, 'notice' => 'A seleção apoia a preparação e não confirma benefícios, licenças, direitos ou disponibilidade.'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preparationDocuments(string $id): array
|
||||
{
|
||||
return DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->whereNull('d.deleted_at')->get(['l.id', 'l.document_id', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.version_no', 'd.sha256'])->map(fn ($row) => (array) $row)->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function landPreparation(\stdClass $case, ?string $opportunity = null): array
|
||||
{
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
@@ -648,6 +741,10 @@ final class InvestorContext
|
||||
return ['need' => in_array($need, ['yes', 'no'], true) ? $need : 'unknown', 'reason' => $key ? ($path['opportunity_fact_reasons'][$key]['land_needed'] ?? '') : ($path['fact_reasons']['land_needed'] ?? '')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $ctx
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function prefill(array $ctx, ?string $opportunity = null): array
|
||||
{
|
||||
$original = $ctx;
|
||||
@@ -659,15 +756,21 @@ final class InvestorContext
|
||||
$sim += ['journey_type' => 'investor', 'journey_type_label' => 'Avaliar o meu investimento', 'purpose' => 'simulate_only', 'purpose_label' => 'Apenas simular'];
|
||||
if (($ctx['land_preparation']['need'] ?? null) === 'yes') {
|
||||
$tenure = ['duat' => ['duat', 'DUAT'], 'lease' => ['leased', 'Arrendado']][$f['site_tenure'] ?? ''] ?? null;
|
||||
if ($tenure) [$sim['land_status'], $sim['land_status_label']] = $tenure;
|
||||
if ($tenure) {
|
||||
[$sim['land_status'], $sim['land_status_label']] = $tenure;
|
||||
}
|
||||
}
|
||||
// Human labels travel with the exact existing identifiers, not inferred locations.
|
||||
foreach (app(InvestmentGeography::class)->publicReferences()->whereIn('id', array_values(Arr::only($f, array_keys(InvestmentGeography::FIELDS))))->get(['id', 'name']) as $place) {
|
||||
foreach (array_keys(InvestmentGeography::FIELDS) as $key) {
|
||||
if (($f[$key] ?? null) === $place->id) $sim[$key.'_label'] = $place->name;
|
||||
if (($f[$key] ?? null) === $place->id) {
|
||||
$sim[$key.'_label'] = $place->name;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (! empty($f['sector_id']) && ($sector = Sector::where('is_active', true)->find($f['sector_id']))) $sim['sector_id_label'] = $sector->name;
|
||||
if (! empty($f['sector_id']) && ($sector = Sector::where('is_active', true)->whereKey($f['sector_id'])->first())) {
|
||||
$sim['sector_id_label'] = $sector->name;
|
||||
}
|
||||
$zone = $ctx['selection']['park'] ?? null;
|
||||
$sim['context_applicability_snapshot'] = json_encode([
|
||||
'version' => 1, 'context_revision' => $ctx['revision'],
|
||||
@@ -675,12 +778,13 @@ final class InvestorContext
|
||||
'portfolio_origin' => $ctx['selection']['portfolio'] ?? null,
|
||||
'zone' => $zone ? Arr::only($zone, ['id', 'title', 'href', 'version', 'sha256', 'fields', 'analysis']) : null,
|
||||
'provenance' => $ctx['provenance'],
|
||||
'opportunity_choices' => $ctx['opportunity_choices'] ?? [],
|
||||
// Retain dossier options as provenance when no consumer is selected; scoped fields remain empty.
|
||||
'opportunity_choices' => ($ctx['opportunity_choices'] ?? []) ?: ($original['opportunity_choices'] ?? []),
|
||||
'complements' => $ctx['complements'] ?? [],
|
||||
'requirements_assessment' => $ctx['requirements_assessment'] ?? null,
|
||||
'path' => $ctx['path_applicability'] ?? null,
|
||||
'land_preparation' => $ctx['land_preparation'] ?? null,
|
||||
'field_provenance' => array_map(fn($origin) => Arr::only($origin, ['kind', 'title', 'version', 'context_revision']), $ctx['provenance'] ?? []),
|
||||
'field_provenance' => array_map(fn ($origin) => Arr::only($origin, ['kind', 'title', 'version', 'context_revision']), $ctx['provenance'] ?? []),
|
||||
'preparation' => isset($ctx['preparation_assessment']) ? Arr::except($ctx['preparation_assessment'], ['questions']) : null,
|
||||
'fields' => Arr::only($f, ['investor_origin', 'tax_residency_country', 'entity_stage', 'currency', 'expected_start_date', 'investment_regime']),
|
||||
'notice' => 'Referências e declarações para preparação; sem reconhecimento automático de elegibilidade ou benefício.',
|
||||
@@ -688,6 +792,7 @@ final class InvestorContext
|
||||
|
||||
$scoped = app(InvestmentConsumerScope::class)->context($original, $opportunity);
|
||||
$f = $scoped['fields'];
|
||||
|
||||
return ['simulator' => $sim, 'land' => array_filter(['project_reference' => $f['project_title'] ?? null, 'activity' => $f['sector'] ?? null, 'purpose' => $f['project_summary'] ?? null, 'parcels' => [Arr::only($f, array_keys(InvestmentGeography::FIELDS))]], fn ($v) => $v !== null),
|
||||
'desk' => array_filter(['title' => $f['project_title'] ?? null, 'territory_id' => $f['locality_id'] ?? $f['admin_post_id'] ?? $f['district_id'] ?? $f['province_id'] ?? null, 'location_source' => isset($f['province_id']) ? 'Referência consultada no contexto v'.($ctx['revision'] ?? 0).': '.($f['location'] ?? 'território identificado').'. Não confirma disponibilidade.' : null, 'description' => $f['project_summary'] ?? null, 'sector' => $f['sector'] ?? null, ...Arr::only($f, array_keys(InvestmentGeography::FIELDS))], fn ($v) => $v !== null),
|
||||
'submission' => array_filter(['currency' => $f['currency'] ?? null, 'sector' => $f['sector'] ?? null, 'objective' => $f['project_summary'] ?? null, 'location' => $f['location'] ?? null], fn ($v) => $v !== null)];
|
||||
|
||||
Reference in New Issue
Block a user