44 lines
1.8 KiB
PHP
44 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Concerns;
|
|
|
|
use App\Models\User;
|
|
use App\Services\WorkContext;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
trait HasWorkContext
|
|
{
|
|
protected static function bootHasWorkContext(): void
|
|
{
|
|
static::addGlobalScope('work_context', function (Builder $query) {
|
|
if (! app()->bound('request') || ! request()->hasSession() || request()->is('candidaturas/*')) {
|
|
return;
|
|
}
|
|
$actor = request()->user('web');
|
|
if ($actor instanceof User && app(WorkContext::class)->enforced($actor)) {
|
|
$key = app(WorkContext::class)->active(request());
|
|
$query->where($query->getModel()->qualifyColumn('work_context_key'), $key ?? '__no_context__');
|
|
}
|
|
});
|
|
static::creating(function (Model $model) {
|
|
if (! app()->bound('request') || ! request()->hasSession()) {
|
|
return;
|
|
}
|
|
$actor = request()->user('web');
|
|
if ($actor instanceof User && app(WorkContext::class)->enforced($actor)) {
|
|
$key = app(WorkContext::class)->active(request());
|
|
$area = $model->getTable() === 'people_processes' ? 'people' : 'procurement';
|
|
abort_unless($key !== null && WorkContext::OPTIONS[$key]['operational'] && WorkContext::OPTIONS[$key]['area'] === $area, 403);
|
|
$model->setAttribute('work_context_key', $key);
|
|
}
|
|
});
|
|
static::updating(function (Model $model) {
|
|
if ($model->isDirty('work_context_key')) {
|
|
throw ValidationException::withMessages(['context' => 'O contexto de origem do processo não pode ser alterado.']);
|
|
}
|
|
});
|
|
}
|
|
}
|