Refactoring ongoing on week view.
[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 ttTimeHelper::makeRecordIdentifier().
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       $record_id_no_suffix = ttTimeHelper::makeRecordIdentifier($record);
155       // Handle potential multiple records with the same attributes by using a numerical suffix.
156       $suffix = 0;
157       $record_id = $record_id_no_suffix.'_'.$suffix;
158       $day_header = substr($record['date'], 8); // Day number in month.
159       while (ttTimeHelper::cellExists($record_id, $day_header, $dataArray)) {
160         $suffix++;
161         $record_id = $record_id_no_suffix.'_'.$suffix;
162       }
163       // Find row.
164       $pos = ttTimeHelper::findRow($record_id, $dataArray);
165       if ($pos < 0) {
166         $dataArray[] = array('row_id' => $record_id,'label' => ttWeekViewHelper::makeRowLabel($record)); // Insert row.
167         $pos = ttTimeHelper::findRow($record_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   // getDayHeadersForWeek - obtains day column headers for week view, which are simply day numbers in month.
181   static function getDayHeadersForWeek($start_date) {
182     $dayHeaders = array();
183     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
184     $dayHeaders[] = (string) $objDate->getDate(); // It returns an int on first call.
185     if (strlen($dayHeaders[0]) == 1)              // Which is an implementation detail of DateAndTime class.
186       $dayHeaders[0] = '0'.$dayHeaders[0];        // Add a 0 for single digit day.
187     $objDate->incDay();
188     $dayHeaders[] = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
189     $objDate->incDay();
190     $dayHeaders[] = $objDate->getDate();
191     $objDate->incDay();
192     $dayHeaders[] = $objDate->getDate();
193     $objDate->incDay();
194     $dayHeaders[] = $objDate->getDate();
195     $objDate->incDay();
196     $dayHeaders[] = $objDate->getDate();
197     $objDate->incDay();
198     $dayHeaders[] = $objDate->getDate();
199     unset($objDate);
200     return $dayHeaders;
201   }
202
203   // getLockedDaysForWeek - builds an array of locked days in week.
204   static function getLockedDaysForWeek($start_date) {
205     global $user;
206     $lockedDays = array();
207     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
208     for ($i = 0; $i < 7; $i++) {
209       $lockedDays[] = $user->isDateLocked($objDate);
210       $objDate->incDay();
211     }
212     unset($objDate);
213     return $lockedDays;
214   }
215
216   // makeRowLabel - builds a human readable label for a row in week view,
217   // which is a combination ot record properties.
218   // Client - Project - Task - Custom field 1.
219   // Note that billable property is not part of the label. Instead,
220   // we identify such records with a different color in week view.
221   static function makeRowLabel($record) {
222     global $user;
223     // Start with client.
224     if ($user->isPluginEnabled('cl'))
225       $label = $record['client'];
226
227     // Add project.
228     if (!empty($label) && !empty($record['project'])) $label .= ' - ';
229     $label .= $record['project'];
230
231     // Add task.
232     if (!empty($label) && !empty($record['task'])) $label .= ' - ';
233     $label .= $record['task'];
234
235     // Add custom field 1.
236     if ($user->isPluginEnabled('cf')) {
237       if (!empty($label) && !empty($record['cf_1_value'])) $label .= ' - ';
238       $label .= $record['cf_1_value'];
239     }
240
241     return $label;
242   }
243
244   // parseFromWeekViewRow - obtains field value encoded in row identifier.
245   // For example, for a row id like "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
246   // requesting a client "cl" should return 546.
247   static function parseFromWeekViewRow($row_id, $field_label) {
248     // Find beginning of label.
249     $pos = strpos($row_id, $field_label);
250     if ($pos === false) return null; // Not found.
251
252     // Strip suffix from row id.
253     $suffixPos = strrpos($row_id, '_');
254     if ($suffixPos)
255       $remaninder = substr($row_id, 0, $suffixPos);
256
257     // Find beginning of value.
258     $posBegin = 1 + strpos($remaninder, ':', $pos);
259     // Find end of value.
260     $posEnd = strpos($remaninder, ',', $posBegin);
261     if ($posEnd === false) $posEnd = strlen($remaninder);
262     // Return value.
263     return substr($remaninder, $posBegin, $posEnd - $posBegin);
264   }
265 }