summaryrefslogtreecommitdiff
path: root/app/Model/Timetable.php
blob: 6ddf826b37154e77adfcf93dc16f6bda8003d4d7 (plain)
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
<?php

namespace Model;

use DateTime;
use DateInterval;

/**
 * Timetable
 *
 * @package  model
 * @author   Frederic Guillot
 */
class Timetable extends Base
{
    /**
     * User time slots
     *
     * @access private
     * @var array
     */
    private $day;
    private $week;
    private $overtime;
    private $timeoff;

    /**
     * Get a set of events by using the intersection between the timetable and the time tracking data
     *
     * @access public
     * @param  integer  $user_id
     * @param  array    $events     Time tracking data
     * @param  string   $start      ISO8601 date
     * @param  string   $end        ISO8601 date
     * @return array
     */
    public function calculateEventsIntersect($user_id, array $events, $start, $end)
    {
        $start_dt = new DateTime($start);
        $start_dt->setTime(0, 0);

        $end_dt = new DateTime($end);
        $end_dt->setTime(23, 59);

        $timetable = $this->calculate($user_id, $start_dt, $end_dt);

        // The user has no timetable
        if (empty($this->week)) {
            return $events;
        }

        $results = array();

        foreach ($events as $event) {
            $results = array_merge($results, $this->calculateEventIntersect($event, $timetable));
        }

        return $results;
    }

    /**
     * Get a serie of events based on the timetable and the provided event
     *
     * @access public
     * @param  array    $event
     * @param  array    $timetable
     * @return array
     */
    public function calculateEventIntersect(array $event, array $timetable)
    {
        $events = array();

        foreach ($timetable as $slot) {

            $start_ts = $slot[0]->getTimestamp();
            $end_ts = $slot[1]->getTimestamp();

            if ($start_ts > $event['end']) {
                break;
            }

            if ($event['start'] <= $start_ts) {
                $event['start'] = $start_ts;
            }

            if ($event['start'] >= $start_ts && $event['start'] <= $end_ts) {

                if ($event['end'] >= $end_ts) {
                    $events[] = array_merge($event, array('end' => $end_ts));
                }
                else {
                    $events[] = $event;
                    break;
                }
            }
        }

        return $events;
    }

    /**
     * Calculate effective worked hours by taking into consideration the timetable
     *
     * @access public
     * @param  integer     $user_id
     * @param  \DateTime   $start
     * @param  \DateTime   $end
     * @return float
     */
    public function calculateEffectiveDuration($user_id, DateTime $start, DateTime $end)
    {
        $end_timetable = clone($end);
        $end_timetable->setTime(23, 59);

        $timetable = $this->calculate($user_id, $start, $end_timetable);
        $found_start = false;
        $hours = 0;

        // The user has no timetable
        if (empty($this->week)) {
            return $this->dateParser->getHours($start, $end);
        }

        foreach ($timetable as $slot) {

            $isStartSlot = $this->dateParser->withinDateRange($start, $slot[0], $slot[1]);
            $isEndSlot = $this->dateParser->withinDateRange($end, $slot[0], $slot[1]);

            // Start and end are within the same time slot
            if ($isStartSlot && $isEndSlot) {
                return $this->dateParser->getHours($start, $end);
            }

            // We found the start slot
            if (! $found_start && $isStartSlot) {
                $found_start = true;
                $hours = $this->dateParser->getHours($start, $slot[1]);
            }
            else if ($found_start) {

                // We found the end slot
                if ($isEndSlot) {
                    $hours += $this->dateParser->getHours($slot[0], $end);
                    break;
                }
                else {

                    // Sum hours of the intermediate time slots
                    $hours += $this->dateParser->getHours($slot[0], $slot[1]);
                }
            }
        }

        // The start date was not found in regular hours so we get the nearest time slot
        if (! empty($timetable) && ! $found_start) {
            $slot = $this->findClosestTimeSlot($start, $timetable);

            if ($start < $slot[0]) {
                return $this->calculateEffectiveDuration($user_id, $slot[0], $end);
            }
        }

        return $hours;
    }

    /**
     * Find the nearest time slot
     *
     * @access public
     * @param  DateTime  $date
     * @param  array     $timetable
     * @return array
     */
    public function findClosestTimeSlot(DateTime $date, array $timetable)
    {
        $values = array();

        foreach ($timetable as $slot) {
            $t1 = abs($slot[0]->getTimestamp() - $date->getTimestamp());
            $t2 = abs($slot[1]->getTimestamp() - $date->getTimestamp());

            $values[] = min($t1, $t2);
        }

        asort($values);
        return $timetable[key($values)];
    }

