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