| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace App\Services;
- use App\Models\StudentContract;
- use Carbon\Carbon;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Facades\Storage;
- class StudentContractService
- {
- public function getAll(int $unitId, ?int $studentId = null): Collection
- {
- return StudentContract::with(['student.city', 'student.state'])
- ->where('unit_id', $unitId)
- ->when($studentId, fn ($q) => $q->where('student_id', $studentId))
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function findById(int $id): ?StudentContract
- {
- return StudentContract::find($id);
- }
- public function create(array $data): StudentContract
- {
- if (!empty($data['due_date'])) {
- $data['recurring_day'] = Carbon::parse($data['due_date'])->day;
- }
- return StudentContract::create($data);
- }
- public function update(int $id, array $data): ?StudentContract
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- if (!empty($data['due_date'])) {
- $data['recurring_day'] = Carbon::parse($data['due_date'])->day;
- }
- $model->update($data);
- return $model->fresh();
- }
- public function attachFile(int $id, $file): ?StudentContract
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- if ($model->file_url) {
- Storage::delete($model->file_url);
- }
- /** @var \Illuminate\Http\UploadedFile $file */
- $model->update([
- 'file_url' => $file->store('student-contracts'),
- 'file_type' => $file->getMimeType(),
- ]);
- return $model->fresh();
- }
- public function updateStatus(int $id, string $status): ?StudentContract
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- $model->update(['status' => $status]);
- return $model->fresh();
- }
- public function delete(int $id): bool
- {
- $model = $this->findById($id);
- if (!$model) {
- return false;
- }
- if ($model->file_url) {
- Storage::delete($model->file_url);
- }
- return $model->delete();
- }
- }
|