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.
11 // | There are only two ways to violate the license:
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).
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).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
29 require_once('initialize.php');
31 import('form.DefaultCellRenderer');
33 import('form.TextField');
34 import('ttUserHelper');
35 import('ttTeamHelper');
36 import('ttWeekViewHelper');
37 import('ttClientHelper');
38 import('ttTimeHelper');
39 import('DateAndTime');
42 if (!ttAccessCheck(right_data_entry)) {
43 header('Location: access_denied.php');
47 // Initialize and store date in session.
48 $cl_date = $request->getParameter('date', @$_SESSION['date']);
49 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
50 if($selected_date->isError())
51 $selected_date = new DateAndTime(DB_DATEFORMAT);
53 $cl_date = $selected_date->toString(DB_DATEFORMAT);
54 $_SESSION['date'] = $cl_date;
56 // Determine selected week start and end dates.
57 $weekStartDay = $user->week_start;
58 $t_arr = localtime($selected_date->getTimestamp());
59 $t_arr[5] = $t_arr[5] + 1900;
60 if ($t_arr[6] < $weekStartDay)
61 $startWeekBias = $weekStartDay - 7;
63 $startWeekBias = $weekStartDay;
64 $startDate = new DateAndTime();
65 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
66 $endDate = new DateAndTime();
67 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
68 // The above is needed to set date range (timestring) in page title.
70 // Use custom fields plugin if it is enabled.
71 if ($user->isPluginEnabled('cf')) {
72 require_once('plugins/CustomFields.class.php');
73 $custom_fields = new CustomFields($user->team_id);
74 $smarty->assign('custom_fields', $custom_fields);
77 // Use Monthly Quotas plugin, if applicable.
78 if ($user->isPluginEnabled('mq')){
79 require_once('plugins/MonthlyQuota.class.php');
80 $quota = new MonthlyQuota();
81 $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
82 $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
83 $minutes_left = ttTimeHelper::toMinutes($month_quota) - ttTimeHelper::toMinutes($month_total);
85 $smarty->assign('month_total', $month_total);
86 $smarty->assign('over_quota', $minutes_left < 0);
87 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
90 // Initialize variables.
92 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
93 $_SESSION['cf_1'] = $cl_cf_1;
95 if ($user->isPluginEnabled('iv')) {
96 if ($request->isPost()) {
97 $cl_billable = $request->getParameter('billable');
98 $_SESSION['billable'] = (int) $cl_billable;
100 if (isset($_SESSION['billable']))
101 $cl_billable = $_SESSION['billable'];
103 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
104 $cl_client = $request->getParameter('client', ($request->getMethod()=='POST'? null : @$_SESSION['client']));
105 $_SESSION['client'] = $cl_client;
106 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
107 $_SESSION['project'] = $cl_project;
108 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? null : @$_SESSION['task']));
109 $_SESSION['task'] = $cl_task;
111 // Get the data we need to display week view.
112 // Get column headers, which are day numbers in month.
113 $dayHeaders = ttWeekViewHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
114 $lockedDays = ttWeekViewHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
115 // Get already existing records.
116 $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
117 // Build data array for the table. Format is described in the function.
118 $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
119 // Build day totals (total durations for each day in week).
120 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
122 // Define rendering class for a label field to the left of durations.
123 class LabelCellRenderer extends DefaultCellRenderer {
124 function render(&$table, $value, $row, $column, $selected = false) {
125 $this->setOptions(array('width'=>200,'valign'=>'middle'));
126 // Special handling for row 0, which represents a new week entry.
128 $this->setOptions(array('style'=>'text-align: center; font-weight: bold;'));
129 } else if (0 != $row % 2) {
130 $this->setOptions(array('style'=>'text-align: right;'));
132 // Special handling for not billable entries.
133 if ($row > 1 && 0 == $row % 2) {
134 $row_id = $table->getValueAtName($row,'row_id');
135 $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
137 $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
140 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
141 return $this->toString();
145 // Define rendering class for a single cell for time entry in week view table.
146 // TODO: Refactor the class name, as we now handle both durations and comments in these cells.
147 class TimeCellRenderer extends DefaultCellRenderer {
148 function render(&$table, $value, $row, $column, $selected = false) {
149 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
150 $field = new TextField($field_name);
151 // Disable control if the date is locked.
153 if ($lockedDays[$column-1])
154 $field->setEnabled(false);
155 $field->setFormName($table->getFormName());
156 $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
158 $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
160 $field->setValue($table->getValueAt($row,$column)['note']); // Comment for odd rows.
161 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
162 // because we can't supply start and finish times in week view - there are no fields for them.
164 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
165 $field->setEnabled(false);
167 $this->setValue($field->getHtml());
168 return $this->toString();
172 // Elements of weekTimeForm.
173 $form = new Form('weekTimeForm');
175 if ($user->canManageTeam()) {
176 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
177 if (count($user_list) > 1) {
178 $form->addInput(array('type'=>'combobox',
179 'onchange'=>'this.form.submit();',
180 'name'=>'onBehalfUser',
181 'style'=>'width: 250px;',
182 'value'=>$on_behalf_id,
184 'datakeys'=>array('id','name')));
185 $smarty->assign('on_behalf_control', 1);
189 // Create week_durations table.
190 $table = new Table('week_durations', 'week_view_table');
191 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
192 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
193 $table->setData($dataArray);
194 // Add columns to table.
195 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
196 for ($i = 0; $i < 7; $i++) {
197 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new TimeCellRenderer(), $dayTotals[$dayHeaders[$i]]));
199 $table->setInteractive(false);
200 $form->addInputElement($table);
202 // Dropdown for clients in MODE_TIME. Use all active clients.
203 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
204 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
205 $form->addInput(array('type'=>'combobox',
206 'onchange'=>'fillProjectDropdown(this.value);',
208 'style'=>'width: 250px;',
210 'data'=>$active_clients,
211 'datakeys'=>array('id', 'name'),
212 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
213 // Note: in other modes the client list is filtered to relevant clients only. See below.
216 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
217 // Dropdown for projects assigned to user.
218 $project_list = $user->getAssignedProjects();
219 $form->addInput(array('type'=>'combobox',
220 'onchange'=>'fillTaskDropdown(this.value);',
222 'style'=>'width: 250px;',
223 'value'=>$cl_project,
224 'data'=>$project_list,
225 'datakeys'=>array('id','name'),
226 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
228 // Dropdown for clients if the clients plugin is enabled.
229 if ($user->isPluginEnabled('cl')) {
230 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
231 // We need an array of assigned project ids to do some trimming.
232 foreach($project_list as $project)
233 $projects_assigned_to_user[] = $project['id'];
235 // Build a client list out of active clients. Use only clients that are relevant to user.
236 // Also trim their associated project list to only assigned projects (to user).
237 foreach($active_clients as $client) {
238 $projects_assigned_to_client = explode(',', $client['projects']);
239 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
240 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
242 $client['projects'] = implode(',', $intersection);
243 $client_list[] = $client;
246 $form->addInput(array('type'=>'combobox',
247 'onchange'=>'fillProjectDropdown(this.value);',
249 'style'=>'width: 250px;',
251 'data'=>$client_list,
252 'datakeys'=>array('id', 'name'),
253 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
257 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
258 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
259 $form->addInput(array('type'=>'combobox',
261 'style'=>'width: 250px;',
264 'datakeys'=>array('id','name'),
265 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
268 // Add other controls.
269 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
270 if ($user->isPluginEnabled('iv'))
271 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
272 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
273 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
275 // If we have custom fields - add controls for them.
276 if ($custom_fields && $custom_fields->fields[0]) {
277 // Only one custom field is supported at this time.
278 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
279 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
280 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
281 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
282 'style'=>'width: 250px;',
284 'data'=>$custom_fields->options,
285 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
290 if ($request->isPost()) {
291 if ($request->getParameter('btn_submit')) {
292 // Validate user input for row 0.
293 // Determine if a new entry was posted.
294 $newEntryPosted = false;
295 foreach($dayHeaders as $dayHeader) {
296 $control_id = '0_'.$dayHeader;
297 if ($request->getParameter($control_id)) {
298 $newEntryPosted = true;
302 if ($newEntryPosted) {
303 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
304 $err->add($i18n->getKey('error.client'));
305 if ($custom_fields) {
306 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
308 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
309 if (!$cl_project) $err->add($i18n->getKey('error.project'));
311 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
312 if (!$cl_task) $err->add($i18n->getKey('error.task'));
316 // Process the table of values.
319 // Obtain values. Iterate through posted parameters one by one,
320 // see if value changed, apply one change at a time until we see an error.
323 // Iterate through existing rows.
324 foreach ($dataArray as $row) {
325 // Iterate through days.
326 foreach ($dayHeaders as $key => $dayHeader) {
327 // Do not process locked days.
328 if ($lockedDays[$key]) continue;
329 // Make control id for the cell.
330 $control_id = $rowNumber.'_'.$dayHeader;
332 // Handle durations and comments in separate blocks of code.
333 if (0 == $rowNumber % 2) {
334 // Handle durations row here.
336 // Obtain existing and posted durations.
337 $postedDuration = $request->getParameter($control_id);
338 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
339 // If posted value is not null, check and normalize it.
340 if ($postedDuration) {
341 if (ttTimeHelper::isValidDuration($postedDuration)) {
342 $postedDuration = ttTimeHelper::normalizeDuration($postedDuration, false); // No leading zero.
344 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
345 $result = false; break; // Break out. Stop any further processing.
348 // Do not process if value has not changed.
349 if ($postedDuration == $existingDuration)
351 // Posted value is different.
352 if ($existingDuration == null) {
353 // Skip inserting 0 duration values.
354 if (0 == ttTimeHelper::toMinutes($postedDuration))
356 // Insert a new record.
358 $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
359 if (!$fields['row_id']) {
360 // Special handling for row 0, a new entry. Need to construct new row_id.
362 $record['client_id'] = $cl_client;
363 $record['billable'] = $cl_billable ? '1' : '0';
364 $record['project_id'] = $cl_project;
365 $record['task_id'] = $cl_task;
366 $record['cf_1_value'] = $cl_cf_1;
367 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
368 // Note: no need to check for a possible conflict with an already existing row
369 // because we are doing an insert that does not affect already existing data.
371 $fields['day_header'] = $dayHeader;
372 $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
373 $fields['duration'] = $postedDuration;
374 $fields['browser_today'] = $request->getParameter('browser_today', null);
375 // Take note value from the control below duration.
376 $noteRowNumber = $rowNumber + 1;
377 $note_control_id = $noteRowNumber.'_'.$dayHeader;
378 $fields['note'] = $request->getParameter($note_control_id);
379 $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
380 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
381 // Delete an already existing record here.
382 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
385 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
386 $fields['duration'] = $postedDuration;
387 $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
389 if (!$result) break; // Break out of the loop in case of first error.
392 // Handle commments row here.
394 // Obtain existing and posted comments.
395 $postedComment = $request->getParameter($control_id);
396 $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
397 // If posted value is not null, check it.
398 if ($postedComment && !ttValidString($postedComment, true)) {
399 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
400 $result = false; break; // Break out. Stop any further processing.
402 // Do not process if value has not changed.
403 if ($postedComment == $existingComment)
406 // Posted value is different.
407 // TODO: handle new entries separately in the durations block above.
409 // Here, only update the comment on an already existing record.
411 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
412 if ($fields['tt_log_id']) {
413 $fields['comment'] = $postedComment;
414 $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
416 if (!$result) break; // Break out of the loop in case of first error.
419 if (!$result) break; // Break out of the loop in case of first error.
423 header('Location: week.php'); // Normal exit.
428 elseif ($request->getParameter('onBehalfUser')) {
429 if($user->canManageTeam()) {
430 unset($_SESSION['behalf_id']);
431 unset($_SESSION['behalf_name']);
433 if($on_behalf_id != $user->id) {
434 $_SESSION['behalf_id'] = $on_behalf_id;
435 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
437 header('Location: week.php');
443 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
445 $smarty->assign('selected_date', $selected_date);
446 $smarty->assign('week_total', $week_total);
448 $smarty->assign('client_list', $client_list);
449 $smarty->assign('project_list', $project_list);
450 $smarty->assign('task_list', $task_list);
451 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
452 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
453 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
454 $smarty->assign('time_records', $records);
456 $smarty->assign('title', $i18n->getKey('title.time'));
457 $smarty->assign('content_page_name', 'week.tpl');
458 $smarty->display('index.tpl');