feat: prepare private offers through existing opportunities

This commit is contained in:
2026-11-14 13:41:31 +02:00
parent e8408c27d9
commit 1f2990e4da
17 changed files with 1211 additions and 26 deletions
@@ -0,0 +1,59 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Services\OpportunityCanonicalContract;
use App\Services\PortalProfileAccess;
use App\Services\PrivateOfferPreparation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class PrivateOfferPreparationController extends Controller
{
public function index(Request $request, PortalProfileAccess $access): Response
{
$records = $access->scope(Opportunity::query(), $request->user())->whereNotNull('workflow_context->private_offer_preparation')
->orderByDesc('id')->paginate(20);
return Inertia::render('offers/preparation-index', ['records' => $records->through(fn ($r) => [
'id' => $r->id, 'title' => $r->title, 'reference' => $r->reference,
'state' => data_get($r->workflow_context, 'private_offer_preparation.state'),
]), 'canCreate' => count($access->navigation($request->user())['contexts']) > 0]);
}
public function edit(Request $request, PrivateOfferPreparation $service, ?int $id = null): Response|JsonResponse
{
$record = $id ? $service->record($request->user(), $id) : null;
$contexts = app(PortalProfileAccess::class)->navigation($request->user())['contexts'];
abort_unless($record || count($contexts) > 0, 403, 'É necessária uma atribuição de promotor no âmbito da oferta.');
$presentation = $record ? $service->presentation($request->user(), $record) : null;
if ($request->expectsJson() && ! $request->header('X-Inertia')) {
return response()->json(['record' => $presentation]);
}
$options = app(OpportunityCanonicalContract::class)->options($request->user(), $record);
return Inertia::render('offers/preparation', ['record' => $presentation, 'contexts' => $contexts,
'contacts' => $options['contacts'], 'contactInvestors' => $options['contactInvestors']]);
}
public function save(Request $request, PrivateOfferPreparation $service, ?int $id = null): JsonResponse
{
if ($id) {
$service->record($request->user(), $id, true);
}
$record = $service->save($request->user(), $request->all(), $id);
return response()->json(['record' => $service->presentation($request->user(), $record)], $id ? 200 : 201);
}
public function submit(Request $request, PrivateOfferPreparation $service, int $id): JsonResponse
{
$record = $service->submit($request->user(), $id, $request->all());
return response()->json(['record' => $service->presentation($request->user(), $record),
'message' => 'Submissão privada registada. A oferta não foi publicada.']);
}
}
@@ -23,6 +23,14 @@ class ProtectProfileOpportunity
}
if ($request->user() && $id !== null && Schema::hasColumn('opportunities', 'owner_user_id')) {
$record = Opportunity::withTrashed()->find($id);
if ($record?->isPrivateOfferPreparation()) {
app(PortalProfileAccess::class)->authorize($request->user(), $request->isMethod('GET') ? 'view' : 'edit', $record);
if ($request->isMethod('GET') && $request->is('minhas-oportunidades/*/edit', 'minhas-oportunidades/*/view', 'management/opportunities/*/edit', 'management/opportunities/*/view')) {
return redirect('/minhas-oportunidades/ofertas/'.$record->id)->header('Cache-Control', 'private, no-store');
}
// Contact registration reuses the CRM master and its fresh-MFA gate.
abort_unless($request->isMethod('POST') && $request->is('minhas-oportunidades/*/contacts'), 403, 'Use a preparação privada da oferta.');
}
if ($record && $record->owner_user_id === null && ! $request->isMethod('GET')) {
abort_unless(app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()), 403, 'O papel v1 não contorna os controlos através de um registo legado.');
}
+18
View File
@@ -30,6 +30,23 @@ class Opportunity extends Model
{
use SoftDeletes;
public function isPrivateOfferPreparation(): bool
{
return isset($this->workflow_context['private_offer_preparation']);
}
protected static function booted(): void
{
static::saving(function (self $record) {
$original = $record->getRawOriginal('workflow_context');
$wasPrivate = is_string($original) && isset(json_decode($original, true)['private_offer_preparation']);
abort_if($wasPrivate && ! $record->isPrivateOfferPreparation(), 403, 'A preparação privada não pode ser convertida neste percurso.');
if ($record->isPrivateOfferPreparation()) {
abort_unless($record->status === 'draft' && $record->published_at === null, 403, 'A publicação de Ofertas não está disponível nesta fase.');
}
});
}
protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once', 'owner_user_id', 'organization_id', 'workflow_context'];
protected $appends = ['maturity_catalogue_version'];
@@ -115,6 +132,7 @@ class Opportunity extends Model
public function scopePublished(Builder $query): Builder
{
if (Schema::hasColumn('opportunities', 'workflow_context')) {
$query->whereNull('workflow_context->private_offer_preparation');
$query->where(fn ($q) => $q->whereNull('owner_user_id')->orWhere('workflow_context->publication->visibility', 'public'));
}
@@ -279,14 +279,7 @@ class OpportunityCanonicalContract
'economic_activity_id', 'Sector, subsector e atividade devem corresponder à hierarquia/versão publicada; os cinco níveis originais são conservados.');
foreach (['internal_contact_id', 'public_contact_id'] as $field) {
if (! empty($payload[$field])) {
$contacts = DB::table('contacts')->where('contacts.id', $payload[$field])->whereNull('contacts.deleted_at');
if ($record->organization_id) {
$contacts->whereExists(fn ($q) => $q->selectRaw('1')->from('investor_contacts as ic')->join('investors as i', 'i.id', '=', 'ic.investor_id')
->whereColumn('ic.contact_id', 'contacts.id')->where('i.organization_id', $record->organization_id)->whereNull('i.deleted_at'));
} else {
$contacts->where('source_system', 'portal-user-contact')->where('external_id', 'user:'.$record->owner_user_id);
}
$check($contacts->exists(), $field, 'Contacto inexistente ou sem relação com o Promotor.');
$check(app(OpportunityContacts::class)->related($record, $payload[$field]), $field, 'Contacto inexistente ou sem relação com o Promotor.');
}
}
$resources = [];
+13
View File
@@ -14,6 +14,19 @@ use Illuminate\Validation\ValidationException;
/** Reuse the CRM master without manufacturing an interest, lead or consent. */
class OpportunityContacts
{
public function related(Opportunity $record, string $id): bool
{
$contacts = DB::table('contacts')->where('contacts.id', $id)->whereNull('contacts.deleted_at');
if ($record->organization_id) {
$contacts->whereExists(fn ($q) => $q->selectRaw('1')->from('investor_contacts as ic')->join('investors as i', 'i.id', '=', 'ic.investor_id')
->whereColumn('ic.contact_id', 'contacts.id')->where('i.organization_id', $record->organization_id)->whereNull('i.deleted_at'));
} else {
$contacts->where('source_system', 'portal-user-contact')->where('external_id', 'user:'.$record->owner_user_id);
}
return $contacts->exists();
}
/**
* @param array<array-key, mixed> $input
* @return array<array-key, mixed>
+14 -5
View File
@@ -21,7 +21,7 @@ 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', 'proactive'];
public const PRIVATE_DRAFT_FIELDS = [...self::MATURITY_FIELDS, 'real_estate', 'canonical', 'proactive', 'private_offer'];
/** @return array<string,mixed> */
public function values(Opportunity $record): array
@@ -51,12 +51,13 @@ class OpportunityManagement
}
/** @param array<string,mixed> $input */
public function save(User $actor, array $input, ?int $id = null): Opportunity
public function save(User $actor, array $input, ?int $id = null, bool $privateOffer = false): Opportunity
{
$access = app(PortalProfileAccess::class);
$profileCreation = $id === null && str_starts_with(request()->path(), 'minhas-oportunidades');
if ($id !== null) {
$existingRecord = Opportunity::withTrashed()->findOrFail($id);
abort_if($existingRecord->isPrivateOfferPreparation() && ! $privateOffer, 403, 'Use a preparação privada da oferta.');
$access->authorize($actor, 'edit', $existingRecord);
if ($existingRecord->owner_user_id !== null) {
abort_unless($access->canEdit($actor, $existingRecord, $input['opportunity_category'] ?? null), 403);
@@ -100,6 +101,9 @@ class OpportunityManagement
'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();
if ($privateOffer && ($id === null || array_key_exists('private_offer', $input))) {
$data['private_offer'] = app(PrivateOfferPreparation::class)->validate($input['private_offer'] ?? []);
}
$data = app(OpportunityMaturity::class)->normalize($data);
if (array_key_exists('real_estate', $data)) {
$data['real_estate'] = app(OpportunityRealEstateDraft::class)->validate($data['real_estate']);
@@ -108,10 +112,11 @@ class OpportunityManagement
$data['canonical'] = app(OpportunityCanonicalContract::class)->draft($data['canonical']);
}
return DB::transaction(function () use ($actor, $data, $id, $profileCreation, $access) {
return DB::transaction(function () use ($actor, $data, $id, $profileCreation, $access, $privateOffer) {
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($existing->isPrivateOfferPreparation() === $privateOffer, 409);
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::PRIVATE_DRAFT_FIELDS])) as $key => $value) {
@@ -124,6 +129,7 @@ class OpportunityManagement
}
$record = $id ? Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail() : new Opportunity;
if ($id) {
abort_unless($record->isPrivateOfferPreparation() === $privateOffer, 409);
$access->authorize($actor, 'edit', $record);
$this->check($record, $data['etag']);
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
@@ -191,12 +197,12 @@ class OpportunityManagement
$record->management_draft = json_encode([...$previous, ...$changes], JSON_THROW_ON_ERROR);
} else {
foreach ($changes as $key => $value) {
if (in_array($key, ['real_estate', 'canonical', 'proactive', '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', 'proactive', 'private_offer', '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']) || array_key_exists('real_estate', $changes) || array_key_exists('canonical', $changes) || array_key_exists('proactive', $changes)) {
if (isset($changes['maturity_catalogue_version']) || array_key_exists('real_estate', $changes) || array_key_exists('canonical', $changes) || array_key_exists('proactive', $changes) || array_key_exists('private_offer', $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::PRIVATE_DRAFT_FIELDS))], JSON_THROW_ON_ERROR);
@@ -204,6 +210,9 @@ class OpportunityManagement
}
if ($record->owner_user_id !== null) {
$context = $record->workflow_context ?? [];
if ($privateOffer) {
$context['private_offer_preparation'] ??= ['version' => 1, 'state' => 'draft'];
}
unset($context['approval']);
$context['content_revision'] = ($context['content_revision'] ?? 0) + 1;
$context['contributors'] = array_values(array_unique([...($context['contributors'] ?? []), $actor->id]));
+2 -1
View File
@@ -24,7 +24,7 @@ class OpportunityProfileWorkflow
/** @return list<string> */
public function actions(User $actor, Opportunity $record): array
{
if ($record->owner_user_id === null || ! $this->access->canView($actor, $record)) {
if ($record->isPrivateOfferPreparation() || $record->owner_user_id === null || ! $this->access->canView($actor, $record)) {
return [];
}
$actions = [];
@@ -520,6 +520,7 @@ class OpportunityProfileWorkflow
private function authorizeAction(User $actor, Opportunity $record, string $action): void
{
abort_if($record->isPrivateOfferPreparation(), 403, 'A oferta está em preparação privada; o circuito editorial não está disponível nesta fase.');
$this->access->authorize($actor, 'view', $record);
$promoter = $this->access->promoterRecordScope($actor, $record)
&& ($record->organization_id !== null || (int) $record->owner_user_id === $actor->id);
+1 -1
View File
@@ -22,7 +22,7 @@ final class OpportunityPromotion
public function allowed(User $actor, Opportunity $record): bool
{
$access = app(PortalProfileAccess::class);
if ($record->trashed() || $record->owner_user_id === null || ! $access->canView($actor, $record)
if ($record->isPrivateOfferPreparation() || $record->trashed() || $record->owner_user_id === null || ! $access->canView($actor, $record)
|| $access->has($actor, 'auditor') || in_array($record->status, ['archived', 'rejected'], true)) {
return false;
}
+3
View File
@@ -241,6 +241,9 @@ class PortalProfileAccess
public function canEdit(User $actor, Opportunity $record, ?string $newType = null): bool
{
if ($record->isPrivateOfferPreparation() && data_get($record->workflow_context, 'private_offer_preparation.state') !== 'draft') {
return false;
}
if ($record->owner_user_id === null) {
return $this->legacyWriteAllowed($actor);
}
+119
View File
@@ -0,0 +1,119 @@
<?php
namespace App\Services;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
/** Phase 1 adapter: the existing opportunity owns identity, versions and audit. */
final class PrivateOfferPreparation
{
/** @return array<string,mixed> */
public function validate(mixed $input, bool $complete = false): array
{
return Validator::make(['private_offer' => $input], [
'private_offer' => 'present|array:price_mode,amount,currency,contact_id',
'private_offer.price_mode' => 'nullable|in:amount,negotiable',
'private_offer.amount' => ['nullable', 'string', ...($complete ? ['required_if:private_offer.price_mode,amount'] : []), 'prohibited_unless:private_offer.price_mode,amount', 'regex:/^\d{1,16}(\.\d{1,2})?$/'],
'private_offer.currency' => ['nullable', ...($complete ? ['required_if:private_offer.price_mode,amount'] : []), 'prohibited_unless:private_offer.price_mode,amount', 'in:MZN,USD'],
'private_offer.contact_id' => 'nullable|uuid',
])->validate()['private_offer'];
}
/** @param array<string,mixed> $input */
public function save(User $actor, array $input, ?int $id = null): Opportunity
{
foreach (['title', 'description'] as $field) {
if (is_string($input[$field] ?? null)) {
$input[$field] = trim($input[$field]);
}
}
$allowed = ['creation_key', 'etag', 'reason', 'title', 'description', 'opportunity_category', 'organization_id', 'private_offer', ...array_keys(InvestmentGeography::FIELDS)];
if (array_diff(array_keys($input), $allowed)) {
throw ValidationException::withMessages(['offer' => 'O pedido contém campos fora da preparação privada.']);
}
Validator::make($input, ['opportunity_category' => ['sometimes', 'required', Rule::in(OpportunityManagement::CATEGORIES)]])->validate();
return DB::transaction(function () use ($actor, $input, $id) {
$record = app(OpportunityManagement::class)->save($actor, $input, $id, true);
$contactId = app(OpportunityManagement::class)->values($record)['private_offer']['contact_id'] ?? null;
if ($contactId && ! app(OpportunityContacts::class)->related($record, $contactId)) {
throw ValidationException::withMessages(['private_offer.contact_id' => 'Seleccione um contacto autorizado do promotor.']);
}
return $record;
});
}
public function record(User $actor, int $id, bool $edit = false): Opportunity
{
$record = Opportunity::findOrFail($id);
abort_unless($record->isPrivateOfferPreparation(), 404);
app(PortalProfileAccess::class)->authorize($actor, $edit ? 'edit' : 'view', $record);
return $record;
}
/** Register private submission only: no editorial task, approval or publication.
* @param array<string,mixed> $input */
public function submit(User $actor, int $id, array $input): Opportunity
{
$data = Validator::make($input, ['etag' => 'required|string|size:64', 'confirm' => 'required|accepted'])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$record = Opportunity::whereKey($id)->lockForUpdate()->firstOrFail();
abort_unless($record->isPrivateOfferPreparation(), 404);
$access = app(PortalProfileAccess::class);
$access->authorize($actor, 'view', $record);
abort_unless($access->promoterRecordScope($actor, $record)
&& $access->canCreate($actor, $record->organization_id, $record->opportunity_category)
&& $access->operational($actor, 'edit', $record->id), 403);
$management = app(OpportunityManagement::class);
abort_unless(hash_equals($management->etag($record), $data['etag']), 409, 'A oferta mudou. Recupere a versão actual antes de submeter.');
if (data_get($record->workflow_context, 'private_offer_preparation.state') === 'submitted') {
return $record;
}
$access->authorize($actor, 'edit', $record);
$values = $management->values($record);
Validator::make($values, ['title' => 'required|string|max:150', 'description' => 'required|string|max:50000',
'opportunity_category' => 'required', 'private_offer.price_mode' => 'required|in:amount,negotiable', 'private_offer.contact_id' => 'required|uuid'])->validate();
$this->validate($values['private_offer'], true);
if (! app(OpportunityContacts::class)->related($record, $values['private_offer']['contact_id'])) {
throw ValidationException::withMessages(['private_offer.contact_id' => 'O contacto já não está disponível neste âmbito.']);
}
// Recheck revoked grants and representation inside the same transaction.
abort_unless($access->canCreate($actor, $record->organization_id, $record->opportunity_category), 403);
$path = app(InvestmentGeography::class)->path($record->primary_territory_id, true);
if ($record->primary_territory_id && $path === []) {
throw ValidationException::withMessages(['province_id' => 'Reconcilie a localização antes de submeter.']);
}
if ($path !== []) {
app(InvestmentGeography::class)->selection(array_combine(array_slice(array_keys(InvestmentGeography::FIELDS), 0, count($path)), array_column($path, 'id')), true);
}
$context = $record->workflow_context;
$context['private_offer_preparation'] = ['version' => 1, 'state' => 'submitted', 'submitted_by' => $actor->id,
'submitted_at' => now()->toIso8601String(), 'submitted_revision' => $record->management_version];
$record->workflow_context = $context;
$record->management_version++;
$record->save();
$access->audit($actor, 'private_offer_submitted', ['record_id' => $record->id, 'version' => $record->management_version, 'public' => false]);
return $record;
});
}
/** @return array<string,mixed> */
public function presentation(User $actor, Opportunity $record): array
{
app(PortalProfileAccess::class)->authorize($actor, 'view', $record);
return ['id' => $record->id, 'reference' => $record->reference, 'values' => app(OpportunityManagement::class)->values($record),
'etag' => app(OpportunityManagement::class)->etag($record), 'state' => data_get($record->workflow_context, 'private_offer_preparation.state'),
'canEdit' => app(PortalProfileAccess::class)->canEdit($actor, $record), 'organization_id' => $record->organization_id,
'territory' => app(InvestmentGeography::class)->path($record->primary_territory_id, true)];
}
}