StudentService.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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('signature_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 getFranchisorStudents(array $unitIds = []): Collection
  108. {
  109. return Student::with('unit')
  110. ->when(! empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  111. ->orderBy('name')
  112. ->get();
  113. }
  114. public function getFranchisorStudentDetail(int $id): ?array
  115. {
  116. $student = Student::with('unit')->find($id);
  117. if (! $student) {
  118. return null;
  119. }
  120. $contract = StudentContract::latestVersion()
  121. ->where('student_id', $id)
  122. ->where('status', 'active')
  123. ->first();
  124. return [
  125. 'id' => $student->id,
  126. 'name' => $student->name,
  127. 'phone' => $student->phone,
  128. 'unit' => $student->unit ? ['fantasy_name' => $student->unit->fantasy_name] : null,
  129. 'protocol' => $contract?->protocol,
  130. ];
  131. }
  132. public function getFranchisorSummary(array $unitIds = []): array
  133. {
  134. $query = Student::query()->when(! empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds));
  135. $total = $query->count();
  136. $active = (clone $query)->where('status', 'active')->count();
  137. $byStatus = [
  138. 'lead' => (clone $query)->where('status', Student::STATUS_LEAD)->count(),
  139. 'active' => $active,
  140. 'ex_student' => (clone $query)->where('status', Student::STATUS_EX_STUDENT)->count(),
  141. 'locked' => (clone $query)->where('status', Student::STATUS_LOCKED)->count(),
  142. ];
  143. return ['total' => $total, 'active' => $active, 'by_status' => $byStatus];
  144. }
  145. //
  146. private function handlePhoto(array $data, ?string $oldPhotoPath = null): array
  147. {
  148. if (! isset($data['avatar'])) {
  149. return $data;
  150. }
  151. if ($data['avatar'] instanceof UploadedFile) {
  152. if ($oldPhotoPath) {
  153. Storage::delete($oldPhotoPath);
  154. }
  155. $data['photo_url'] = $data['avatar']->store('students/photos');
  156. } elseif (is_null($data['avatar'])) {
  157. if ($oldPhotoPath) {
  158. Storage::delete($oldPhotoPath);
  159. }
  160. $data['photo_url'] = null;
  161. }
  162. unset($data['avatar']);
  163. return $data;
  164. }
  165. private function persistStudent(array $data, ?array $responsibleData, int $unitId): Student
  166. {
  167. $data = $this->handlePhoto($data);
  168. return DB::transaction(function () use ($data, $responsibleData, $unitId): Student {
  169. $student = (new Student)
  170. ->fill(array_merge($data, ['unit_id' => $unitId]))
  171. ->withResponsibleForCreation($responsibleData);
  172. $student->save();
  173. if ($responsibleData !== null) {
  174. $student->responsibles()->create($responsibleData);
  175. }
  176. return $student->load('responsibles');
  177. });
  178. }
  179. private function resolveUnitId(User $user): int
  180. {
  181. $activeUnitId = request()->input('active_unit_id');
  182. if ($activeUnitId) {
  183. $unit = $user->units()->where('units.id', $activeUnitId)->first();
  184. abort_if(! $unit, 403, 'Unidade não autorizada para este usuário.');
  185. return $unit->id;
  186. }
  187. $unit = $user->units()->first();
  188. abort_if(! $unit, 403, 'Usuário sem unidade associada.');
  189. return $unit->id;
  190. }
  191. }