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