Moved week view related functions in ttWeekViewHelper class.
[timetracker.git] / WEB-INF / lib / ttWeekViewHelper.class.php
1 <?php
2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
10 // |
11 // | There are only two ways to violate the license:
12 // |
13 // | 1. To redistribute this code in source form, with the copyright
14 // |    notice or license removed or altered. (Distributing in compiled
15 // |    forms without embedded copyright notices is permitted).
16 // |
17 // | 2. To redistribute modified versions of this code in *any* form
18 // |    that bears insufficient indications that the modifications are
19 // |    not the work of the original author(s).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 // ttWeekViewHelper class groups together functions used in week view.
30 class ttWeekViewHelper {
31
32   // getRecordsForInterval - returns time records for a user for a given interval of dates.
33   static function getRecordsForInterval($user_id, $start_date, $end_date) {
34     global $user;
35     $sql_time_format = "'%k:%i'"; //  24 hour format.
36     if ('%I:%M %p' == $user->time_format)
37       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
38
39     $result = array();
40     $mdb2 = getConnection();
41
42     $client_field = null;
43     if ($user->isPluginEnabled('cl'))
44       $client_field = ', c.id as client_id, c.name as client';
45
46     $custom_field_1 = null;
47     if ($user->isPluginEnabled('cf')) {
48       $custom_fields = new CustomFields($user->team_id);
49       $cf_1_type = $custom_fields->fields[0]['type'];
50       if ($cf_1_type == CustomFields::TYPE_TEXT) {
51         $custom_field_1 = ', cfl.value as cf_1_value';
52       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
53         $custom_field_1 = ', cfo.id as cf_1_id, cfo.value as cf_1_value';
54       }
55     }
56
57     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
58       " left join tt_tasks t on (l.task_id = t.id)";
59     if ($user->isPluginEnabled('cl'))
60       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
61     if ($user->isPluginEnabled('cf')) {
62       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
63         $left_joins .= 'left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.value = cfo.id) ';
64       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
65         $left_joins .= 'left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.option_id = cfo.id) ';
66     }
67
68     $sql = "select l.id as id, l.date as date, TIME_FORMAT(l.start, $sql_time_format) as start,
69       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,
70       TIME_FORMAT(l.duration, '%k:%i') as duration, p.id as project_id, p.name as project,
71       t.id as task_id, t.name as task, l.comment, l.billable, l.invoice_id $client_field $custom_field_1
72       from tt_log l
73       $left_joins
74       where l.date >= '$start_date' and l.date <= '$end_date' and l.user_id = $user_id and l.status = 1
75       order by p.name, t.name, l.date, l.start, l.id";
76     $res = $mdb2->query($sql);
77     if (!is_a($res, 'PEAR_Error')) {
78       while ($val = $res->fetchRow()) {
79         if($val['duration']=='0:00')
80           $val['finish'] = '';
81         $result[] = $val;
82       }
83     } else return false;
84
85     return $result;
86   }
87
88   // getDataForWeekView - builds an array to render a table of durations for week view.
89   // In a week view we want one row representing the same attributes to have 7 values for each day of week.
90   // We identify simlar records by a combination of client, billable, project, task, and custom field values.
91   // This will allow us to extend the feature when more custom fields are added.
92   //
93   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:example text"
94   // The above means client 546, billable, project 23456, task 27464, custom field text "example text".
95   //
96   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:7623"
97   // The above means client 546, not billable, project 23456, task 27464, custom field option id 7623.
98   //
99   // Description of $dataArray format that the function returns.
100   // $dataArray = array(
101   //   array( // Row 0. This is a special, one-off row for a new week entry with empty values.
102   //     'row_id' => null', // Row identifier. Null for a new entry.
103   //     'label' => 'New entry', // Human readable label for the row describing what this time entry is for.
104   //     'day_0' => array('control_id' => '0_day_0', 'tt_log_id' => null, 'duration' => null), // control_id is row_id plus day header for column.
105   //     'day_1' => array('control_id' => '0_day_1', 'tt_log_id' => null, 'duration' => null),
106   //     'day_2' => array('control_id' => '0_day_2', 'tt_log_id' => null, 'duration' => null),
107   //     'day_3' => array('control_id' => '0_day_3', 'tt_log_id' => null, 'duration' => null),
108   //     'day_4' => array('control_id' => '0_day_4', 'tt_log_id' => null, 'duration' => null),
109   //     'day_5' => array('control_id' => '0_day_5', 'tt_log_id' => null, 'duration' => null),
110   //     'day_6' => array('control_id' => '0_day_6', 'tt_log_id' => null, 'duration' => null)
111   //   ),
112   //   array( // Row 1.
113   //     'row_id' => 'cl:546,bl:1,pr:23456,ts:27464,cf_1:7623_0', // Row identifier. See ttWeekViewHelper::makeRowIdentifier().
114   //     'label' => 'Anuko - Time Tracker - Coding',              // Human readable label for the row describing what this time entry is for.
115   //     'day_0' => array('control_id' => '1_day_0', 'tt_log_id' => 12345, 'duration' => '00:00'), // control_id is row_id plus day header for column.
116   //     'day_1' => array('control_id' => '1_day_1', 'tt_log_id' => 12346, 'duration' => '01:00'),
117   //     'day_2' => array('control_id' => '1_day_2', 'tt_log_id' => 12347, 'duration' => '02:00'),
118   //     'day_3' => array('control_id' => '1_day_3', 'tt_log_id' => null, 'duration' => null),
119   //     'day_4' => array('control_id' => '1_day_4', 'tt_log_id' => 12348, 'duration' => '04:00'),
120   //     'day_5' => array('control_id' => '1_day_5', 'tt_log_id' => 12349, 'duration' => '04:00'),
121   //     'day_6' => array('control_id' => '1_day_6', 'tt_log_id' => null, 'duration' => null)
122   //   ),
123   //   array( // Row 2.
124   //     'row_id' => 'bl:0_0',
125   //     'label' => '', // In this case the label is empty as we don't have anything to put into it, as we only have billable flag.
126   //     'day_0' => array('control_id' => '2_day_0', 'tt_log_id' => null, 'duration' => null),
127   //     'day_1' => array('control_id' => '2_day_1', 'tt_log_id' => 12350, 'duration' => '01:30'),
128   //     'day_2' => array('control_id' => '2_day_2', 'tt_log_id' => null, 'duration' => null),
129   //     'day_3' => array('control_id' => '2_day_3', 'tt_log_id' => 12351,'duration' => '02:30'),
130   //     'day_4' => array('control_id' => '2_day_4', 'tt_log_id' => 12352, 'duration' => '04:00'),
131   //     'day_5' => array('control_id' => '2_day_5', 'tt_log_id' => null, 'duration' => null),
132   //     'day_6' => array('control_id' => '2_day_6', 'tt_log_id' => null, 'duration' => null)
133   //   )
134   // );
135   static function getDataForWeekView($user_id, $start_date, $end_date, $dayHeaders) {
136     global $i18n;
137
138     // Start by obtaining all records in interval.
139     $records = ttWeekViewHelper::getRecordsForInterval($user_id, $start_date, $end_date);
140
141     $dataArray = array();
142
143     // Construct the first row for a brand new entry.
144     $dataArray[] = array('row_id' => null,'label' => $i18n->getKey('form.week.new_entry')); // Insert row.
145     // Insert empty cells with proper control ids.
146     for ($i = 0; $i < 7; $i++) {
147       $control_id = '0_'. $dayHeaders[$i];
148       $dataArray[0][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
149     }
150
151     // Iterate through records and build $dataArray cell by cell.
152     foreach ($records as $record) {
153       // Create record id without suffix.
154       $row_id_no_suffix = ttWeekViewHelper::makeRowIdentifier($record);
155       // Handle potential multiple records with the same attributes by using a numerical suffix.
156       $suffix = 0;
157       $row_id = $row_id_no_suffix.'_'.$suffix;
158       $day_header = substr($record['date'], 8); // Day number in month.
159       while (ttWeekViewHelper::cellExists($row_id, $day_header, $dataArray)) {
160         $suffix++;
161         $row_id = $row_id_no_suffix.'_'.$suffix;
162       }
163       // Find row.
164       $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
165       if ($pos < 0) {
166         $dataArray[] = array('row_id' => $row_id,'label' => ttWeekViewHelper::makeRowLabel($record)); // Insert row.
167         $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
168         // Insert empty cells with proper control ids.
169         for ($i = 0; $i < 7; $i++) {
170           $control_id = $pos.'_'. $dayHeaders[$i];
171           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
172         }
173       }
174       // Insert actual cell data from $record (one cell only).
175       $dataArray[$pos][$day_header] = array('control_id' => $pos.'_'. $day_header, 'tt_log_id' => $record['id'],'duration' => $record['duration']);
176     }
177     return $dataArray;
178   }
179
180   // cellExists is a helper function for getDataForWeekView() to see if a cell with a given label
181   // and a day header already exists.
182   static function cellExists($row_id, $day_header, $dataArray) {
183     foreach($dataArray as $row) {
184       if ($row['row_id'] == $row_id && !empty($row[$day_header]['duration']))
185         return true;
186     }
187     return false;
188   }
189
190   // findRow returns an existing row position in $dataArray, -1 otherwise.
191   static function findRow($row_id, $dataArray) {
192     $pos = 0; // Row position in array.
193     foreach($dataArray as $row) {
194       if ($row['row_id'] == $row_id)
195         return $pos;
196       $pos++; // Increment for search.
197     }
198     return -1; // Row not found.
199   }
200
201   // getDayTotals calculates total durations for each day from the existing data in $dataArray.
202   static function getDayTotals($dataArray, $dayHeaders) {
203     $dayTotals = array();
204
205     // Insert label.
206     global $i18n;
207     $dayTotals['label'] = $i18n->getKey('label.day_total');
208
209     foreach ($dataArray as $row) {
210       foreach($dayHeaders as $dayHeader) {
211         if (array_key_exists($dayHeader, $row)) {
212           $minutes = ttTimeHelper::toMinutes($row[$dayHeader]['duration']);
213           $dayTotals[$dayHeader] += $minutes;
214         }
215       }
216     }
217     // Convert minutes to hh:mm for display.
218     foreach($dayHeaders as $dayHeader) {
219       $dayTotals[$dayHeader] = ttTimeHelper::toAbsDuration($dayTotals[$dayHeader]);
220     }
221     return $dayTotals;
222   }
223
224   // getDayHeadersForWeek - obtains day column headers for week view, which are simply day numbers in month.
225   static function getDayHeadersForWeek($start_date) {
226     $dayHeaders = array();
227     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
228     $dayHeaders[] = (string) $objDate->getDate(); // It returns an int on first call.
229     if (strlen($dayHeaders[0]) == 1)              // Which is an implementation detail of DateAndTime class.
230       $dayHeaders[0] = '0'.$dayHeaders[0];        // Add a 0 for single digit day.
231     $objDate->incDay();
232     $dayHeaders[] = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
233     $objDate->incDay();
234     $dayHeaders[] = $objDate->getDate();
235     $objDate->incDay();
236     $dayHeaders[] = $objDate->getDate();
237     $objDate->incDay();
238     $dayHeaders[] = $objDate->getDate();
239     $objDate->incDay();
240     $dayHeaders[] = $objDate->getDate();
241     $objDate->incDay();
242     $dayHeaders[] = $objDate->getDate();
243     unset($objDate);
244     return $dayHeaders;
245   }
246
247   // getLockedDaysForWeek - builds an array of locked days in week.
248   static function getLockedDaysForWeek($start_date) {
249     global $user;
250     $lockedDays = array();
251     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
252     for ($i = 0; $i < 7; $i++) {
253       $lockedDays[] = $user->isDateLocked($objDate);
254       $objDate->incDay();
255     }
256     unset($objDate);
257     return $lockedDays;
258   }
259
260   // makeRowIdentifier - builds a string identifying a row for a week view from a single record properties.
261   //                     Note that the return value is without a suffix.
262   // For example:
263   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
264   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:7623"
265   static function makeRowIdentifier($record) {
266     global $user;
267     // Start with client.
268     if ($user->isPluginEnabled('cl'))
269       $row_identifier = $record['client_id'] ? 'cl:'.$record['client_id'] : '';
270     // Add billable flag.
271     if (!empty($row_identifier)) $row_identifier .= ',';
272     $row_identifier .= 'bl:'.$record['billable'];
273     // Add project.
274     $row_identifier .= $record['project_id'] ? ',pr:'.$record['project_id'] : '';
275     // Add task.
276     $row_identifier .= $record['task_id'] ? ',ts:'.$record['task_id'] : '';
277     // Add custom field 1.
278     if ($user->isPluginEnabled('cf')) {
279       if ($record['cf_1_id'])
280         $row_identifier .= ',cf_1:'.$record['cf_1_id'];
281       else if ($record['cf_1_value'])
282         $row_identifier .= ',cf_1:'.$record['cf_1_value'];
283     }
284
285     return $row_identifier;
286   }
287
288   // makeRowLabel - builds a human readable label for a row in week view,
289   // which is a combination ot record properties.
290   // Client - Project - Task - Custom field 1.
291   // Note that billable property is not part of the label. Instead,
292   // we identify such records with a different color in week view.
293   static function makeRowLabel($record) {
294     global $user;
295     // Start with client.
296     if ($user->isPluginEnabled('cl'))
297       $label = $record['client'];
298
299     // Add project.
300     if (!empty($label) && !empty($record['project'])) $label .= ' - ';
301     $label .= $record['project'];
302
303     // Add task.
304     if (!empty($label) && !empty($record['task'])) $label .= ' - ';
305     $label .= $record['task'];
306
307     // Add custom field 1.
308     if ($user->isPluginEnabled('cf')) {
309       if (!empty($label) && !empty($record['cf_1_value'])) $label .= ' - ';
310       $label .= $record['cf_1_value'];
311     }
312
313     return $label;
314   }
315
316   // parseFromWeekViewRow - obtains field value encoded in row identifier.
317   // For example, for a row id like "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
318   // requesting a client "cl" should return 546.
319   static function parseFromWeekViewRow($row_id, $field_label) {
320     // Find beginning of label.
321     $pos = strpos($row_id, $field_label);
322     if ($pos === false) return null; // Not found.
323
324     // Strip suffix from row id.
325     $suffixPos = strrpos($row_id, '_');
326     if ($suffixPos)
327       $remaninder = substr($row_id, 0, $suffixPos);
328
329     // Find beginning of value.
330     $posBegin = 1 + strpos($remaninder, ':', $pos);
331     // Find end of value.
332     $posEnd = strpos($remaninder, ',', $posBegin);
333     if ($posEnd === false) $posEnd = strlen($remaninder);
334     // Return value.
335     return substr($remaninder, $posBegin, $posEnd - $posBegin);
336   }
337
338   // dateFromDayHeader calculates date from start date and day header in week view.
339   static function dateFromDayHeader($start_date, $day_header) {
340     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
341     $currentDayHeader = (string) $objDate->getDate(); // It returns an int on first call.
342     if (strlen($currentDayHeader) == 1)               // Which is an implementation detail of DateAndTime class.
343       $currentDayHeader = '0'.$currentDayHeader;      // Add a 0 for single digit day.
344     $i = 1;
345     while ($currentDayHeader != $day_header && $i < 7) {
346       // Iterate through remaining days to find a match.
347       $objDate->incDay();
348       $currentDayHeader = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
349       $i++;
350     }
351     return $objDate->toString(DB_DATEFORMAT);
352   }
353
354   // insertDurationFromWeekView - inserts a new record in log tables from a week view post.
355   static function insertDurationFromWeekView($fields, $custom_fields, $err) {
356     global $i18n;
357     global $user;
358
359     // Determine date for a new entry.
360     $entry_date = ttWeekViewHelper::dateFromDayHeader($fields['start_date'], $fields['day_header']);
361     $objEntryDate = new DateAndTime(DB_DATEFORMAT, $entry_date);
362
363     // Prohibit creating entries in future.
364     if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES) && $fields['browser_today']) {
365       $objBrowserToday = new DateAndTime(DB_DATEFORMAT, $fields['browser_today']);
366       if ($objEntryDate->after($objBrowserToday)) {
367         $err->add($i18n->getKey('error.future_date'));
368         return false;
369       }
370     }
371
372     // Prepare an array of fields for regular insert function.
373     $fields4insert = array();
374     $fields4insert['user_id'] = $user->getActiveUser();
375     $fields4insert['date'] = $entry_date;
376     $fields4insert['duration'] = $fields['duration'];
377     $fields4insert['client'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'cl');
378     $fields4insert['billable'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'bl');
379     $fields4insert['project'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'pr');
380     $fields4insert['task'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'ts');
381     $fields4insert['note'] = $fields['note'];
382
383     // Try to insert a record.
384     $id = ttTimeHelper::insert($fields4insert);
385     if (!$id) return false; // Something failed.
386
387     // Insert custom field if we have it.
388     $result = true;
389     $cf_1 = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'cf_1');
390     if ($custom_fields && $cf_1) {
391       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
392         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cf_1);
393       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
394         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cf_1, null);
395     }
396
397     return $result;
398   }
399
400   // modifyDurationFromWeekView - modifies a duration of an existing record from a week view post.
401   static function modifyDurationFromWeekView($fields, $err) {
402     global $i18n;
403     global $user;
404
405     // Possible errors: 1) Overlap if the existing record has start time. 2) Going beyond 24 hour boundary.
406     // TODO: rename this function.
407     // Handle different errors with specific error messages.
408     if (!ttWeekViewHelper::canModify($fields['tt_log_id'], $fields['duration'], $err)) {
409       // $err->add($i18n->getKey('error.overlap'));
410       return false;
411     }
412
413     $mdb2 = getConnection();
414     $duration = $fields['duration'];
415     $tt_log_id = $fields['tt_log_id'];
416     $user_id = $user->getActiveUser();
417     $sql = "update tt_log set duration = '$duration' where id = $tt_log_id and user_id = $user_id";
418     $affected = $mdb2->exec($sql);
419     if (is_a($affected, 'PEAR_Error'))
420       return false;
421
422     return true;
423   }
424
425   // canModify - determines if an  already existing tt_log record
426   // can be modified with a new user-provided duration.
427   static function canModify($tt_log_id, $new_duration, $err) {
428     global $i18n;
429     $mdb2 = getConnection();
430
431     // Determine if we have start time in record, as further checking does not makes sense otherwise.
432     $sql = "select user_id, date, start, duration from tt_log  where id = $tt_log_id";
433     $res = $mdb2->query($sql);
434     if (!is_a($res, 'PEAR_Error')) {
435       if (!$res->numRows()) {
436         $err->add($i18n->getKey('error.db')); // This is not expected.
437         return false;
438       }
439       $val = $res->fetchRow();
440       $oldDuration = $val['duration'];
441       if (!$val['start'])
442         return true; // There is no start time in the record, therefore safe to modify.
443     }
444
445     // We do have start time.
446     // Quick test if new duration is less then already existing.
447     $newMinutes = ttTimeHelper::toMinutes($new_duration);
448     $oldMinutes = ttTimeHelper::toMinutes($oldDuration);
449     if ($newMinutes < $oldMinutes)
450       return true; // Safe to modify.
451
452     // Does the new duration put the record beyond 24:00 boundary?
453     $startMinutes = ttTimeHelper::toMinutes($val['start']);
454     $newEndMinutes = $startMinutes + $newMinutes;
455     if ($newEndMinutes > 1440) {
456       // Invalid duration, as new duration puts the record beyond current day.
457       $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
458       return false;
459     }
460
461     // Does the new duration causes the record to overlap with others?
462     $user_id = $val['user_id'];
463     $date = $val['date'];
464     $startMinutes = ttTimeHelper::toMinutes($val['start']);
465     $start = ttTimeHelper::toAbsDuration($startMinutes);
466     $finish = ttTimeHelper::toAbsDuration($newEndMinutes);
467     if (ttTimeHelper::overlaps($user_id, $date, $start, $finish, $tt_log_id)) {
468       $err->add($i18n->getKey('error.overlap'));
469       return false;
470     }
471
472     return true; // There are no conflicts, safe to modify.
473   }
474 }