SupportRequestService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\SupportRequestStatusEnum;
  4. use App\Mail\SupportRequestAlert;
  5. use App\Models\SupportRequest;
  6. use Illuminate\Pagination\LengthAwarePaginator;
  7. use Illuminate\Support\Facades\Log;
  8. use Illuminate\Support\Facades\Mail;
  9. class SupportRequestService
  10. {
  11. public function paginate(
  12. ?string $status = null,
  13. ?string $search = null,
  14. int $page = 1,
  15. int $perPage = 10,
  16. ): LengthAwarePaginator {
  17. return SupportRequest::query()
  18. ->with('handler:id,name')
  19. ->when($status, fn ($query) => $query->where('status', $status))
  20. ->when($search, function ($query) use ($search) {
  21. $query->where(function ($sub) use ($search) {
  22. $sub->where('title', 'like', "%{$search}%")
  23. ->orWhere('name', 'like', "%{$search}%")
  24. ->orWhere('email', 'like', "%{$search}%");
  25. });
  26. })
  27. ->orderByRaw("CASE status WHEN 'pending' THEN 0 WHEN 'in_progress' THEN 1 WHEN 'resolved' THEN 2 ELSE 3 END")
  28. ->orderBy('created_at', 'desc')
  29. ->paginate($perPage, ['*'], 'page', $page);
  30. }
  31. public function findById(int $id): ?SupportRequest
  32. {
  33. return SupportRequest::with('handler')->find($id);
  34. }
  35. public function create(array $data): SupportRequest
  36. {
  37. $data['status'] ??= SupportRequestStatusEnum::PENDING->value;
  38. $supportRequest = SupportRequest::create($data);
  39. $this->sendAlert($supportRequest);
  40. return $supportRequest;
  41. }
  42. public function updateStatus(int $id, string $status, ?int $handledBy = null): ?SupportRequest
  43. {
  44. $supportRequest = $this->findById($id);
  45. if (! $supportRequest) {
  46. return null;
  47. }
  48. $payload = ['status' => $status];
  49. if ($status === SupportRequestStatusEnum::IN_PROGRESS->value && ! $supportRequest->handled_by) {
  50. $payload['handled_by'] = $handledBy;
  51. }
  52. $payload['resolved_at'] = $status === SupportRequestStatusEnum::RESOLVED->value ? now() : null;
  53. $supportRequest->update($payload);
  54. return $supportRequest->fresh('handler');
  55. }
  56. private function sendAlert(SupportRequest $supportRequest): void
  57. {
  58. $recipient = config('services.support.email');
  59. if (! $recipient) {
  60. return;
  61. }
  62. try {
  63. Mail::to($recipient)->send(new SupportRequestAlert($supportRequest));
  64. } catch (\Throwable $e) {
  65. // Alerta é best-effort: o registro no backoffice continua sendo a fonte da verdade.
  66. Log::error('Support request alert email failed', [
  67. 'support_request_id' => $supportRequest->id,
  68. 'error' => $e->getMessage(),
  69. ]);
  70. }
  71. }
  72. }