Added a field for note value in week view to apply to new entries.
[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('ttClientHelper');
37 import('ttTimeHelper');
38 import('DateAndTime');
39
40 // Access check.
41 if (!ttAccessCheck(right_data_entry)) {
42   header('Location: access_denied.php');
43   exit();
44 }
45
46 // Initialize and store date in session.
47 $cl_date = $request->getParameter('date', @$_SESSION['date']);
48 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
49 if($selected_date->isError())
50   $selected_date = new DateAndTime(DB_DATEFORMAT);
51 if(!$cl_date)
52   $cl_date = $selected_date->toString(DB_DATEFORMAT);
53 $_SESSION['date'] = $cl_date;
54
55 // Determine selected week start and end dates.
56 $weekStartDay = $user->week_start;
57 $t_arr = localtime($selected_date->getTimestamp());
58 $t_arr[5] = $t_arr[5] + 1900;
59 if ($t_arr[6] < $weekStartDay)
60   $startWeekBias = $weekStartDay - 7;
61 else
62   $startWeekBias = $weekStartDay;
63 $startDate = new DateAndTime();
64 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
65 $endDate = new DateAndTime();
66 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
67 // The above is needed to set date range (timestring) in page title.
68
69 // Use custom fields plugin if it is enabled.
70 if ($user->isPluginEnabled('cf')) {
71   require_once('plugins/CustomFields.class.php');
72   $custom_fields = new CustomFields($user->team_id);
73   $smarty->assign('custom_fields', $custom_fields);
74 }
75
76 // TODO: how is this plugin supposed to work for week view?
77 if ($user->isPluginEnabled('mq')){
78   require_once('plugins/MonthlyQuota.class.php');
79   $quota = new MonthlyQuota();
80   $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
81   $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
82   $minutes_left = ttTimeHelper::toMinutes($month_quota) - ttTimeHelper::toMinutes($month_total);
83
84   $smarty->assign('month_total', $month_total);
85   $smarty->assign('over_quota', $minutes_left < 0);
86   $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
87 }
88
89 // Initialize variables.
90 // Custom field.
91 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
92 $_SESSION['cf_1'] = $cl_cf_1;
93 $cl_billable = 1;
94 if ($user->isPluginEnabled('iv')) {
95   if ($request->isPost()) {
96     $cl_billable = $request->getParameter('billable');
97     $_SESSION['billable'] = (int) $cl_billable;
98   } else
99     if (isset($_SESSION['billable']))
100       $cl_billable = $_SESSION['billable'];
101 }
102 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
103 $cl_client = $request->getParameter('client', ($request->getMethod()=='POST'? null : @$_SESSION['client']));
104 $_SESSION['client'] = $cl_client;
105 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
106 $_SESSION['project'] = $cl_project;
107 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? null : @$_SESSION['task']));
108 $_SESSION['task'] = $cl_task;
109 $cl_note = trim($request->getParameter('note'));
110
111 // Get the data we need to display week view.
112 // Get column headers, which are day numbers in month.
113 $dayHeaders = ttTimeHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
114 $lockedDays = ttTimeHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
115 // Build data array for the table. Format is described in the function..
116 $dataArray = ttTimeHelper::getDataForWeekView($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT), $dayHeaders);
117 // Build day totals (total durations for each day in week).
118 $dayTotals = ttTimeHelper::getDayTotals($dataArray, $dayHeaders);
119
120 // Define rendering class for a label field to the left of durations.
121 class LabelCellRenderer extends DefaultCellRenderer {
122   function render(&$table, $value, $row, $column, $selected = false) {
123     $this->setOptions(array('width'=>200,'valign'=>'middle'));
124     // Special handling for row 0, which represents a new week entry.
125     if (0 == $row) {
126       $this->setOptions(array('style'=>'text-align: center; font-weight: bold;'));
127     }
128     // Special handling for not billable entries.
129     /* // TODO: this does not work and should be coded properly.
130     if ($row > 0) {
131       $row_id = $table->getValueAt($row,1+$column)['row_id'];
132       $billable = ttTimeHelper::parseFromWeekViewRow($row_id, 'bl');
133       if (!$billable) {
134         $this->setOptions(array('class'=>'not_billable')); // TODO: Should not we add options instead? How does it work exactly?
135       }
136     }*/
137     $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
138     return $this->toString();
139   }
140 }
141
142 // Define rendering class for a single cell for time entry in week view table.
143 class TimeCellRenderer extends DefaultCellRenderer {
144   function render(&$table, $value, $row, $column, $selected = false) {
145     $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
146     $field = new TextField($field_name);
147     // Disable control if the date is locked.
148     global $lockedDays;
149     if ($lockedDays[$column-1])
150       $field->setEnabled(false);
151     $field->setFormName($table->getFormName());
152     $field->setSize(2);
153     $field->setValue($table->getValueAt($row,$column)['duration']);
154     // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
155     // because we can't supply start and finish times in week view - there are no fields for them.
156     global $user;
157     if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
158         $field->setEnabled(false);
159     }
160     $this->setValue($field->getHtml());
161     return $this->toString();
162   }
163 }
164
165 // Elements of weekTimeForm.
166 $form = new Form('weekTimeForm');
167
168 if ($user->canManageTeam()) {
169   $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
170   if (count($user_list) > 1) {
171     $form->addInput(array('type'=>'combobox',
172       'onchange'=>'this.form.submit();',
173       'name'=>'onBehalfUser',
174       'style'=>'width: 250px;',
175       'value'=>$on_behalf_id,
176       'data'=>$user_list,
177       'datakeys'=>array('id','name')));
178     $smarty->assign('on_behalf_control', 1);
179   }
180 }
181
182 // Create week_durations table.
183 $table = new Table('week_durations');
184 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
185 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
186 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
187 $table->setData($dataArray);
188 // Add columns to table.
189 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
190 for ($i = 0; $i < 7; $i++) {
191   $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new TimeCellRenderer(), $dayTotals[$dayHeaders[$i]]));
192 }
193 $table->setInteractive(false);
194 $form->addInputElement($table);
195
196 // Dropdown for clients in MODE_TIME. Use all active clients.
197 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
198   $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
199   $form->addInput(array('type'=>'combobox',
200     'onchange'=>'fillProjectDropdown(this.value);',
201     'name'=>'client',
202     'style'=>'width: 250px;',
203     'value'=>$cl_client,
204     'data'=>$active_clients,
205     'datakeys'=>array('id', 'name'),
206     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
207   // Note: in other modes the client list is filtered to relevant clients only. See below.
208 }
209
210 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
211   // Dropdown for projects assigned to user.
212   $project_list = $user->getAssignedProjects();
213   $form->addInput(array('type'=>'combobox',
214     'onchange'=>'fillTaskDropdown(this.value);',
215     'name'=>'project',
216     'style'=>'width: 250px;',
217     'value'=>$cl_project,
218     'data'=>$project_list,
219     'datakeys'=>array('id','name'),
220     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
221
222   // Dropdown for clients if the clients plugin is enabled.
223   if ($user->isPluginEnabled('cl')) {
224     $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
225     // We need an array of assigned project ids to do some trimming.
226     foreach($project_list as $project)
227       $projects_assigned_to_user[] = $project['id'];
228
229     // Build a client list out of active clients. Use only clients that are relevant to user.
230     // Also trim their associated project list to only assigned projects (to user).
231     foreach($active_clients as $client) {
232       $projects_assigned_to_client = explode(',', $client['projects']);
233       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
234         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
235       if ($intersection) {
236         $client['projects'] = implode(',', $intersection);
237         $client_list[] = $client;
238       }
239     }
240     $form->addInput(array('type'=>'combobox',
241       'onchange'=>'fillProjectDropdown(this.value);',
242       'name'=>'client',
243       'style'=>'width: 250px;',
244       'value'=>$cl_client,
245       'data'=>$client_list,
246       'datakeys'=>array('id', 'name'),
247       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
248   }
249 }
250
251 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
252   $task_list = ttTeamHelper::getActiveTasks($user->team_id);
253   $form->addInput(array('type'=>'combobox',
254     'name'=>'task',
255     'style'=>'width: 250px;',
256     'value'=>$cl_task,
257     'data'=>$task_list,
258     'datakeys'=>array('id','name'),
259     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
260 }
261 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
262
263 // Add other controls.
264 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
265 if ($user->isPluginEnabled('iv'))
266   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
267 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
268 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
269
270 // If we have custom fields - add controls for them.
271 if ($custom_fields && $custom_fields->fields[0]) {
272   // Only one custom field is supported at this time.
273   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
274     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
275   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
276     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
277       'style'=>'width: 250px;',
278       'value'=>$cl_cf_1,
279       'data'=>$custom_fields->options,
280       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
281   }
282 }
283
284 // Submit.
285 if ($request->isPost()) {
286   if ($request->getParameter('btn_submit')) {
287     // Validate user input for row 0.
288     // Determine if a new entry was posted.
289     $newEntryPosted = false;
290     foreach($dayHeaders as $dayHeader) {
291       $control_id = '0_'.$dayHeader;
292       if ($request->getParameter($control_id)) {
293         $newEntryPosted = true;
294         break;
295       }
296     }
297     if ($newEntryPosted) {
298       if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
299         $err->add($i18n->getKey('error.client'));
300       if ($custom_fields) {
301         if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
302       }
303       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
304         if (!$cl_project) $err->add($i18n->getKey('error.project'));
305       }
306       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
307         if (!$cl_task) $err->add($i18n->getKey('error.task'));
308       }
309     }
310
311     // Process the table of values.
312     if ($err->no()) {
313
314       // Obtain values. Perhaps, it's best to iterate throigh posted parameters one by one,
315       // see if anything changed, and apply one change at a time until we see an error.
316       $result = true;
317       $rowNumber = 0;
318       // Iterate through existing rows.
319       foreach ($dataArray as $row) {
320         // Iterate through days.
321         foreach ($dayHeaders as $key => $dayHeader) {
322           // Do not process locked days.
323           if ($lockedDays[$key]) continue;
324           // Make control id for the cell.
325           $control_id = $rowNumber.'_'.$dayHeader;
326           // Optain existing and posted durations.
327           $postedDuration = $request->getParameter($control_id);
328           $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
329           // If posted value is not null, check and normalize it.
330           if ($postedDuration) {
331             if (ttTimeHelper::isValidDuration($postedDuration)) {
332               $postedDuration = ttTimeHelper::normalizeDuration($postedDuration, false); // No leading zero.
333             } else {
334               $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
335               $result = false; break; // Break out. Stop any further processing.
336             }
337           }
338           // Do not process if value has not changed.
339           if ($postedDuration == $existingDuration)
340             continue;
341           // Posted value is different.
342           if ($existingDuration == null) {
343             // Skip inserting 0 duration values.
344             if (0 == ttTimeHelper::toMinutes($postedDuration))
345               continue;
346             // Insert a new record.
347             $fields = array();
348             $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
349             if (!$fields['row_id']) {
350               // Special handling for row 0, a new entry. Need to construct row_id.
351               $record = array();
352               $record['client_id'] = $cl_client;
353               $record['billable'] = $cl_billable ? '1' : '0';
354               $record['project_id'] = $cl_project;
355               $record['task_id'] = $cl_task;
356               $record['cf_1_value'] = $cl_cf_1;
357               $fields['row_id'] = ttTimeHelper::makeRecordIdentifier($record).'_0';
358               $fields['note'] = $cl_note;
359             }
360             $fields['day_header'] = $dayHeader;
361             $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
362             $fields['duration'] = $postedDuration;
363             $fields['browser_today'] = $request->getParameter('browser_today', null);
364             $result = ttTimeHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
365           } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
366             // Delete an already existing record here.
367             $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
368           } else {
369             $fields = array();
370             $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
371             $fields['duration'] = $postedDuration;
372             $result = ttTimeHelper::modifyDurationFromWeekView($fields, $err);
373           }
374           if (!$result) break; // Break out of the loop in case of first error.
375         }
376         if (!$result) break; // Break out of the loop in case of first error.
377         $rowNumber++;
378       }
379       if ($result) {
380         header('Location: week.php'); // Normal exit.
381         exit();
382       }
383     }
384   }
385   elseif ($request->getParameter('onBehalfUser')) {
386     if($user->canManageTeam()) {
387       unset($_SESSION['behalf_id']);
388       unset($_SESSION['behalf_name']);
389
390       if($on_behalf_id != $user->id) {
391         $_SESSION['behalf_id'] = $on_behalf_id;
392         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
393       }
394       header('Location: week.php');
395       exit();
396     }
397   }
398 } // isPost
399
400 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
401
402 $smarty->assign('selected_date', $selected_date);
403 $smarty->assign('week_total', $week_total);
404
405 $smarty->assign('client_list', $client_list);
406 $smarty->assign('project_list', $project_list);
407 $smarty->assign('task_list', $task_list);
408 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
409 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
410 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
411
412 $smarty->assign('title', $i18n->getKey('title.time'));
413 $smarty->assign('content_page_name', 'week.tpl');
414 $smarty->display('index.tpl');