StudentService.php 6.9 KB

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