@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||
|
||||
/** Resolve optional levels into the existing lifecycle; never grant profile permissions. */
|
||||
class RequisitionApprovalLevels
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$isolated = DB::getDriverName() === 'sqlite' ? DB::connection()->getDatabaseName() === ':memory:'
|
||||
: DB::getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName());
|
||||
// Installed distributed runtimes may precede this host source; negotiate the capability.
|
||||
$runtime = new \ReflectionClass(InternalRequisitions::class);
|
||||
|
||||
$available = config('requisition_approval.enabled') === true
|
||||
|| (config('requisition_approval.qa_enabled') === true && app()->environment(['testing', 'payable-testing']) && $isolated);
|
||||
|
||||
return $available
|
||||
&& Schema::hasColumn('tenants', 'requisition_approval_policy') && Schema::hasColumn('approval_steps', 'routing')
|
||||
&& Schema::hasTable('requisition_commands') && Schema::hasColumn('requisitions', 'process_version')
|
||||
&& $runtime->hasMethod('supportsAdditionalLevels') && $runtime->getMethod('supportsAdditionalLevels')->invoke(null) === true;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function rules(User $actor): array
|
||||
{
|
||||
return ['enabled' => 'required|boolean', 'levels' => 'present|array|list|max:5', 'levels.*' => 'array:name,profile_ids,scope,min_amount,categories,cost_center_ids',
|
||||
'levels.*.name' => 'required|string|max:120', 'levels.*.profile_ids' => 'required|array|list|min:1|max:50',
|
||||
'levels.*.profile_ids.*' => ['required', 'integer', Rule::exists('organization_profiles', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||
'levels.*.scope' => 'required|in:department,company', 'levels.*.min_amount' => ['present', 'nullable', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'],
|
||||
'levels.*.categories' => 'present|array|list|max:50', 'levels.*.categories.*' => 'required|string|max:100',
|
||||
'levels.*.cost_center_ids' => 'present|array|list|max:100',
|
||||
'levels.*.cost_center_ids.*' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||
'reason' => 'required|string|min:10|max:4000'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function prepare(User $actor, array $data): array
|
||||
{
|
||||
abort_unless($this->ready(), 503, 'A instalação ainda não disponibiliza os níveis adicionais de aprovação.');
|
||||
abort_unless(app(OrganizationAccess::class)->active($actor->tenant_id), 409, 'Active os perfis da empresa antes de configurar os níveis por perfil.');
|
||||
$data = Validator::make($data, $this->rules($actor), $this->messages())->validate();
|
||||
if ($data['enabled'] && $data['levels'] === []) {
|
||||
throw ValidationException::withMessages(['levels' => 'Configure pelo menos um nível adicional ou mantenha o plano desligado.']);
|
||||
}
|
||||
foreach ($data['levels'] as $index => $level) {
|
||||
foreach ($level['profile_ids'] as $id) {
|
||||
$profile = DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->where('id', $id)->first();
|
||||
if ($profile === null || ! in_array('requisition_approve', json_decode($profile->permissions, true, 32, JSON_THROW_ON_ERROR), true)) {
|
||||
throw ValidationException::withMessages(['levels.'.$index.'.profile_ids' => 'Escolha perfis da empresa com competência própria para aprovar requisições. O plano não concede essa competência.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['revision' => ((Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy['revision'] ?? 0) + 1), 'enabled' => (bool) $data['enabled'],
|
||||
'quorum' => 'one_eligible', 'levels' => array_map(fn ($level) => ['name' => $level['name'], 'profile_ids' => array_values(array_unique(array_map('intval', $level['profile_ids']))), 'scope' => $level['scope'],
|
||||
'min_minor' => $level['min_amount'] === null ? null : BigDecimal::of($level['min_amount'])->multipliedBy(100)->toInt(),
|
||||
'categories' => array_values(array_unique(array_map(fn ($name) => mb_strtolower(trim($name)), $level['categories']))),
|
||||
'cost_center_ids' => array_values(array_unique(array_map('intval', $level['cost_center_ids'])))], $data['levels'])];
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
public function messages(): array
|
||||
{
|
||||
return ['levels.max' => 'Configure no máximo cinco níveis adicionais, até oito com os controlos base.',
|
||||
'levels.list' => 'Indique os níveis pela ordem de aprovação.', 'levels.*.name.required' => 'Dê uma designação a cada nível.',
|
||||
'levels.*.profile_ids.required' => 'Escolha pelo menos um perfil elegível por nível.',
|
||||
'levels.*.profile_ids.*.exists' => 'Escolha perfis da empresa.', 'levels.*.cost_center_ids.*.exists' => 'Escolha centros de custo da empresa.',
|
||||
'levels.*.min_amount.regex' => 'Use um valor MZN não negativo com até duas casas decimais.',
|
||||
'reason.required' => 'Indique o motivo da alteração.', 'reason.min' => 'Descreva o motivo com pelo menos dez caracteres.'];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function policy(Requisition $request): array
|
||||
{
|
||||
$company = Tenant::query()->findOrFail($request->tenant_id);
|
||||
$plan = $company->requisition_approval_policy;
|
||||
if (! ($plan['enabled'] ?? false)) {
|
||||
return [];
|
||||
}
|
||||
abort_unless($this->ready(), 503, 'O plano de aprovação exige a composição compatível; não é permitido ignorar os níveis configurados.');
|
||||
$amount = $company->approval_includes_tax ? $request->total_minor : $request->subtotal_minor;
|
||||
if ($amount === null) {
|
||||
throw ValidationException::withMessages(['submission' => 'Complete os montantes antes de determinar os níveis de aprovação.']);
|
||||
}
|
||||
$categories = array_map(fn ($name) => mb_strtolower(trim($name)), $request->items->pluck('category')->all());
|
||||
$selected = [];
|
||||
foreach ($plan['levels'] as $index => $level) {
|
||||
if ($level['min_minor'] !== null && $amount < $level['min_minor']) {
|
||||
continue;
|
||||
}
|
||||
if ($level['categories'] !== [] && array_intersect($categories, $level['categories']) === []) {
|
||||
continue;
|
||||
}
|
||||
if ($level['cost_center_ids'] !== [] && ! in_array($request->cost_center_id, $level['cost_center_ids'], true)) {
|
||||
continue;
|
||||
}
|
||||
$selected['configured_'.($index + 1)] = $level;
|
||||
}
|
||||
|
||||
return ['additional_levels' => $selected, 'routing_plan_revision' => $plan['revision'], 'routing_quorum' => 'one_eligible'];
|
||||
}
|
||||
|
||||
/** @return list<int> */
|
||||
private function profiles(User $actor): array
|
||||
{
|
||||
if (! $this->ready() || ! app(OrganizationAccess::class)->active($actor->tenant_id) || ! $actor->hasFunctions(['requisition_approve']) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||
return [];
|
||||
}
|
||||
$query = 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)->where('m.maintenance', false)
|
||||
->where(fn ($q) => $q->whereNull('m.expires_at')->orWhere('m.expires_at', '>', now()))->whereJsonContains('p.permissions', 'requisition_approve');
|
||||
if (app(WorkContext::class)->enforced($actor)) {
|
||||
$query->whereJsonContains('p.work_contexts', 'procurement.internal');
|
||||
}
|
||||
|
||||
return array_values($query->pluck('p.id')->map(fn ($id) => (int) $id)->all());
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $step */
|
||||
public function eligible(User $actor, Requisition $request, array $step): bool
|
||||
{
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->find($actor->id);
|
||||
if ($actor === null) {
|
||||
return false;
|
||||
}
|
||||
$routing = $step['routing'] ?? null;
|
||||
|
||||
return is_array($routing) && is_array($routing['profile_ids'] ?? null) && in_array($routing['scope'] ?? null, ['company', 'department'], true)
|
||||
&& preg_match('/^configured_[1-5]$/D', $step['role'] ?? '') === 1 && $actor->tenant_id === $request->tenant_id && $actor->id !== $request->requester_id
|
||||
&& ($routing['scope'] === 'company' || $actor->department_id === $request->department_id)
|
||||
&& array_intersect($routing['profile_ids'], $this->profiles($actor)) !== [];
|
||||
}
|
||||
|
||||
/** @param Builder<Requisition> $query */
|
||||
public function includeVisible(Builder $query, User $actor): void
|
||||
{
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->find($actor->id);
|
||||
if ($actor === null) {
|
||||
return;
|
||||
}
|
||||
$ids = $this->profiles($actor);
|
||||
if ($ids === []) {
|
||||
return;
|
||||
}
|
||||
$query->orWhereExists(function ($steps) use ($ids, $actor) {
|
||||
$steps->selectRaw('1')->from('approval_steps as configured_steps')->whereColumn('configured_steps.requisition_id', 'requisitions.id')
|
||||
->whereIn('configured_steps.role', ['configured_1', 'configured_2', 'configured_3', 'configured_4', 'configured_5'])
|
||||
->whereColumn('configured_steps.tenant_id', 'requisitions.tenant_id')->whereNotNull('configured_steps.routing')
|
||||
->where(function ($profiles) use ($ids) {
|
||||
foreach ($ids as $id) {
|
||||
$profiles->orWhereJsonContains('configured_steps.routing->profile_ids', $id);
|
||||
}
|
||||
})
|
||||
->where(fn ($scope) => $scope->where('configured_steps.routing->scope', 'company')->orWhere(fn ($department) => $department->where('configured_steps.routing->scope', 'department')->where('requisitions.department_id', $actor->department_id)));
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user