StudentContractService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App\Services;
  3. use App\Models\StudentContract;
  4. use Illuminate\Database\Eloquent\Collection;
  5. use Illuminate\Support\Facades\Storage;
  6. class StudentContractService
  7. {
  8. public function getAll(int $unitId, ?int $studentId = null): Collection
  9. {
  10. return StudentContract::with(['student.city', 'student.state', 'classPackageUnit'])
  11. ->where('unit_id', $unitId)
  12. ->when($studentId, fn ($q) => $q->where('student_id', $studentId))
  13. ->orderBy('created_at', 'desc')
  14. ->get();
  15. }
  16. public function findById(int $id): ?StudentContract
  17. {
  18. return StudentContract::find($id);
  19. }
  20. public function create(array $data): StudentContract
  21. {
  22. if (!empty($data['due_day'])) {
  23. $data['recurring_day'] = (int) $data['due_day'];
  24. }
  25. unset($data['due_day']);
  26. return StudentContract::create($data);
  27. }
  28. public function update(int $id, array $data): ?StudentContract
  29. {
  30. $model = $this->findById($id);
  31. if (!$model) {
  32. return null;
  33. }
  34. if (!empty($data['due_day'])) {
  35. $data['recurring_day'] = (int) $data['due_day'];
  36. }
  37. unset($data['due_day']);
  38. $model->update($data);
  39. return $model->fresh();
  40. }
  41. public function attachFile(int $id, $file): ?StudentContract
  42. {
  43. $model = $this->findById($id);
  44. if (!$model) {
  45. return null;
  46. }
  47. if ($model->file_url) {
  48. Storage::delete($model->file_url);
  49. }
  50. /** @var \Illuminate\Http\UploadedFile $file */
  51. $model->update([
  52. 'file_url' => $file->store('student-contracts'),
  53. 'file_type' => $file->getMimeType(),
  54. ]);
  55. return $model->fresh();
  56. }
  57. public function updateStatus(int $id, string $status): ?StudentContract
  58. {
  59. $model = $this->findById($id);
  60. if (!$model) {
  61. return null;
  62. }
  63. $model->update(['status' => $status]);
  64. return $model->fresh();
  65. }
  66. public function delete(int $id): bool
  67. {
  68. $model = $this->findById($id);
  69. if (!$model) {
  70. return false;
  71. }
  72. if ($model->file_url) {
  73. Storage::delete($model->file_url);
  74. }
  75. return $model->delete();
  76. }
  77. }