feat(offers): complete phase five operational controls in QA
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\OfferAvailability;
|
||||
use App\Services\PrivateOfferOperations;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
final class ExpirePrivateOffers extends Command
|
||||
{
|
||||
protected $signature = 'investmoz:offers-expire {--confirm : Persist the already effective expiry}';
|
||||
|
||||
protected $description = 'Conferir expiração de Ofertas sem publicar conteúdos ou alterar o NDA';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$count = 0;
|
||||
Opportunity::query()->whereNotNull('workflow_context->private_offer_preparation')->orderBy('id')->chunkById(100, function ($records) use (&$count) {
|
||||
foreach ($records as $record) {
|
||||
if (app(OfferAvailability::class)->record($record)['state'] !== 'expired') {
|
||||
continue;
|
||||
}
|
||||
if ($this->option('confirm')) {
|
||||
if (app(PrivateOfferOperations::class)->expire($record->id)) {
|
||||
$count++;
|
||||
}
|
||||
} else {
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
});
|
||||
$this->info(($this->option('confirm') ? 'Expirações registadas: ' : 'Expiradas, sem escrita: ').$count);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use App\Services\OpportunityManagement;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
final class OfferPublicCatalogueController extends Controller
|
||||
@@ -17,30 +17,30 @@ final class OfferPublicCatalogueController extends Controller
|
||||
{
|
||||
$filters = $catalogue->filters($request);
|
||||
|
||||
return Inertia::render('offers/catalogue', [...$catalogue->page($request, $filters), 'filters' => $filters,
|
||||
return $this->uncached(Inertia::render('offers/catalogue', [...$catalogue->page($request, $filters), 'filters' => $filters,
|
||||
'mapData' => in_array($filters['view'] ?? '', ['map', 'combined'], true) ? $catalogue->map($filters) : null,
|
||||
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
|
||||
'references' => ['categories' => OpportunityManagement::CATEGORIES, 'options' => [], 'clusters' => [], 'corridors' => [], 'projects' => [], 'locations' => [], 'sectors' => []]]);
|
||||
'references' => ['categories' => OpportunityManagement::CATEGORIES, 'options' => [], 'clusters' => [], 'corridors' => [], 'projects' => [], 'locations' => [], 'sectors' => []]])->toResponse($request));
|
||||
}
|
||||
|
||||
public function show(int $id, OfferPublicCatalogue $catalogue): Response
|
||||
public function show(Request $request, int $id, OfferPublicCatalogue $catalogue): Response
|
||||
{
|
||||
return Inertia::render('offers/public-detail', ['offer' => $catalogue->detail($id)]);
|
||||
return $this->uncached(Inertia::render('offers/public-detail', ['offer' => $catalogue->detail($id)])->toResponse($request));
|
||||
}
|
||||
|
||||
public function search(Request $request, OfferPublicCatalogue $catalogue): JsonResponse
|
||||
{
|
||||
return response()->json($catalogue->page($request, $catalogue->filters($request)));
|
||||
return response()->json($catalogue->page($request, $catalogue->filters($request)))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function detail(int $id, OfferPublicCatalogue $catalogue): JsonResponse
|
||||
{
|
||||
return response()->json(['data' => $catalogue->detail($id)]);
|
||||
return response()->json(['data' => $catalogue->detail($id)])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function map(Request $request, OfferPublicCatalogue $catalogue): JsonResponse
|
||||
{
|
||||
return response()->json($catalogue->map($catalogue->filters($request)));
|
||||
return response()->json($catalogue->map($catalogue->filters($request)))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function export(Request $request, OfferPublicCatalogue $catalogue): StreamedResponse
|
||||
@@ -60,6 +60,13 @@ final class OfferPublicCatalogueController extends Controller
|
||||
fputcsv($stream, array_map(fn ($value) => preg_match('/^[\s]*[=+@-]/u', (string) $value) ? "'".$value : $value, $fields), ';', '"', '');
|
||||
}
|
||||
fclose($stream);
|
||||
}, 'ofertas.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'X-Export-Limit' => '1000', 'X-Results-Truncated' => $result['truncated'] ? 'true' : 'false']);
|
||||
}, 'ofertas.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store', 'X-Export-Limit' => '1000', 'X-Results-Truncated' => $result['truncated'] ? 'true' : 'false']);
|
||||
}
|
||||
|
||||
private function uncached(Response $response): Response
|
||||
{
|
||||
$response->headers->set('Cache-Control', 'private, no-store');
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +107,7 @@ final class PortalEditorialWorkflowController extends Controller
|
||||
$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,
|
||||
'offersUrl' => isset($destinations['opportunities']['index']) && app(PortalProfileAccess::class)->available() ? '/minhas-oportunidades/ofertas' : null,
|
||||
'offerOperationsUrl' => ! app(PortalProfileAccess::class)->has($actor, 'auditor') && (app(PortalProfileAccess::class)->has($actor, 'validator') || app(PortalProfileAccess::class)->has($actor, 'publisher')) ? '/minhas-oportunidades/ofertas?operational=1' : 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,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\PrivateOfferOperations;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class PrivateOfferOperationsController extends Controller
|
||||
{
|
||||
public function show(Request $request, int $id, PrivateOfferOperations $operations): Response
|
||||
{
|
||||
return response()->json($operations->presentation($request->user(), $id));
|
||||
}
|
||||
|
||||
public function owner(Request $request, int $id, PrivateOfferOperations $operations): Response
|
||||
{
|
||||
$operations->ownerAction($request->user(), $id, $request->all());
|
||||
|
||||
return response()->json($operations->presentation($request->user(), $id));
|
||||
}
|
||||
|
||||
public function reportForm(Request $request, int $id, PrivateOfferOperations $operations): Response
|
||||
{
|
||||
$record = Opportunity::findOrFail($id);
|
||||
abort_unless($record->isPrivateOfferPreparation() && $operations->canReport($request->user(), $record), 404);
|
||||
|
||||
return Inertia::render('offers/report', ['offerId' => $id])->toResponse($request);
|
||||
}
|
||||
|
||||
public function report(Request $request, int $id, PrivateOfferOperations $operations): Response
|
||||
{
|
||||
return response()->json($operations->report($request->user(), $id, $request->all()), 201);
|
||||
}
|
||||
|
||||
public function handleReport(Request $request, int $id, string $reportId, PrivateOfferOperations $operations): Response
|
||||
{
|
||||
$operations->handleReport($request->user(), $id, $reportId, $request->all());
|
||||
|
||||
return response()->json($operations->presentation($request->user(), $id));
|
||||
}
|
||||
|
||||
public function highlight(Request $request, int $id, PrivateOfferOperations $operations): Response
|
||||
{
|
||||
$operations->highlight($request->user(), $id, $request->all());
|
||||
|
||||
return response()->json($operations->presentation($request->user(), $id));
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,14 @@
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\OfferAvailability;
|
||||
use App\Services\OpportunityCanonicalContract;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityProfileWorkflow;
|
||||
use App\Services\OpportunityResources;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\PrivateOfferConfidentiality;
|
||||
use App\Services\PrivateOfferOperations;
|
||||
use App\Services\PrivateOfferPreparation;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -86,14 +88,20 @@ 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')
|
||||
$filters = $request->validate(['state' => 'nullable|in:draft,submitted,in_review,needs_information,rejected,approved', 'operational' => 'nullable|boolean', 'pending_reports' => 'nullable|boolean']);
|
||||
$query = ($filters['operational'] ?? false) ? app(PrivateOfferOperations::class)->staffQuery($request->user()) : $access->scope(Opportunity::query(), $request->user());
|
||||
if ($filters['pending_reports'] ?? false) {
|
||||
$query = app(PrivateOfferOperations::class)->staffQuery($request->user());
|
||||
$query->whereRaw("jsonb_path_exists(COALESCE(workflow_context->'offer_reports','{}'::jsonb), '$.* ? (@.status == \"open\" || @.status == \"in_review\")')");
|
||||
}
|
||||
$records = $query->whereNotNull('workflow_context->private_offer_preparation')
|
||||
->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' => app(OpportunityManagement::class)->values($r)['title'] ?? null, 'reference' => $r->reference,
|
||||
'state' => $access->state($r),
|
||||
'availability' => app(OfferAvailability::class)->record($r)['state'],
|
||||
]), 'filters' => $filters, 'canCreate' => count($access->navigation($request->user())['contexts']) > 0]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/** Read-time exclusion never depends on the scheduler or the NDA. */
|
||||
final class OfferAvailability
|
||||
{
|
||||
/** @return array{state:string,expires_at:?string,policy_pending:bool} */
|
||||
public function view(mixed $operation, mixed $publication): array
|
||||
{
|
||||
// Legacy public snapshots without an editorial hash retain their first frozen policy.
|
||||
$key = is_array($publication) ? ($publication['editorial_hash'] ?? '') : null;
|
||||
$key ??= is_array($operation) ? ($operation['last_approval_hash'] ?? '') : '';
|
||||
if (! is_string($key)) {
|
||||
return ['state' => 'unavailable', 'expires_at' => null, 'policy_pending' => true];
|
||||
}
|
||||
$policy = is_array($operation) ? ($operation['validity_policies'][$key] ?? $operation['validity'] ?? null) : null;
|
||||
$pending = ! is_array($policy) || ($policy['days'] ?? null) === null;
|
||||
$result = ['state' => 'available', 'expires_at' => null, 'policy_pending' => $pending];
|
||||
if ($operation !== null && ! is_array($operation)) {
|
||||
return [...$result, 'state' => 'unavailable'];
|
||||
}
|
||||
$state = $operation['status'] ?? 'available';
|
||||
if (! is_int($operation['cycle'] ?? 0) || ($operation['cycle'] ?? 0) < 0) {
|
||||
return [...$result, 'state' => 'unavailable'];
|
||||
}
|
||||
if (! in_array($state, ['available', 'withdrawn', 'expired', 'revalidation'], true)) {
|
||||
return [...$result, 'state' => 'unavailable'];
|
||||
}
|
||||
if ($state !== 'available') {
|
||||
return [...$result, 'state' => $state];
|
||||
}
|
||||
$days = $policy['days'] ?? null;
|
||||
if (($operation['cycle'] ?? 0) > 0 && ($publication['offer_cycle'] ?? null) !== $operation['cycle']) {
|
||||
return $result;
|
||||
}
|
||||
if ($days === null || ! is_array($publication) || ($publication['publication']['state'] ?? null) !== 'published') {
|
||||
return $result;
|
||||
}
|
||||
if (! is_int($days) || $days < 1 || $days > 36500) {
|
||||
return [...$result, 'state' => 'unavailable'];
|
||||
}
|
||||
try {
|
||||
$at = $publication['publication']['at'] ?? null;
|
||||
if (! is_string($at) || ! preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/D', $at)) {
|
||||
return [...$result, 'state' => 'unavailable'];
|
||||
}
|
||||
$start = CarbonImmutable::parse($at);
|
||||
$end = $start->addDays($days)->utc();
|
||||
} catch (\Throwable) {
|
||||
return [...$result, 'state' => 'unavailable'];
|
||||
}
|
||||
|
||||
return [...$result, 'expires_at' => $end->toIso8601String(), 'state' => $end->lte(CarbonImmutable::now()) ? 'expired' : 'available'];
|
||||
}
|
||||
|
||||
/** @return array{state:string,expires_at:?string,policy_pending:bool} */
|
||||
public function record(Opportunity $record): array
|
||||
{
|
||||
return $this->view($record->workflow_context['offer_operation'] ?? null, $record->workflow_context['offer_publication'] ?? null);
|
||||
}
|
||||
|
||||
public function publicAllowed(mixed $operation, mixed $publication): bool
|
||||
{
|
||||
if ($this->view($operation, $publication)['state'] !== 'available') {
|
||||
return false;
|
||||
}
|
||||
$cycle = $operation['cycle'] ?? 0;
|
||||
if (! is_int($cycle) || $cycle < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A new validation must never resurrect the previous public snapshot.
|
||||
return $cycle === 0 || (is_array($publication) && ($publication['offer_cycle'] ?? null) === $cycle
|
||||
&& is_string($operation['activated_hash'] ?? null) && ($publication['editorial_hash'] ?? null) === $operation['activated_hash']);
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,7 @@ final class OfferPublicCatalogue
|
||||
return ['records' => [], 'truncated' => false];
|
||||
}
|
||||
$rows = Opportunity::query()->whereNotNull('workflow_context->private_offer_preparation')->whereNotNull('workflow_context->offer_publication')
|
||||
->orderBy('id')->limit(1001)->get(['id', DB::raw("workflow_context->'offer_publication' AS public_snapshot")]);
|
||||
->orderBy('id')->limit(1001)->get(['id', DB::raw("workflow_context->'offer_publication' AS public_snapshot"), DB::raw("workflow_context->'offer_operation' AS operation_state")]);
|
||||
$records = [];
|
||||
foreach ($rows->take(1000) as $row) {
|
||||
if (! is_string($row->getAttribute('public_snapshot'))) {
|
||||
@@ -128,13 +128,21 @@ final class OfferPublicCatalogue
|
||||
}
|
||||
try {
|
||||
$publication = json_decode($row->getAttribute('public_snapshot'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$operation = json_decode($row->getAttribute('operation_state') ?? 'null', true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $error) {
|
||||
continue;
|
||||
}
|
||||
if (! app(OfferAvailability::class)->publicAllowed($operation, $publication)) {
|
||||
continue;
|
||||
}
|
||||
$p = $this->project($row->id, $publication);
|
||||
if (! $p) {
|
||||
continue;
|
||||
}
|
||||
$expires = app(OfferAvailability::class)->view($operation, $publication)['expires_at'];
|
||||
if ($expires !== null) {
|
||||
$p['expires_at'] = $expires;
|
||||
}
|
||||
if (! empty($filters['q']) && ! str_contains(mb_strtolower($p['title'].' '.$p['summary']), mb_strtolower($filters['q']))) {
|
||||
continue;
|
||||
}
|
||||
@@ -184,17 +192,23 @@ final class OfferPublicCatalogue
|
||||
public function detail(int $id): array
|
||||
{
|
||||
abort_unless($this->fixtureReadAllowed(), 404);
|
||||
$row = Opportunity::query()->whereKey($id)->whereNotNull('workflow_context->private_offer_preparation')->first(['id', DB::raw("workflow_context->'offer_publication' AS public_snapshot")]);
|
||||
$row = Opportunity::query()->whereKey($id)->whereNotNull('workflow_context->private_offer_preparation')->first(['id', DB::raw("workflow_context->'offer_publication' AS public_snapshot"), DB::raw("workflow_context->'offer_operation' AS operation_state")]);
|
||||
if (! $row || ! is_string($row->getAttribute('public_snapshot'))) {
|
||||
abort(404);
|
||||
}
|
||||
try {
|
||||
$publication = json_decode($row->getAttribute('public_snapshot'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$operation = json_decode($row->getAttribute('operation_state') ?? 'null', true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $error) {
|
||||
abort(404);
|
||||
}
|
||||
abort_unless(app(OfferAvailability::class)->publicAllowed($operation, $publication), 404);
|
||||
$record = $this->project($id, $publication);
|
||||
abort_unless($record !== null, 404);
|
||||
$expires = app(OfferAvailability::class)->view($operation, $publication)['expires_at'];
|
||||
if ($expires !== null) {
|
||||
$record['expires_at'] = $expires;
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
@@ -116,7 +116,9 @@ class OpportunityProfileWorkflow
|
||||
if (in_array($state, ['draft', 'needs_information'], true)) {
|
||||
$actions[] = 'submit';
|
||||
}
|
||||
if (in_array($state, ['rejected', 'approved'], true)) {
|
||||
if (in_array($state, ['rejected', 'approved'], true) || (isset($record->workflow_context['submission']) && ($record->workflow_context['offer_operation']['status'] ?? null) === 'revalidation'
|
||||
&& ($record->workflow_context['offer_operation']['requested_by'] ?? null) === $actor->id && (int) $record->owner_user_id === $actor->id
|
||||
&& in_array($state, ['draft', 'needs_information', 'submitted', 'in_review', 'information_pending'], true))) {
|
||||
$actions[] = 'request_revision';
|
||||
}
|
||||
}
|
||||
@@ -232,7 +234,8 @@ class OpportunityProfileWorkflow
|
||||
'review_gate' => ['submitted', 'in_review', 'information_pending', 'approved'],
|
||||
'publish' => ['approved'], 'suspend' => [$state],
|
||||
'assign_publication' => ['approved'],
|
||||
'request_revision' => $offer ? ['approved', 'rejected'] : ['approved', 'published', 'suspended'],
|
||||
'request_revision' => $offer ? (($context['offer_operation']['status'] ?? null) === 'revalidation'
|
||||
? ['draft', 'needs_information', 'submitted', 'in_review', 'information_pending', 'approved', 'rejected'] : ['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'],
|
||||
@@ -378,6 +381,9 @@ class OpportunityProfileWorkflow
|
||||
&& $this->responsibility($reviewer, $record, preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Revisor revogado, sem responsabilidade ou com conflito.');
|
||||
}
|
||||
$context['approval'] = [...$decision, 'hash' => $snapshot['hash'], 'gates' => $context['reviews'] ?? []];
|
||||
if ($offer) {
|
||||
$context['offer_operation'] = app(PrivateOfferOperations::class)->afterApproval($context);
|
||||
}
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$record->workflow_context = $context;
|
||||
if (! $offer) {
|
||||
|
||||
@@ -61,6 +61,7 @@ final class PrivateOfferConfidentiality
|
||||
|
||||
private function approvedHash(Opportunity $record): string
|
||||
{
|
||||
abort_unless(app(OfferAvailability::class)->record($record)['state'] === 'available', 409, 'A oferta não está disponível.');
|
||||
$hash = $record->workflow_context['approval']['hash'] ?? null;
|
||||
abort_unless(is_string($hash) && app(PortalProfileAccess::class)->state($record) === 'approved', 409, 'Esta versão não tem aprovação editorial actual.');
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Availability, reports and administrative plans in the existing opportunity and CRM tasks. */
|
||||
final class PrivateOfferOperations
|
||||
{
|
||||
/** @param array<string,mixed> $context
|
||||
* @return array<string,mixed> */
|
||||
public function afterApproval(array $context): array
|
||||
{
|
||||
$days = config('private_offers.validity_days');
|
||||
$reference = config('private_offers.validity_policy_reference');
|
||||
if ($days !== null && (! is_int($days) || $days < 1 || $days > 36500 || ! is_string($reference) || trim($reference) === '')) {
|
||||
throw ValidationException::withMessages(['validity' => 'Configuração de validade incompleta. Não foi aplicado um prazo presumido.']);
|
||||
}
|
||||
$operation = $context['offer_operation'] ?? ['status' => 'available', 'cycle' => 0];
|
||||
$hash = $context['approval']['hash'];
|
||||
$policy = ['days' => $days, 'policy_reference' => $reference, 'approval_hash' => $hash];
|
||||
$operation['validity_policies'][$hash] ??= $policy;
|
||||
$operation['validity'] ??= $operation['validity_policies'][$hash];
|
||||
$operation['last_approval_hash'] = $hash;
|
||||
|
||||
return $operation;
|
||||
}
|
||||
|
||||
private function offer(int $id, bool $lock = false): Opportunity
|
||||
{
|
||||
$record = Opportunity::query()->when($lock, fn ($q) => $q->lockForUpdate())->findOrFail($id);
|
||||
abort_unless($record->isPrivateOfferPreparation(), 404);
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
public function publisher(User $actor, Opportunity $record): bool
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
|
||||
return $access->canView($actor, $record) && $access->mfa($actor) && ! $access->has($actor, 'auditor') && ! $access->conflict($actor, $record)
|
||||
&& $access->scoped($actor, 'publisher', $record->organization_id, $record->opportunity_category) && $access->operational($actor, 'publish', $record->id);
|
||||
}
|
||||
|
||||
/** @return Builder<Opportunity> */
|
||||
public function staffQuery(User $actor): Builder
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_unless($access->mfa($actor) && ! $access->has($actor, 'auditor'), 403);
|
||||
$grants = [...$access->grants($actor, 'validator'), ...$access->grants($actor, 'publisher')];
|
||||
abort_unless($grants !== [], 403);
|
||||
|
||||
return $access->scope(Opportunity::query(), $actor)->whereNotNull('workflow_context->private_offer_preparation')
|
||||
->where('owner_user_id', '!=', $actor->id)->whereRaw("NOT COALESCE(workflow_context->'contributors','[]'::jsonb) @> ?::jsonb", [json_encode([$actor->id])])
|
||||
->where(fn ($q) => $q->whereNull('organization_id')->orWhereNotIn('organization_id', DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->select('organization_id')))
|
||||
->where(function ($q) use ($grants) {
|
||||
foreach ($grants as $grant) {
|
||||
$q->orWhere(function ($scope) use ($grant) {
|
||||
$scope->whereIn('opportunity_category', json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR));
|
||||
if ($grant->organization_id !== null) {
|
||||
$scope->where('organization_id', $grant->organization_id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function presentation(User $actor, int $id): array
|
||||
{
|
||||
$record = app(PrivateOfferPreparation::class)->record($actor, $id);
|
||||
$reviewer = app(PrivateOfferConfidentiality::class)->internal($actor, $record);
|
||||
$publisher = $this->publisher($actor, $record);
|
||||
$reports = [];
|
||||
if ($reviewer) {
|
||||
foreach ($record->workflow_context['offer_reports'] ?? [] as $report) {
|
||||
$reports[] = [...$report, 'reason' => Crypt::decryptString($report['reason']), 'resolution_reason' => isset($report['resolution_reason']) ? Crypt::decryptString($report['resolution_reason']) : null,
|
||||
'source_snapshot' => isset($report['source_snapshot']) ? json_decode(Crypt::decryptString($report['source_snapshot']), true, 512, JSON_THROW_ON_ERROR) : null];
|
||||
}
|
||||
}
|
||||
$highlight = $record->workflow_context['offer_highlight'] ?? null;
|
||||
|
||||
return ['id' => $id, 'etag' => app(OpportunityManagement::class)->etag($record),
|
||||
'availability' => app(OfferAvailability::class)->record($record), 'cycle' => $record->workflow_context['offer_operation']['cycle'] ?? 0,
|
||||
'owner' => app(PrivateOfferConfidentiality::class)->seller($actor, $record), 'reviewer' => $reviewer, 'publisher' => $publisher,
|
||||
'editorial_state' => app(PortalProfileAccess::class)->state($record), 'reports' => $reports,
|
||||
'highlight' => $publisher && $highlight ? [...$highlight, 'note' => Crypt::decryptString($highlight['note'])] : null,
|
||||
'commercial_activation' => false,
|
||||
'history' => array_map(fn ($event) => array_intersect_key($event, array_flip(['id', 'action', 'actor_id', 'at', 'cycle'])), $record->workflow_context['offer_operation_history'] ?? [])];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $context
|
||||
* @param array<string,mixed> $metadata */
|
||||
private function save(Opportunity $record, ?User $actor, array $context, string $action, array $metadata = []): void
|
||||
{
|
||||
$event = ['id' => (string) Str::uuid(), 'action' => $action, 'actor_id' => $actor?->id, 'at' => now()->toIso8601String(),
|
||||
'cycle' => $context['offer_operation']['cycle'] ?? 0, ...$metadata];
|
||||
$context['offer_operation_history'][] = $event;
|
||||
$record->workflow_context = $context;
|
||||
$record->management_version++;
|
||||
$record->save();
|
||||
DB::table('audit_events')->insert(['source_system' => 'private-offers', 'entity_type' => 'opportunity', 'actor_user_id' => $actor?->id,
|
||||
'action' => $action, 'data_classification' => 'restricted', 'correlation_id' => (string) Str::uuid(),
|
||||
'after_data' => json_encode(['record_id' => $record->id, 'record_version' => $record->management_version, ...$event], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $context
|
||||
* @return array<string,mixed> */
|
||||
private function withdraw(array $context, string $origin): array
|
||||
{
|
||||
$context['offer_operation'] = [...($context['offer_operation'] ?? ['cycle' => 0]), 'status' => 'withdrawn', 'withdrawn_at' => now()->toIso8601String(), 'origin' => $origin];
|
||||
|
||||
return $context;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function ownerAction(User $actor, int $id, array $input): Opportunity
|
||||
{
|
||||
$data = validator($input, ['action' => 'required|in:withdraw,request_reactivation,reactivate', 'confirm' => 'required|accepted',
|
||||
'etag' => 'required_unless:action,withdraw|string|size:64', 'reason' => 'nullable|string|max:1000'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$record = $this->offer($id, true);
|
||||
abort_unless(app(PrivateOfferConfidentiality::class)->seller($actor, $record), 403);
|
||||
$context = $record->workflow_context;
|
||||
$state = app(OfferAvailability::class)->record($record)['state'];
|
||||
if ($data['action'] === 'withdraw') {
|
||||
if (($context['offer_operation']['status'] ?? null) === 'withdrawn') {
|
||||
return $record;
|
||||
}
|
||||
$this->save($record, $actor, $this->withdraw($context, 'owner'), 'offer_withdrawn', ['reason' => Crypt::encryptString($data['reason'] ?? '')]);
|
||||
|
||||
return $record;
|
||||
}
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $data['etag']), 409);
|
||||
if ($data['action'] === 'request_reactivation') {
|
||||
abort_unless(in_array($state, ['withdrawn', 'expired'], true), 409, 'A oferta não está retirada ou expirada.');
|
||||
$editorialState = app(PortalProfileAccess::class)->state($record);
|
||||
abort_unless(isset($context['submission']) || in_array($editorialState, ['draft', 'needs_information'], true), 409,
|
||||
'A preparação anterior ainda precisa da vinculação editorial existente antes de abrir nova revisão.');
|
||||
$context['offer_operation'] = [...($context['offer_operation'] ?? []), 'status' => 'revalidation', 'cycle' => ($context['offer_operation']['cycle'] ?? 0) + 1,
|
||||
'requested_by' => $actor->id, 'requested_at' => now()->toIso8601String()];
|
||||
// Reopen the same editorial engine, retaining old submissions and decisions.
|
||||
$record->workflow_context = $context;
|
||||
$record->save();
|
||||
if (isset($context['submission'])) {
|
||||
$record = app(OpportunityProfileWorkflow::class)->transition($actor, $id, ['etag' => app(OpportunityManagement::class)->etag($record),
|
||||
'action' => 'request_revision', 'reason' => 'Pedido explícito de nova validação para reactivar a oferta. '.($data['reason'] ?? '')]);
|
||||
}
|
||||
$this->save($record, $actor, $record->workflow_context, 'offer_reactivation_requested');
|
||||
|
||||
return $record;
|
||||
}
|
||||
abort_unless($state === 'revalidation' && app(PortalProfileAccess::class)->state($record) === 'approved', 409, 'É necessária nova validação editorial.');
|
||||
$snapshot = app(PrivateOfferPreparation::class)->snapshot($record);
|
||||
abort_unless(($snapshot['payload']['operational_cycle'] ?? null) === $context['offer_operation']['cycle']
|
||||
&& hash_equals($context['approval']['hash'] ?? '', $snapshot['hash'])
|
||||
&& ($context['submission']['payload']['operational_cycle'] ?? null) === $context['offer_operation']['cycle'], 409);
|
||||
$context['offer_operation']['status'] = 'available';
|
||||
$context['offer_operation']['activated_hash'] = $snapshot['hash'];
|
||||
$this->save($record, $actor, $context, 'offer_reactivated_privately');
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
public function expire(int $id): bool
|
||||
{
|
||||
return DB::transaction(function () use ($id) {
|
||||
$record = $this->offer($id, true);
|
||||
$availability = app(OfferAvailability::class)->record($record);
|
||||
if ($availability['state'] !== 'expired' || ($record->workflow_context['offer_operation']['status'] ?? null) === 'expired') {
|
||||
return false;
|
||||
}
|
||||
$context = $record->workflow_context;
|
||||
$context['offer_operation'] = [...($context['offer_operation'] ?? []), 'status' => 'expired', 'expired_at' => $availability['expires_at']];
|
||||
$this->save($record, null, $context, 'offer_expired', ['expires_at' => $availability['expires_at']]);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public function canReport(User $actor, Opportunity $record): bool
|
||||
{
|
||||
if (app(PortalProfileAccess::class)->canView($actor, $record)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
app(OfferPublicCatalogue::class)->detail($record->id);
|
||||
|
||||
return true;
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function report(User $actor, int $id, array $input): array
|
||||
{
|
||||
$data = validator($input, ['client_key' => 'required|uuid', 'reason' => 'required|string|min:20|max:2000', 'confirm' => 'required|accepted'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$record = $this->offer($id, true);
|
||||
$context = $record->workflow_context;
|
||||
$key = $data['client_key'];
|
||||
$hash = hash('sha256', $data['reason']);
|
||||
if (isset($context['offer_reports'][$key])) {
|
||||
$previous = $context['offer_reports'][$key];
|
||||
abort_unless($previous['reporter_id'] === $actor->id, 404);
|
||||
abort_unless($previous['command_hash'] === $hash, 409);
|
||||
|
||||
return ['id' => $key, 'replayed' => true];
|
||||
}
|
||||
abort_unless($this->canReport($actor, $record), 404);
|
||||
try {
|
||||
$source = app(OfferPublicCatalogue::class)->detail($id);
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
$source = Arr::only(app(OpportunityManagement::class)->values($record), ['title', 'description', 'opportunity_category', 'private_offer']);
|
||||
}
|
||||
$task = app(OpportunityWorkflowTasks::class)->ensure($record, 'offer_report_'.$key, 'Denúncia da Oferta '.$record->reference);
|
||||
$context['offer_reports'][$key] = ['id' => $key, 'reporter_id' => $actor->id, 'at' => now()->toIso8601String(), 'command_hash' => $hash,
|
||||
'reason' => Crypt::encryptString($data['reason']), 'version' => 1, 'status' => 'open', 'task_id' => $task,
|
||||
'source_snapshot' => Crypt::encryptString(json_encode($source, JSON_THROW_ON_ERROR)),
|
||||
'source_record_version' => $record->management_version, 'source_approval_hash' => $context['approval']['hash'] ?? null,
|
||||
'source_public_hash' => $context['offer_publication']['publication']['hash'] ?? null];
|
||||
$this->save($record, $actor, $context, 'offer_reported', ['report_id' => $key]);
|
||||
|
||||
return ['id' => $key, 'replayed' => false];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function handleReport(User $actor, int $id, string $reportId, array $input): void
|
||||
{
|
||||
$data = validator($input, ['etag' => 'required|string|size:64', 'version' => 'required|integer|min:1', 'action' => 'required|in:start_review,resolve_no_withdrawal,resolve_withdrawal',
|
||||
'reason' => 'required|string|min:20|max:2000', 'confirm' => 'required|accepted'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $reportId, $data) {
|
||||
$record = $this->offer($id, true);
|
||||
abort_unless(app(PrivateOfferConfidentiality::class)->internal($actor, $record), 403);
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $data['etag']), 409);
|
||||
$context = $record->workflow_context;
|
||||
$report = $context['offer_reports'][$reportId] ?? null;
|
||||
abort_unless($report !== null, 404);
|
||||
abort_unless($report['version'] === (int) $data['version'] && in_array($report['status'], ['open', 'in_review'], true), 409);
|
||||
if ($data['action'] === 'start_review') {
|
||||
abort_unless($report['status'] === 'open', 409);
|
||||
app(OpportunityWorkflowTasks::class)->assign($record, $report['task_id'], $actor);
|
||||
$report['status'] = 'in_review';
|
||||
} else {
|
||||
abort_unless($report['status'] === 'in_review' && $report['reviewer_id'] === $actor->id, 409, 'A denúncia deve ser tratada pelo revisor que a iniciou.');
|
||||
app(OpportunityWorkflowTasks::class)->complete($report['task_id'], 'Denúncia tratada; decisão no histórico privado.');
|
||||
$report['status'] = 'resolved';
|
||||
$report['resolution'] = $data['action'];
|
||||
if ($data['action'] === 'resolve_withdrawal') {
|
||||
$context = $this->withdraw($context, 'moderation');
|
||||
}
|
||||
}
|
||||
$report['reviewer_id'] = $actor->id;
|
||||
$report['version']++;
|
||||
$report['updated_at'] = now()->toIso8601String();
|
||||
$report['resolution_reason'] = Crypt::encryptString($data['reason']);
|
||||
$report['history'][] = ['action' => $data['action'], 'actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'reason' => Crypt::encryptString($data['reason'])];
|
||||
$context['offer_reports'][$reportId] = $report;
|
||||
$this->save($record, $actor, $context, 'offer_report_'.$data['action'], ['report_id' => $reportId]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function highlight(User $actor, int $id, array $input): void
|
||||
{
|
||||
$data = validator($input, ['etag' => 'required|string|size:64', 'version' => 'required|integer|min:0', 'status' => 'required|in:draft,archived',
|
||||
'label' => 'required|string|max:150', 'starts_at' => 'nullable|date', 'ends_at' => 'nullable|required_with:starts_at|date|after:starts_at',
|
||||
'note' => 'required|string|min:20|max:1000', 'confirm' => 'required|accepted'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $data) {
|
||||
$record = $this->offer($id, true);
|
||||
abort_unless($this->publisher($actor, $record), 403);
|
||||
$context = $record->workflow_context;
|
||||
$before = $context['offer_highlight'] ?? null;
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $data['etag']) && (int) $data['version'] === ($before['version'] ?? 0), 409);
|
||||
$plan = ['version' => (int) $data['version'] + 1, 'status' => $data['status'], 'label' => $data['label'], 'starts_at' => $data['starts_at'] ?? null,
|
||||
'ends_at' => $data['ends_at'] ?? null, 'note' => Crypt::encryptString($data['note']), 'actor_id' => $actor->id, 'at' => now()->toIso8601String()];
|
||||
$context['offer_highlight_history'][] = $before;
|
||||
$context['offer_highlight'] = $plan;
|
||||
$this->save($record, $actor, $context, 'offer_highlight_prepared', ['plan_version' => $plan['version'], 'status' => $plan['status']]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,10 @@ final class PrivateOfferPreparation
|
||||
if ($extended) {
|
||||
$payload['resources'] = $resources;
|
||||
}
|
||||
$cycle = $record->workflow_context['offer_operation']['cycle'] ?? 0;
|
||||
if ($cycle > 0) {
|
||||
$payload['operational_cycle'] = $cycle;
|
||||
}
|
||||
$normalize = function (mixed $value) use (&$normalize): mixed {
|
||||
if (is_object($value)) {
|
||||
$value = get_object_vars($value);
|
||||
@@ -169,7 +173,7 @@ final class PrivateOfferPreparation
|
||||
};
|
||||
$payload = $normalize($payload);
|
||||
|
||||
$contract = $extended ? 'private-offer-editorial-v3' : 'private-offer-editorial-v2';
|
||||
$contract = $cycle > 0 ? 'private-offer-editorial-v4' : ($extended ? 'private-offer-editorial-v3' : 'private-offer-editorial-v2');
|
||||
|
||||
return ['payload' => $payload, 'hash' => hash('sha256', json_encode(['contract' => $contract, 'payload' => $payload], JSON_THROW_ON_ERROR)),
|
||||
'record_version' => $record->management_version, 'contract_version' => $contract, 'resources' => $resources];
|
||||
|
||||
Reference in New Issue
Block a user