@@ -20,13 +20,15 @@ class OpportunityManagement
|
||||
|
||||
public const MATURITY_FIELDS = ['maturity_level', 'maturity_label', 'maturity_stage', 'maturity_catalogue_version'];
|
||||
|
||||
public const PRIVATE_DRAFT_FIELDS = [...self::MATURITY_FIELDS, 'real_estate', 'canonical'];
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function values(Opportunity $record): array
|
||||
{
|
||||
$base = $record->only(self::FIELDS);
|
||||
$draft = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
|
||||
return [...$base, ...($this->closed($record) ? $draft : array_intersect_key($draft, array_flip(self::MATURITY_FIELDS)))];
|
||||
return [...$base, ...($this->closed($record) ? $draft : array_intersect_key($draft, array_flip(self::PRIVATE_DRAFT_FIELDS)))];
|
||||
}
|
||||
|
||||
public function installed(): bool
|
||||
@@ -47,7 +49,20 @@ class OpportunityManagement
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input, ?int $id = null): Opportunity
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$profileCreation = $id === null && str_starts_with(request()->path(), 'minhas-oportunidades');
|
||||
if ($id !== null) {
|
||||
$existingRecord = Opportunity::withTrashed()->findOrFail($id);
|
||||
$access->authorize($actor, 'edit', $existingRecord);
|
||||
if ($existingRecord->owner_user_id !== null) {
|
||||
abort_unless($access->canEdit($actor, $existingRecord, $input['opportunity_category'] ?? null), 403);
|
||||
abort_if(array_key_exists('organization_id', $input) && $input['organization_id'] !== $existingRecord->organization_id, 403, 'A organização não pode ser alterada por edição.');
|
||||
}
|
||||
} elseif ($profileCreation) {
|
||||
abort_unless($access->canCreate($actor, $input['organization_id'] ?? null, $input['opportunity_category'] ?? ''), 403);
|
||||
} else {
|
||||
abort_unless($access->legacyWriteAllowed($actor), 403, 'O papel v1 não usa a criação legada para contornar o seu âmbito.');
|
||||
}
|
||||
abort_unless($this->installed(), 503, 'Instalação autenticada ainda necessária.');
|
||||
$data = Validator::make($input, [
|
||||
'etag' => [$id ? 'required' : 'nullable', 'string', 'size:64'],
|
||||
@@ -62,18 +77,30 @@ class OpportunityManagement
|
||||
'expected_impact' => ['nullable', 'string', 'max:10000'],
|
||||
'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
|
||||
'opportunity_category' => ['nullable', Rule::in(self::CATEGORIES)],
|
||||
'real_estate' => ['sometimes', 'array'],
|
||||
'canonical' => ['sometimes', 'array'],
|
||||
'estimated_investment_amount' => ['nullable', 'regex:/^\d{1,16}(\.\d{1,2})?$/'],
|
||||
'estimated_investment_currency' => ['nullable', 'in:MZN,USD,EUR,ZAR'],
|
||||
'reason' => ['required', 'string', 'min:20', 'max:1000'],
|
||||
'organization_id' => ['nullable', 'uuid', Rule::exists('organizations', 'id')->whereNull('deleted_at')],
|
||||
'owner_user_id' => 'prohibited', 'workflow_context' => 'prohibited', 'status' => 'prohibited', 'first_submitted_at' => 'prohibited',
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
])->validate();
|
||||
$data = app(OpportunityMaturity::class)->normalize($data);
|
||||
if (array_key_exists('real_estate', $data)) {
|
||||
$data['real_estate'] = app(OpportunityRealEstateDraft::class)->validate($data['real_estate']);
|
||||
}
|
||||
if (array_key_exists('canonical', $data)) {
|
||||
$data['canonical'] = app(OpportunityCanonicalContract::class)->draft($data['canonical']);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $id) {
|
||||
return DB::transaction(function () use ($actor, $data, $id, $profileCreation, $access) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(91026, 100000)');
|
||||
if (! $id && ($existing = Opportunity::withTrashed()->where('management_creation_key', $data['creation_key'])->first())) {
|
||||
$access->authorize($actor, 'view', $existing);
|
||||
abort_unless($profileCreation === ($existing->owner_user_id !== null) && (! $profileCreation || $existing->organization_id === ($data['organization_id'] ?? null)), 409);
|
||||
$snapshot = $this->values($existing);
|
||||
foreach (array_intersect_key($data, array_flip([...self::FIELDS, ...self::MATURITY_FIELDS])) as $key => $value) {
|
||||
foreach (array_intersect_key($data, array_flip([...self::FIELDS, ...self::PRIVATE_DRAFT_FIELDS])) as $key => $value) {
|
||||
if (($snapshot[$key] ?? null) != $value) {
|
||||
throw ValidationException::withMessages(['creation_key' => 'Esta chave já foi utilizada com dados diferentes.']);
|
||||
}
|
||||
@@ -83,11 +110,33 @@ class OpportunityManagement
|
||||
}
|
||||
$record = $id ? Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail() : new Opportunity;
|
||||
if ($id) {
|
||||
$access->authorize($actor, 'edit', $record);
|
||||
$this->check($record, $data['etag']);
|
||||
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
|
||||
}
|
||||
$before = $record->getAttributes();
|
||||
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::MATURITY_FIELDS]));
|
||||
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::PRIVATE_DRAFT_FIELDS]));
|
||||
if (array_key_exists('canonical', $changes)) {
|
||||
$previous = $record->exists ? $this->values($record) : [];
|
||||
$changes['canonical'] = [...($previous['canonical'] ?? []), ...$changes['canonical']];
|
||||
if (($changes['canonical']['opportunity_category'] ?? ($changes['opportunity_category'] ?? $record->opportunity_category)) !== ($changes['opportunity_category'] ?? $record->opportunity_category)) {
|
||||
throw ValidationException::withMessages(['canonical.opportunity_category' => 'Contrato e registo devem usar a mesma categoria.']);
|
||||
}
|
||||
// One entry of common data feeds the existing fields; a closed/public version stays untouched.
|
||||
foreach (['official_title' => 'title', 'executive_summary' => 'summary', 'demand_statement' => 'description', 'sector_id' => 'sector_id', 'promoter_type' => 'promoter_type'] as $source => $target) {
|
||||
if (array_key_exists($source, $changes['canonical'])) {
|
||||
$changes[$target] = $changes['canonical'][$source];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (array_key_exists('real_estate', $changes)) {
|
||||
$previousValues = $record->exists ? $this->values($record) : [];
|
||||
$category = array_key_exists('opportunity_category', $data) ? $data['opportunity_category'] : ($previousValues['opportunity_category'] ?? null);
|
||||
if ($category !== 'real_estate') {
|
||||
throw ValidationException::withMessages(['real_estate' => 'O contrato imobiliário pertence à categoria real_estate.']);
|
||||
}
|
||||
$changes['real_estate'] = [...($previousValues['real_estate'] ?? []), ...$changes['real_estate']];
|
||||
}
|
||||
if (array_intersect_key($data, InvestmentGeography::FIELDS) !== []) {
|
||||
$path = app(InvestmentGeography::class)->selection($data, true);
|
||||
$changes['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
@@ -102,6 +151,12 @@ class OpportunityManagement
|
||||
$record->management_creation_key = $data['creation_key'];
|
||||
$record->management_version = 1;
|
||||
$record->estimated_investment_currency = null;
|
||||
if ($profileCreation) {
|
||||
abort_unless($access->canCreate($actor, $data['organization_id'] ?? null, $data['opportunity_category'] ?? ''), 403);
|
||||
$record->owner_user_id = $actor->id;
|
||||
$record->organization_id = $data['organization_id'] ?? null;
|
||||
$record->workflow_context = ['policy_version' => PortalProfileAccess::VERSION, 'contributors' => [$actor->id]];
|
||||
}
|
||||
} else {
|
||||
$record->management_version++;
|
||||
}
|
||||
@@ -111,17 +166,24 @@ class OpportunityManagement
|
||||
$record->management_draft = json_encode([...$previous, ...$changes], JSON_THROW_ON_ERROR);
|
||||
} else {
|
||||
foreach ($changes as $key => $value) {
|
||||
if (in_array($key, ['maturity_stage', 'maturity_catalogue_version'], true) || (($changes['maturity_catalogue_version'] ?? null) === OpportunityMaturity::VERSION && in_array($key, ['maturity_level', 'maturity_label'], true))) {
|
||||
if (in_array($key, ['real_estate', 'canonical', 'maturity_stage', 'maturity_catalogue_version'], true) || (($changes['maturity_catalogue_version'] ?? null) === OpportunityMaturity::VERSION && in_array($key, ['maturity_level', 'maturity_label'], true))) {
|
||||
continue;
|
||||
}
|
||||
$record->{$key} = $value;
|
||||
}
|
||||
if (isset($changes['maturity_catalogue_version'])) {
|
||||
if (isset($changes['maturity_catalogue_version']) || array_key_exists('real_estate', $changes) || array_key_exists('canonical', $changes)) {
|
||||
// The existing draft JSON holds the versioned catalogue; legacy columns stay intact.
|
||||
$previous = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
$record->management_draft = json_encode([...$previous, ...array_intersect_key($changes, array_flip(self::MATURITY_FIELDS))], JSON_THROW_ON_ERROR);
|
||||
$record->management_draft = json_encode([...$previous, ...array_intersect_key($changes, array_flip(self::PRIVATE_DRAFT_FIELDS))], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
if ($record->owner_user_id !== null) {
|
||||
$context = $record->workflow_context ?? [];
|
||||
unset($context['approval'], $context['reviews']);
|
||||
$context['content_revision'] = ($context['content_revision'] ?? 0) + 1;
|
||||
$context['contributors'] = array_values(array_unique([...($context['contributors'] ?? []), $actor->id]));
|
||||
$record->workflow_context = $context;
|
||||
}
|
||||
$record->save();
|
||||
$this->audit($record, $actor, $before, $id ? 'draft_updated' : 'draft_created', $data['reason']);
|
||||
|
||||
@@ -132,11 +194,13 @@ class OpportunityManagement
|
||||
/** @param array<string,mixed> $input */
|
||||
public function lifecycle(User $actor, int $id, array $input): Opportunity
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
$data = Validator::make($input, ['etag' => ['required', 'string', 'size:64'], 'action' => ['required', 'in:delete,restore'], 'reason' => ['required', 'string', 'min:20', 'max:1000'], 'confirm' => ['required', 'accepted']])->validate();
|
||||
abort_unless(app(PortalProfileAccess::class)->legacyWriteAllowed($actor), 403);
|
||||
$actions = config('portal.opportunity_dashboard_access_enabled') ? 'in:delete,archive,restore' : 'in:delete,restore';
|
||||
$data = Validator::make($input, ['etag' => ['required', 'string', 'size:64'], 'action' => ['required', $actions], 'reason' => ['required', 'string', 'min:20', 'max:1000'], 'confirm' => ['required', 'accepted']])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$record = Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_if($record->owner_user_id !== null, 403, 'A v1 exige pedido e decisão de arquivo; não concede exclusão ou restauro ao Promotor.');
|
||||
$this->check($record, $data['etag']);
|
||||
$before = $record->getAttributes();
|
||||
if ($data['action'] === 'restore') {
|
||||
@@ -152,8 +216,10 @@ class OpportunityManagement
|
||||
}
|
||||
} else {
|
||||
abort_if($record->trashed() || $record->status === 'archived', 409, 'Registo já eliminado/arquivado.');
|
||||
if ($this->closed($record)) {
|
||||
$record->management_closed_once = true;
|
||||
if ($data['action'] === 'archive' || $this->closed($record)) {
|
||||
if ($this->closed($record)) {
|
||||
$record->management_closed_once = true;
|
||||
}
|
||||
$record->status = 'archived';
|
||||
} else {
|
||||
$record->deleted_at = now();
|
||||
|
||||
Reference in New Issue
Block a user