Added proper IDs to week view controls.
[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), $dayHeaders);
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 // 1) Start coding modification of existing records.
120 // 2) Then adding new records for existing rows.
121 // 3) Then add code and UI for adding a new row.
122
123 // Actually this is work in progress at this point, even documenting the array, as we still miss control IDs, and
124 // editing entries is not yet implemented. When this is done, we will have to re-document the above.
125
126 // Define rendering class for a label field to the left of durations.
127 class LabelCellRenderer extends DefaultCellRenderer {
128   function render(&$table, $value, $row, $column, $selected = false) {
129     $this->setOptions(array('width'=>200,'valign'=>'middle'));
130     $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
131     return $this->toString();
132   }
133 }
134
135 // Define rendering class for a single cell for time entry in week view table.
136 class TimeCellRenderer extends DefaultCellRenderer {
137   function render(&$table, $value, $row, $column, $selected = false) {
138     $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
139     $field = new TextField($field_name);
140     $field->setFormName($table->getFormName());
141     $field->setSize(2);
142     $field->setValue($table->getValueAt($row,$column)['duration']);
143     $this->setValue($field->getHtml());
144     return $this->toString();
145   }
146 }
147
148 // Elements of weekTimeForm.
149 $form = new Form('weekTimeForm');
150
151 if ($user->canManageTeam()) {
152   $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
153   if (count($user_list) > 1) {
154     $form->addInput(array('type'=>'combobox',
155       'onchange'=>'this.form.submit();',
156       'name'=>'onBehalfUser',
157       'style'=>'width: 250px;',
158       'value'=>$on_behalf_id,
159       'data'=>$user_list,
160       'datakeys'=>array('id','name')));
161     $smarty->assign('on_behalf_control', 1);
162   }
163 }
164
165 // Create week_durations table.
166 $table = new Table('week_durations');
167 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
168 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
169 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
170 $table->setData($dataArray);
171 // Add columns to table.
172 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
173 for ($i = 0; $i < 7; $i++) {
174   $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new TimeCellRenderer(), $dayTotals[$dayHeaders[$i]]));
175 }
176 $table->setInteractive(false);
177 $form->addInputElement($table);
178
179 // Dropdown for clients in MODE_TIME. Use all active clients.
180 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
181   $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
182   $form->addInput(array('type'=>'combobox',
183     'onchange'=>'fillProjectDropdown(this.value);',
184     'name'=>'client',
185     'style'=>'width: 250px;',
186     'value'=>$cl_client,
187     'data'=>$active_clients,
188     'datakeys'=>array('id', 'name'),
189     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
190   // Note: in other modes the client list is filtered to relevant clients only. See below.
191 }
192
193 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
194   // Dropdown for projects assigned to user.
195   $project_list = $user->getAssignedProjects();
196   $form->addInput(array('type'=>'combobox',
197     'onchange'=>'fillTaskDropdown(this.value);',
198     'name'=>'project',
199     'style'=>'width: 250px;',
200     'value'=>$cl_project,
201     'data'=>$project_list,
202     'datakeys'=>array('id','name'),
203     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
204
205   // Dropdown for clients if the clients plugin is enabled.
206   if ($user->isPluginEnabled('cl')) {
207     $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
208     // We need an array of assigned project ids to do some trimming.
209     foreach($project_list as $project)
210       $projects_assigned_to_user[] = $project['id'];
211
212     // Build a client list out of active clients. Use only clients that are relevant to user.
213     // Also trim their associated project list to only assigned projects (to user).
214     foreach($active_clients as $client) {
215       $projects_assigned_to_client = explode(',', $client['projects']);
216       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
217         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
218       if ($intersection) {
219         $client['projects'] = implode(',', $intersection);
220         $client_list[] = $client;
221       }
222     }
223     $form->addInput(array('type'=>'combobox',
224       'onchange'=>'fillProjectDropdown(this.value);',
225       'name'=>'client',
226       'style'=>'width: 250px;',
227       'value'=>$cl_client,
228       'data'=>$client_list,
229       'datakeys'=>array('id', 'name'),
230       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
231   }
232 }
233
234 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
235   $task_list = ttTeamHelper::getActiveTasks($user->team_id);
236   $form->addInput(array('type'=>'combobox',
237     'name'=>'task',
238     'style'=>'width: 250px;',
239     'value'=>$cl_task,
240     'data'=>$task_list,
241     'datakeys'=>array('id','name'),
242     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
243 }
244
245 // Add other controls.
246 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
247   $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
248   $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
249   if (!$user->canManageTeam() && defined('READONLY_START_FINISH') && isTrue(READONLY_START_FINISH)) {
250     // Make the start and finish fields read-only.
251     $form->getElement('start')->setEnabled(false);
252     $form->getElement('finish')->setEnabled(false);
253   }
254 }
255 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
256   $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
257 if (!defined('NOTE_INPUT_HEIGHT'))
258         define('NOTE_INPUT_HEIGHT', 40);
259 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
260 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
261 if ($user->isPluginEnabled('iv'))
262   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
263 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
264 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
265
266 // If we have custom fields - add controls for them.
267 if ($custom_fields && $custom_fields->fields[0]) {
268   // Only one custom field is supported at this time.
269   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
270     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
271   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
272     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
273       'style'=>'width: 250px;',
274       'value'=>$cl_cf_1,
275       'data'=>$custom_fields->options,
276       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
277   }
278 }
279
280 // Submit.
281 if ($request->isPost()) {
282   if ($request->getParameter('btn_submit')) {
283
284     // Validate user input.
285     if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
286       $err->add($i18n->getKey('error.client'));
287     if ($custom_fields) {
288       if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
289     }
290     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
291       if (!$cl_project) $err->add($i18n->getKey('error.project'));
292     }
293     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
294       if (!$cl_task) $err->add($i18n->getKey('error.task'));
295     }
296     if (strlen($cl_duration) == 0) {
297       if ($cl_start || $cl_finish) {
298         if (!ttTimeHelper::isValidTime($cl_start))
299           $err->add($i18n->getKey('error.field'), $i18n->getKey('label.start'));
300         if ($cl_finish) {
301           if (!ttTimeHelper::isValidTime($cl_finish))
302             $err->add($i18n->getKey('error.field'), $i18n->getKey('label.finish'));
303           if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
304             $err->add($i18n->getKey('error.interval'), $i18n->getKey('label.finish'), $i18n->getKey('label.start'));
305         }
306       } else {
307         if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
308           $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.start'));
309           $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.finish'));
310         }
311         if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
312           $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.duration'));
313       }
314     } else {
315       if (!ttTimeHelper::isValidDuration($cl_duration))
316         $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
317     }
318     if (!ttValidString($cl_note, true)) $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
319     // Finished validating user input.
320
321     // Prohibit creating entries in future.
322     if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES)) {
323       $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
324       if ($selected_date->after($browser_today))
325         $err->add($i18n->getKey('error.future_date'));
326     }
327
328     // Prohibit creating entries in locked range.
329     if ($user->isDateLocked($selected_date))
330       $err->add($i18n->getKey('error.range_locked'));
331
332     // Prohibit creating another uncompleted record.
333     if ($err->no()) {
334       if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
335         $err->add($i18n->getKey('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->getKey('error.goto_uncompleted')."</a>");
336     }
337
338     // Prohibit creating an overlapping record.
339     if ($err->no()) {
340       if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
341         $err->add($i18n->getKey('error.overlap'));
342     }
343
344     // Insert record.
345     if ($err->no()) {
346       $id = ttTimeHelper::insert(array(
347         'date' => $cl_date,
348         'user_id' => $user->getActiveUser(),
349         'client' => $cl_client,
350         'project' => $cl_project,
351         'task' => $cl_task,
352         'start' => $cl_start,
353         'finish' => $cl_finish,
354         'duration' => $cl_duration,
355         'note' => $cl_note,
356         'billable' => $cl_billable));
357
358       // Insert a custom field if we have it.
359       $result = true;
360       if ($id && $custom_fields && $cl_cf_1) {
361         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
362           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
363         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
364           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
365       }
366       if ($id && $result) {
367         header('Location: time.php');
368         exit();
369       }
370       $err->add($i18n->getKey('error.db'));
371     }
372   } elseif ($request->getParameter('btn_stop')) {
373     // Stop button pressed to finish an uncompleted record.
374     $record_id = $request->getParameter('record_id');
375     $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
376     $browser_date = $request->getParameter('browser_date');
377     $browser_time = $request->getParameter('browser_time');
378
379     // Can we complete this record?
380     if ($record['date'] == $browser_date                                // closing today's record
381       && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
382       && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
383       $res = ttTimeHelper::update(array(
384           'id'=>$record['id'],
385           'date'=>$record['date'],
386           'user_id'=>$user->getActiveUser(),
387           'client'=>$record['client_id'],
388           'project'=>$record['project_id'],
389           'task'=>$record['task_id'],
390           'start'=>$record['start'],
391           'finish'=>$browser_time,
392           'note'=>$record['comment'],
393           'billable'=>$record['billable']));
394       if (!$res)
395         $err->add($i18n->getKey('error.db'));
396     } else {
397       // Cannot complete, redirect for manual edit.
398       header('Location: time_edit.php?id='.$record_id);
399       exit();
400     }
401   }
402   elseif ($request->getParameter('onBehalfUser')) {
403     if($user->canManageTeam()) {
404       unset($_SESSION['behalf_id']);
405       unset($_SESSION['behalf_name']);
406
407       if($on_behalf_id != $user->id) {
408         $_SESSION['behalf_id'] = $on_behalf_id;
409         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
410       }
411       header('Location: week.php');
412       exit();
413     }
414   }
415 } // isPost
416
417 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
418
419 $smarty->assign('selected_date', $selected_date);
420 $smarty->assign('week_total', $week_total);
421
422 $smarty->assign('client_list', $client_list);
423 $smarty->assign('project_list', $project_list);
424 $smarty->assign('task_list', $task_list);
425 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
426 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
427 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
428
429 $smarty->assign('title', $i18n->getKey('title.time'));
430 $smarty->assign('content_page_name', 'week.tpl');
431 $smarty->display('index.tpl');