A bit of cleanup in week view.
[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('ttUserHelper');
34 import('ttTeamHelper');
35 import('ttClientHelper');
36 import('ttTimeHelper');
37 import('DateAndTime');
38
39 // Access check.
40 if (!ttAccessCheck(right_data_entry)) {
41   header('Location: access_denied.php');
42   exit();
43 }
44
45 // Initialize and store date in session.
46 $cl_date = $request->getParameter('date', @$_SESSION['date']);
47 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
48 if($selected_date->isError())
49   $selected_date = new DateAndTime(DB_DATEFORMAT);
50 if(!$cl_date)
51   $cl_date = $selected_date->toString(DB_DATEFORMAT);
52 $_SESSION['date'] = $cl_date;
53
54 // Determine selected week start and end dates.
55 $weekStartDay = $user->week_start;
56 $t_arr = localtime($selected_date->getTimestamp());
57 $t_arr[5] = $t_arr[5] + 1900;
58 if ($t_arr[6] < $weekStartDay)
59   $startWeekBias = $weekStartDay - 7;
60 else
61   $startWeekBias = $weekStartDay;
62 $startDate = new DateAndTime();
63 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
64 $endDate = new DateAndTime();
65 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
66 // The above is needed to set date range (timestring) in page title.
67
68 // Use custom fields plugin if it is enabled.
69 if ($user->isPluginEnabled('cf')) {
70   require_once('plugins/CustomFields.class.php');
71   $custom_fields = new CustomFields($user->team_id);
72   $smarty->assign('custom_fields', $custom_fields);
73 }
74
75 // TODO: how is this plugin supposed to work for week view?
76 if ($user->isPluginEnabled('mq')){
77   require_once('plugins/MonthlyQuota.class.php');
78   $quota = new MonthlyQuota();
79   $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
80   $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
81   $minutes_left = ttTimeHelper::toMinutes($month_quota) - ttTimeHelper::toMinutes($month_total);
82
83   $smarty->assign('month_total', $month_total);
84   $smarty->assign('over_quota', $minutes_left < 0);
85   $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
86 }
87
88 // Initialize variables.
89 // Custom field.
90 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
91 $_SESSION['cf_1'] = $cl_cf_1;
92 $cl_billable = 1;
93 if ($user->isPluginEnabled('iv')) {
94   if ($request->isPost()) {
95     $cl_billable = $request->getParameter('billable');
96     $_SESSION['billable'] = (int) $cl_billable;
97   } else
98     if (isset($_SESSION['billable']))
99       $cl_billable = $_SESSION['billable'];
100 }
101 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
102 $cl_client = $request->getParameter('client', ($request->getMethod()=='POST'? null : @$_SESSION['client']));
103 $_SESSION['client'] = $cl_client;
104 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
105 $_SESSION['project'] = $cl_project;
106 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? null : @$_SESSION['task']));
107 $_SESSION['task'] = $cl_task;
108
109 // Get the data we need to display week view.
110 // Get column headers, which are day numbers in month.
111 $dayHeaders = ttTimeHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
112 // Build data array for the table. Format is described in the function..
113 $dataArray = ttTimeHelper::getDataForWeekView($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
114 // Build day totals (total durations for each day in week).
115 $dayTotals = ttTimeHelper::getDayTotals($dataArray, $dayHeaders);
116
117 // TODO: refactoring ongoing down from here.
118
119
120
121
122
123
124
125 // Actually this is work in progress at this point, even documenting the array, as we still miss control IDs, and
126 // editing entries is not yet implemented. When this is done, we will have to re-document the above.
127
128 // TODO:
129 // 1) escape cf_1 values in record identifiers as this may come from user for text fields.
130 // 2) make sure we have IDs for cells, which are now missing.
131
132 // Define rendering class for a label field to the left of durations.
133 class LabelCellRenderer extends DefaultCellRenderer {
134   function render(&$table, $value, $row, $column, $selected = false) {
135     $this->setOptions(array('width'=>200,'valign'=>'middle'));
136     $this->setValue(htmlspecialchars($value));
137     return $this->toString();
138   }
139 }
140
141 // Define rendering class for a single cell for time entry in week view table.
142 class TimeCellRenderer extends DefaultCellRenderer {
143   function render(&$table, $value, $row, $column, $selected = false) {
144     $field_name = $table->getValueAtName($row,$column)['id']; // Our text field names (and ids) are like x_y (row_column).
145     $field = new TextField($field_name);
146     $field->setFormName($table->getFormName());
147     $field->setSize(2);
148     $field->setValue($table->getValueAt($row,$column)['duration']);
149     $this->setValue($field->getHtml());
150     return $this->toString();
151   }
152 }
153
154 // Elements of weekTimeForm.
155 $form = new Form('weekTimeForm');
156
157 if ($user->canManageTeam()) {
158   $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
159   if (count($user_list) > 1) {
160     $form->addInput(array('type'=>'combobox',
161       'onchange'=>'this.form.submit();',
162       'name'=>'onBehalfUser',
163       'style'=>'width: 250px;',
164       'value'=>$on_behalf_id,
165       'data'=>$user_list,
166       'datakeys'=>array('id','name')));
167     $smarty->assign('on_behalf_control', 1);
168   }
169 }
170
171 // Create week_durations table.
172 $table = new Table('week_durations');
173 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
174 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
175 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
176 $table->setData($dataArray);
177 // Add columns to table.
178 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
179 $table->addColumn(new TableColumn($dayHeaders['day_header_0'], $dayHeaders['day_header_0'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_0']]));
180 $table->addColumn(new TableColumn($dayHeaders['day_header_1'], $dayHeaders['day_header_1'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_1']]));
181 $table->addColumn(new TableColumn($dayHeaders['day_header_2'], $dayHeaders['day_header_2'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_2']]));
182 $table->addColumn(new TableColumn($dayHeaders['day_header_3'], $dayHeaders['day_header_3'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_3']]));
183 $table->addColumn(new TableColumn($dayHeaders['day_header_4'], $dayHeaders['day_header_4'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_4']]));
184 $table->addColumn(new TableColumn($dayHeaders['day_header_5'], $dayHeaders['day_header_5'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_5']]));
185 $table->addColumn(new TableColumn($dayHeaders['day_header_6'], $dayHeaders['day_header_6'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_6']]));
186 $table->setInteractive(false);
187 $form->addInputElement($table);
188
189 // Dropdown for clients in MODE_TIME. Use all active clients.
190 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
191   $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
192   $form->addInput(array('type'=>'combobox',
193     'onchange'=>'fillProjectDropdown(this.value);',
194     'name'=>'client',
195     'style'=>'width: 250px;',
196     'value'=>$cl_client,
197     'data'=>$active_clients,
198     'datakeys'=>array('id', 'name'),
199     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
200   // Note: in other modes the client list is filtered to relevant clients only. See below.
201 }
202
203 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
204   // Dropdown for projects assigned to user.
205   $project_list = $user->getAssignedProjects();
206   $form->addInput(array('type'=>'combobox',
207     'onchange'=>'fillTaskDropdown(this.value);',
208     'name'=>'project',
209     'style'=>'width: 250px;',
210     'value'=>$cl_project,
211     'data'=>$project_list,
212     'datakeys'=>array('id','name'),
213     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
214
215   // Dropdown for clients if the clients plugin is enabled.
216   if ($user->isPluginEnabled('cl')) {
217     $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
218     // We need an array of assigned project ids to do some trimming.
219     foreach($project_list as $project)
220       $projects_assigned_to_user[] = $project['id'];
221
222     // Build a client list out of active clients. Use only clients that are relevant to user.
223     // Also trim their associated project list to only assigned projects (to user).
224     foreach($active_clients as $client) {
225       $projects_assigned_to_client = explode(',', $client['projects']);
226       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
227         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
228       if ($intersection) {
229         $client['projects'] = implode(',', $intersection);
230         $client_list[] = $client;
231       }
232     }
233     $form->addInput(array('type'=>'combobox',
234       'onchange'=>'fillProjectDropdown(this.value);',
235       'name'=>'client',
236       'style'=>'width: 250px;',
237       'value'=>$cl_client,
238       'data'=>$client_list,
239       'datakeys'=>array('id', 'name'),
240       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
241   }
242 }
243
244 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
245   $task_list = ttTeamHelper::getActiveTasks($user->team_id);
246   $form->addInput(array('type'=>'combobox',
247     'name'=>'task',
248     'style'=>'width: 250px;',
249     'value'=>$cl_task,
250     'data'=>$task_list,
251     'datakeys'=>array('id','name'),
252     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
253 }
254
255 // Add other controls.
256 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
257   $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
258   $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
259   if (!$user->canManageTeam() && defined('READONLY_START_FINISH') && isTrue(READONLY_START_FINISH)) {
260     // Make the start and finish fields read-only.
261     $form->getElement('start')->setEnabled(false);
262     $form->getElement('finish')->setEnabled(false);
263   }
264 }
265 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
266   $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
267 if (!defined('NOTE_INPUT_HEIGHT'))
268         define('NOTE_INPUT_HEIGHT', 40);
269 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
270 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
271 if ($user->isPluginEnabled('iv'))
272   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
273 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
274 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
275
276 // If we have custom fields - add controls for them.
277 if ($custom_fields && $custom_fields->fields[0]) {
278   // Only one custom field is supported at this time.
279   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
280     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
281   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
282     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
283       'style'=>'width: 250px;',
284       'value'=>$cl_cf_1,
285       'data'=>$custom_fields->options,
286       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
287   }
288 }
289
290 // Submit.
291 if ($request->isPost()) {
292   if ($request->getParameter('btn_submit')) {
293
294     // Validate user input.
295     if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
296       $err->add($i18n->getKey('error.client'));
297     if ($custom_fields) {
298       if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
299     }
300     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
301       if (!$cl_project) $err->add($i18n->getKey('error.project'));
302     }
303     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
304       if (!$cl_task) $err->add($i18n->getKey('error.task'));
305     }
306     if (strlen($cl_duration) == 0) {
307       if ($cl_start || $cl_finish) {
308         if (!ttTimeHelper::isValidTime($cl_start))
309           $err->add($i18n->getKey('error.field'), $i18n->getKey('label.start'));
310         if ($cl_finish) {
311           if (!ttTimeHelper::isValidTime($cl_finish))
312             $err->add($i18n->getKey('error.field'), $i18n->getKey('label.finish'));
313           if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
314             $err->add($i18n->getKey('error.interval'), $i18n->getKey('label.finish'), $i18n->getKey('label.start'));
315         }
316       } else {
317         if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
318           $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.start'));
319           $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.finish'));
320         }
321         if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
322           $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.duration'));
323       }
324     } else {
325       if (!ttTimeHelper::isValidDuration($cl_duration))
326         $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
327     }
328     if (!ttValidString($cl_note, true)) $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
329     // Finished validating user input.
330
331     // Prohibit creating entries in future.
332     if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES)) {
333       $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
334       if ($selected_date->after($browser_today))
335         $err->add($i18n->getKey('error.future_date'));
336     }
337
338     // Prohibit creating entries in locked range.
339     if ($user->isDateLocked($selected_date))
340       $err->add($i18n->getKey('error.range_locked'));
341
342     // Prohibit creating another uncompleted record.
343     if ($err->no()) {
344       if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
345         $err->add($i18n->getKey('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->getKey('error.goto_uncompleted')."</a>");
346     }
347
348     // Prohibit creating an overlapping record.
349     if ($err->no()) {
350       if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
351         $err->add($i18n->getKey('error.overlap'));
352     }
353
354     // Insert record.
355     if ($err->no()) {
356       $id = ttTimeHelper::insert(array(
357         'date' => $cl_date,
358         'user_id' => $user->getActiveUser(),
359         'client' => $cl_client,
360         'project' => $cl_project,
361         'task' => $cl_task,
362         'start' => $cl_start,
363         'finish' => $cl_finish,
364         'duration' => $cl_duration,
365         'note' => $cl_note,
366         'billable' => $cl_billable));
367
368       // Insert a custom field if we have it.
369       $result = true;
370       if ($id && $custom_fields && $cl_cf_1) {
371         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
372           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
373         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
374           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
375       }
376       if ($id && $result) {
377         header('Location: time.php');
378         exit();
379       }
380       $err->add($i18n->getKey('error.db'));
381     }
382   } elseif ($request->getParameter('btn_stop')) {
383     // Stop button pressed to finish an uncompleted record.
384     $record_id = $request->getParameter('record_id');
385     $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
386     $browser_date = $request->getParameter('browser_date');
387     $browser_time = $request->getParameter('browser_time');
388
389     // Can we complete this record?
390     if ($record['date'] == $browser_date                                // closing today's record
391       && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
392       && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
393       $res = ttTimeHelper::update(array(
394           'id'=>$record['id'],
395           'date'=>$record['date'],
396           'user_id'=>$user->getActiveUser(),
397           'client'=>$record['client_id'],
398           'project'=>$record['project_id'],
399           'task'=>$record['task_id'],
400           'start'=>$record['start'],
401           'finish'=>$browser_time,
402           'note'=>$record['comment'],
403           'billable'=>$record['billable']));
404       if (!$res)
405         $err->add($i18n->getKey('error.db'));
406     } else {
407       // Cannot complete, redirect for manual edit.
408       header('Location: time_edit.php?id='.$record_id);
409       exit();
410     }
411   }
412   elseif ($request->getParameter('onBehalfUser')) {
413     if($user->canManageTeam()) {
414       unset($_SESSION['behalf_id']);
415       unset($_SESSION['behalf_name']);
416
417       if($on_behalf_id != $user->id) {
418         $_SESSION['behalf_id'] = $on_behalf_id;
419         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
420       }
421       header('Location: week.php');
422       exit();
423     }
424   }
425 } // isPost
426
427 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
428
429 $smarty->assign('selected_date', $selected_date);
430 $smarty->assign('week_total', $week_total);
431
432 $smarty->assign('client_list', $client_list);
433 $smarty->assign('project_list', $project_list);
434 $smarty->assign('task_list', $task_list);
435 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
436 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
437 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
438
439 $smarty->assign('title', $i18n->getKey('title.time'));
440 $smarty->assign('content_page_name', 'week.tpl');
441 $smarty->display('index.tpl');