    /**
     * Get the timetable for a user for a given date range
     *
     * @access public
     * @param  integer     $user_id
     * @param  \DateTime   $start
     * @param  \DateTime   $end
     * @return array
     */
    public function calculate($user_id, DateTime $start, DateTime $end)
    {
        $timetable = array();

        $this->day = $this->timetableDay->getByUser($user_id);
        $this->week = $this->timetableWeek->getByUser($user_id);
        $this->overtime = $this->timetableExtra->getByUserAndDate($user_id, $start->format('Y-m-d'), $end->format('Y-m-d'));
        $this->timeoff = $this->timetableOff->getByUserAndDate($user_id, $start->format('Y-m-d'), $end->format('Y-m-d'));

        for ($today = clone($start); $today <= $end; $today->add(new DateInterval('P1D'))) {
            $week_day = $today->format('N');
            $timetable = array_merge($timetable, $this->getWeekSlots($today, $week_day));
            $timetable = array_merge($timetable, $this->getOvertimeSlots($today, $week_day));
        }

        return $timetable;
    }

    /**
     * Return worked time slots for the given day
     *
     * @access public
     * @param  \DateTime   $today
     * @param  string      $week_day
     * @return array
     */
    public function getWeekSlots(DateTime $today, $week_day)
    {
        $slots = array();
        $dayoff = $this->getDayOff($today);

        if (! empty($dayoff) && $dayoff['all_day'] == 1) {
            return array();
        }

        foreach ($this->week as $slot) {
            if ($week_day == $slot['day']) {
                $slots = array_merge($slots, $this->getDayWorkSlots($slot, $dayoff, $today));
            }
        }

        return $slots;
    }

    /**
     * Get the overtime time slots for the given day
     *
     * @access public
     * @param  \DateTime   $today
     * @param  string      $week_day
     * @return array
     */
    public function getOvertimeSlots(DateTime $today, $week_day)
    {
        $slots = array();

        foreach ($this->overtime as $slot) {

            $day = new DateTime($slot['date']);

            if ($week_day == $day->format('N')) {

                if ($slot['all_day'] == 1) {
                    $slots = array_merge($slots, $this->getDaySlots($today));
                }
                else {
                    $slots[] = $this->getTimeSlot($slot, $day);
                }
            }
        }

        return $slots;
    }

    /**
     * Get worked time slots and remove time off
     *
     * @access public
     * @param  array       $slot
     * @param  array       $dayoff
     * @param  \DateTime   $today
     * @return array
     */
    public function getDayWorkSlots(array $slot, array $dayoff, DateTime $today)
    {
        $slots = array();

        if (! empty($dayoff) && $dayoff['start'] < $slot['end']) {

            if ($dayoff['start'] > $slot['start']) {
                $slots[] = $this->getTimeSlot(array('end' => $dayoff['start']) + $slot, $today);
            }

            if ($dayoff['end'] < $slot['end']) {
                $slots[] = $this->getTimeSlot(array('start' => $dayoff['end']) + $slot, $today);
            }
        }
        else {
            $slots[] = $this->getTimeSlot($slot, $today);
        }

        return $slots;
    }

    /**
     * Get regular day work time slots
     *
     * @access public
     * @param  \DateTime   $today
     * @return array
     */
    public function getDaySlots(DateTime $today)
    {
        $slots = array();

        foreach ($this->day as $day) {
            $slots[] = $this->getTimeSlot($day, $today);
        }

        return $slots;
    }

    /**
     * Get the start and end time slot for a given day
     *
     * @access public
     * @param  array       $slot
     * @param  \DateTime   $today
     * @return array
     */
    public function getTimeSlot(array $slot, DateTime $today)
    {
        $date = $today->format('Y-m-d');

        return array(
            new DateTime($date.' '.$slot['start']),
            new DateTime($date.' '.$slot['end']),
        );
    }

    /**
     * Return day off time slot
     *
     * @access public
     * @param  \DateTime   $today
     * @return array
     */
    public function getDayOff(DateTime $today)
    {
        foreach ($this->timeoff as $day) {

            if ($day['date'] === $today->format('Y-m-d')) {
                return $day;
            }
        }

        return array();
    }
}