Adjusted monthly quotas plugin to use configurable holidays.
[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('ttGroupHelper');
36 import('ttWeekViewHelper');
37 import('ttClientHelper');
38 import('ttTimeHelper');
39 import('DateAndTime');
40
41 // Access checks.
42 if (!(ttAccessAllowed('track_own_time') || ttAccessAllowed('track_time'))) {
43   header('Location: access_denied.php');
44   exit();
45 }
46 if (!$user->isPluginEnabled('wv')) {
47   header('Location: feature_disabled.php');
48   exit();
49 }
50 if ($user->behalf_id && (!$user->can('track_time') || !$user->checkBehalfId())) {
51   header('Location: access_denied.php'); // Trying on behalf, but no right or wrong user.
52   exit();
53 }
54 if (!$user->behalf_id && !$user->can('track_own_time') && !$user->adjustBehalfId()) {
55   header('Location: access_denied.php'); // Trying as self, but no right for self, and noone to work on behalf.
56   exit();
57 }
58 // End of access checks.
59
60 $showClient = $user->isPluginEnabled('cl');
61 $showFiles = $user->isPluginEnabled('at');
62
63 // Initialize and store date in session.
64 $cl_date = $request->getParameter('date', @$_SESSION['date']);
65 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
66 if($selected_date->isError())
67   $selected_date = new DateAndTime(DB_DATEFORMAT);
68 if(!$cl_date)
69   $cl_date = $selected_date->toString(DB_DATEFORMAT);
70 $_SESSION['date'] = $cl_date;
71
72 // Determine selected week start and end dates.
73 $weekStartDay = $user->week_start;
74 $t_arr = localtime($selected_date->getTimestamp());
75 $t_arr[5] = $t_arr[5] + 1900;
76 if ($t_arr[6] < $weekStartDay)
77   $startWeekBias = $weekStartDay - 7;
78 else
79   $startWeekBias = $weekStartDay;
80 $startDate = new DateAndTime();
81 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
82 $endDate = new DateAndTime();
83 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
84 // The above is needed to set date range (timestring) in page title.
85
86 // Use custom fields plugin if it is enabled.
87 if ($user->isPluginEnabled('cf')) {
88   require_once('plugins/CustomFields.class.php');
89   $custom_fields = new CustomFields();
90   $smarty->assign('custom_fields', $custom_fields);
91 }
92
93 // Use Monthly Quotas plugin, if applicable.
94 if ($user->isPluginEnabled('mq')){
95   require_once('plugins/MonthlyQuota.class.php');
96   $quota = new MonthlyQuota();
97   $month_quota_minutes = $quota->getUserQuota($selected_date->mYear, $selected_date->mMonth);
98   $month_total = ttTimeHelper::getTimeForMonth($selected_date);
99   $minutes_left = $month_quota_minutes - ttTimeHelper::toMinutes($month_total);
100
101   $smarty->assign('month_total', $month_total);
102   $smarty->assign('over_quota', $minutes_left < 0);
103   $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
104 }
105
106 // Initialize variables.
107 // Custom field.
108 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
109 $_SESSION['cf_1'] = $cl_cf_1;
110 $cl_billable = 1;
111 if ($user->isPluginEnabled('iv')) {
112   if ($request->isPost()) {
113     $cl_billable = $request->getParameter('billable');
114     $_SESSION['billable'] = (int) $cl_billable;
115   } else
116     if (isset($_SESSION['billable']))
117       $cl_billable = $_SESSION['billable'];
118 }
119 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
120 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
121 $_SESSION['client'] = $cl_client;
122 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
123 $_SESSION['project'] = $cl_project;
124 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
125 $_SESSION['task'] = $cl_task;
126 $cl_note = $request->getParameter('note', ($request->isPost() ? null : @$_SESSION['note']));
127 $_SESSION['note'] = $cl_note;
128
129 // Get the data we need to display week view.
130 // Get column headers, which are day numbers in month.
131 $dayHeaders = ttWeekViewHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
132 $lockedDays = ttWeekViewHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
133 // Get already existing records.
134 $records = ttWeekViewHelper::getRecordsForInterval($startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT), $showFiles);
135 // Build data array for the table. Format is described in ttWeekViewHelper::getDataForWeekView function.
136 if ($records)
137   $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
138 else
139   $dataArray = ttWeekViewHelper::prePopulateFromPastWeeks($startDate->toString(DB_DATEFORMAT), $dayHeaders);
140
141 // Build day totals (total durations for each day in week).
142 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
143
144 // Define rendering class for a label field to the left of durations.
145 class LabelCellRenderer extends DefaultCellRenderer {
146   function render(&$table, $value, $row, $column, $selected = false) {
147     global $user;
148
149     $this->setOptions(array('width'=>200,'valign'=>'middle'));
150
151     // Special handling for a new week entry (row 0, or 0 and 1 if we show notes).
152     if (0 == $row) {
153       $this->setOptions(array('style'=>'text-align: center; font-weight: bold; vertical-align: top;'));
154     } else if ($user->isPluginEnabled('wvns') && (1 == $row)) {
155       $this->setOptions(array('style'=>'text-align: right; vertical-align: top;'));
156     } else if ($user->isPluginEnabled('wvns') && (0 != $row % 2)) {
157       $this->setOptions(array('style'=>'text-align: right;'));
158     }
159     // Special handling for not billable entries.
160     $ignoreRow = $user->isPluginEnabled('wvns') ? 1 : 0; 
161     if ($row > $ignoreRow) {
162       $row_id = $table->getValueAtName($row,'row_id');
163       $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
164       if (!$billable) {
165         if (($user->isPluginEnabled('wvns') && (0 == $row % 2)) || !$user->isPluginEnabled('wvns')) {
166           $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
167         }
168       }
169     }
170     $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
171     return $this->toString();
172   }
173 }
174
175 // Define rendering class for a single cell for a time or a comment entry in week view table.
176 class WeekViewCellRenderer extends DefaultCellRenderer {
177   function render(&$table, $value, $row, $column, $selected = false) {
178     global $user;
179
180     $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
181     $field = new TextField($field_name);
182     // Disable control if the date is locked.
183     global $lockedDays;
184     if ($lockedDays[$column-1])
185       $field->setEnabled(false);
186     $field->setFormName($table->getFormName());
187     $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
188     // Provide visual separation for new entry row.
189     $rowToSeparate = $user->isPluginEnabled('wvns') ? 1 : 0;
190     if ($rowToSeparate == $row) {
191       $field->setStyle('width: 60px; margin-bottom: 40px');
192     }
193     if ($user->isPluginEnabled('wvns')) {
194       if (0 == $row % 2) {
195         $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
196       } else {
197         $field->setValue($table->getValueAt($row,$column)['note']);     // Comment for odd rows.
198         $field->setTitle($table->getValueAt($row,$column)['note']);     // Tooltip to help view the entire comment.
199       }
200     } else {
201       $field->setValue($table->getValueAt($row,$column)['duration']);
202       // $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to see comment. TODO - value not available.
203     }
204     // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
205     // because we can't supply start and finish times in week view - there are no fields for them.
206     if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
207         $field->setEnabled(false);
208     }
209     $this->setValue($field->getHtml());
210     return $this->toString();
211   }
212 }
213
214 // Elements of weekTimeForm.
215 $form = new Form('weekTimeForm');
216
217 if ($user->can('track_time')) {
218   if ($user->can('track_own_time'))
219     $options = array('status'=>ACTIVE,'max_rank'=>$user->rank-1,'include_self'=>true,'self_first'=>true);
220   else
221     $options = array('status'=>ACTIVE,'max_rank'=>$user->rank-1);
222   $user_list = $user->getUsers($options);
223   if (count($user_list) >= 1) {
224     $form->addInput(array('type'=>'combobox',
225       'onchange'=>'this.form.submit();',
226       'name'=>'onBehalfUser',
227       'style'=>'width: 250px;',
228       'value'=>$on_behalf_id,
229       'data'=>$user_list,
230       'datakeys'=>array('id','name')));
231     $smarty->assign('on_behalf_control', 1);
232   }
233 }
234
235 // Create week_durations table.
236 $table = new Table('week_durations', 'week_view_table');
237 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
238 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
239 $table->setData($dataArray);
240 // Add columns to table.
241 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
242 for ($i = 0; $i < 7; $i++) {
243   $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new WeekViewCellRenderer(), $dayTotals[$dayHeaders[$i]]));
244 }
245 $table->setInteractive(false);
246 $form->addInputElement($table);
247
248 // Dropdown for clients in MODE_TIME. Use all active clients.
249 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
250   $active_clients = ttGroupHelper::getActiveClients(true);
251   $form->addInput(array('type'=>'combobox',
252     'onchange'=>'fillProjectDropdown(this.value);',
253     'name'=>'client',
254     'style'=>'width: 250px;',
255     'value'=>$cl_client,
256     'data'=>$active_clients,
257     'datakeys'=>array('id', 'name'),
258     'empty'=>array(''=>$i18n->get('dropdown.select'))));
259   // Note: in other modes the client list is filtered to relevant clients only. See below.
260 }
261
262 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
263   // Dropdown for projects assigned to user.
264   $project_list = $user->getAssignedProjects();
265   $form->addInput(array('type'=>'combobox',
266     'onchange'=>'fillTaskDropdown(this.value);',
267     'name'=>'project',
268     'style'=>'width: 250px;',
269     'value'=>$cl_project,
270     'data'=>$project_list,
271     'datakeys'=>array('id','name'),
272     'empty'=>array(''=>$i18n->get('dropdown.select'))));
273
274   // Dropdown for clients if the clients plugin is enabled.
275   if ($user->isPluginEnabled('cl')) {
276     $active_clients = ttGroupHelper::getActiveClients(true);
277     // We need an array of assigned project ids to do some trimming.
278     foreach($project_list as $project)
279       $projects_assigned_to_user[] = $project['id'];
280
281     // Build a client list out of active clients. Use only clients that are relevant to user.
282     // Also trim their associated project list to only assigned projects (to user).
283     foreach($active_clients as $client) {
284       $projects_assigned_to_client = explode(',', $client['projects']);
285       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
286         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
287       if ($intersection) {
288         $client['projects'] = implode(',', $intersection);
289         $client_list[] = $client;
290       }
291     }
292     $form->addInput(array('type'=>'combobox',
293       'onchange'=>'fillProjectDropdown(this.value);',
294       'name'=>'client',
295       'style'=>'width: 250px;',
296       'value'=>$cl_client,
297       'data'=>$client_list,
298       'datakeys'=>array('id', 'name'),
299       'empty'=>array(''=>$i18n->get('dropdown.select'))));
300   }
301 }
302
303 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
304   $task_list = ttGroupHelper::getActiveTasks();
305   $form->addInput(array('type'=>'combobox',
306     'name'=>'task',
307     'style'=>'width: 250px;',
308     'value'=>$cl_task,
309     'data'=>$task_list,
310     'datakeys'=>array('id','name'),
311     'empty'=>array(''=>$i18n->get('dropdown.select'))));
312 }
313 if (!defined('NOTE_INPUT_HEIGHT'))
314   define('NOTE_INPUT_HEIGHT', 40);
315 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
316
317 // Add other controls.
318 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
319 if ($user->isPluginEnabled('iv'))
320   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
321 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
322 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->get('button.submit')));
323
324 // If we have custom fields - add controls for them.
325 if ($custom_fields && $custom_fields->fields[0]) {
326   // Only one custom field is supported at this time.
327   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
328     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
329   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
330     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
331       'style'=>'width: 250px;',
332       'value'=>$cl_cf_1,
333       'data'=>$custom_fields->options,
334       'empty'=>array(''=>$i18n->get('dropdown.select'))));
335   }
336 }
337
338 // Submit.
339 if ($request->isPost()) {
340   if ($request->getParameter('btn_submit')) {
341     // Validate user input for row 0.
342     // Determine if a new entry was posted.
343     $newEntryPosted = false;
344     foreach($dayHeaders as $dayHeader) {
345       $control_id = '0_'.$dayHeader;
346       if ($request->getParameter($control_id)) {
347         $newEntryPosted = true;
348         break;
349       }
350     }
351     if ($newEntryPosted) {
352       if ($user->isPluginEnabled('cl') && $user->isOptionEnabled('client_required') && !$cl_client)
353         $err->add($i18n->get('error.client'));
354       if ($custom_fields) {
355         if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->get('error.field'), $custom_fields->fields[0]['label']);
356       }
357       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
358         if (!$cl_project) $err->add($i18n->get('error.project'));
359       }
360       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
361         if (!$cl_task) $err->add($i18n->get('error.task'));
362       }
363     }
364     // Finished validating user input for row 0.
365
366     // Process the table of values.
367     if ($err->no()) {
368
369       // Obtain values. Iterate through posted parameters one by one,
370       // see if value changed, apply one change at a time until we see an error.
371       $result = true;
372       $rowNumber = 0;
373       // Iterate through existing rows.
374       foreach ($dataArray as $row) {
375         // Iterate through days.
376         foreach ($dayHeaders as $key => $dayHeader) {
377           // Do not process locked days.
378           if ($lockedDays[$key]) continue;
379           // Make control id for the cell.
380           $control_id = $rowNumber.'_'.$dayHeader;
381
382           // Handle durations and comments in separate blocks of code.
383           if (!$user->isPluginEnabled('wvns') || (0 == $rowNumber % 2)) {
384             // Handle durations row here.
385
386             // Obtain existing and posted durations.
387             $postedDuration = $request->getParameter($control_id);
388             $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
389             // If posted value is not null, check and normalize it.
390             if ($postedDuration) {
391               if (false === ttTimeHelper::postedDurationToMinutes($postedDuration)) {
392                 $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
393                 $result = false; break; // Break out. Stop any further processing.
394               } else {
395                 $minutes = ttTimeHelper::postedDurationToMinutes($postedDuration);
396                 $postedDuration = ttTimeHelper::minutesToDuration($minutes);
397               }
398             }
399             // Do not process if value has not changed.
400             if ($postedDuration == $existingDuration)
401               continue;
402             // Posted value is different.
403             if ($existingDuration == null) {
404               // Skip inserting 0 duration values.
405               if (0 == ttTimeHelper::toMinutes($postedDuration))
406                 continue;
407               // Insert a new record.
408               $fields = array();
409               $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
410               if (!$fields['row_id']) {
411                 // Special handling for row 0, a new entry. Need to construct new row_id.
412                 $record = array();
413                 $record['client_id'] = $cl_client;
414                 $record['billable'] = $cl_billable ? '1' : '0';
415                 $record['project_id'] = $cl_project;
416                 $record['task_id'] = $cl_task;
417                 $record['cf_1_value'] = $cl_cf_1;
418                 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
419                 // Note: no need to check for a possible conflict with an already existing row
420                 // because we are doing an insert that does not affect already existing data.
421
422                 if ($user->isPluginEnabled('wvn')) {
423                   $fields['note'] = $request->getParameter('note');
424                 }
425               }
426               $fields['day_header'] = $dayHeader;
427               $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
428               $fields['duration'] = $postedDuration;
429               $fields['browser_today'] = $request->getParameter('browser_today', null);
430               if ($user->isPluginEnabled('wvns')) {
431                 // Take note value from the control below duration.
432                 $noteRowNumber = $rowNumber + 1;
433                 $note_control_id =  $noteRowNumber.'_'.$dayHeader;
434                 $fields['note'] = $request->getParameter($note_control_id);
435               }
436               $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
437             } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
438               // Delete an already existing record here.
439               $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getUser());
440             } else {
441               $fields = array();
442               $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
443               $fields['duration'] = $postedDuration;
444               $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
445             }
446             if (!$result) break; // Break out of the loop in case of first error.
447
448           } else if ($user->isPluginEnabled('wvns')) {
449             // Handle commments row here.
450
451             // Obtain existing and posted comments.
452             $postedComment = $request->getParameter($control_id);
453             $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
454             // If posted value is not null, check it.
455             if ($postedComment && !ttValidString($postedComment, true)) {
456               $err->add($i18n->get('error.field'), $i18n->get('label.note'));
457               $result = false; break; // Break out. Stop any further processing.
458             }
459             // Do not process if value has not changed.
460             if ($postedComment == $existingComment)
461               continue;
462
463             // Posted value is different.
464             // TODO: handle new entries separately in the durations block above.
465
466             // Here, only update the comment on an already existing record.
467             $fields = array();
468             $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
469             if ($fields['tt_log_id']) {
470               $fields['comment'] = $postedComment;
471               $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
472             }
473             if (!$result) break; // Break out of the loop in case of first error.
474           }
475         }
476         if (!$result) break; // Break out of the loop in case of first error.
477         $rowNumber++;
478       }
479       if ($result) {
480         header('Location: week.php'); // Normal exit.
481         exit();
482       }
483     }
484   }
485   elseif ($request->getParameter('onBehalfUser')) {
486     if($user->can('track_time')) {
487       unset($_SESSION['behalf_id']);
488       unset($_SESSION['behalf_name']);
489
490       if($on_behalf_id != $user->id) {
491         $_SESSION['behalf_id'] = $on_behalf_id;
492         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
493       }
494       header('Location: week.php');
495       exit();
496     }
497   }
498 } // isPost
499
500 $week_total = ttTimeHelper::getTimeForWeek($selected_date);
501
502 $smarty->assign('selected_date', $selected_date);
503 $smarty->assign('week_total', $week_total);
504
505 $smarty->assign('client_list', $client_list);
506 $smarty->assign('project_list', $project_list);
507 $smarty->assign('task_list', $task_list);
508 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
509 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
510 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
511 $smarty->assign('time_records', $records);
512 $smarty->assign('show_navigation', !$user->getConfigOption('menu_week'));
513 $smarty->assign('show_client', $showClient);
514 $smarty->assign('show_files', $showFiles);
515 $smarty->assign('title', $i18n->get('menu.week'));
516 $smarty->assign('content_page_name', 'week.tpl');
517 $smarty->display('index.tpl');