feat: integrate private offers with existing editorial workflow
This commit is contained in:
@@ -105,7 +105,9 @@ final class PortalEditorialWorkflowController extends Controller
|
||||
}
|
||||
$items = $query->orderByDesc('e.updated_at')->paginate(25, ['r.id', DB::raw("e.payload->'resource'->>'title' AS title"), 'r.document_type', 'r.published', 'e.id as edition_id', 'e.revision_no', 'e.state', 'e.legal_required', 'u.name as responsible'])->withQueryString();
|
||||
$destinations = app(ContentManagement::class)->access($actor);
|
||||
$data = ['items' => $items, 'filters' => $filters, 'notices' => $workflow->notices($actor), 'resourceAccess' => $access->full($actor) || $access->editorial($actor), 'opportunitiesUrl' => $destinations['opportunities']['index'] ?? null, 'opportunityPending' => $workflow->opportunityPending($actor), 'clustersUrl' => $destinations['clusters']['index'] ?? null,
|
||||
$data = ['items' => $items, 'filters' => $filters, 'notices' => $workflow->notices($actor), 'resourceAccess' => $access->full($actor) || $access->editorial($actor), 'opportunitiesUrl' => $destinations['opportunities']['index'] ?? null,
|
||||
'offersUrl' => isset($destinations['opportunities']['index']) && app(PortalProfileAccess::class)->available() ? '/minhas-oportunidades/ofertas' : null,
|
||||
'opportunityPending' => $workflow->opportunityPending($actor), 'clustersUrl' => $destinations['clusters']['index'] ?? null,
|
||||
'portfolioUrl' => $destinations['portfolio']['index'] ?? null, 'portfolioPending' => $workflow->portfolioPending($actor), 'demographyUrl' => $destinations['demography']['index'] ?? null, 'demographyPending' => $workflow->demographyPending($actor),
|
||||
'territorialUrl' => app(TerritorialRegistry::class)->editorialAvailable() && $actor->can('manage-portal') ? '/management/territorial/editorial' : null,
|
||||
'nativePending' => app(PortalEditorialNativeNotices::class)->pending($actor), 'zonesUrl' => app(PortalEditorialNativeNotices::class)->access($actor, 'investment-zones') ? '/management/investment/zones' : null,
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\OpportunityCanonicalContract;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityProfileWorkflow;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\PrivateOfferPreparation;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -15,13 +17,15 @@ final class PrivateOfferPreparationController extends Controller
|
||||
{
|
||||
public function index(Request $request, PortalProfileAccess $access): Response
|
||||
{
|
||||
$filters = $request->validate(['state' => 'nullable|in:draft,submitted,in_review,needs_information,rejected,approved']);
|
||||
$records = $access->scope(Opportunity::query(), $request->user())->whereNotNull('workflow_context->private_offer_preparation')
|
||||
->orderByDesc('id')->paginate(20);
|
||||
->when($filters['state'] ?? null, fn ($q, $state) => $q->where('workflow_context->private_offer_preparation->state', $state))
|
||||
->orderByDesc('id')->paginate(20)->withQueryString();
|
||||
|
||||
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]);
|
||||
'id' => $r->id, 'title' => app(OpportunityManagement::class)->values($r)['title'] ?? null, 'reference' => $r->reference,
|
||||
'state' => $access->state($r),
|
||||
]), 'filters' => $filters, 'canCreate' => count($access->navigation($request->user())['contexts']) > 0]);
|
||||
}
|
||||
|
||||
public function edit(Request $request, PrivateOfferPreparation $service, ?int $id = null): Response|JsonResponse
|
||||
@@ -56,4 +60,15 @@ final class PrivateOfferPreparationController extends Controller
|
||||
return response()->json(['record' => $service->presentation($request->user(), $record),
|
||||
'message' => 'Submissão privada registada. A oferta não foi publicada.']);
|
||||
}
|
||||
|
||||
public function transition(Request $request, PrivateOfferPreparation $service, OpportunityProfileWorkflow $workflow, int $id): JsonResponse
|
||||
{
|
||||
$service->record($request->user(), $id);
|
||||
$data = $request->validate(['etag' => 'required|string|size:64', 'action' => 'required|in:start_review,assign_review,request_correction,reject,approve,request_revision',
|
||||
'assignee_user_id' => 'required_if:action,assign_review|integer|min:1',
|
||||
'reason' => 'required|string|min:20|max:1000', 'correction_items' => 'sometimes|array', 'correction_items.*' => 'string']);
|
||||
$record = $workflow->transition($request->user(), $id, $data);
|
||||
|
||||
return response()->json(['record' => $service->presentation($request->user(), $record), 'message' => 'Decisão privada registada. A oferta não foi publicada.']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\PortalEditorialWorkflow;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/** Existing email transport and operational allowlist; no confidential payload. */
|
||||
final class NotifyPrivateOfferDecision implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public int $tries = 3;
|
||||
|
||||
public int $timeout = 30;
|
||||
|
||||
public function __construct(public string $noticeId) {}
|
||||
|
||||
/** @return list<int> */
|
||||
public function backoff(): array
|
||||
{
|
||||
return [60, 300, 900];
|
||||
}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
if (! config('portal.notifications_enabled')) {
|
||||
return;
|
||||
}
|
||||
$notice = DB::table('portal_editorial_notifications')->where('id', $this->noticeId)->first();
|
||||
$user = $notice ? User::query()->whereKey($notice->user_id)->first() : null;
|
||||
$record = $notice ? Opportunity::query()->whereKey($notice->opportunity_id)->first() : null;
|
||||
if (! $notice || ! $user || ! $record?->isPrivateOfferPreparation()
|
||||
|| ! in_array($user->email, config('portal.notification_recipients', []), true)
|
||||
|| ! app(PortalEditorialWorkflow::class)->visibleNotice($user, $notice)) {
|
||||
return;
|
||||
}
|
||||
$body = 'Existe uma actualização na revisão privada da oferta '.$record->reference.'. Consulte a decisão e a versão na área protegida: '.url('/minhas-oportunidades/ofertas/'.$record->id);
|
||||
Mail::raw($body, fn ($message) => $message->to($user->email)->subject('Actualização da oferta — '.$record->reference));
|
||||
}
|
||||
}
|
||||
@@ -195,6 +195,12 @@ class OpportunityManagement
|
||||
$record->management_closed_once = true;
|
||||
$previous = $record->management_draft ? json_decode($record->management_draft, true) : $record->only(self::FIELDS);
|
||||
$record->management_draft = json_encode([...$previous, ...$changes], JSON_THROW_ON_ERROR);
|
||||
if ($privateOffer) {
|
||||
// All columns of an Offer remain private; keep scope/category and location current.
|
||||
foreach (array_intersect_key($changes, array_flip(self::FIELDS)) as $field => $value) {
|
||||
$record->{$field} = $value;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
foreach ($changes as $key => $value) {
|
||||
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))) {
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -24,9 +25,12 @@ class OpportunityProfileWorkflow
|
||||
/** @return list<string> */
|
||||
public function actions(User $actor, Opportunity $record): array
|
||||
{
|
||||
if ($record->isPrivateOfferPreparation() || $record->owner_user_id === null || ! $this->access->canView($actor, $record)) {
|
||||
if ($record->owner_user_id === null || ! $this->access->canView($actor, $record)) {
|
||||
return [];
|
||||
}
|
||||
if ($record->isPrivateOfferPreparation()) {
|
||||
return $this->offerActions($actor, $record);
|
||||
}
|
||||
$actions = [];
|
||||
$state = $this->access->state($record);
|
||||
if ($this->access->promoterRecordScope($actor, $record)
|
||||
@@ -99,6 +103,42 @@ class OpportunityProfileWorkflow
|
||||
return $actions;
|
||||
}
|
||||
|
||||
/** Existing roles and transition engine, bounded to the private offer contract.
|
||||
* @return list<string> */
|
||||
private function offerActions(User $actor, Opportunity $record): array
|
||||
{
|
||||
if (! app(PortalEditorialWorkflow::class)->available()) {
|
||||
return [];
|
||||
}
|
||||
$state = $this->access->state($record);
|
||||
$actions = [];
|
||||
if ($this->access->promoterRecordScope($actor, $record) && $this->access->operational($actor, 'edit', $record->id)) {
|
||||
if (in_array($state, ['draft', 'needs_information'], true)) {
|
||||
$actions[] = 'submit';
|
||||
}
|
||||
if (in_array($state, ['rejected', 'approved'], true)) {
|
||||
$actions[] = 'request_revision';
|
||||
}
|
||||
}
|
||||
if ($this->access->scoped($actor, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& $this->access->operational($actor, 'validate', $record->id) && ! $this->access->conflict($actor, $record)) {
|
||||
if (in_array($state, ['submitted', 'in_review'], true) && $this->responsibility($actor, $record, 'validation_coordinator')) {
|
||||
$actions[] = 'assign_review';
|
||||
}
|
||||
$assigned = data_get($record->workflow_context, 'assignment.assignee_user_id');
|
||||
if ($assigned === null || (int) $assigned === $actor->id) {
|
||||
if ($state === 'submitted') {
|
||||
$actions[] = 'start_review';
|
||||
}
|
||||
if ($state === 'in_review') {
|
||||
array_push($actions, 'request_correction', 'reject', 'approve');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $actions;
|
||||
}
|
||||
|
||||
public function reauthenticationRequired(User $actor, Opportunity $record): bool
|
||||
{
|
||||
return ! $this->access->mfa($actor)
|
||||
@@ -178,6 +218,7 @@ class OpportunityProfileWorkflow
|
||||
abort_unless(hash_equals($this->management->etag($record), $data['etag']), 409, 'Versão alterada.');
|
||||
$this->authorizeAction($actor, $record, $action);
|
||||
$context = $record->workflow_context ?? [];
|
||||
$offer = $record->isPrivateOfferPreparation();
|
||||
if ($action === 'submit' && app(PortalEditorialWorkflow::class)->available()) {
|
||||
$context['editorial_version_binding'] = 'phase1-exact-v1';
|
||||
$record->workflow_context = $context;
|
||||
@@ -191,7 +232,7 @@ class OpportunityProfileWorkflow
|
||||
'review_gate' => ['submitted', 'in_review', 'information_pending', 'approved'],
|
||||
'publish' => ['approved'], 'suspend' => [$state],
|
||||
'assign_publication' => ['approved'],
|
||||
'request_revision' => ['approved', 'published', 'suspended'],
|
||||
'request_revision' => $offer ? ['approved', 'rejected'] : ['approved', 'published', 'suspended'],
|
||||
'archive' => ['draft', 'submitted', 'in_review', 'information_pending', 'needs_information', 'approved', 'rejected', 'published', 'suspended'],
|
||||
'request_archive' => ['draft', 'submitted', 'in_review', 'information_pending', 'needs_information', 'approved', 'published', 'suspended'],
|
||||
'appeal', 'appeal_uphold', 'appeal_reopen' => ['rejected'],
|
||||
@@ -205,11 +246,35 @@ class OpportunityProfileWorkflow
|
||||
}
|
||||
$next = $state;
|
||||
$snapshot = [];
|
||||
if ($action === 'submit' && $record->opportunity_category === 'land_rights') {
|
||||
if ($offer) {
|
||||
$snapshot = in_array($action, ['request_revision', 'request_correction'], true)
|
||||
? ($context['submission'] ?? []) : app(PrivateOfferPreparation::class)->snapshot($record);
|
||||
// Explicit first review of an immutable phase-1 submission; no writes on read.
|
||||
if (in_array($action, ['start_review', 'assign_review'], true) && empty($context['submission'])) {
|
||||
abort_unless(($context['private_offer_preparation']['version'] ?? null) === 1
|
||||
&& $record->management_version === (int) ($context['private_offer_preparation']['submitted_revision'] ?? -2) + 1, 409, 'Reconcilie a submissão privada anterior.');
|
||||
$snapshot['record_version'] = $context['private_offer_preparation']['submitted_revision'];
|
||||
$context['submission'] = [...$snapshot, 'actor_id' => $context['private_offer_preparation']['submitted_by'], 'at' => $context['private_offer_preparation']['submitted_at']];
|
||||
$context['phase1_binding'] = ['bound_at' => $decision['at'], 'bound_by' => $actor->id, 'hash' => $snapshot['hash'], 'original_reference_fingerprint' => 'not_recorded'];
|
||||
$context['review_cycle'] = 1;
|
||||
$decision['review_cycle'] = 1;
|
||||
$context['phase1_submission'] = $context['private_offer_preparation'];
|
||||
$record->first_submitted_at ??= $context['private_offer_preparation']['submitted_at'];
|
||||
$record->management_closed_once = true;
|
||||
}
|
||||
if ($action !== 'submit') {
|
||||
abort_unless(hash_equals($context['submission']['hash'] ?? '', $snapshot['hash']), 409, 'A oferta ou as referências mudaram; prepare nova revisão antes da decisão.');
|
||||
}
|
||||
$decision['hash'] = $snapshot['hash'];
|
||||
$decision['opportunity_version'] = $record->management_version;
|
||||
$decision['submitted_revision'] = $action === 'submit' ? $snapshot['record_version'] : ($context['submission']['record_version'] ?? $record->management_version);
|
||||
$record->workflow_context = $context;
|
||||
}
|
||||
if (! $offer && $action === 'submit' && $record->opportunity_category === 'land_rights') {
|
||||
// Serialize the existing JSON-backed §27 uniqueness check across records.
|
||||
DB::select('SELECT pg_advisory_xact_lock(111026,270000)');
|
||||
}
|
||||
if (in_array($action, ['submit', 'review_gate', 'pending_opinion', 'respond_opinion', 'approve', 'publish'], true)) {
|
||||
if (! $offer && in_array($action, ['submit', 'review_gate', 'pending_opinion', 'respond_opinion', 'approve', 'publish'], true)) {
|
||||
$blockers = $this->contract->deliveryBlockers($this->management->values($record)['canonical'] ?? []);
|
||||
try {
|
||||
$snapshot = $this->contract->validateSubmission($record);
|
||||
@@ -228,6 +293,12 @@ class OpportunityProfileWorkflow
|
||||
}
|
||||
}
|
||||
if ($action === 'submit') {
|
||||
if ($offer && isset($context['submission'])) {
|
||||
$context['submission_history'][] = ['submission' => $context['submission'], 'approval' => $context['approval'] ?? null, 'rejection' => $context['rejection'] ?? null];
|
||||
}
|
||||
if ($offer) {
|
||||
unset($context['rejection'], $context['correction_items']);
|
||||
}
|
||||
// New review attempt, even when the canonical content is unchanged.
|
||||
// Historical decisions/tasks and the content revision keep their IDs.
|
||||
$context['review_cycle'] = max((int) ($context['review_cycle'] ?? 0), $this->submissionCount($context)) + 1;
|
||||
@@ -239,7 +310,7 @@ class OpportunityProfileWorkflow
|
||||
}
|
||||
}
|
||||
$baseline = $context['review_baseline'] ?? $context['submission'] ?? [];
|
||||
$materiality = app(OpportunityReviewMateriality::class)->reconcile($baseline, $snapshot, $context['reviews'] ?? [], $this->contract->gates($record), ! empty($context['force_review']), $strictEditorial);
|
||||
$materiality = app(OpportunityReviewMateriality::class)->reconcile($baseline, $snapshot, $context['reviews'] ?? [], $offer ? [] : $this->contract->gates($record), ! empty($context['force_review']), $strictEditorial);
|
||||
$context['materiality'] = array_diff_key($materiality, ['reviews' => true]);
|
||||
$context['reviews'] = $materiality['reviews'];
|
||||
app(OpportunityReviewConditions::class)->reconcile($context, $snapshot, $materiality['reopened']);
|
||||
@@ -270,6 +341,11 @@ class OpportunityProfileWorkflow
|
||||
}
|
||||
$context['review_task_id'] ??= $this->tasks->ensure($record, 'opportunity_review', 'Validação da oportunidade '.$record->reference);
|
||||
$this->tasks->assign($record, $context['review_task_id'], $subject);
|
||||
if ($offer) {
|
||||
$decision['previous_assignee_user_id'] = $context['assignment']['assignee_user_id'] ?? null;
|
||||
$decision['assignee_user_id'] = $subject->id;
|
||||
$context['assignment_history'][] = $decision;
|
||||
}
|
||||
$context['assignment'] = [...$decision, 'assignee_user_id' => $subject->id];
|
||||
$next = 'in_review';
|
||||
} elseif ($action === 'review_gate') {
|
||||
@@ -292,7 +368,7 @@ class OpportunityProfileWorkflow
|
||||
app(OpportunityReviewConditions::class)->authorize($context, $snapshot, 'approve');
|
||||
abort_if(count(array_filter($context['opinions'] ?? [], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['status'] ?? '') === 'pending')) > 0, 422, 'Parecer da versão atual ainda pendente.');
|
||||
abort_if(count(array_filter($context['opinions'] ?? [], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['response']['decision'] ?? '') === 'rejected')) > 0, 422, 'Parecer desfavorável exige correção e nova versão.');
|
||||
foreach ($this->contract->gates($record) as $gate) {
|
||||
foreach ($offer ? [] : $this->contract->gates($record) as $gate) {
|
||||
$review = $context['reviews'][$gate] ?? [];
|
||||
abort_unless(($review['decision'] ?? null) === 'approved' && (($review['hash'] ?? '') === $snapshot['hash'] || ($review['accepted_submission_hash'] ?? '') === $snapshot['hash']), 422, 'Gate '.$gate.' pendente, rejeitado ou de outra versão.');
|
||||
abort_unless(app(OpportunityReviewMateriality::class)->matches($snapshot, $gate, $review, $strictEditorial), 409, 'Âmbito ou versão da revisão alterado.');
|
||||
@@ -304,7 +380,9 @@ class OpportunityProfileWorkflow
|
||||
$context['approval'] = [...$decision, 'hash' => $snapshot['hash'], 'gates' => $context['reviews'] ?? []];
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$record->workflow_context = $context;
|
||||
$context['publication_task_id'] = $this->tasks->ensure($record, 'opportunity_publication', 'Preparação editorial '.$record->reference);
|
||||
if (! $offer) {
|
||||
$context['publication_task_id'] = $this->tasks->ensure($record, 'opportunity_publication', 'Preparação editorial '.$record->reference);
|
||||
}
|
||||
$next = 'approved';
|
||||
} elseif ($action === 'assign_publication') {
|
||||
$subject = User::whereKey($data['assignee_user_id'] ?? 0)->firstOrFail();
|
||||
@@ -414,6 +492,9 @@ class OpportunityProfileWorkflow
|
||||
$next = count(array_filter($context['opinions'], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['status'] ?? '') === 'pending')) > 0 ? 'information_pending' : 'in_review';
|
||||
} elseif ($action === 'request_correction') {
|
||||
abort_unless($data['correction_items'] ?? [], 422, 'Indique campos e documentos a corrigir.');
|
||||
if ($offer) {
|
||||
abort_if(array_diff($data['correction_items'], ['title', 'description', 'opportunity_category', 'private_offer', 'contact', 'location']) !== [], 422, 'Seleccione campos desta oferta.');
|
||||
}
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$context['correction_items'] = $data['correction_items'];
|
||||
$context['correction_cycles'] = ($context['correction_cycles'] ?? 0) + 1;
|
||||
@@ -423,7 +504,7 @@ class OpportunityProfileWorkflow
|
||||
} elseif ($action === 'request_revision' || $action === 'appeal_reopen') {
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$this->tasks->complete($context['publication_task_id'] ?? null, $data['reason']);
|
||||
$context['decision_history'][] = ['approval' => $context['approval'] ?? null, 'reviews' => $context['reviews'] ?? null, 'submission' => $context['submission'] ?? null];
|
||||
$context['decision_history'][] = ['approval' => $context['approval'] ?? null, 'reviews' => $context['reviews'] ?? null, 'submission' => $context['submission'] ?? null, ...($offer ? ['rejection' => $context['rejection'] ?? null] : [])];
|
||||
$context['review_baseline'] = $context['submission'] ?? [];
|
||||
$context['force_review'] = $action === 'appeal_reopen' || $state === 'suspended';
|
||||
unset($context['approval']);
|
||||
@@ -476,7 +557,14 @@ class OpportunityProfileWorkflow
|
||||
$context['working_state'] = $next;
|
||||
$context['last_decision'] = $decision;
|
||||
$context['events'][] = [...$decision, 'from' => $state, 'to' => $next];
|
||||
if ($record->status !== 'published' || in_array($action, ['suspend', 'archive'], true)) {
|
||||
if ($offer) {
|
||||
$context['private_offer_preparation'] = [...$context['private_offer_preparation'], 'version' => 2, 'state' => $next];
|
||||
if ($action === 'submit') {
|
||||
$context['private_offer_preparation'] = [...$context['private_offer_preparation'], 'submitted_by' => $actor->id,
|
||||
'submitted_at' => $decision['at'], 'submitted_revision' => $snapshot['record_version']];
|
||||
}
|
||||
}
|
||||
if (! $offer && ($record->status !== 'published' || in_array($action, ['suspend', 'archive'], true))) {
|
||||
$record->status = $next;
|
||||
}
|
||||
$record->management_version++;
|
||||
@@ -484,7 +572,12 @@ class OpportunityProfileWorkflow
|
||||
$record->save();
|
||||
app(PortalEditorialWorkflow::class)->notifyOpportunity($actor, $record, $action);
|
||||
$this->access->audit($actor, 'workflow_'.$action, ['record_id' => $record->id, 'before' => $before,
|
||||
'after' => ['status' => $next, 'publication_status' => $record->status, 'version' => $record->management_version], 'reason' => $data['reason']]);
|
||||
'after' => ['status' => $next, 'publication_status' => $record->status, 'version' => $record->management_version], 'reason' => $data['reason'],
|
||||
...($offer ? ['decision' => $decision, 'submission_hash' => $context['submission']['hash'] ?? null,
|
||||
'snapshot' => Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR))] : [])]);
|
||||
if ($offer && $action === 'submit') {
|
||||
$this->access->audit($actor, 'private_offer_submitted', ['record_id' => $record->id, 'version' => $record->management_version, 'public' => false]);
|
||||
}
|
||||
|
||||
return $record;
|
||||
});
|
||||
@@ -520,7 +613,9 @@ 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.');
|
||||
if ($record->isPrivateOfferPreparation()) {
|
||||
abort_unless(in_array($action, $this->actions($actor, $record), true), 403, 'Operação editorial não autorizada para esta oferta privada.');
|
||||
}
|
||||
$this->access->authorize($actor, 'view', $record);
|
||||
$promoter = $this->access->promoterRecordScope($actor, $record)
|
||||
&& ($record->organization_id !== null || (int) $record->owner_user_id === $actor->id);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Jobs\NotifyPrivateOfferDecision;
|
||||
use App\Models\DevelopmentCorridor;
|
||||
use App\Models\EconomicCluster;
|
||||
use App\Models\InvestmentDossier;
|
||||
@@ -237,12 +238,50 @@ final class PortalEditorialWorkflow
|
||||
}
|
||||
$context = $record->workflow_context ?? [];
|
||||
$recipients = array_unique(array_filter([$record->owner_user_id, $context['assignment']['assignee_user_id'] ?? null, $context['publication_assignment']['assignee_user_id'] ?? null]));
|
||||
$profiles = app(PortalProfileAccess::class);
|
||||
if ($record->isPrivateOfferPreparation() && $action === 'assign_review' && isset($context['last_decision']['previous_assignee_user_id'])) {
|
||||
$recipients[] = $context['last_decision']['previous_assignee_user_id'];
|
||||
}
|
||||
if ($record->isPrivateOfferPreparation() && $action === 'submit') {
|
||||
$coordinators = DB::table('portal_role_assignments')->where('role', 'validator')->whereNull('revoked_at')
|
||||
->where('starts_at', '<=', now())->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
|
||||
->whereJsonContains('responsibilities', 'validation_coordinator')->pluck('user_id');
|
||||
foreach (User::whereIn('id', $coordinators)->get() as $candidate) {
|
||||
if ($profiles->scoped($candidate, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& $profiles->operational($candidate, 'validate', $record->id) && ! $profiles->conflict($candidate, $record)) {
|
||||
$recipients[] = $candidate->id;
|
||||
}
|
||||
}
|
||||
}
|
||||
$recipients = array_unique($recipients);
|
||||
foreach ($recipients as $recipient) {
|
||||
if ((int) $recipient === $actor->id) {
|
||||
continue;
|
||||
}
|
||||
DB::table('portal_editorial_notifications')->insertOrIgnore(['user_id' => $recipient, 'edition_id' => null, 'opportunity_id' => $record->id, 'opportunity_version' => $record->management_version,
|
||||
if ($record->isPrivateOfferPreparation()) {
|
||||
$candidate = User::query()->whereKey($recipient)->first();
|
||||
if (! $candidate || ! $profiles->canView($candidate, $record) || ! $this->canEnter($candidate)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
$inserted = DB::table('portal_editorial_notifications')->insertOrIgnore(['user_id' => $recipient, 'edition_id' => null, 'opportunity_id' => $record->id, 'opportunity_version' => $record->management_version,
|
||||
'content_hash' => $context['submission']['hash'] ?? $context['approval']['hash'] ?? null, 'action' => $action, 'created_at' => now()]);
|
||||
if ($inserted && $record->isPrivateOfferPreparation()) {
|
||||
$notice = DB::table('portal_editorial_notifications')->where('user_id', $recipient)->where('opportunity_id', $record->id)
|
||||
->where('opportunity_version', $record->management_version)->where('action', $action)->first();
|
||||
if ($notice) {
|
||||
DB::afterCommit(function () use ($notice, $actor, $record): void {
|
||||
try {
|
||||
NotifyPrivateOfferDecision::dispatch($notice->id);
|
||||
} catch (\Throwable $error) {
|
||||
// A committed decision must not become an uncertain HTTP failure.
|
||||
app(PortalProfileAccess::class)->audit($actor, 'offer_notification_delivery_failed', [
|
||||
'record_id' => $record->id, 'notice_id' => $notice->id, 'error_type' => get_class($error),
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,6 +373,9 @@ final class PortalEditorialWorkflow
|
||||
}
|
||||
$edition = $notice->edition_id ? DB::table('portal_editorial_editions')->where('id', $notice->edition_id)->first() : null;
|
||||
$subjectHref = ($edition->subject_kind ?? null) ? '/management/editorial/subjects/'.$edition->subject_kind.'/'.$edition->subject_key.'?edition='.$edition->id : null;
|
||||
if ($notice->opportunity_id !== null && Opportunity::query()->whereKey($notice->opportunity_id)->first()?->isPrivateOfferPreparation()) {
|
||||
$subjectHref = '/minhas-oportunidades/ofertas/'.$notice->opportunity_id;
|
||||
}
|
||||
$result[] = ['id' => $notice->id, 'action' => $notice->action, 'read_at' => $notice->read_at,
|
||||
'href' => $subjectHref ?? ($notice->opportunity_id !== null ? '/minhas-oportunidades/'.$notice->opportunity_id : (($edition->demographic_import_id ?? null) ? '/management/editorial/demography/'.$edition->demographic_import_id : (($edition->dossier_id ?? null) ? '/management/editorial/portfolio/'.$edition->dossier_id : '/management/editorial/resources/'.$edition->resource_id)).'?edition='.$notice->edition_id), 'reference' => $notice->opportunity_id !== null ? 'Revisão '.$notice->opportunity_version : 'Edição '.$edition->revision_no];
|
||||
if (count($result) === 50) {
|
||||
|
||||
@@ -241,7 +241,7 @@ 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') {
|
||||
if ($record->isPrivateOfferPreparation() && ! in_array($this->state($record), ['draft', 'needs_information'], true)) {
|
||||
return false;
|
||||
}
|
||||
if ($record->owner_user_id === null) {
|
||||
@@ -267,6 +267,10 @@ class PortalProfileAccess
|
||||
|
||||
public function state(Opportunity $record): string
|
||||
{
|
||||
if ($record->isPrivateOfferPreparation()) {
|
||||
return data_get($record->workflow_context, 'private_offer_preparation.state', 'draft');
|
||||
}
|
||||
|
||||
return $record->workflow_context['working_state'] ?? $record->status;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Phase 1 adapter: the existing opportunity owns identity, versions and audit. */
|
||||
/** Private commercial adapter: the existing opportunity owns identity, workflow and audit. */
|
||||
final class PrivateOfferPreparation
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
@@ -58,17 +58,31 @@ final class PrivateOfferPreparation
|
||||
return $record;
|
||||
}
|
||||
|
||||
/** Register private submission only: no editorial task, approval or publication.
|
||||
/** Register submission through the existing editorial engine when available.
|
||||
* @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();
|
||||
if (app(PortalEditorialWorkflow::class)->available()) {
|
||||
$record = $this->record($actor, $id);
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if ($access->state($record) === 'submitted') {
|
||||
abort_unless($access->promoterRecordScope($actor, $record) && $access->canCreate($actor, $record->organization_id, $record->opportunity_category)
|
||||
&& $access->operational($actor, 'edit', $id), 403);
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $data['etag']), 409);
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
return app(OpportunityProfileWorkflow::class)->transition($actor, $id, [...$data, 'action' => 'submit', 'reason' => 'Submissão privada da oferta conferida pelo promotor.']);
|
||||
}
|
||||
|
||||
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_if(($record->workflow_context['private_offer_preparation']['version'] ?? 1) >= 2, 503, 'O circuito editorial está indisponível. A versão e o histórico foram preservados; não é permitida a retoma pelo percurso anterior.');
|
||||
abort_unless($access->promoterRecordScope($actor, $record)
|
||||
&& $access->canCreate($actor, $record->organization_id, $record->opportunity_category)
|
||||
&& $access->operational($actor, 'edit', $record->id), 403);
|
||||
@@ -106,14 +120,93 @@ final class PrivateOfferPreparation
|
||||
});
|
||||
}
|
||||
|
||||
/** Adapter of the five common fields; never relaxes the full canonical contract.
|
||||
* @return array<string,mixed> */
|
||||
public function snapshot(Opportunity $record): array
|
||||
{
|
||||
$values = app(OpportunityManagement::class)->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();
|
||||
$offer = $this->validate($values['private_offer'], true);
|
||||
if (! app(OpportunityContacts::class)->related($record, $offer['contact_id'])) {
|
||||
throw ValidationException::withMessages(['private_offer.contact_id' => 'O contacto já não está disponível neste âmbito.']);
|
||||
}
|
||||
$contact = DB::table('contacts')->where('id', $offer['contact_id'])->first();
|
||||
$path = app(InvestmentGeography::class)->path($values['primary_territory_id'] ?? null, true);
|
||||
if (! empty($values['primary_territory_id']) && $path === []) {
|
||||
throw ValidationException::withMessages(['province_id' => 'Reconcilie a localização antes da decisão.']);
|
||||
}
|
||||
if ($path !== []) {
|
||||
app(InvestmentGeography::class)->selection(array_combine(array_slice(array_keys(InvestmentGeography::FIELDS), 0, count($path)), array_column($path, 'id')), true);
|
||||
}
|
||||
$payload = ['title' => $values['title'], 'description' => $values['description'], 'opportunity_category' => $values['opportunity_category'],
|
||||
'owner_user_id' => $record->owner_user_id, 'organization_id' => $record->organization_id, 'private_offer' => $offer,
|
||||
'contact_fingerprint' => hash('sha256', json_encode($contact, JSON_THROW_ON_ERROR)), 'territory' => $path];
|
||||
$normalize = function (mixed $value) use (&$normalize): mixed {
|
||||
if (is_object($value)) {
|
||||
$value = get_object_vars($value);
|
||||
}
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
if (! array_is_list($value)) {
|
||||
ksort($value);
|
||||
}
|
||||
|
||||
return array_map($normalize, $value);
|
||||
};
|
||||
$payload = $normalize($payload);
|
||||
|
||||
return ['payload' => $payload, 'hash' => hash('sha256', json_encode(['contract' => 'private-offer-editorial-v2', 'payload' => $payload], JSON_THROW_ON_ERROR)),
|
||||
'record_version' => $record->management_version, 'contract_version' => 'private-offer-editorial-v2', 'resources' => ['documents' => [], 'images' => [], 'locations' => []]];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function presentation(User $actor, Opportunity $record): array
|
||||
{
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'view', $record);
|
||||
$values = app(OpportunityManagement::class)->values($record);
|
||||
$fresh = null;
|
||||
$contactId = $values['private_offer']['contact_id'] ?? null;
|
||||
$contactLabel = $contactId && app(OpportunityContacts::class)->related($record, $contactId)
|
||||
? DB::table('contacts')->where('id', $contactId)->value('full_name') : null;
|
||||
if (isset($record->workflow_context['approval'])) {
|
||||
try {
|
||||
$fresh = hash_equals($record->workflow_context['approval']['hash'], $this->snapshot($record)['hash']);
|
||||
} catch (ValidationException $error) {
|
||||
$fresh = false;
|
||||
}
|
||||
}
|
||||
$history = $record->workflow_context['events'] ?? [];
|
||||
$names = User::whereIn('id', array_filter([...array_column($history, 'actor_id'), ...array_column($history, 'assignee_user_id')]))->pluck('name', 'id');
|
||||
$history = array_map(fn ($event) => [...$event, 'actor_name' => $names[$event['actor_id']] ?? 'Interveniente indisponível',
|
||||
'assignee_name' => isset($event['assignee_user_id']) ? ($names[$event['assignee_user_id']] ?? 'Interveniente indisponível') : null], $history);
|
||||
$versions = [...($record->workflow_context['decision_history'] ?? []), ...($record->workflow_context['submission_history'] ?? [])];
|
||||
if (isset($record->workflow_context['submission'])) {
|
||||
$versions[] = ['submission' => $record->workflow_context['submission'], 'approval' => $record->workflow_context['approval'] ?? null,
|
||||
'rejection' => $record->workflow_context['rejection'] ?? null];
|
||||
}
|
||||
$uniqueVersions = [];
|
||||
foreach ($versions as $version) {
|
||||
if (! isset($version['submission']['payload']['private_offer'])) {
|
||||
continue;
|
||||
}
|
||||
$key = $version['submission']['record_version'].':'.$version['submission']['hash'].':'.($version['submission']['review_cycle'] ?? 0);
|
||||
$previous = $uniqueVersions[$key] ?? [];
|
||||
$uniqueVersions[$key] = ['submission' => $version['submission'], 'approval' => $version['approval'] ?? $previous['approval'] ?? null,
|
||||
'rejection' => $version['rejection'] ?? $previous['rejection'] ?? null];
|
||||
}
|
||||
$workflow = app(OpportunityProfileWorkflow::class);
|
||||
$actions = $workflow->actions($actor, $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'),
|
||||
return ['id' => $record->id, 'reference' => $record->reference, 'values' => $values,
|
||||
'etag' => app(OpportunityManagement::class)->etag($record), 'state' => app(PortalProfileAccess::class)->state($record),
|
||||
'canEdit' => app(PortalProfileAccess::class)->canEdit($actor, $record), 'organization_id' => $record->organization_id,
|
||||
'territory' => app(InvestmentGeography::class)->path($record->primary_territory_id, true)];
|
||||
'actions' => $actions,
|
||||
'reviewers' => in_array('assign_review', $actions, true) ? $workflow->participants($actor, $record)['validators'] : [],
|
||||
'reauthenticationRequired' => app(OpportunityProfileWorkflow::class)->reauthenticationRequired($actor, $record),
|
||||
'history' => $history, 'submittedVersions' => array_values($uniqueVersions), 'correctionItems' => $record->workflow_context['correction_items'] ?? [],
|
||||
'approval' => $record->workflow_context['approval'] ?? null, 'approvalFresh' => $fresh, 'contactLabel' => $contactLabel, 'tasks' => app(OpportunityWorkflowTasks::class)->listing($record),
|
||||
'territory' => app(InvestmentGeography::class)->path($values['primary_territory_id'] ?? null, true)];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user