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