Enhanced week view ith a list of editable records.
[timetracker.git] / week.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 require_once('initialize.php');
30 import('form.Form');
31 import('form.DefaultCellRenderer');
32 import('form.Table');
33 import('form.TextField');
34 import('ttUserHelper');
35 import('ttTeamHelper');
36 import('ttWeekViewHelper');
37 import('ttClientHelper');
38 import('ttTimeHelper');
39 import('DateAndTime');
40
41 // Access check.
42 if (!ttAccessCheck(right_data_entry)) {
43   header('Location: access_denied.php');
44   exit();
45 }
46
47 // Initialize and store date in session.
48 $cl_date = $request->getParameter('date', @$_SESSION['date']);
49 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
50 if($selected_date->isError())
51   $selected_date = new DateAndTime(DB_DATEFORMAT);
52 if(!$cl_date)
53   $cl_date = $selected_date->toString(DB_DATEFORMAT);
54 $_SESSION['date'] = $cl_date;
55
56 // Determine selected week start and end dates.
57 $weekStartDay = $user->week_start;
58 $t_arr = localtime($selected_date->getTimestamp());
59 $t_arr[5] = $t_arr[5] + 1900;
60 if ($t_arr[6] < $weekStartDay)
61   $startWeekBias = $weekStartDay - 7;
62 else
63   $startWeekBias = $weekStartDay;
64 $startDate = new DateAndTime();
65 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
66 $endDate = new DateAndTime();
67 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
68 // The above is needed to set date range (timestring) in page title.
69
70 // Use custom fields plugin if it is enabled.
71 if ($user->isPluginEnabled('cf')) {
72   require_once('plugins/CustomFields.class.php');
73   $custom_fields = new CustomFields($user->team_id);
74   $smarty->assign('custom_fields', $custom_fields);
75 }
76
77 // Use Monthly Quotas plugin, if applicable.
78 if ($user->isPluginEnabled('mq')){
79   require_once('plugins/MonthlyQuota.class.php');
80   $quota = new MonthlyQuota();
81   $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
82   $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
83   $minutes_left = ttTimeHelper::toMinutes($month_quota) - ttTimeHelper::toMinutes($month_total);
84
85   $smarty->assign('month_total', $month_total);
86   $smarty->assign('over_quota', $minutes_left < 0);
87   $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
88 }
89
90 // Initialize variables.
91 // Custom field.
92 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
93 $_SESSION['cf_1'] = $cl_cf_1;
94 $cl_billable = 1;
95 if ($user->isPluginEnabled('iv')) {
96   if ($request->isPost()) {
97     $cl_billable = $request->getParameter('billable');
98     $_SESSION['billable'] = (int) $cl_billable;
99   } else
100     if (isset($_SESSION['billable']))
101       $cl_billable = $_SESSION['billable'];
102 }
103 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
104 $cl_client = $request->getParameter('client', ($request->getMethod()=='POST'? null : @$_SESSION['client']));
105 $_SESSION['client'] = $cl_client;
106 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
107 $_SESSION['project'] = $cl_project;
108 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? null : @$_SESSION['task']));
109 $_SESSION['task'] = $cl_task;
110 $cl_note = trim($request->getParameter('note'));
111
112 // Get the data we need to display week view.
113 // Get column headers, which are day numbers in month.
114 $dayHeaders = ttWeekViewHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
115 $lockedDays = ttWeekViewHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
116 // Get already existing records.
117 $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
118 // Build data array for the table. Format is described in the function.
119 $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
120 // Build day totals (total durations for each day in week).
121 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
122
123 // Define rendering class for a label field to the left of durations.
124 class LabelCellRenderer extends DefaultCellRenderer {
125   function render(&$table, $value, $row, $column, $selected = false) {
126     $this->setOptions(array('width'=>200,'valign'=>'middle'));
127     // Special handling for row 0, which represents a new week entry.
128     if (0 == $row) {
129       $this->setOptions(array('style'=>'text-align: center; font-weight: bold;'));
130     }
131     // Special handling for not billable entries.
132     if ($row > 0) {
133       $row_id = $table->getValueAtName($row,'row_id');
134       $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
135       if (!$billable) {
136         $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
137       }
138     }
139     $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
140     return $this->toString();
141   }
142 }
143
144 // Define rendering class for a single cell for time entry in week view table.
145 class TimeCellRenderer extends DefaultCellRenderer {
146   function render(&$table, $value, $row, $column, $selected = false) {
147     $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
148     $field = new TextField($field_name);
149     // Disable control if the date is locked.
150     global $lockedDays;
151     if ($lockedDays[$column-1])
152       $field->setEnabled(false);
153     $field->setFormName($table->getFormName());
154     $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
155     $field->setValue($table->getValueAt($row,$column)['duration']);
156     // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
157     // because we can't supply start and finish times in week view - there are no fields for them.
158     global $user;
159     if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
160         $field->setEnabled(false);
161     }
162     $this->setValue($field->getHtml());
163     return $this->toString();
164   }
165 }
166
167 // Elements of weekTimeForm.
168 $form = new Form('weekTimeForm');
169
170 if ($user->canManageTeam()) {
171   $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
172   if (count($user_list) > 1) {
173     $form->addInput(array('type'=>'combobox',
174       'onchange'=>'this.form.submit();',
175       'name'=>'onBehalfUser',
176       'style'=>'width: 250px;',
177       'value'=>$on_behalf_id,
178       'data'=>$user_list,
179       'datakeys'=>array('id','name')));
180     $smarty->assign('on_behalf_control', 1);
181   }
182 }
183
184 // Create week_durations table.
185 $table = new Table('week_durations', 'week_view_table');
186 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
187 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
188 $table->setData($dataArray);
189 // Add columns to table.
190 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
191 for ($i = 0; $i < 7; $i++) {
192   $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new TimeCellRenderer(), $dayTotals[$dayHeaders[$i]]));
193 }
194 $table->setInteractive(false);
195 $form->addInputElement($table);
196
197 // Dropdown for clients in MODE_TIME. Use all active clients.
198 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
199   $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
200   $form->addInput(array('type'=>'combobox',
201     'onchange'=>'fillProjectDropdown(this.value);',
202     'name'=>'client',
203     'style'=>'width: 250px;',
204     'value'=>$cl_client,
205     'data'=>$active_clients,
206     'datakeys'=>array('id', 'name'),
207     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
208   // Note: in other modes the client list is filtered to relevant clients only. See below.
209 }
210
211 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
212   // Dropdown for projects assigned to user.
213   $project_list = $user->getAssignedProjects();
214   $form->addInput(array('type'=>'combobox',
215     'onchange'=>'fillTaskDropdown(this.value);',
216     'name'=>'project',
217     'style'=>'width: 250px;',
218     'value'=>$cl_project,
219     'data'=>$project_list,
220     'datakeys'=>array('id','name'),
221     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
222
223   // Dropdown for clients if the clients plugin is enabled.
224   if ($user->isPluginEnabled('cl')) {
225     $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
226     // We need an array of assigned project ids to do some trimming.
227     foreach($project_list as $project)
228       $projects_assigned_to_user[] = $project['id'];
229
230     // Build a client list out of active clients. Use only clients that are relevant to user.
231     // Also trim their associated project list to only assigned projects (to user).
232     foreach($active_clients as $client) {
233       $projects_assigned_to_client = explode(',', $client['projects']);
234       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
235         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
236       if ($intersection) {
237         $client['projects'] = implode(',', $intersection);
238         $client_list[] = $client;
239       }
240     }
241     $form->addInput(array('type'=>'combobox',
242       'onchange'=>'fillProjectDropdown(this.value);',
243       'name'=>'client',
244       'style'=>'width: 250px;',
245       'value'=>$cl_client,
246       'data'=>$client_list,
247       'datakeys'=>array('id', 'name'),
248       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
249   }
250 }
251
252 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
253   $task_list = ttTeamHelper::getActiveTasks($user->team_id);
254   $form->addInput(array('type'=>'combobox',
255     'name'=>'task',
256     'style'=>'width: 250px;',
257     'value'=>$cl_task,
258     'data'=>$task_list,
259     'datakeys'=>array('id','name'),
260     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
261 }
262 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
263
264 // Add other controls.
265 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
266 if ($user->isPluginEnabled('iv'))
267   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
268 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
269 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
270
271 // If we have custom fields - add controls for them.
272 if ($custom_fields && $custom_fields->fields[0]) {
273   // Only one custom field is supported at this time.
274   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
275     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
276   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
277     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
278       'style'=>'width: 250px;',
279       'value'=>$cl_cf_1,
280       'data'=>$custom_fields->options,
281       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
282   }
283 }
284
285 // Submit.
286 if ($request->isPost()) {
287   if ($request->getParameter('btn_submit')) {
288     // Validate user input for row 0.
289     // Determine if a new entry was posted.
290     $newEntryPosted = false;
291     foreach($dayHeaders as $dayHeader) {
292       $control_id = '0_'.$dayHeader;
293       if ($request->getParameter($control_id)) {
294         $newEntryPosted = true;
295         break;
296       }
297     }
298     if ($newEntryPosted) {
299       if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
300         $err->add($i18n->getKey('error.client'));
301       if ($custom_fields) {
302         if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
303       }
304       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
305         if (!$cl_project) $err->add($i18n->getKey('error.project'));
306       }
307       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
308         if (!$cl_task) $err->add($i18n->getKey('error.task'));
309       }
310     }
311
312     // Process the table of values.
313     if ($err->no()) {
314
315       // Obtain values. Iterate through posted parameters one by one,
316       // see if value changed, apply one change at a time until we see an error.
317       $result = true;
318       $rowNumber = 0;
319       // Iterate through existing rows.
320       foreach ($dataArray as $row) {
321         // Iterate through days.
322         foreach ($dayHeaders as $key => $dayHeader) {
323           // Do not process locked days.
324           if ($lockedDays[$key]) continue;
325           // Make control id for the cell.
326           $control_id = $rowNumber.'_'.$dayHeader;
327           // Optain existing and posted durations.
328           $postedDuration = $request->getParameter($control_id);
329           $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
330           // If posted value is not null, check and normalize it.
331           if ($postedDuration) {
332             if (ttTimeHelper::isValidDuration($postedDuration)) {
333               $postedDuration = ttTimeHelper::normalizeDuration($postedDuration, false); // No leading zero.
334             } else {
335               $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
336               $result = false; break; // Break out. Stop any further processing.
337             }
338           }
339           // Do not process if value has not changed.
340           if ($postedDuration == $existingDuration)
341             continue;
342           // Posted value is different.
343           if ($existingDuration == null) {
344             // Skip inserting 0 duration values.
345             if (0 == ttTimeHelper::toMinutes($postedDuration))
346               continue;
347             // Insert a new record.
348             $fields = array();
349             $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
350             if (!$fields['row_id']) {
351               // Special handling for row 0, a new entry. Need to construct new row_id.
352               $record = array();
353               $record['client_id'] = $cl_client;
354               $record['billable'] = $cl_billable ? '1' : '0';
355               $record['project_id'] = $cl_project;
356               $record['task_id'] = $cl_task;
357               $record['cf_1_value'] = $cl_cf_1;
358               $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
359               // Note: no need to check for a possible conflict with an already existing row
360               // because we are doing an insert that does not affect already existing data.
361
362               $fields['note'] = $cl_note;
363             }
364             $fields['day_header'] = $dayHeader;
365             $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
366             $fields['duration'] = $postedDuration;
367             $fields['browser_today'] = $request->getParameter('browser_today', null);
368             $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
369           } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
370             // Delete an already existing record here.
371             $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
372           } else {
373             $fields = array();
374             $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
375             $fields['duration'] = $postedDuration;
376             $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
377           }
378           if (!$result) break; // Break out of the loop in case of first error.
379         }
380         if (!$result) break; // Break out of the loop in case of first error.
381         $rowNumber++;
382       }
383       if ($result) {
384         header('Location: week.php'); // Normal exit.
385         exit();
386       }
387     }
388   }
389   elseif ($request->getParameter('onBehalfUser')) {
390     if($user->canManageTeam()) {
391       unset($_SESSION['behalf_id']);
392       unset($_SESSION['behalf_name']);
393
394       if($on_behalf_id != $user->id) {
395         $_SESSION['behalf_id'] = $on_behalf_id;
396         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
397       }
398       header('Location: week.php');
399       exit();
400     }
401   }
402 } // isPost
403
404 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
405
406 $smarty->assign('selected_date', $selected_date);
407 $smarty->assign('week_total', $week_total);
408
409 $smarty->assign('client_list', $client_list);
410 $smarty->assign('project_list', $project_list);
411 $smarty->assign('task_list', $task_list);
412 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
413 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
414 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
415 $smarty->assign('time_records', $records);
416
417 $smarty->assign('title', $i18n->getKey('title.time'));
418 $smarty->assign('content_page_name', 'week.tpl');
419 $smarty->display('index.tpl');