StudentService.php 7.0 KB

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