AppointmentService.php 9.1 KB

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