-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathUserAttendance.php
126 lines (109 loc) · 2.95 KB
/
UserAttendance.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;
/**
* @property Collection sessions
*/
class UserAttendance extends Model
{
public static $HOLIDAY = 'holiday';
public static $LEAVE = 'leave';
public static $ABSENT = 'absent';
/**
* @var array
*/
protected $fillable = [
'date', 'total_times', 'status',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function sessions()
{
return $this->hasMany(AttendanceSession::class, 'attendance_id');
}
/**
* Get total times in hours.
*
* @return float
*/
public function getHoursAttribute()
{
return hoursFromSeconds($this->total_times);
}
/**
* @return mixed
*/
public function getTotalTimeAttribute()
{
return $this->sessions->sum('total_times');
}
/**
* @param User $user
* @return Model
*/
public function createSession(User $user)
{
return $this->sessions()
->create([
'user_id' => $user->getKey(),
'start_time' => now(),
'end_time' => now(),
]);
}
/**
* @return Model|\Illuminate\Database\Eloquent\Relations\HasMany|\Illuminate\Database\Query\Builder|null|object
*/
public function incrementSession()
{
$session = $this->sessions()->latest('start_time')
->first();
$endTime = now();
if ($endTime->diffInSeconds($session->end_time) > config('rm.ping_timeout')) {
$session = $this->createSession($session->user);
}
$session->fill([
'end_time' => $endTime,
'total_times' => $endTime->diffInSeconds($session->start_time),
])->save();
$this->fill([
'total_times' => $this->totalTime,
])->save();
return $session;
}
/**
* @param \Illuminate\Database\Eloquent\Model $type
* @param \App\User $user
* @param \Carbon\Carbon $date
* @param $hour
*
* @return $this
*/
public function createAttandanceSession(Model $type, User $user, Carbon $date, $hour)
{
$startTime = $date->setTime(0, 0, 0);
$endTime = $startTime->copy()->addHour($hour);
$this->sessions()
->create([
'user_id' => $user->getKey(),
'start_time' => $startTime,
'end_time' => $endTime,
'total_times' => $endTime->diffInSeconds($startTime),
'parent_id' => $type->getKey(),
'parent_type' => get_class($type),
]);
$this->fill([
'total_times' => $this->totalTime,
])->save();
return $this;
}
}