StudentService.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Student;
  4. use App\Models\StudentContract;
  5. use App\Models\User;
  6. use Illuminate\Database\Eloquent\Collection;
  7. use Illuminate\Http\UploadedFile;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Storage;
  10. class StudentService
  11. {
  12. public function __construct(
  13. private readonly StudentRegistrationDraftService $registrationDraftService,
  14. ) {}
  15. public function getAll(User $user, array $filters = []): Collection
  16. {
  17. $unitId = $this->resolveUnitId($user);
  18. $startDate = $filters['contract_start_date'] ?? null;
  19. $endDate = $filters['contract_end_date'] ?? null;
  20. return Student::where('unit_id', $unitId)
  21. ->when($startDate || $endDate, function ($query) use ($startDate, $endDate) {
  22. $query->whereHas('contracts', function ($contractQuery) use ($startDate, $endDate) {
  23. $contractQuery->where('status', 'active');
  24. if ($endDate) {
  25. $contractQuery->where('started_date', '<=', $endDate);
  26. }
  27. if ($startDate) {
  28. $contractQuery->where(function ($periodQuery) use ($startDate) {
  29. $periodQuery
  30. ->whereNull('end_date')
  31. ->orWhere('end_date', '>=', $startDate);
  32. });
  33. }
  34. });
  35. })
  36. ->orderBy('created_at', 'desc')
  37. ->get();
  38. }
  39. public function getFranchisorActive(array $unitIds = []): Collection
  40. {
  41. return Student::with('unit')
  42. ->whereHas('contracts', fn ($q) => $q->where('status', 'active'))
  43. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  44. ->orderBy('name')
  45. ->get();
  46. }
  47. public function getFranchisorStudentDetail(int $id): ?array
  48. {
  49. $student = Student::with('unit')->find($id);
  50. if (!$student) {
  51. return null;
  52. }
  53. $contract = StudentContract::where('student_id', $id)
  54. ->where('status', 'active')
  55. ->first();
  56. return [
  57. 'id' => $student->id,
  58. 'name' => $student->name,
  59. 'phone' => $student->phone,
  60. 'unit' => $student->unit ? ['fantasy_name' => $student->unit->fantasy_name] : null,
  61. 'protocol' => $contract?->protocol,
  62. ];
  63. }
  64. public function getFranchisorSummary(array $unitIds = []): array
  65. {
  66. $query = Student::query()->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds));
  67. $total = $query->count();
  68. $active = (clone $query)->where('status', 'active')->count();
  69. return ['total' => $total, 'active' => $active];
  70. }
  71. public function findById(int $id): ?Student
  72. {
  73. return Student::find($id);
  74. }
  75. public function create(User $user, array $data): Student
  76. {
  77. $token = $data['registration_draft_token'];
  78. $responsibleData = $data['responsible'] ?? null;
  79. $avatar = $data['avatar'] ?? null;
  80. return $this->registrationDraftService->consume(
  81. $user,
  82. $token,
  83. function (array $studentData, int $unitId) use ($responsibleData, $avatar): Student {
  84. if ($avatar !== null) {
  85. $studentData['avatar'] = $avatar;
  86. }
  87. $studentData = $this->handlePhoto($studentData);
  88. return DB::transaction(function () use ($studentData, $responsibleData, $unitId): Student {
  89. $student = (new Student)
  90. ->fill(array_merge($studentData, ['unit_id' => $unitId]))
  91. ->withResponsibleForCreation($responsibleData);
  92. $student->save();
  93. if ($responsibleData !== null) {
  94. $student->responsibles()->create($responsibleData);
  95. }
  96. return $student->load('responsibles');
  97. });
  98. },
  99. );
  100. }
  101. public function update(int $id, array $data): ?Student
  102. {
  103. $model = $this->findById($id);
  104. if (!$model) {
  105. return null;
  106. }
  107. $data = $this->handlePhoto($data, $model->photo_url);
  108. $model->update($data);
  109. return $model->fresh();
  110. }
  111. public function delete(int $id): bool
  112. {
  113. $model = $this->findById($id);
  114. if (!$model) {
  115. return false;
  116. }
  117. if ($model->photo_url) {
  118. Storage::delete($model->photo_url);
  119. }
  120. return $model->delete();
  121. }
  122. private function handlePhoto(array $data, ?string $oldPhotoPath = null): array
  123. {
  124. if (!isset($data['avatar'])) {
  125. return $data;
  126. }
  127. if ($data['avatar'] instanceof UploadedFile) {
  128. if ($oldPhotoPath) {
  129. Storage::delete($oldPhotoPath);
  130. }
  131. $data['photo_url'] = $data['avatar']->store('students/photos');
  132. } elseif (is_null($data['avatar'])) {
  133. if ($oldPhotoPath) {
  134. Storage::delete($oldPhotoPath);
  135. }
  136. $data['photo_url'] = null;
  137. }
  138. unset($data['avatar']);
  139. return $data;
  140. }
  141. private function resolveUnitId(User $user): int
  142. {
  143. $activeUnitId = request()->input('active_unit_id');
  144. if ($activeUnitId) {
  145. $unit = $user->units()->where('units.id', $activeUnitId)->first();
  146. abort_if(!$unit, 403, 'Unidade não autorizada para este usuário.');
  147. return $unit->id;
  148. }
  149. $unit = $user->units()->first();
  150. abort_if(!$unit, 403, 'Usuário sem unidade associada.');
  151. return $unit->id;
  152. }
  153. }