Attendance::student()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace App\Models;
4
5
use App\Jobs\WatchAttendance;
6
use Illuminate\Database\Eloquent\Model;
7
use Spatie\Activitylog\Traits\LogsActivity;
8
9
/**
10
 * @mixin IdeHelperAttendance
11
 */
12
class Attendance extends Model
13
{
14
    use LogsActivity;
15
16
    protected $guarded = ['id'];
17
18
    protected $with = ['attendance_type'];
19
20
    protected static bool $logUnguarded = true;
21
22
    protected static function boot()
23
    {
24
        parent::boot();
25
26
        // when an attendance record is added, we check if this is an absence
27
        static::saved(function (self $attendance) {
28
            if (config('app.send_emails_for_absences') && $attendance->attendance_type_id == 4) { // todo move to configurable settings
29
                // Log::info('Absence marked for student '.$attendance->student->name);
30
                // will check the record again and send a notification if it hasn't changed
31
                WatchAttendance::dispatch($attendance)
32
                ->delay(now()); // todo move to configurable settings
33
            }
34
        });
35
    }
36
37
    /** RELATIONS */
38
    public function student()
39
    {
40
        return $this->belongsTo(Student::class);
41
    }
42
43
    /** event = one instance of the course */
44
    public function event()
45
    {
46
        return $this->belongsTo(Event::class);
47
    }
48
49
    public function attendance_type()
50
    {
51
        return $this->belongsTo(AttendanceType::class);
52
    }
53
54
    /** METHODS */
55
56
    /**
57
     * get absences count per student
58
     * this is useful for monitoring the absences.
59
     */
60
    public function get_absence_count_per_student(Period $period)
61
    {
62
        // return attendance records for period
63
        $coursesIds = $period->courses->pluck('id');
64
        $eventsIds = Event::whereIn('course_id', $coursesIds)->pluck('id');
65
66
        return self::with('event.course')->with('student')->whereIn('event_id', $eventsIds)->whereIn('attendance_type_id', [3, 4])->get()->groupBy('student_id');
67
    }
68
69
    public function getStudentNameAttribute(): string
70
    {
71
        return $this->student->name ?? '';
72
    }
73
}
74