StudentContractService.php 2.3 KB

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