StudentService.php 5.2 KB

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