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('ttClientHelper');
37 import('ttTimeHelper');
38 import('DateAndTime');
41 if (!ttAccessCheck(right_data_entry)) {
42 header('Location: access_denied.php');
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);
52 $cl_date = $selected_date->toString(DB_DATEFORMAT);
53 $_SESSION['date'] = $cl_date;
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;
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.
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);
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);
84 $smarty->assign('month_total', $month_total);
85 $smarty->assign('over_quota', $minutes_left < 0);
86 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
89 // Initialize variables.
91 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
92 $_SESSION['cf_1'] = $cl_cf_1;
94 if ($user->isPluginEnabled('iv')) {
95 if ($request->isPost()) {
96 $cl_billable = $request->getParameter('billable');
97 $_SESSION['billable'] = (int) $cl_billable;
99 if (isset($_SESSION['billable']))
100 $cl_billable = $_SESSION['billable'];
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'));
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);
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.
126 $this->setOptions(array('style'=>'text-align: center; font-weight: bold;'));
128 // Special handling for not billable entries.
130 $row_id = $table->getValueAtName($row,'row_id');
131 $billable = ttTimeHelper::parseFromWeekViewRow($row_id, 'bl');
133 $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
136 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
137 return $this->toString();
141 // Define rendering class for a single cell for time entry in week view table.
142 class TimeCellRenderer extends DefaultCellRenderer {
143 function render(&$table, $value, $row, $column, $selected = false) {
144 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
145 $field = new TextField($field_name);
146 // Disable control if the date is locked.
148 if ($lockedDays[$column-1])
149 $field->setEnabled(false);
150 $field->setFormName($table->getFormName());
151 $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
152 $field->setValue($table->getValueAt($row,$column)['duration']);
153 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
154 // because we can't supply start and finish times in week view - there are no fields for them.
156 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
157 $field->setEnabled(false);
159 $this->setValue($field->getHtml());
160 return $this->toString();
164 // Elements of weekTimeForm.
165 $form = new Form('weekTimeForm');
167 if ($user->canManageTeam()) {
168 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
169 if (count($user_list) > 1) {
170 $form->addInput(array('type'=>'combobox',
171 'onchange'=>'this.form.submit();',
172 'name'=>'onBehalfUser',
173 'style'=>'width: 250px;',
174 'value'=>$on_behalf_id,
176 'datakeys'=>array('id','name')));
177 $smarty->assign('on_behalf_control', 1);
181 // Create week_durations table.
182 $table = new Table('week_durations', 'week_view_table');
183 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
184 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
185 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
186 $table->setData($dataArray);
187 // Add columns to table.
188 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
189 for ($i = 0; $i < 7; $i++) {
190 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new TimeCellRenderer(), $dayTotals[$dayHeaders[$i]]));
192 $table->setInteractive(false);
193 $form->addInputElement($table);
195 // Dropdown for clients in MODE_TIME. Use all active clients.
196 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
197 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
198 $form->addInput(array('type'=>'combobox',
199 'onchange'=>'fillProjectDropdown(this.value);',
201 'style'=>'width: 250px;',
203 'data'=>$active_clients,
204 'datakeys'=>array('id', 'name'),
205 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
206 // Note: in other modes the client list is filtered to relevant clients only. See below.
209 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
210 // Dropdown for projects assigned to user.
211 $project_list = $user->getAssignedProjects();
212 $form->addInput(array('type'=>'combobox',
213 'onchange'=>'fillTaskDropdown(this.value);',
215 'style'=>'width: 250px;',
216 'value'=>$cl_project,
217 'data'=>$project_list,
218 'datakeys'=>array('id','name'),
219 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
221 // Dropdown for clients if the clients plugin is enabled.
222 if ($user->isPluginEnabled('cl')) {
223 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
224 // We need an array of assigned project ids to do some trimming.
225 foreach($project_list as $project)
226 $projects_assigned_to_user[] = $project['id'];
228 // Build a client list out of active clients. Use only clients that are relevant to user.
229 // Also trim their associated project list to only assigned projects (to user).
230 foreach($active_clients as $client) {
231 $projects_assigned_to_client = explode(',', $client['projects']);
232 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
233 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
235 $client['projects'] = implode(',', $intersection);
236 $client_list[] = $client;
239 $form->addInput(array('type'=>'combobox',
240 'onchange'=>'fillProjectDropdown(this.value);',
242 'style'=>'width: 250px;',
244 'data'=>$client_list,
245 'datakeys'=>array('id', 'name'),
246 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
250 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
251 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
252 $form->addInput(array('type'=>'combobox',
254 'style'=>'width: 250px;',
257 'datakeys'=>array('id','name'),
258 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
260 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
262 // Add other controls.
263 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
264 if ($user->isPluginEnabled('iv'))
265 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
266 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
267 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
269 // If we have custom fields - add controls for them.
270 if ($custom_fields && $custom_fields->fields[0]) {
271 // Only one custom field is supported at this time.
272 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
273 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
274 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
275 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
276 'style'=>'width: 250px;',
278 'data'=>$custom_fields->options,
279 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
284 if ($request->isPost()) {
285 if ($request->getParameter('btn_submit')) {
286 // Validate user input for row 0.
287 // Determine if a new entry was posted.
288 $newEntryPosted = false;
289 foreach($dayHeaders as $dayHeader) {
290 $control_id = '0_'.$dayHeader;
291 if ($request->getParameter($control_id)) {
292 $newEntryPosted = true;
296 if ($newEntryPosted) {
297 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
298 $err->add($i18n->getKey('error.client'));
299 if ($custom_fields) {
300 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
302 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
303 if (!$cl_project) $err->add($i18n->getKey('error.project'));
305 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
306 if (!$cl_task) $err->add($i18n->getKey('error.task'));
310 // Process the table of values.
313 // Obtain values. Perhaps, it's best to iterate throigh posted parameters one by one,
314 // see if anything changed, and apply one change at a time until we see an error.
317 // Iterate through existing rows.
318 foreach ($dataArray as $row) {
319 // Iterate through days.
320 foreach ($dayHeaders as $key => $dayHeader) {
321 // Do not process locked days.
322 if ($lockedDays[$key]) continue;
323 // Make control id for the cell.
324 $control_id = $rowNumber.'_'.$dayHeader;
325 // Optain existing and posted durations.
326 $postedDuration = $request->getParameter($control_id);
327 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
328 // If posted value is not null, check and normalize it.
329 if ($postedDuration) {
330 if (ttTimeHelper::isValidDuration($postedDuration)) {
331 $postedDuration = ttTimeHelper::normalizeDuration($postedDuration, false); // No leading zero.
333 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
334 $result = false; break; // Break out. Stop any further processing.
337 // Do not process if value has not changed.
338 if ($postedDuration == $existingDuration)
340 // Posted value is different.
341 if ($existingDuration == null) {
342 // Skip inserting 0 duration values.
343 if (0 == ttTimeHelper::toMinutes($postedDuration))
345 // Insert a new record.
347 $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
348 if (!$fields['row_id']) {
349 // Special handling for row 0, a new entry. Need to construct row_id.
351 $record['client_id'] = $cl_client;
352 $record['billable'] = $cl_billable ? '1' : '0';
353 $record['project_id'] = $cl_project;
354 $record['task_id'] = $cl_task;
355 $record['cf_1_value'] = $cl_cf_1;
356 $fields['row_id'] = ttTimeHelper::makeRecordIdentifier($record).'_0';
357 $fields['note'] = $cl_note;
359 $fields['day_header'] = $dayHeader;
360 $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
361 $fields['duration'] = $postedDuration;
362 $fields['browser_today'] = $request->getParameter('browser_today', null);
363 $result = ttTimeHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
364 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
365 // Delete an already existing record here.
366 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
369 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
370 $fields['duration'] = $postedDuration;
371 $result = ttTimeHelper::modifyDurationFromWeekView($fields, $err);
373 if (!$result) break; // Break out of the loop in case of first error.
375 if (!$result) break; // Break out of the loop in case of first error.
379 header('Location: week.php'); // Normal exit.
384 elseif ($request->getParameter('onBehalfUser')) {
385 if($user->canManageTeam()) {
386 unset($_SESSION['behalf_id']);
387 unset($_SESSION['behalf_name']);
389 if($on_behalf_id != $user->id) {
390 $_SESSION['behalf_id'] = $on_behalf_id;
391 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
393 header('Location: week.php');
399 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
401 $smarty->assign('selected_date', $selected_date);
402 $smarty->assign('week_total', $week_total);
404 $smarty->assign('client_list', $client_list);
405 $smarty->assign('project_list', $project_list);
406 $smarty->assign('task_list', $task_list);
407 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
408 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
409 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
411 $smarty->assign('title', $i18n->getKey('title.time'));
412 $smarty->assign('content_page_name', 'week.tpl');
413 $smarty->display('index.tpl');