Started refactoring reports.php for timesheets.
[timetracker.git] / reports.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.ActionForm');
32 import('DateAndTime');
33 import('ttGroupHelper');
34 import('Period');
35 import('ttProjectHelper');
36 import('ttFavReportHelper');
37 import('ttClientHelper');
38 import('ttReportHelper');
39
40 // Access check.
41 if (!(ttAccessAllowed('view_own_reports') || ttAccessAllowed('view_reports') || ttAccessAllowed('view_all_reports'))) {
42   header('Location: access_denied.php');
43   exit();
44 }
45 if (!$user->exists()) {
46   header('Location: access_denied.php'); // No users in subgroup.
47   exit();
48 }
49 // End of access checks.
50
51 $trackingMode = $user->getTrackingMode();
52 $showClient = $user->isPluginEnabled('cl') && !$user->isClient();
53
54 // Use custom fields plugin if it is enabled.
55 if ($user->isPluginEnabled('cf')) {
56   require_once('plugins/CustomFields.class.php');
57   $custom_fields = new CustomFields();
58   $smarty->assign('custom_fields', $custom_fields);
59   $showCustomFieldCheckbox = $custom_fields->fields[0];
60   $showCustomFieldDropdown = $custom_fields->fields[0] && $custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN;
61 }
62
63 $form = new Form('reportForm');
64
65 // Get saved favorite reports for user.
66 $report_list = ttFavReportHelper::getReports();
67 $form->addInput(array('type'=>'combobox',
68   'name'=>'favorite_report',
69   'onchange'=>'this.form.fav_report_changed.value=1;this.form.submit();',
70   'style'=>'width: 250px;',
71   'data'=>$report_list,
72   'datakeys'=>array('id','name'),
73   'empty'=>array('-1'=>$i18n->get('dropdown.no'))));
74 $form->addInput(array('type'=>'hidden','name'=>'fav_report_changed'));
75 // Generate and Delete buttons.
76 $form->addInput(array('type'=>'submit','name'=>'btn_generate','value'=>$i18n->get('button.generate')));
77 $form->addInput(array('type'=>'submit','name'=>'btn_delete','value'=>$i18n->get('label.delete'),'onclick'=>"return confirm('".$i18n->get('form.reports.confirm_delete')."')"));
78
79 // Dropdown for clients if the clients plugin is enabled.
80 if ($showClient) {
81   if ($user->can('view_reports') || $user->can('view_all_reports')) {
82     $client_list = ttClientHelper::getClients(); // TODO: improve getClients for "view_reports"
83                                                  // by filtering out not relevant clients.
84   } else
85     $client_list = ttClientHelper::getClientsForUser();
86   $form->addInput(array('type'=>'combobox',
87     'name'=>'client',
88     'style'=>'width: 250px;',
89     'data'=>$client_list,
90     'datakeys'=>array('id', 'name'),
91     'empty'=>array(''=>$i18n->get('dropdown.all'))));
92 }
93
94 // If we have a TYPE_DROPDOWN custom field - add a control to select an option.
95 if ($showCustomFieldDropdown) {
96   $form->addInput(array('type'=>'combobox','name'=>'option',
97     'style'=>'width: 250px;',
98     'value'=>$cl_cf_1,
99     'data'=>$custom_fields->options,
100     'empty'=>array(''=>$i18n->get('dropdown.all'))));
101 }
102
103 // Add controls for projects and tasks.
104 if ($user->can('view_reports') || $user->can('view_all_reports')) {
105   $project_list = ttProjectHelper::getProjects(); // All active and inactive projects.
106 } elseif ($user->isClient()) {
107   $project_list = ttProjectHelper::getProjectsForClient();
108 } else {
109   $project_list = ttProjectHelper::getAssignedProjects($user->getUser());
110 }
111 $form->addInput(array('type'=>'combobox',
112   'onchange'=>'fillTaskDropdown(this.value);selectAssignedUsers(this.value);',
113   'name'=>'project',
114   'style'=>'width: 250px;',
115   'data'=>$project_list,
116   'datakeys'=>array('id','name'),
117   'empty'=>array(''=>$i18n->get('dropdown.all'))));
118 if (MODE_PROJECTS_AND_TASKS == $trackingMode) {
119   $task_list = ttGroupHelper::getActiveTasks();
120   $form->addInput(array('type'=>'combobox',
121     'name'=>'task',
122     'style'=>'width: 250px;',
123     'data'=>$task_list,
124     'datakeys'=>array('id','name'),
125     'empty'=>array(''=>$i18n->get('dropdown.all'))));
126 }
127
128 // Add include records control.
129 $include_options = array('1'=>$i18n->get('form.reports.include_billable'),
130   '2'=>$i18n->get('form.reports.include_not_billable'));
131 $form->addInput(array('type'=>'combobox',
132   'name'=>'include_records',
133   'style'=>'width: 250px;',
134   'data'=>$include_options,
135   'empty'=>array(''=>$i18n->get('dropdown.all'))));
136
137 // Add invoiced / not invoiced selector.
138 if ($user->can('manage_invoices')) {
139   $invoice_options = array('1'=>$i18n->get('form.reports.include_invoiced'),
140     '2'=>$i18n->get('form.reports.include_not_invoiced'));
141   $form->addInput(array('type'=>'combobox',
142     'name'=>'invoice',
143     'style'=>'width: 250px;',
144     'data'=>$invoice_options,
145     'empty'=>array(''=>$i18n->get('dropdown.all'))));
146 }
147
148 if ($user->can('manage_invoices') && $user->isPluginEnabled('ps')) {
149   $form->addInput(array('type'=>'combobox',
150    'name'=>'paid_status',
151    'style'=>'width: 250px;',
152    'data'=>array('1'=>$i18n->get('dropdown.paid'),'2'=>$i18n->get('dropdown.not_paid')),
153    'empty'=>array(''=>$i18n->get('dropdown.all'))
154  ));
155 }
156
157 // TODO: check rights.
158 if ($user->isPluginEnabled('ts')) {
159   $form->addInput(array('type'=>'combobox',
160    'name'=>'timesheet',
161    'style'=>'width: 250px;',
162    'data'=>array('1'=>$i18n->get('form.reports.include_assigned'),'2'=>$i18n->get('form.reports.include_not_assigned')),
163    'empty'=>array(''=>$i18n->get('dropdown.all'))
164  ));
165 }
166
167 $user_list = array();
168 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient()) {
169   // Prepare user and assigned projects arrays.
170   if ($user->can('view_reports') || $user->can('view_all_reports')) {
171     $rank = $user->getMaxRankForGroup($user->getGroup());
172     if ($user->can('view_all_reports')) $max_rank = MAX_RANK;
173     if ($user->can('view_own_reports'))
174       $options = array('max_rank'=>$max_rank,'include_self'=>true);
175     else
176       $options = array('max_rank'=>$max_rank);
177     $users = $user->getUsers($options); // Active and inactive users.
178   }
179   elseif ($user->isClient())
180     $users = ttGroupHelper::getUsersForClient(); // Active and inactive users for clients.
181
182   foreach ($users as $single_user) {
183     $user_list[$single_user['id']] = $single_user['name'];
184     $projects = ttProjectHelper::getAssignedProjects($single_user['id']);
185     if ($projects) {
186       foreach ($projects as $single_project) {
187         $assigned_projects[$single_user['id']][] = $single_project['id'];
188       }
189     }
190   }
191   $row_count = ceil(count($user_list)/3);
192   $form->addInput(array('type'=>'checkboxgroup',
193     'name'=>'users',
194     'data'=>$user_list,
195     'layout'=>'V',
196     'groupin'=>$row_count,
197     'style'=>'width: 100%;'));
198 }
199
200 // Add control for time period.
201 $form->addInput(array('type'=>'combobox',
202   'name'=>'period',
203   'style'=>'width: 250px;',
204   'data'=>array(INTERVAL_THIS_MONTH=>$i18n->get('dropdown.current_month'),
205     INTERVAL_LAST_MONTH=>$i18n->get('dropdown.previous_month'),
206     INTERVAL_THIS_WEEK=>$i18n->get('dropdown.current_week'),
207     INTERVAL_LAST_WEEK=>$i18n->get('dropdown.previous_week'),
208     INTERVAL_THIS_DAY=>$i18n->get('dropdown.current_day'),
209     INTERVAL_LAST_DAY=>$i18n->get('dropdown.previous_day')),
210   'empty'=>array(''=>$i18n->get('dropdown.select'))));
211 // Add controls for start and end dates.
212 $form->addInput(array('type'=>'datefield','maxlength'=>'20','name'=>'start_date'));
213 $form->addInput(array('type'=>'datefield','maxlength'=>'20','name'=>'end_date'));
214
215 // Add checkboxes for fields.
216 if ($showClient)
217   $form->addInput(array('type'=>'checkbox','name'=>'chclient'));
218 if (($user->can('manage_invoices') || $user->isClient()) && $user->isPluginEnabled('iv'))
219   $form->addInput(array('type'=>'checkbox','name'=>'chinvoice'));
220 if ($user->can('manage_invoices') && $user->isPluginEnabled('ps'))
221   $form->addInput(array('type'=>'checkbox','name'=>'chpaid'));
222 if ($user->can('view_reports') || $user->can('view_all_reports'))
223   $form->addInput(array('type'=>'checkbox','name'=>'chip'));
224 if (MODE_PROJECTS == $trackingMode || MODE_PROJECTS_AND_TASKS == $trackingMode)
225   $form->addInput(array('type'=>'checkbox','name'=>'chproject'));
226 if (MODE_PROJECTS_AND_TASKS == $trackingMode)
227   $form->addInput(array('type'=>'checkbox','name'=>'chtask'));
228 if ((TYPE_START_FINISH == $user->getRecordType()) || (TYPE_ALL == $user->getRecordType())) {
229   $form->addInput(array('type'=>'checkbox','name'=>'chstart'));
230   $form->addInput(array('type'=>'checkbox','name'=>'chfinish'));
231 }
232 $form->addInput(array('type'=>'checkbox','name'=>'chduration'));
233 $form->addInput(array('type'=>'checkbox','name'=>'chnote'));
234 $form->addInput(array('type'=>'checkbox','name'=>'chcost'));
235 // If we have a custom field - add a checkbox for it.
236 if ($custom_fields && $custom_fields->fields[0])
237   $form->addInput(array('type'=>'checkbox','name'=>'chcf_1'));
238 if ($user->isPluginEnabled('wu'))
239   $form->addInput(array('type'=>'checkbox','name'=>'chunits'));
240
241 // Add group by control.
242 $group_by_options['no_grouping'] = $i18n->get('form.reports.group_by_no');
243 $group_by_options['date'] = $i18n->get('form.reports.group_by_date');
244 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
245   $group_by_options['user'] = $i18n->get('form.reports.group_by_user');
246 if ($user->isPluginEnabled('cl') && !($user->isClient() && $user->client_id))
247   $group_by_options['client'] = $i18n->get('form.reports.group_by_client');
248 if (MODE_PROJECTS == $trackingMode || MODE_PROJECTS_AND_TASKS == $trackingMode)
249   $group_by_options['project'] = $i18n->get('form.reports.group_by_project');
250 if (MODE_PROJECTS_AND_TASKS == $trackingMode)
251   $group_by_options['task'] = $i18n->get('form.reports.group_by_task');
252 if ($custom_fields && $custom_fields->fields[0] && $custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
253   $group_by_options['cf_1'] = $custom_fields->fields[0]['label'];
254 }
255 $group_by_options_size = sizeof($group_by_options);
256 $form->addInput(array('type'=>'combobox','onchange'=>'handleCheckboxes();','name'=>'group_by1','data'=>$group_by_options));
257 if ($group_by_options_size > 2) $form->addInput(array('type'=>'combobox','onchange'=>'handleCheckboxes();','name'=>'group_by2','data'=>$group_by_options));
258 if ($group_by_options_size > 3) $form->addInput(array('type'=>'combobox','onchange'=>'handleCheckboxes();','name'=>'group_by3','data'=>$group_by_options));
259 $form->addInput(array('type'=>'checkbox','name'=>'chtotalsonly'));
260
261 // Add text field for a new favorite report name.
262 $form->addInput(array('type'=>'text','name'=>'new_fav_report','maxlength'=>'30','style'=>'width: 250px;'));
263 // Save button.
264 $form->addInput(array('type'=>'submit','name'=>'btn_save','value'=>$i18n->get('button.save')));
265
266 $form->addInput(array('type'=>'submit','name'=>'btn_generate','value'=>$i18n->get('button.generate')));
267
268 // Create a bean (which is a mechanism to remember form values in session).
269 $bean = new ActionForm('reportBean', $form, $request);
270 // At this point form values are obtained from session if they are there.
271
272 if ($request->isGet() && !$bean->isSaved()) {
273   // No previous form data were found in session. Use the following default values.
274   $form->setValueByElement('users', array_keys($user_list));
275   $period = new Period(INTERVAL_THIS_MONTH, new DateAndTime($user->getDateFormat()));
276   $form->setValueByElement('start_date', $period->getStartDate());
277   $form->setValueByElement('end_date', $period->getEndDate());
278   $form->setValueByElement('chclient', '1');
279   $form->setValueByElement('chinvoice', '0');
280   $form->setValueByElement('chpaid', '0');
281   $form->setValueByElement('chip', '0');
282   $form->setValueByElement('chproject', '1');
283   $form->setValueByElement('chstart', '1');
284   $form->setValueByElement('chduration', '1');
285   $form->setValueByElement('chcost', '0');
286   $form->setValueByElement('chtask', '1');
287   $form->setValueByElement('chfinish', '1');
288   $form->setValueByElement('chnote', '1');
289   $form->setValueByElement('chcf_1', '0');
290   $form->setValueByElement('chunits', '0');
291   $form->setValueByElement('chtotalsonly', '0');
292 }
293
294 $form->setValueByElement('fav_report_changed','');
295
296 // Disable the Delete button when no favorite report is selected.
297 if (!$bean->getAttribute('favorite_report') || ($bean->getAttribute('favorite_report') == -1))
298   $form->getElement('btn_delete')->setEnabled(false);
299
300 if ($request->isPost()) {
301   if((!$bean->getAttribute('btn_generate') && ($request->getParameter('fav_report_changed')))) {
302     // User changed favorite report. We need to load new values into the form.
303     if ($bean->getAttribute('favorite_report')) {
304       // This loads new favorite report options into the bean (into our form).
305       ttFavReportHelper::loadReport($bean);
306
307       // If user selected no favorite report - mark all user checkboxes (most probable scenario).
308       if ($bean->getAttribute('favorite_report') == -1)
309         $form->setValueByElement('users', array_keys($user_list));
310
311       // Save form data in session for future use.
312       $bean->saveBean();
313       header('Location: reports.php');
314       exit();
315     }
316   } elseif ($bean->getAttribute('btn_save')) {
317     // User clicked the Save button. We need to save form options as new favorite report.
318     if (!ttValidString($bean->getAttribute('new_fav_report'))) $err->add($i18n->get('error.field'), $i18n->get('form.reports.save_as_favorite'));
319
320     if ($err->no()) {
321       $id = ttFavReportHelper::saveReport($bean);
322       if (!$id)
323         $err->add($i18n->get('error.db'));
324       if ($err->no()) {
325         $bean->setAttribute('favorite_report', $id);
326         $bean->saveBean();
327         header('Location: reports.php');
328         exit();
329       }
330     }
331   } elseif($bean->getAttribute('btn_delete')) {
332     // Delete button pressed. User wants to delete a favorite report.
333     if ($bean->getAttribute('favorite_report')) {
334       ttFavReportHelper::deleteReport($bean->getAttribute('favorite_report'));
335       // Load default report.
336       $bean->setAttribute('favorite_report','');
337       $bean->setAttribute('new_fav_report', $report_list[0]['name']);
338       ttFavReportHelper::loadReport($bean);
339       $form->setValueByElement('users', array_keys($user_list));
340       $bean->saveBean();
341       header('Location: reports.php');
342       exit();
343     }
344   } else {
345     // Generate button pressed. Check some values.
346     if (!$bean->getAttribute('period')) {
347       $start_date = new DateAndTime($user->getDateFormat(), $bean->getAttribute('start_date'));
348
349       if ($start_date->isError() || !$bean->getAttribute('start_date'))
350         $err->add($i18n->get('error.field'), $i18n->get('label.start_date'));
351
352       $end_date = new DateAndTime($user->getDateFormat(), $bean->getAttribute('end_date'));
353       if ($end_date->isError() || !$bean->getAttribute('end_date'))
354         $err->add($i18n->get('error.field'), $i18n->get('label.end_date'));
355
356       if ($start_date->compare($end_date) > 0)
357         $err->add($i18n->get('error.interval'), $i18n->get('label.end_date'), $i18n->get('label.start_date'));
358     }
359     $group_by1 = $bean->getAttribute('group_by1');
360     $group_by2 = $bean->getAttribute('group_by2');
361     $group_by3 = $bean->getAttribute('group_by3');
362     if (($group_by3 != null && $group_by3 != 'no_grouping') && ($group_by3 == $group_by1 || $group_by3 == $group_by2))
363       $err->add($i18n->get('error.field'), $i18n->get('form.reports.group_by'));
364     if (($group_by2 != null && $group_by2 != 'no_grouping') && ($group_by2 == $group_by1 || $group_by3 == $group_by2))
365       $err->add($i18n->get('error.field'), $i18n->get('form.reports.group_by'));
366     // Check remaining values.
367     if (!ttReportHelper::verifyBean($bean)) $err->add($i18n->get('error.sys'));
368
369     if ($err->no()) {
370       $bean->saveBean();
371       // Now we can go ahead and create a report.
372       header('Location: report.php');
373       exit();
374     }
375   }
376 } // isPost
377
378 $smarty->assign('show_client', $showClient);
379 $smarty->assign('project_list', $project_list);
380 $smarty->assign('task_list', $task_list);
381 $smarty->assign('assigned_projects', $assigned_projects);
382 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
383 $smarty->assign('onload', 'onLoad="handleCheckboxes()"');
384 $smarty->assign('title', $i18n->get('title.reports'));
385 $smarty->assign('content_page_name', 'reports.tpl');
386 $smarty->display('index.tpl');