316 lines
19 KiB
PHP
316 lines
19 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\PurchaseOrder;
|
|
use App\Models\Requisition;
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use Carbon\CarbonImmutable;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\Rule;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Tempo\Finance\Budget\BudgetControl;
|
|
use Tempo\Purchasing\Internal\InternalRequisitions;
|
|
|
|
/** Company-defined elapsed-time policy; no default deadlines, approvers or grants. */
|
|
final class RequisitionExpiry
|
|
{
|
|
public const ROLES = ['department_head', 'procurement', 'finance', 'configured_1', 'configured_2', 'configured_3', 'configured_4', 'configured_5'];
|
|
|
|
public function ready(): bool
|
|
{
|
|
$db = DB::connection();
|
|
$purchasing = new \ReflectionClass(InternalRequisitions::class);
|
|
|
|
return config('requisition-expiry.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())))
|
|
&& $purchasing->hasMethod('supportsExpiryCycles') && $purchasing->getMethod('supportsExpiryCycles')->invoke(null) === true
|
|
&& defined(BudgetControl::class.'::REQUISITION_CYCLES_VERSION')
|
|
&& constant(BudgetControl::class.'::REQUISITION_CYCLES_VERSION') === CommonBudget::REQUISITION_CYCLES_CONTRACT
|
|
&& Schema::hasTable('budget_requisition_cycles') && Schema::hasColumn('requisitions', 'approval_cycle')
|
|
&& Schema::hasTable('workflow_notices') && Schema::hasTable('requisition_commands') && Schema::hasColumn('requisitions', 'process_version')
|
|
&& Schema::hasColumn('approval_steps', 'approval_cycle') && Schema::hasColumn('budget_entries', 'requisition_cycle');
|
|
}
|
|
|
|
/** @return array<int,int> */
|
|
public static function cycles(Requisition $request): array
|
|
{
|
|
return [$request->id => (int) ($request->getAttribute('approval_cycle') ?? 1)];
|
|
}
|
|
|
|
/** Identifiers can originate in a validated command payload; resolve actual scoped models.
|
|
* @param array<mixed> $originIds
|
|
* @return array<int,int>
|
|
*/
|
|
public static function origins(array $originIds): array
|
|
{
|
|
Validator::make(['origins' => $originIds], ['origins' => 'required|array|list', 'origins.*' => 'required|integer|min:1'])->validate();
|
|
$requests = Requisition::query()->whereIn('id', $originIds)->get(Schema::hasColumn('requisitions', 'approval_cycle') ? ['id', 'approval_cycle'] : ['id']);
|
|
abort_unless($requests->count() === count(array_unique($originIds)), 404);
|
|
$result = [];
|
|
foreach ($requests as $request) {
|
|
$result += self::cycles($request);
|
|
}
|
|
ksort($result, SORT_NUMERIC);
|
|
|
|
return $result;
|
|
}
|
|
|
|
/** @return array<int,int> */
|
|
public static function orderCycles(PurchaseOrder $order): array
|
|
{
|
|
return self::origins(app(OrderPartsAccess::class)->origins($order));
|
|
}
|
|
|
|
public function assertOperational(Requisition $request): void
|
|
{
|
|
if ((int) ($request->getAttribute('approval_cycle') ?? 1) > 1 || isset($request->approval_snapshot['approval_expiry'])) {
|
|
abort_unless($this->ready(), 503, 'Preserve a composição compatível dos ciclos antes de alterar esta requisição.');
|
|
}
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function settings(User $actor): array
|
|
{
|
|
abort_unless($this->ready(), 503);
|
|
|
|
return DB::transaction(function () use ($actor) {
|
|
app(ConflictGuard::class)->lockCompany($actor);
|
|
$actor = app(CurrentActor::class)->lock($actor);
|
|
abort_unless($actor->hasFunctions(['admin']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
|
|
|
return ['current' => SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first(),
|
|
'history' => SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->paginate(15)->withQueryString(),
|
|
'profiles' => DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
|
'roles' => ['department_head' => 'Chefia de departamento', 'procurement' => 'Compras', 'finance' => 'Finanças',
|
|
'configured_1' => 'Nível adicional 1', 'configured_2' => 'Nível adicional 2', 'configured_3' => 'Nível adicional 3',
|
|
'configured_4' => 'Nível adicional 4', 'configured_5' => 'Nível adicional 5'],
|
|
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
|
});
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function workspace(User $actor, Requisition $request): array
|
|
{
|
|
abort_unless($this->ready(), 503);
|
|
|
|
return DB::transaction(function () use ($actor, $request) {
|
|
app(ConflictGuard::class)->lockCompany($actor);
|
|
$actor = app(CurrentActor::class)->lock($actor);
|
|
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
|
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
|
|
$request = Requisition::query()->visibleTo($actor)->whereKey($request->id)->firstOrFail();
|
|
$deadline = $this->deadline($request);
|
|
unset($deadline['profile_ids']);
|
|
$history = SupplyRecord::query()->where('kind', 'req_expiration')->where('data->requisition_id', $request->id)->latest('id')->paginate(15)->withQueryString();
|
|
$history->through(fn ($row) => ['id' => $row->id, 'data' => $row->data, 'reason' => $row->reason,
|
|
'request' => $row->snapshot['request'], 'steps' => $row->snapshot['steps'], 'created_at' => $row->created_at]);
|
|
|
|
return ['requisition' => [...$request->only(['id', 'number', 'status', 'process_version', 'requester_id']),
|
|
'approval_cycle' => $request->getAttribute('approval_cycle') ?? 1], 'deadline' => $deadline, 'history' => $history,
|
|
'canExpire' => $deadline['state'] === 'expired' && ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
|
'canEdit' => $request->status === 'draft' && (int) ($request->getAttribute('approval_cycle') ?? 1) > 1
|
|
&& $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor),
|
|
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
|
});
|
|
}
|
|
|
|
/** @param array<string,mixed> $input */
|
|
public function savePolicy(User $actor, array $input): SupplyRecord
|
|
{
|
|
abort_unless($this->ready(), 503);
|
|
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'enabled' => 'required|boolean',
|
|
'levels' => 'present|array|list|max:8', 'levels.*' => 'array:role,expire_minutes,reminder_minutes,escalation_minutes,profile_ids',
|
|
'levels.*.role' => ['required', 'distinct', Rule::in(self::ROLES)], 'levels.*.expire_minutes' => 'required|integer|min:1|max:5256000',
|
|
'levels.*.reminder_minutes' => 'present|nullable|integer|min:1|max:5256000',
|
|
'levels.*.escalation_minutes' => 'present|nullable|integer|min:1|max:5256000', 'levels.*.profile_ids' => 'present|array|list|max:50',
|
|
'levels.*.profile_ids.*' => 'required|distinct|integer|min:1', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
|
$data['operation_key'] = strtolower($data['operation_key']);
|
|
$data['enabled'] = (bool) $data['enabled'];
|
|
foreach ($data['levels'] as $index => &$level) {
|
|
foreach (['expire_minutes', 'reminder_minutes', 'escalation_minutes'] as $field) {
|
|
$level[$field] = $level[$field] === null ? null : (int) $level[$field];
|
|
}
|
|
$level['profile_ids'] = array_map(intval(...), $level['profile_ids']);
|
|
sort($level['profile_ids'], SORT_NUMERIC);
|
|
if (($level['reminder_minutes'] !== null && $level['reminder_minutes'] >= $level['expire_minutes'])
|
|
|| ($level['escalation_minutes'] !== null && ($level['escalation_minutes'] >= $level['expire_minutes'] || $level['profile_ids'] === []))
|
|
|| ($level['reminder_minutes'] !== null && $level['escalation_minutes'] !== null && $level['reminder_minutes'] >= $level['escalation_minutes'])
|
|
|| ($level['escalation_minutes'] === null && $level['profile_ids'] !== [])) {
|
|
throw ValidationException::withMessages(['levels.'.$index => 'Configure lembrete e escalamento antes da expiração, com destinatários explícitos apenas quando houver escalamento.']);
|
|
}
|
|
}
|
|
unset($level);
|
|
usort($data['levels'], fn ($a, $b) => strcmp($a['role'], $b['role']));
|
|
if ($data['enabled'] && $data['levels'] === []) {
|
|
throw ValidationException::withMessages(['levels' => 'Configure pelo menos um nível antes de activar a política.']);
|
|
}
|
|
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
|
|
|
return DB::transaction(function () use ($actor, $data, $hash) {
|
|
app(ConflictGuard::class)->lockCompany($actor);
|
|
$actor = app(CurrentActor::class)->lock($actor);
|
|
abort_unless($actor->hasFunctions(['admin']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
|
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
|
if ($retry !== null) {
|
|
abort_unless($retry->kind === 'req_expiry_policy' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
|
|
|
return $retry;
|
|
}
|
|
$old = SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first();
|
|
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A política mudou. Consulte a versão actual.');
|
|
foreach ($data['levels'] as $level) {
|
|
abort_unless(DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->whereIn('id', $level['profile_ids'])->count() === count($level['profile_ids']), 422);
|
|
}
|
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_expiry_policy',
|
|
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
|
'state' => $data['enabled'] ? 'active' : 'inactive', 'created_by' => $actor->id,
|
|
'data' => ['enabled' => $data['enabled'], 'levels' => $data['levels'], 'time_basis' => 'elapsed_minutes', 'expiry_effect' => 'return_to_requester_draft'],
|
|
'snapshot' => ['new_permissions' => false], 'reason' => trim($data['reason']), 'operation_key' => $data['operation_key'],
|
|
'input_hash' => $hash, 'created_at' => now()]);
|
|
app(RequisitionWorkflow::class)->audit($actor, 'requisition.expiry_policy_saved', null, $old?->toArray(), ['record' => $record->toArray()]);
|
|
|
|
return $record;
|
|
});
|
|
}
|
|
|
|
/** @return array<string,mixed>|null */
|
|
public function policy(Requisition $request): ?array
|
|
{
|
|
$this->assertOperational($request);
|
|
if (! $this->ready()) {
|
|
return null;
|
|
}
|
|
$source = SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first();
|
|
if ($source === null || $source->state !== 'active') {
|
|
return null;
|
|
}
|
|
|
|
return ['id' => $source->id, 'version' => $source->version, 'data' => $source->data,
|
|
'fingerprint' => hash('sha256', json_encode($source->data, JSON_THROW_ON_ERROR))];
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function deadline(Requisition $request): array
|
|
{
|
|
$this->assertOperational($request);
|
|
$inactive = ['state' => 'inactive', 'step_id' => null, 'expires_at' => null, 'basis_hash' => null];
|
|
if ($request->status !== 'pending') {
|
|
return $inactive;
|
|
}
|
|
$policy = $request->approval_snapshot['approval_expiry'] ?? null;
|
|
if ($policy === null) {
|
|
return [...$inactive, 'state' => 'unconfigured'];
|
|
}
|
|
$source = SupplyRecord::query()->where('kind', 'req_expiry_policy')->whereKey($policy['id'])->firstOrFail();
|
|
abort_unless($source->version === $policy['version'] && $source->data === $policy['data']
|
|
&& hash_equals(hash('sha256', json_encode($source->data, JSON_THROW_ON_ERROR)), $policy['fingerprint']), 409, 'A política preservada requer conferência.');
|
|
$steps = $request->steps()->orderBy('position')->get();
|
|
$step = $steps->firstWhere('decision', 'pending');
|
|
$settings = null;
|
|
if ($step !== null) {
|
|
foreach ($policy['data']['levels'] as $level) {
|
|
if ($level['role'] === $step->role) {
|
|
$settings = $level;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if ($step === null || $settings === null || $request->submitted_at === null) {
|
|
return [...$inactive, 'state' => 'unconfigured', 'step_id' => $step?->id];
|
|
}
|
|
$start = CarbonImmutable::parse($request->submitted_at);
|
|
foreach ($steps->where('position', '<', $step->position) as $previous) {
|
|
if ($previous->decision !== 'approved' || $previous->decided_at === null) {
|
|
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
|
}
|
|
$date = CarbonImmutable::parse($previous->decided_at, config('app.timezone'));
|
|
if ($date < $start || $date > now()) {
|
|
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
|
}
|
|
$start = $date;
|
|
}
|
|
if ($start > now()) {
|
|
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
|
}
|
|
$end = $start->addMinutes($settings['expire_minutes']);
|
|
$basis = [$request->id, $request->getAttribute('approval_cycle') ?? 1, $request->getAttribute('process_version'), $step->id,
|
|
$policy['fingerprint'], $start->toIso8601String(), $end->toIso8601String()];
|
|
|
|
return ['state' => now()->greaterThanOrEqualTo($end) ? 'expired' : 'running', 'step_id' => $step->id,
|
|
'started_at' => $start->toIso8601String(), 'expires_at' => $end->toIso8601String(),
|
|
'reminder_at' => $settings['reminder_minutes'] === null ? null : $start->addMinutes($settings['reminder_minutes'])->toIso8601String(),
|
|
'escalation_at' => $settings['escalation_minutes'] === null ? null : $start->addMinutes($settings['escalation_minutes'])->toIso8601String(),
|
|
'profile_ids' => $settings['profile_ids'], 'policy_id' => $source->id, 'basis_hash' => hash('sha256', json_encode($basis, JSON_THROW_ON_ERROR))];
|
|
}
|
|
|
|
/** @param array<string,mixed> $policy */
|
|
public function begin(User $actor, Requisition $request, array $policy, ?string $operation): void
|
|
{
|
|
$cycle = (int) ($request->getAttribute('approval_cycle') ?? 1);
|
|
if ($cycle === 1 && ! isset($policy['approval_expiry'])) {
|
|
return;
|
|
}
|
|
abort_unless($this->ready(), 503);
|
|
if ($operation === null) {
|
|
throw ValidationException::withMessages(['operation_key' => 'A submissão por ciclos exige uma operação identificada.']);
|
|
}
|
|
$engine = app(CommonBudget::class)->for($actor, self::cycles($request));
|
|
app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'beginRequisitionCycle'))->invoke($engine, $request->id, $cycle, $operation));
|
|
}
|
|
|
|
/** @param array<string,mixed> $input
|
|
* @return array<string,mixed>
|
|
*/
|
|
public function proof(User $actor, Requisition $request, array $input): array
|
|
{
|
|
abort_unless($this->ready() && DB::transactionLevel() > 0, 503);
|
|
Requisition::query()->visibleTo($actor)->whereKey($request->id)->firstOrFail();
|
|
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'],
|
|
'comment' => 'nullable|string|max:2000'])->validate();
|
|
$deadline = $this->deadline($request);
|
|
abort_unless($deadline['state'] === 'expired' && hash_equals($deadline['basis_hash'], $data['basis_hash']), 409,
|
|
'O prazo ou a etapa mudou, ou ainda não terminou. Actualize a conferência antes de devolver o pedido.');
|
|
abort_if(SupplyRecord::query()->where('operation_key', $data['operation_key'])->exists(), 409, 'A operação pertence a outro registo.');
|
|
|
|
return [...$deadline, 'operation_key' => strtolower($data['operation_key']),
|
|
'reason' => 'Prazo da etapa terminado em '.$deadline['expires_at'].'; devolução para nova submissão conforme a política #'.$deadline['policy_id'].'.'
|
|
.(empty($data['comment']) ? '' : ' '.trim($data['comment']))];
|
|
}
|
|
|
|
/** @param array<string,mixed> $proof */
|
|
public function returned(User $actor, Requisition $request, array $proof): void
|
|
{
|
|
abort_unless($this->ready() && DB::transactionLevel() > 0 && $request->status === 'pending', 409);
|
|
$cycle = (int) $request->getAttribute('approval_cycle');
|
|
abort_unless($cycle > 0 && $cycle < 1000000, 409);
|
|
$engine = app(CommonBudget::class)->for($actor, self::cycles($request));
|
|
app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'closeRequisitionCycle'))->invoke($engine, $request->id, $cycle, $proof['operation_key']));
|
|
$before = $request->only(['id', 'number', 'status', 'approval_cycle', 'submitted_at', 'process_version', 'requester_id', 'department_id',
|
|
'cost_center_id', 'priority', 'needed_by', 'justification', 'subtotal_minor', 'tax_minor', 'total_minor']);
|
|
$steps = $request->steps()->get()->toArray();
|
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_expiration', 'record_key' => (string) Str::uuid(),
|
|
'version' => 1, 'state' => 'returned', 'created_by' => $actor->id,
|
|
'data' => ['requisition_id' => $request->id, 'cycle' => $cycle, 'step_id' => $proof['step_id'], 'expires_at' => $proof['expires_at'],
|
|
'policy_id' => $proof['policy_id'], 'next_cycle' => $cycle + 1],
|
|
'snapshot' => ['request' => $before, 'items' => $request->items()->orderBy('id')->get()->toArray(), 'steps' => $steps,
|
|
'approval_snapshot' => $request->approval_snapshot, 'proof' => $proof],
|
|
'reason' => $proof['reason'], 'operation_key' => $proof['operation_key'], 'input_hash' => hash('sha256', json_encode($proof, JSON_THROW_ON_ERROR)), 'created_at' => now()]);
|
|
// Close only unacted tasks. Approved decisions remain unchanged in their original rows.
|
|
$request->steps()->where('decision', 'pending')->update(['decision' => 'expired', 'comment' => $proof['reason']]);
|
|
$request->setAttribute('status', 'draft');
|
|
$request->setAttribute('approval_cycle', $cycle + 1);
|
|
$request->setAttribute('submitted_at', null);
|
|
$request->setAttribute('process_version', (int) $request->getAttribute('process_version') + 1);
|
|
$request->save();
|
|
app(WorkflowNotices::class)->expired($request, $proof['step_id']);
|
|
app(RequisitionWorkflow::class)->audit($actor, 'requisition.expired_returned', $request, $before,
|
|
['status' => 'draft', 'cycle' => $cycle + 1, 'expiration_record_id' => $record->id, 'reason' => $proof['reason']]);
|
|
}
|
|
}
|