StudentService.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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'] ?? null;
  78. $responsibleData = $data['responsible'] ?? null;
  79. $avatar = $data['avatar'] ?? null;
  80. unset($data['registration_draft_token'], $data['responsible']);
  81. if ($token === null) {
  82. return $this->registrationDraftService->executeWithoutDraft(
  83. $user,
  84. $data,
  85. fn (array $studentData, int $unitId): Student => $this->persistStudent(
  86. $studentData,
  87. $responsibleData,
  88. $unitId,
  89. ),
  90. );
  91. }
  92. return $this->registrationDraftService->consume(
  93. $user,
  94. $token,
  95. function (array $studentData, int $unitId) use ($responsibleData, $avatar): Student {
  96. if ($avatar !== null) {
  97. $studentData['avatar'] = $avatar;
  98. }
  99. return $this->persistStudent($studentData, $responsibleData, $unitId);
  100. },
  101. );
  102. }
  103. private function persistStudent(array $data, ?array $responsibleData, int $unitId): Student
  104. {
  105. $data = $this->handlePhoto($data);
  106. return DB::transaction(function () use ($data, $responsibleData, $unitId): Student {
  107. $student = (new Student)
  108. ->fill(array_merge($data, ['unit_id' => $unitId]))
  109. ->withResponsibleForCreation($responsibleData);
  110. $student->save();
  111. if ($responsibleData !== null) {
  112. $student->responsibles()->create($responsibleData);
  113. }
  114. return $student->load('responsibles');
  115. });
  116. }
  117. public function update(int $id, array $data): ?Student
  118. {
  119. $model = $this->findById($id);
  120. if (!$model) {
  121. return null;
  122. }
  123. $data = $this->handlePhoto($data, $model->photo_url);
  124. $model->update($data);
  125. return $model->fresh();
  126. }
  127. public function delete(int $id): bool
  128. {
  129. $model = $this->findById($id);
  130. if (!$model) {
  131. return false;
  132. }
  133. if ($model->photo_url) {
  134. Storage::delete($model->photo_url);
  135. }
  136. return $model->delete();
  137. }
  138. private function handlePhoto(array $data, ?string $oldPhotoPath = null): array
  139. {
  140. if (!isset($data['avatar'])) {
  141. return $data;
  142. }
  143. if ($data['avatar'] instanceof UploadedFile) {
  144. if ($oldPhotoPath) {
  145. Storage::delete($oldPhotoPath);
  146. }
  147. $data['photo_url'] = $data['avatar']->store('students/photos');
  148. } elseif (is_null($data['avatar'])) {
  149. if ($oldPhotoPath) {
  150. Storage::delete($oldPhotoPath);
  151. }
  152. $data['photo_url'] = null;
  153. }
  154. unset($data['avatar']);
  155. return $data;
  156. }
  157. private function resolveUnitId(User $user): int
  158. {
  159. $activeUnitId = request()->input('active_unit_id');
  160. if ($activeUnitId) {
  161. $unit = $user->units()->where('units.id', $activeUnitId)->first();
  162. abort_if(!$unit, 403, 'Unidade não autorizada para este usuário.');
  163. return $unit->id;
  164. }
  165. $unit = $user->units()->first();
  166. abort_if(!$unit, 403, 'Usuário sem unidade associada.');
  167. return $unit->id;
  168. }
  169. }