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 $write = false): User { abort_unless($this->ready(), 503); app(ConflictGuard::class)->lockCompany($actor); $actor = app(CurrentActor::class)->lock($actor); abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403); // Reuse the native equipment register's capabilities and departmental scope. abort_unless($actor->hasFunctions($write ? ['admin', 'warehouse', 'procurement'] : ['admin', 'warehouse', 'procurement', 'finance', 'department_head']), 403); return $actor; } /** @return Builder */ private function visible(User $actor): Builder { return app(SupplyPlanning::class)->latest('capital_register') ->when($actor->departmentScoped(), fn ($q) => $q->where('data->department_id', $actor->department_id)); } /** @return array */ public function workspace(User $actor, ?string $historyKey = null): array { return DB::transaction(function () use ($actor, $historyKey) { $actor = $this->actor($actor); if ($historyKey !== null) { $this->visible($actor)->where('record_key', $historyKey)->firstOrFail(); } $departments = Department::query()->when($actor->departmentScoped(), fn ($q) => $q->whereKey($actor->department_id)); $equipment = Equipment::query()->when($actor->departmentScoped(), fn ($q) => $q->where('department_id', $actor->department_id)); return ['records' => $this->visible($actor)->orderBy('data->code')->paginate(15)->withQueryString(), 'history' => $historyKey === null ? null : SupplyRecord::query()->where('kind', 'capital_register')->where('record_key', $historyKey) ->orderByDesc('version')->paginate(15, ['*'], 'history_page')->withQueryString(), 'trace' => $historyKey === null ? null : app(CapitalTrace::class)->workspace($actor, $historyKey), 'departments' => $departments->orderBy('name')->get(['id', 'name']), 'equipment' => $equipment->orderBy('code')->get(['id', 'code', 'description', 'department_id']), 'canManage' => $actor->hasFunctions(['admin', 'warehouse', 'procurement']), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id]; }); } /** @param array $input */ public function save(User $actor, array $input): SupplyRecord { $input = array_map(fn ($v) => is_string($v) ? trim($v) : $v, $input); $input['code'] = is_string($input['code'] ?? null) ? Str::upper($input['code']) : ($input['code'] ?? null); $data = Validator::make(['record_key' => null, 'equipment_id' => null, ...$input], [ 'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0', 'type' => 'required|in:project,asset', 'code' => ['required', 'string', 'regex:/^[A-Z0-9][A-Z0-9._-]{0,39}$/D'], 'name' => 'required|string|min:3|max:200', 'department_id' => 'required|integer|min:1', 'equipment_id' => 'nullable|integer|min:1', 'reference' => 'required|string|min:3|max:1000', 'state' => 'required|in:active,archived', 'reason' => 'required|string|min:10|max:4000', ])->validate(); $data['operation_key'] = strtolower($data['operation_key']); $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 === 'capital_register' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409); return $retry; } $old = $data['record_key'] === null ? null : $this->visible($actor)->where('record_key', $data['record_key'])->firstOrFail(); abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'O cadastro mudou. Reveja a versão actual.'); $department = Department::query()->when($actor->departmentScoped(), fn ($q) => $q->whereKey($actor->department_id))->whereKey($data['department_id'])->firstOrFail(); if ($old !== null && ($old->data['type'] !== $data['type'] || $old->data['code'] !== $data['code'])) { throw ValidationException::withMessages(['code' => 'Preserve o tipo e o código da identidade já registada.']); } if ($old === null && SupplyRecord::query()->where('kind', 'capital_register')->where('data->type', $data['type'])->where('data->code', $data['code'])->exists()) { throw ValidationException::withMessages(['code' => 'Este código já existe, incluindo no histórico arquivado.']); } $equipment = null; if ($data['equipment_id'] !== null) { abort_unless($data['type'] === 'asset', 422); $equipment = Equipment::query()->where('department_id', $department->id)->whereKey($data['equipment_id'])->firstOrFail(); if (SupplyRecord::query()->where('kind', 'capital_register')->where('data->equipment_id', $equipment->id) ->when($old !== null, fn ($q) => $q->where('record_key', '!=', $old->record_key))->exists()) { throw ValidationException::withMessages(['equipment_id' => 'Este equipamento já está identificado noutra referência de imobilizado.']); } if ($old !== null && ($old->data['equipment_id'] ?? null) !== null && (int) $data['equipment_id'] !== $old->data['equipment_id']) { throw ValidationException::withMessages(['equipment_id' => 'Preserve a ligação ao equipamento já identificado.']); } } elseif (($old?->data['equipment_id'] ?? null) !== null) { throw ValidationException::withMessages(['equipment_id' => 'Preserve a ligação ao equipamento já identificado.']); } $canonical = ['type' => $data['type'], 'code' => $data['code'], 'name' => $data['name'], 'department_id' => $department->id, 'equipment_id' => $equipment?->id, 'reference' => $data['reference']]; $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'capital_register', 'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => $data['state'], 'created_by' => $actor->id, 'data' => $canonical, 'snapshot' => ['department' => $department->only(['id', 'name']), 'equipment' => $equipment?->only(['id', 'code', 'description', 'version']), 'accounting_effects' => false, 'source_system' => 'compras'], 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]); app(RequisitionWorkflow::class)->audit($actor, 'capital.register_recorded', null, $old?->toArray(), ['record' => $record->toArray()]); return $record; }); } }