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