Files
compras/app/Services/UrgentRequisitionReviews.php
T
nala eb32c74c56
tests / ci (push) Waiting to run
commit compras1 2811
2026-11-28 07:11:35 +02:00

297 lines
19 KiB
PHP

<?php
namespace App\Services;
use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
/** Posterior documentary review of a concluded cycle, never another approval or financial writer. */
final class UrgentRequisitionReviews
{
public function ready(): bool
{
$db = DB::connection();
return config('urgent-reviews.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
}
private function actor(User $actor, bool $settings = false, bool $write = true): User
{
abort_unless($this->ready(), 503);
if ($write) {
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor);
} else {
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
$actor = User::query()->where('tenant_id', $actor->tenant_id)->whereKey($actor->id)->firstOrFail();
}
abort_unless($actor->hasFunctions($settings ? ['admin'] : ['admin', 'procurement']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
return $actor;
}
public function canReview(User $actor): bool
{
if (! $this->ready() || auth()->id() !== $actor->id) {
return false;
}
$actor = User::query()->where('tenant_id', $actor->tenant_id)->whereKey($actor->id)->first();
if ($actor === null || ! $actor->hasFunctions(['procurement']) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
return false;
}
$policy = SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first();
if ($policy === null || $policy->state !== 'active') {
return false;
}
$members = DB::table('organization_memberships as m')->join('organization_profiles as p', 'p.id', '=', 'm.profile_id')
->where('m.tenant_id', $actor->tenant_id)->where('p.tenant_id', $actor->tenant_id)->where('m.user_id', $actor->id)
->whereIn('p.id', $policy->data['profile_ids'])->where('m.maintenance', false)
->where(fn ($q) => $q->whereNull('m.expires_at')->orWhere('m.expires_at', '>', now()));
if (app(WorkContext::class)->enforced($actor)) {
$members->whereJsonContains('p.work_contexts', 'procurement.internal');
}
return $members->exists();
}
/** @return array<string,mixed> */
public function settings(User $actor): array
{
return DB::transaction(function () use ($actor) {
$actor = $this->actor($actor, true, false);
return ['current' => SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first(),
'history' => SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->paginate(15)->withQueryString(),
'profiles' => DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
});
}
/** @param array<string,mixed> $input */
public function savePolicy(User $actor, array $input): SupplyRecord
{
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'enabled' => 'required|boolean',
'profile_ids' => 'present|array|list|max:50', 'profile_ids.*' => 'required|integer|min:1|distinct', 'reason' => 'required|string|min:10|max:4000'])->validate();
$data['operation_key'] = strtolower($data['operation_key']);
$data['enabled'] = (bool) $data['enabled'];
$data['profile_ids'] = array_map(intval(...), $data['profile_ids']);
sort($data['profile_ids'], SORT_NUMERIC);
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $data, $hash) {
$actor = $this->actor($actor, true);
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($retry !== null) {
abort_unless($retry->kind === 'urgent_review_policy' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
return $retry;
}
abort_unless(! $data['enabled'] || $data['profile_ids'] !== [], 422, 'Seleccione os perfis responsáveis pela revisão posterior.');
abort_unless(DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->whereIn('id', $data['profile_ids'])->count() === count($data['profile_ids']), 422);
$old = SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first();
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'urgent_review_policy',
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => $data['enabled'] ? 'active' : 'inactive',
'data' => ['enabled' => $data['enabled'], 'profile_ids' => $data['profile_ids'], 'trigger' => 'final_decision_including_rejection_expiry'],
'snapshot' => ['new_permissions' => false, 'financial_effects' => false], 'reason' => $data['reason'], 'created_by' => $actor->id,
'created_at' => now(), 'operation_key' => $data['operation_key'], 'input_hash' => $hash]);
app(RequisitionWorkflow::class)->audit($actor, 'urgent.review_policy_saved', null, $old?->toArray(), ['record' => $record->toArray()]);
return $record;
});
}
/** Resolve the actual concluded cycle; drafts/pending work and later edited drafts are never substituted.
* @return array<string,mixed>
*/
private function source(User $actor, int $id, int $cycle): array
{
$request = Requisition::query()->visibleTo($actor)->whereKey($id)->firstOrFail();
$expiration = SupplyRecord::query()->where('kind', 'req_expiration')->where('data->requisition_id', $id)->where('data->cycle', $cycle)->first();
if ($expiration !== null) {
$header = $expiration->snapshot['request'] ?? null;
abort_unless(is_array($header) && is_array($expiration->snapshot['items'] ?? null) && is_array($expiration->snapshot['steps'] ?? null), 409,
'O ciclo expirado exige conferência dos dados preservados.');
abort_unless(($header['priority'] ?? null) === 'urgent', 404);
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $id)
->where('action', 'requisition.expired_returned')->where('after->expiration_record_id', $expiration->id)->first();
abort_unless($audit !== null && is_string($audit->before) && json_decode($audit->before, true, 64, JSON_THROW_ON_ERROR) === $header, 409, 'A expiração exige conferência da sua origem auditada.');
$source = ['kind' => 'expiry', 'id' => $expiration->id, 'outcome' => 'expired', 'closed_at' => (string) $expiration->created_at,
'request' => $header, 'items' => $expiration->snapshot['items'], 'steps' => $expiration->snapshot['steps']];
} else {
abort_unless($request->priority === 'urgent' && in_array($request->status, ['approved', 'rejected'], true)
&& (int) ($request->getAttribute('approval_cycle') ?? 1) === $cycle, 409, 'O ciclo ainda não tem uma decisão final disponível para revisão.');
$steps = $request->steps()->get();
abort_unless($steps->isNotEmpty() && ($request->status !== 'approved' || $steps->every(fn ($step) => $step->decision === 'approved')), 409,
'As etapas preservadas não demonstram a conclusão da aprovação.');
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $id)
->where('action', 'approval.'.$request->status)->where('after->status', $request->status)->whereIn('after->step_id', $steps->modelKeys())->latest('id')->first();
abort_unless($audit !== null, 409, 'A decisão final exige conferência da sua origem auditada.');
$decision = json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR);
abort_unless($steps->where('id', $decision['step_id'])->where('decision', $request->status)->isNotEmpty(), 409);
$source = ['kind' => 'decision', 'id' => $audit->id, 'outcome' => $request->status, 'closed_at' => $audit->created_at,
'request' => $request->only(['id', 'number', 'requester_id', 'department_id', 'cost_center_id', 'priority', 'needed_by', 'justification', 'subtotal_minor', 'tax_minor', 'total_minor']),
'items' => $request->items()->orderBy('id')->get()->toArray(), 'steps' => $steps->toArray()];
}
abort_unless($source['items'] !== [] && $source['steps'] !== [], 409, 'O ciclo concluído exige conferência das linhas e etapas conservadas.');
foreach ($source['steps'] as $step) {
abort_unless(is_array($step) && isset($step['id'], $step['role'], $step['decision']), 409, 'As etapas conservadas exigem conferência.');
}
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
$source['request'][$field] = isset($source['request'][$field]) ? (string) $source['request'][$field] : null;
}
foreach ($source['items'] as &$item) {
abort_unless(is_array($item) && isset($item['id'], $item['description'], $item['quantity'], $item['unit']), 409,
'As linhas conservadas exigem conferência antes da revisão.');
foreach (['unit_price_minor', 'subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
$item[$field] = isset($item[$field]) ? (string) $item[$field] : null;
}
}
unset($item);
$source['cycle'] = $cycle;
$source['fingerprint'] = hash('sha256', json_encode($source, JSON_THROW_ON_ERROR));
return $source;
}
/** @return array<string,mixed> */
public function workspace(User $actor, int $id, int $cycle): array
{
return DB::transaction(function () use ($actor, $id, $cycle) {
$actor = $this->actor($actor, false, false);
$source = $this->source($actor, $id, $cycle);
$current = $this->current($id, $cycle);
$audited = $current === null || $this->audited($current);
$verified = $audited && ($current === null || ($current->snapshot['fingerprint'] ?? null) === $source['fingerprint']);
return ['source' => $source, 'current' => $current, 'currentVerified' => $verified,
'canReview' => $this->canReview($actor) && $audited,
'history' => SupplyRecord::query()->where('kind', 'urgent_review')->where('data->requisition_id', $id)->where('data->cycle', $cycle)
->latest('id')->paginate(15)->withQueryString(), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
});
}
/** @return array<string,mixed> */
public function queue(User $actor, ?int $page = 1, string $state = 'pending'): array
{
return DB::transaction(function () use ($actor, $page, $state) {
$actor = $this->actor($actor, false, false);
$candidates = [];
foreach (Requisition::query()->visibleTo($actor)->where('priority', 'urgent')->whereIn('status', ['approved', 'rejected'])->lazyById(100) as $request) {
$cycle = (int) ($request->getAttribute('approval_cycle') ?? 1);
$candidates[$request->id.':'.$cycle] = ['request_id' => $request->id, 'cycle' => $cycle, 'number' => $request->number,
'outcome' => $request->status];
}
foreach (SupplyRecord::query()->where('kind', 'req_expiration')->where('snapshot->request->priority', 'urgent')->lazyById(100) as $expiration) {
$id = (int) $expiration->data['requisition_id'];
$visible = Requisition::query()->visibleTo($actor)->whereKey($id)->first(['id', 'number']);
if ($visible === null) {
continue;
}
$cycle = (int) $expiration->data['cycle'];
$candidates[$id.':'.$cycle] = ['request_id' => $id, 'cycle' => $cycle, 'number' => $expiration->snapshot['request']['number'] ?? $visible->number,
'outcome' => 'expired'];
}
$coverage = ['pending' => 0, 'reviewed' => 0, 'indeterminate' => 0];
$rows = [];
foreach ($candidates as $key => $candidate) {
$status = 'indeterminate';
$closed = null;
try {
$source = $this->source($actor, $candidate['request_id'], $candidate['cycle']);
$closed = $source['closed_at'];
$review = $this->current($candidate['request_id'], $candidate['cycle']);
$status = $review === null ? 'pending' : ($this->audited($review) && ($review->snapshot['fingerprint'] ?? null) === $source['fingerprint'] ? 'reviewed' : 'indeterminate');
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 409) {
throw $error;
}
}
$coverage[$status]++;
if ($state === 'all' || $state === $status) {
$rows[] = [...$candidate, 'key' => $key, 'status' => $status, 'closed_at' => $closed,
'href' => $status === 'indeterminate' ? '/requisicoes/'.$candidate['request_id']
: '/requisicoes/'.$candidate['request_id'].'/ciclos/'.$candidate['cycle'].'/revisao-urgencia'];
}
}
usort($rows, fn ($a, $b) => strcmp($a['closed_at'] ?? '', $b['closed_at'] ?? '') ?: strcmp($a['key'], $b['key']));
$last = max(1, (int) ceil(count($rows) / 20));
$current = $page === null ? 1 : max(1, min($last, $page));
return ['coverage' => $coverage, 'state' => $state, 'canReview' => $this->canReview($actor),
'canConfigure' => $actor->hasFunctions(['admin']), 'records' => ['data' => $page === null ? $rows : array_slice($rows, ($current - 1) * 20, 20),
'total' => count($rows), 'current_page' => $current, 'last_page' => $last]];
});
}
/** @return list<array<string,mixed>> */
public function tasks(User $actor): array
{
if (! $this->canReview($actor)) {
return [];
}
return array_values(array_map(fn ($row) => ['id' => 'urgent-review:'.$row['key'], 'module' => 'purchases', 'reference' => $row['number'],
'label' => 'Revisão posterior de urgência · ciclo '.$row['cycle'], 'task' => 'urgent_requisition_review', 'status' => 'pending',
'blocked' => false, 'created_at' => $row['closed_at'], 'due_on' => null, 'href' => $row['href']], $this->queue($actor, null)['records']['data']));
}
private function current(int $id, int $cycle): ?SupplyRecord
{
return SupplyRecord::query()->where('kind', 'urgent_review')->where('data->requisition_id', $id)->where('data->cycle', $cycle)->latest('version')->first();
}
private function audited(SupplyRecord $record): bool
{
$audit = DB::table('audit_logs')->where('tenant_id', $record->tenant_id)->where('requisition_id', $record->data['requisition_id'])
->where('action', 'urgent.review_recorded')->where('user_id', $record->created_by)->where('after->record->id', $record->id)->first();
$saved = $audit === null || ! is_string($audit->after) ? null : json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null;
return is_array($saved) && ($saved['data'] ?? null) === $record->data && ($saved['snapshot'] ?? null) === $record->snapshot
&& ($saved['version'] ?? null) === $record->version && ($saved['input_hash'] ?? null) === $record->input_hash;
}
/** @param array<string,mixed> $input */
public function review(User $actor, int $id, int $cycle, array $input): SupplyRecord
{
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
'source_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'notes' => 'required|string|min:10|max:4000'])->validate();
$data['operation_key'] = strtolower($data['operation_key']);
$hash = hash('sha256', json_encode([$id, $cycle, $data], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $id, $cycle, $data, $hash) {
$actor = $this->actor($actor);
abort_unless($this->canReview($actor), 403, 'A revisão exige o perfil designado e a função de Compras actualmente válidos.');
$source = $this->source($actor, $id, $cycle);
$request = Requisition::query()->whereKey($id)->firstOrFail();
app(ConflictGuard::class)->assertParticipation($actor, $request);
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($retry !== null) {
abort_unless($retry->kind === 'urgent_review' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
return $retry;
}
abort_unless(hash_equals($source['fingerprint'], $data['source_hash']), 409, 'A origem mudou. Confira o ciclo concluído antes de registar a revisão.');
$old = $this->current($id, $cycle);
abort_unless($old === null || $this->audited($old), 409, 'A revisão anterior exige conferência da sua origem auditada.');
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'urgent_review',
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => 'reviewed',
'data' => ['requisition_id' => $id, 'cycle' => $cycle, 'outcome' => $source['outcome'], 'notes' => trim($data['notes'])],
'snapshot' => $source, 'reason' => trim($data['notes']), 'created_by' => $actor->id, 'created_at' => now(),
'operation_key' => $data['operation_key'], 'input_hash' => $hash]);
app(RequisitionWorkflow::class)->audit($actor, 'urgent.review_recorded', $request, $old?->toArray(), ['record' => $record->toArray()]);
return $record;
});
}
}