File manager - Edit - /var/www/html/portalHomolog/app/Http/Resources/Accounts/LinhasDoTempo/LinhasDoTempoResource.php
Back
<?php namespace App\Http\Resources\Accounts\LinhasDoTempo; use App\Models\Accounts\LinhasDoTempo\AuditLog; use App\Models\Accounts\LinhasDoTempo\HistoricalPoint; use App\Models\Accounts\LinhasDoTempo\Note; use App\Models\Accounts\LinhasDoTempo\Timeline; use App\Models\User; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; /** * Regras de negócio, auditoria e utilidades do módulo Linhas do Tempo. */ class LinhasDoTempoResource { /** * Indica se o usuário pode gerenciar (editar/excluir) a linha do tempo. */ public function canManageTimeline(User $user, Timeline $timeline): bool { if ($timeline->user_id === $user->id) { return true; } $lista = collect($user->listaPermissoes()); if ($lista->contains('SYSADMIN')) { return true; } return ($user->getAttribute('permission') ?? '') === 'ADMIN'; } /** * Indica se o usuário pode apenas visualizar a linha (inclui dono e perfis amplos). */ public function canViewTimeline(User $user, Timeline $timeline): bool { return $this->canManageTimeline($user, $timeline); } /** * Administrador institucional (painel) com coluna permission ADMIN. */ public function isInstitutionalAdmin(User $user): bool { return ($user->getAttribute('permission') ?? '') === 'ADMIN'; } /** * Pode listar timelines de todos os usuários (admin institucional / SYSADMIN). */ public function canViewAllTimelines(User $user): bool { if ($this->isInstitutionalAdmin($user)) { return true; } return collect($user->listaPermissoes())->contains('SYSADMIN'); } /** * Sanitiza HTML do campo "Processo" (RF-02, RF-07): texto longo da linha ou do ponto histórico. */ public function sanitizeProcessHtml(?string $html): string { if ($html === null || $html === '') { return ''; } $allowed = '<p><br><strong><b><em><i><u><ul><ol><li><a><h1><h2><h3><h4><blockquote><span><div>'; $clean = strip_tags($html, $allowed); return $clean; } /** * Campo opcional "Descrição / resumo" (RF-02), persistido em {@see Timeline::$description}. */ public function normalizeShortProcessField(mixed $value): ?string { if ($value === null) { return null; } $s = trim(strip_tags((string) $value)); return $s === '' ? null : mb_substr($s, 0, 300); } /** * Converte entrada de tags (texto) em array de strings. * * @return list<string> */ public function parseTagsInput(?string $input): array { if ($input === null || trim($input) === '') { return []; } $parts = preg_split('/[,;]+/u', $input) ?: []; $out = []; foreach ($parts as $p) { $t = trim($p); if ($t !== '' && mb_strlen($t) <= 64) { $out[] = $t; } } return array_values(array_unique($out)); } /** * Verifica duplicidade de ponto (RN-09): mesmo nome e mesma data/hora de acontecimento. */ public function historicalPointIsDuplicate(Timeline $timeline, string $name, mixed $eventDate, ?string $ignorePointId = null): bool { $eventAt = is_string($eventDate) ? $eventDate : (\Carbon\Carbon::parse($eventDate)->format('Y-m-d H:i:s')); $q = HistoricalPoint::query() ->where('timeline_id', $timeline->id) ->whereNull('deleted_at') ->whereRaw('LOWER(TRIM(name)) = ?', [mb_strtolower(trim($name))]) ->where('event_date', $eventAt); if ($ignorePointId !== null) { $q->where('id', '!=', $ignorePointId); } return $q->exists(); } /** * Garante que a nota ainda pode ser editada ou excluída (RN-04: bloqueio após 24h). * * @throws \Illuminate\Validation\ValidationException */ public function assertNoteIsMutable(Note $note): void { if ($note->created_at === null) { return; } if ($note->created_at->lt(now()->subDay())) { throw ValidationException::withMessages([ 'content' => [__('Esta nota não pode mais ser alterada após 24 horas. Crie uma nova nota.')], ]); } } /** * Registra auditoria (RF-14). */ public function logAudit(?string $userId, string $auditableType, string $auditableId, string $action, ?string $field = null, ?string $oldValue = null, ?string $newValue = null): void { try { AuditLog::query()->create([ 'user_id' => $userId, 'auditable_type' => $auditableType, 'auditable_id' => $auditableId, 'action' => $action, 'field' => $field, 'old_value' => $oldValue !== null ? Str::limit($oldValue, 65000) : null, 'new_value' => $newValue !== null ? Str::limit($newValue, 65000) : null, ]); } catch (\Throwable $e) { Log::warning('LinhasDoTempoResource: falha ao gravar auditoria', [ 'error' => $e->getMessage(), ]); } } /** * Registra alterações simples em modelo (campos fillable). * * @param array<string, mixed> $old * @param array<string, mixed> $new */ public function logModelChanges(?string $userId, object $model, string $auditableType, array $old, array $new, array $watchKeys): void { foreach ($watchKeys as $key) { $o = $old[$key] ?? null; $n = $new[$key] ?? null; if ((string) $o !== (string) $n) { $this->logAudit($userId, $auditableType, (string) $model->getKey(), 'update', $key, is_scalar($o) ? (string) $o : json_encode($o), is_scalar($n) ? (string) $n : json_encode($n)); } } } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.28 | Generation time: 0.02 |
proxy
|
phpinfo
|
Settings