'Consultar obrigações a fornecedores', 'prepare' => 'Preparar reconhecimento de obrigações', 'validate' => 'Validar reconhecimento de forma independente', 'payments_view' => 'Consultar pagamentos e afectações', 'payment_prepare' => 'Registar um facto de pagamento', 'payment_confirm' => 'Confirmar um facto de pagamento', 'allocation_prepare' => 'Propor afectações a facturas', 'allocation_confirm' => 'Confirmar afectações', 'reversal_prepare' => 'Propor reversão de uma afectação', 'reversal_confirm' => 'Confirmar reversão de forma independente', 'general_ledger.view' => 'Consultar o diário, balancete e razão', 'general_ledger.prepare' => 'Preparar lançamento contabilístico', 'general_ledger.validate' => 'Rever lançamento de forma independente', 'general_ledger.post' => 'Aplicar o lançamento revisto', 'general_ledger.correct_prepare' => 'Preparar estorno e substituição', 'general_ledger.correct_validate' => 'Rever o par de correcção', 'general_ledger.correct_post' => 'Aplicar o par revisto', 'general_ledger.period_prepare' => 'Preparar conferência do período', 'general_ledger.period_validate' => 'Rever conferência de forma independente', 'general_ledger.period_close' => 'Aplicar o fecho revisto', ]; public const EFFECT_LABELS = [ 'supplier_payable.recognised' => 'Reconhecimento da obrigação', 'allocation.confirmed' => 'Afectação confirmada', 'allocation.reversed' => 'Reversão confirmada', 'journal.reversal' => 'Estorno exacto do original', 'journal.replacement' => 'Substituição do lançamento', ]; public function ready(): bool { return app(StandaloneRuntime::class)->enabled() && app(StandaloneRuntime::class)->feature('finance-configuration', DB::connection()) && class_exists(LedgerConfiguration::class, false) && (new \ReflectionClass(LedgerConfiguration::class))->getConstant('VERSION') === 'COMMON-FINANCE-CONFIGURATION-v1'; } private function actor(User $actor): User { abort_unless($this->ready(), 503); app(ConflictGuard::class)->lockCompany($actor); $actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Admin]); abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403); return $actor; } private function eligible(User $target): bool { $access = app(OrganizationAccess::class); $permissions = $access->active($target->tenant_id) ? $access->configuredPermissions($target, 'procurement.internal') : $access->permissions($target); return ! $access->maintenanceOnly($target) && array_intersect($permissions, ['admin', 'finance']) !== []; } private function writer(User $actor): LedgerConfiguration { return new LedgerConfiguration(DB::connection(), ['tenant_id' => (int) $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0], $actor->id, function (string $action, array $data) use ($actor) { $fresh = $this->actor($actor); if (isset($data['user_id'])) { if (! is_int($data['user_id']) || $data['user_id'] < 1) { throw new \InvalidArgumentException('Identificador nominativo inválido.'); } $target = User::query()->where('tenant_id', $fresh->tenant_id)->whereKey($data['user_id'])->lockForUpdate()->firstOrFail(); if ($action === 'access' && ($data['actions'] ?? []) !== [] && ! $this->eligible($target)) { throw ValidationException::withMessages(['user_id' => 'Atribua primeiro uma função de Finanças ou Administração no contexto de Compras internas. A manutenção temporária não recebe estes acessos.']); } } }, fn (string $action, array $before, array $after, array $result) => app(RequisitionWorkflow::class)->audit($actor, 'company.finance_configuration_changed', null, $before, ['configuration_action' => $action, 'result' => $result, 'configuration' => $after])); } /** @return array */ public function workspace(User $actor, ?int $selected = null, string $term = ''): array { return DB::transaction(function () use ($actor, $selected, $term) { $actor = $this->actor($actor); $writer = $this->writer($actor); $target = $selected === null ? null : User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($selected); $access = $target === null ? null : $writer->basis('access', $target->id); if ($access !== null) { $identities = array_values(array_unique(array_column($access['rows'], 'person'))); $access += ['user' => $target->only(['id', 'name', 'email']), 'eligible' => $this->eligible($target), 'person' => collect($access['rows'])->firstWhere('action', 'view')['person'] ?? ($identities[0] ?? ''), 'identity_inconsistent' => count($identities) > 1, 'actions' => array_values(array_intersect(array_column($access['rows'], 'action'), LedgerConfiguration::ACTIONS)), 'other_actions' => array_values(array_diff(array_column($access['rows'], 'action'), LedgerConfiguration::ACTIONS))]; } $needle = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($term)); $people = User::query()->where('tenant_id', $actor->tenant_id) ->when($needle !== '', fn ($query) => $query->where(fn ($filter) => $filter->whereRaw("LOWER(name) LIKE LOWER(?) ESCAPE '!'", ['%'.$needle.'%']) ->orWhereRaw("LOWER(email) LIKE LOWER(?) ESCAPE '!'", ['%'.$needle.'%']))) ->orderBy('name')->orderBy('id')->paginate(25, ['id', 'name', 'email'], 'users_page')->withQueryString(); $scope = ['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0]; $history = DB::table('gl_events')->where($scope)->where('kind', 'like', 'configuration.%')->orderByDesc('id') ->paginate(15, ['id', 'actor_id', 'kind', 'reason', 'previous', 'subsequent', 'created_at'], 'history_page')->withQueryString() ->through(fn ($row) => ['id' => (int) $row->id, 'actor_id' => (int) $row->actor_id, 'kind' => $row->kind, 'reason' => $row->reason, 'before' => json_decode($row->previous, true, 64, JSON_THROW_ON_ERROR), 'after' => json_decode($row->subsequent, true, 64, JSON_THROW_ON_ERROR), 'created_at' => $row->created_at]); return ['actorId' => $actor->id, 'tenantId' => $actor->tenant_id, 'users' => $people, 'selectedAccess' => $access, 'accounts' => $writer->basis('account'), 'periods' => $writer->basis('period'), 'rules' => $writer->basis('rule'), 'actions' => self::LABELS, 'effects' => self::EFFECT_LABELS, 'q' => $term, 'history' => $history]; }); } /** @param array $input * @return array */ public function save(User $actor, string $kind, array $input): array { abort_unless($this->ready(), 503); $rules = ['operation_key' => 'required|uuid', 'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:2000']; $rules += match ($kind) { 'access' => ['user_id' => 'required|integer|min:1', 'person' => 'present|nullable|string|max:160', 'actions' => 'present|array|list|max:20', 'actions.*' => ['required', 'string', 'distinct:strict', Rule::in(LedgerConfiguration::ACTIONS)]], 'account' => ['code' => 'required|string|max:80', 'label' => 'required|string|max:200', 'currency' => 'required|in:MZN', 'is_movement' => 'required|boolean'], 'period' => ['period_key' => 'required|string|max:80', 'starts_on' => 'required|date_format:Y-m-d', 'ends_on' => 'required|date_format:Y-m-d|after_or_equal:starts_on'], 'rule' => ['rule_key' => 'required|string|max:80', 'effect_type' => ['required', Rule::in(LedgerConfiguration::EFFECTS)], 'valid_from' => 'required|date_format:Y-m-d', 'valid_to' => 'required|date_format:Y-m-d|after_or_equal:valid_from', 'debit_account_id' => 'required|integer|min:1', 'credit_account_id' => 'required|integer|min:1|different:debit_account_id'], default => throw new \InvalidArgumentException('Unknown financial configuration action.'), }; $data = Validator::make($input, $rules)->validate(); $operation = strtolower($data['operation_key']); unset($data['operation_key']); if ($kind === 'access') { $data['user_id'] = (int) $data['user_id']; $data['person'] = $data['person'] ?? ''; sort($data['actions'], SORT_STRING); } elseif ($kind === 'account') { $data['is_movement'] = (bool) $data['is_movement']; } elseif ($kind === 'rule') { $data['debit_account_id'] = (int) $data['debit_account_id']; $data['credit_account_id'] = (int) $data['credit_account_id']; } return $this->writer($actor)->command($kind, $data, $operation); } }