AppointmentService.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\AppointmentStatusEnum;
  4. use App\Enums\NotificationRecipientEnum;
  5. use App\Models\Appointment;
  6. use Carbon\Carbon;
  7. use Illuminate\Database\Eloquent\Collection;
  8. use Illuminate\Pagination\LengthAwarePaginator;
  9. use Illuminate\Support\Str;
  10. class AppointmentService
  11. {
  12. public function __construct(protected NotificationService $notificationService) {}
  13. public function getAll(): Collection
  14. {
  15. return Appointment::with(['user', 'partnerAgreement', 'partnerAgreementService'])
  16. ->orderBy('date', 'desc')
  17. ->get();
  18. }
  19. public function getAllByUser(int $userId): Collection
  20. {
  21. return Appointment::with(['partnerAgreement', 'partnerAgreementService'])
  22. ->where('user_id', $userId)
  23. ->orderBy('date', 'desc')
  24. ->get();
  25. }
  26. public function getAllByPartnerUser(int $userId): Collection
  27. {
  28. return Appointment::with(['user', 'partnerAgreement', 'partnerAgreementService'])
  29. ->whereHas('partnerAgreement', fn($q) => $q->where('user_id', $userId))
  30. ->orderBy('date', 'desc')
  31. ->get();
  32. }
  33. public function findById(int $id): ?Appointment
  34. {
  35. return Appointment::with(['user', 'partnerAgreement', 'partnerAgreementService'])->find($id);
  36. }
  37. public function create(array $data): Appointment
  38. {
  39. $data['order_number'] = $this->generateOrderNumber();
  40. $data['requested_at'] = now();
  41. return Appointment::create($data);
  42. }
  43. public function notifyCreation(Appointment $model): void
  44. {
  45. $dateStr = $model->date ? Carbon::parse($model->date)->format('d/m/Y') : null;
  46. $message = $dateStr
  47. ? "Um agendamento #{$model->order_number} foi criado para você" . ($model->time ? " para {$dateStr} às {$model->time}" : " em {$dateStr}") . "."
  48. : "Um agendamento #{$model->order_number} foi criado para você.";
  49. $this->notificationService->createAutoForUser([
  50. 'title' => 'Novo agendamento',
  51. 'message' => $message,
  52. 'recipient' => NotificationRecipientEnum::ASSOCIADO,
  53. 'source' => 'appointment',
  54. 'source_id' => $model->id,
  55. ], $model->user_id);
  56. }
  57. public function update(int $id, array $data, ?int $approvingUserId = null): ?Appointment
  58. {
  59. $model = Appointment::find($id);
  60. if (!$model) {
  61. return null;
  62. }
  63. if (
  64. isset($data['status'])
  65. && $data['status'] === AppointmentStatusEnum::CONFIRMADO->value
  66. && $model->status !== AppointmentStatusEnum::CONFIRMADO
  67. ) {
  68. $data['auto_approved'] = false;
  69. $data['approved_by_user_id'] = $approvingUserId;
  70. }
  71. $model->update($data);
  72. return $model->fresh(['user', 'partnerAgreement', 'partnerAgreementService']);
  73. }
  74. public function delete(int $id): bool
  75. {
  76. $model = Appointment::find($id);
  77. if (!$model) {
  78. return false;
  79. }
  80. return $model->delete();
  81. }
  82. public function getAdminCounters(): array
  83. {
  84. return [
  85. 'pendentes' => Appointment::where('status', AppointmentStatusEnum::PENDENTE)->count(),
  86. 'aprovados' => Appointment::where('status', AppointmentStatusEnum::CONFIRMADO)->count(),
  87. 'recusados' => Appointment::where('status', AppointmentStatusEnum::RECUSADO)->count(),
  88. ];
  89. }
  90. public function getAllPaginated(array $filters = [], int $perPage = 10): LengthAwarePaginator
  91. {
  92. $query = Appointment::with(['user', 'partnerAgreement', 'partnerAgreementService'])
  93. ->orderBy('requested_at', 'desc');
  94. if (!empty($filters['status'])) {
  95. $query->where('status', $filters['status']);
  96. }
  97. if (!empty($filters['search'])) {
  98. $term = '%' . mb_strtolower($filters['search']) . '%';
  99. $query->where(function ($q) use ($term) {
  100. $q->whereHas('user', function ($uq) use ($term) {
  101. $uq->whereRaw('UNACCENT(LOWER(name)) LIKE UNACCENT(?)', [$term]);
  102. })->orWhereHas('partnerAgreement', function ($pq) use ($term) {
  103. $pq->whereRaw('UNACCENT(LOWER(COALESCE(trade_name, company_name))) LIKE UNACCENT(?)', [$term]);
  104. })->orWhereHas('partnerAgreementService', function ($sq) use ($term) {
  105. $sq->whereRaw('UNACCENT(LOWER(name)) LIKE UNACCENT(?)', [$term]);
  106. })->orWhereRaw('UNACCENT(LOWER(order_number)) LIKE UNACCENT(?)', [$term]);
  107. });
  108. }
  109. return $query->paginate($perPage);
  110. }
  111. public function approve(int $id, string $date, string $time, ?int $approvedByUserId = null): ?Appointment
  112. {
  113. $model = Appointment::find($id);
  114. if (!$model) return null;
  115. $model->update([
  116. 'status' => AppointmentStatusEnum::CONFIRMADO,
  117. 'date' => $date,
  118. 'time' => $time,
  119. 'auto_approved' => false,
  120. 'approved_by_user_id' => $approvedByUserId,
  121. ]);
  122. $this->notificationService->createAutoForUser([
  123. 'title' => 'Agendamento confirmado',
  124. 'message' => "Seu agendamento #{$model->order_number} foi confirmado para " . Carbon::parse($date)->format('d/m/Y') . " às {$time}.",
  125. 'recipient' => NotificationRecipientEnum::ASSOCIADO,
  126. 'source' => 'appointment',
  127. 'source_id' => $model->id,
  128. ], $model->user_id);
  129. return $model->fresh(['user', 'partnerAgreement', 'partnerAgreementService']);
  130. }
  131. public function reject(int $id): ?Appointment
  132. {
  133. $model = Appointment::find($id);
  134. if (!$model) return null;
  135. $model->update(['status' => AppointmentStatusEnum::RECUSADO]);
  136. $this->notificationService->createAutoForUser([
  137. 'title' => 'Agendamento recusado',
  138. 'message' => "Seu agendamento #{$model->order_number} foi recusado.",
  139. 'recipient' => NotificationRecipientEnum::ASSOCIADO,
  140. 'source' => 'appointment',
  141. 'source_id' => $model->id,
  142. ], $model->user_id);
  143. return $model->fresh(['user', 'partnerAgreement', 'partnerAgreementService']);
  144. }
  145. public function approveByPartner(int $id, int $userId, string $date, string $time): ?Appointment
  146. {
  147. $model = Appointment::whereHas('partnerAgreement', fn($q) => $q->where('user_id', $userId))->find($id);
  148. if (!$model) return null;
  149. $model->update([
  150. 'status' => AppointmentStatusEnum::CONFIRMADO,
  151. 'date' => $date,
  152. 'time' => $time,
  153. 'auto_approved' => false,
  154. 'approved_by_user_id' => $userId,
  155. ]);
  156. $this->notificationService->createAutoForUser([
  157. 'title' => 'Agendamento confirmado',
  158. 'message' => "Seu agendamento #{$model->order_number} foi confirmado para " . Carbon::parse($date)->format('d/m/Y') . " às {$time}.",
  159. 'recipient' => NotificationRecipientEnum::ASSOCIADO,
  160. 'source' => 'appointment',
  161. 'source_id' => $model->id,
  162. ], $model->user_id);
  163. return $model->fresh(['user', 'partnerAgreement', 'partnerAgreementService']);
  164. }
  165. public function rejectByPartner(int $id, int $userId): ?Appointment
  166. {
  167. $model = Appointment::whereHas('partnerAgreement', fn($q) => $q->where('user_id', $userId))->find($id);
  168. if (!$model) return null;
  169. $model->update(['status' => AppointmentStatusEnum::RECUSADO]);
  170. $this->notificationService->createAutoForUser([
  171. 'title' => 'Agendamento recusado',
  172. 'message' => "Seu agendamento #{$model->order_number} foi recusado.",
  173. 'recipient' => NotificationRecipientEnum::ASSOCIADO,
  174. 'source' => 'appointment',
  175. 'source_id' => $model->id,
  176. ], $model->user_id);
  177. return $model->fresh(['user', 'partnerAgreement', 'partnerAgreementService']);
  178. }
  179. private function generateOrderNumber(): string
  180. {
  181. do {
  182. $number = 'AGD-' . strtoupper(Str::random(8));
  183. } while (Appointment::where('order_number', $number)->exists());
  184. return $number;
  185. }
  186. }