summaryrefslogtreecommitdiff
path: root/app/Model/SubtaskTimeTracking.php
blob: b766b5426053fd8ffa2361d9c6fe729fc2108f4a (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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<?php

namespace Kanboard\Model;

use DateTime;

/**
 * Subtask timesheet
 *
 * @package  model
 * @author   Frederic Guillot
 */
class SubtaskTimeTracking extends Base
{
    /**
     * SQL table name
     *
     * @var string
     */
    const TABLE = 'subtask_time_tracking';

    /**
     * Get query to check if a timer is started for the given user and subtask
     *
     * @access public
     * @param  integer    $user_id   User id
     * @return string
     */
    public function getTimerQuery($user_id)
    {
        return sprintf(
            "SELECT %s FROM %s WHERE %s='%d' AND %s='0' AND %s=%s LIMIT 1",
            $this->db->escapeIdentifier('start'),
            $this->db->escapeIdentifier(self::TABLE),
            $this->db->escapeIdentifier('user_id'),
            $user_id,
            $this->db->escapeIdentifier('end'),
            $this->db->escapeIdentifier('subtask_id'),
            Subtask::TABLE.'.id'
        );
    }

    /**
     * Get query for user timesheet (pagination)
     *
     * @access public
     * @param  integer    $user_id   User id
     * @return \PicoDb\Table
     */
    public function getUserQuery($user_id)
    {
        return $this->db
                    ->table(self::TABLE)
                    ->columns(
                        self::TABLE.'.id',
                        self::TABLE.'.subtask_id',
                        self::TABLE.'.end',
                        self::TABLE.'.start',
                        self::TABLE.'.time_spent',
                        Subtask::TABLE.'.task_id',
                        Subtask::TABLE.'.title AS subtask_title',
                        Task::TABLE.'.title AS task_title',
                        Task::TABLE.'.project_id',
                        Task::TABLE.'.color_id'
                    )
                    ->join(Subtask::TABLE, 'id', 'subtask_id')
                    ->join(Task::TABLE, 'id', 'task_id', Subtask::TABLE)
                    ->eq(self::TABLE.'.user_id', $user_id);
    }

    /**
     * Get query for task timesheet (pagination)
     *
     * @access public
     * @param  integer    $task_id    Task id
     * @return \PicoDb\Table
     */
    public function getTaskQuery($task_id)
    {
        return $this->db
                    ->table(self::TABLE)
                    ->columns(
                        self::TABLE.'.id',
                        self::TABLE.'.subtask_id',
                        self::TABLE.'.end',
                        self::TABLE.'.start',
                        self::TABLE.'.time_spent',
                        self::TABLE.'.user_id',
                        Subtask::TABLE.'.task_id',
                        Subtask::TABLE.'.title AS subtask_title',
                        Task::TABLE.'.project_id',
                        User::TABLE.'.username',
                        User::TABLE.'.name AS user_fullname'
                    )
                    ->join(Subtask::TABLE, 'id', 'subtask_id')
                    ->join(Task::TABLE, 'id', 'task_id', Subtask::TABLE)
                    ->join(User::TABLE, 'id', 'user_id', self::TABLE)
                    ->eq(Task::TABLE.'.id', $task_id);
    }

    /**
     * Get query for project timesheet (pagination)
     *
     * @access public
     * @param  integer    $project_id   Project id
     * @return \PicoDb\Table
     */
    public function getProjectQuery($project_id)
    {
        return $this->db
                    ->table(self::TABLE)
                    ->columns(
                        self::TABLE.'.id',
                        self::TABLE.'.subtask_id',
                        self::TABLE.'.end',
                        self::TABLE.'.start',
                        self::TABLE.'.time_spent',
                        self::TABLE.'.user_id',
                        Subtask::TABLE.'.task_id',
                        Subtask::TABLE.'.title AS subtask_title',
                        Task::TABLE.'.project_id',
                        Task::TABLE.'.color_id',
                        User::TABLE.'.username',
                        User::TABLE.'.name AS user_fullname'
                    )
                    ->join(Subtask::TABLE, 'id', 'subtask_id')
                    ->join(Task::TABLE, 'id', 'task_id', Subtask::TABLE)
                    ->join(User::TABLE, 'id', 'user_id', self::TABLE)
                    ->eq(Task::TABLE.'.project_id', $project_id)
                    ->asc(self::TABLE.'.id');
    }

    /**
     * Get all recorded time slots for a given user
     *
     * @access public
     * @param  integer    $user_id       User id
     * @return array
     */
    public function getUserTimesheet($user_id)
    {
        return $this->db
                    ->table(self::TABLE)
                    ->eq('user_id', $user_id)
                    ->findAll();
    }

    /**
     * Get user calendar events
     *
     * @access public
     * @param  integer   $user_id
     * @param  string    $start      ISO-8601 format
     * @param  string    $end
     * @return array
     */
    public function getUserCalendarEvents($user_id, $start, $end)
    {
        $hook = 'model:subtask-time-tracking:calendar:events';
        $events = $this->getUserQuery($user_id)
            ->addCondition($this->getCalendarCondition(
                $this->dateParser->getTimestampFromIsoFormat($start),
                $this->dateParser->getTimestampFromIsoFormat($end),
                'start',
                'end'
            ))
            ->findAll();

        if ($this->hook->exists($hook)) {
            $events = $this->hook->first($hook, array(
                'user_id' => $user_id,
                'events' => $events,
                'start' => $start,
                'end' => $end,
            ));
        }

        return $this->toCalendarEvents($events);
    }

    /**
     * Get project calendar events
     *
     * @access public
     * @param  integer   $project_id
     * @param  integer   $start
     * @param  integer   $end
     * @return array
     */
    public function getProjectCalendarEvents($project_id, $start, $end)
    {
        $result = $this
            ->getProjectQuery($project_id)
            ->addCondition($this->getCalendarCondition(
                $this->dateParser->getTimestampFromIsoFormat($start),
                $this->dateParser->getTimestampFromIsoFormat($end),
                'start',
                'end'
            ))
            ->findAll();

        return $this->toCalendarEvents($result);
    }

    /**
     * Convert a record set to calendar events
     *
     * @access private
     * @param  array    $rows
     * @return array
     */
    private function toCalendarEvents(array $rows)
    {
        $events = array();

        foreach ($rows as $row) {
            $user = isset($row['username']) ? ' ('.($row['user_fullname'] ?: $row['username']).')' : '';

            $events[] = array(
                'id' => $row['id'],
                'subtask_id' => $row['subtask_id'],
                'title' => t('#%d', $row['task_id']).' '.$row['subtask_title'].$user,
                'start' => date('Y-m-d\TH:i:s', $row['start']),
                'end' => date('Y-m-d\TH:i:s', $row['end'] ?: time()),
                'backgroundColor' => $this->color->getBackgroundColor($row['color_id']),
                'borderColor' => $this->color->getBorderColor($row['color_id']),
                'textColor' => 'black',
                'url' => $this->helper->url->to('task', 'show', array('task_id' => $row['task_id'], 'project_id' => $row['project_id'])),
                'editable' => false,
            );
        }

        return $events;
    }

    /**
     * Return true if a timer is started for this use and subtask
     *
     * @access public
     * @param  integer  $subtask_id
     * @param  integer  $user_id
     * @return boolean
     */
    public function hasTimer($subtask_id, $user_id)
    {
        return $this->db->table(self::TABLE)->eq('subtask_id', $subtask_id)->eq('user_id', $user_id)->eq('end', 0)->exists();
    }

    /**
     * Log start time
     *
     * @access public
     * @param  integer   $subtask_id
     * @param  integer   $user_id
     * @return boolean
     */
    public function logStartTime($subtask_id, $user_id)
    {
        return
            ! $this->hasTimer($subtask_id, $user_id) &&
            $this->db
                ->table(self::TABLE)
                ->insert(array('subtask_id' => $subtask_id, 'user_id' => $user_id, 'start' => time(), 'end' => 0));
    }

    /**
     * Log end time
     *
     * @access public
     * @param  integer   $subtask_id
     * @param  integer   $user_id
     * @return boolean
     */
    public function logEndTime($subtask_id, $user_id)
    {
        $time_spent = $this->getTimeSpent($subtask_id, $user_id);

        if ($time_spent > 0) {
            $this->updateSubtaskTimeSpent($subtask_id, $time_spent);
        }

        return $this->db
                    ->table(self::TABLE)
                    ->eq('subtask_id', $subtask_id)
                    ->eq('user_id', $user_id)
                    ->eq('end', 0)
                    ->update(array(
                        'end' => time(),
                        'time_spent' => $time_spent,
                    ));
    }

    /**
     * Calculate the time spent when the clock is stopped
     *
     * @access public
     * @param  integer   $subtask_id
     * @param  integer   $user_id
     * @return float
     */
    public function getTimeSpent($subtask_id, $user_id)
    {
        $hook = 'model:subtask-time-tracking:calculate:time-spent';
        $start_time = $this->db
            ->table(self::TABLE)
            ->eq('subtask_id', $subtask_id)
            ->eq('user_id', $user_id)
            ->eq('end', 0)
            ->findOneColumn('start');

        if (empty($start_time)) {
            return 0;
        }

        $end = new DateTime;
        $start = new DateTime;
        $start->setTimestamp($start_time);

        if ($this->hook->exists($hook)) {
            return $this->hook->first($hook, array(
                'user_id' => $user_id,
                'start' => $start,
                'end' => $end,
            ));
        }

        return $this->dateParser->getHours($start, $end);
    }

    /**
     * Update subtask time spent
     *
     * @access public
     * @param  integer   $subtask_id
     * @param  float     $time_spent
     * @return bool
     */
    public function updateSubtaskTimeSpent($subtask_id, $time_spent)
    {
        $subtask = $this->subtask->getById($subtask_id);

        // Fire the event subtask.update
        return $this->subtask->update(array(
            'id' => $subtask['id'],
            'time_spent' => $subtask['time_spent'] + $time_spent,
            'task_id' => $subtask['task_id'],
        ), false);
    }

    /**
     * Update task time tracking based on subtasks time tracking
     *
     * @access public
     * @param  integer   $task_id    Task id
     * @return bool
     */
    public function updateTaskTimeTracking($task_id)
    {
        $values = $this->calculateSubtaskTime($task_id);

        return $this->db
                    ->table(Task::TABLE)
                    ->eq('id', $task_id)
                    ->update($values);
    }

    /**
     * Sum time spent and time estimated for all subtasks
     *
     * @access public
     * @param  integer   $task_id    Task id
     * @return array
     */
    public function calculateSubtaskTime($task_id)
    {
        return $this->db
                    ->table(Subtask::TABLE)
                    ->eq('task_id', $task_id)
                    ->columns(
                        'SUM(time_spent) AS time_spent',
                        'SUM(time_estimated) AS time_estimated'
                    )
                    ->findOne();
    }
}