StudentContractService.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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::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_date'])) {
  23. $data['recurring_day'] = Carbon::parse($data['due_date'])->day;
  24. }
  25. return StudentContract::create($data);
  26. }
  27. public function update(int $id, array $data): ?StudentContract
  28. {
  29. $model = $this->findById($id);
  30. if (!$model) {
  31. return null;
  32. }
  33. if (!empty($data['due_date'])) {
  34. $data['recurring_day'] = Carbon::parse($data['due_date'])->day;
  35. }
  36. $model->update($data);
  37. return $model->fresh();
  38. }
  39. public function attachFile(int $id, $file): ?StudentContract
  40. {
  41. $model = $this->findById($id);
  42. if (!$model) {
  43. return null;
  44. }
  45. if ($model->file_url) {
  46. Storage::delete($model->file_url);
  47. }
  48. /** @var \Illuminate\Http\UploadedFile $file */
  49. $model->update([
  50. 'file_url' => $file->store('student-contracts'),
  51. 'file_type' => $file->getMimeType(),
  52. ]);
  53. return $model->fresh();
  54. }
  55. public function delete(int $id): bool
  56. {
  57. $model = $this->findById($id);
  58. if (!$model) {
  59. return false;
  60. }
  61. if ($model->file_url) {
  62. Storage::delete($model->file_url);
  63. }
  64. return $model->delete();
  65. }
  66. }