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 import('ttClientHelper');
30 import('DateAndTime');
32 import('ttTimeHelper');
34 require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
36 // Class ttReportHelper is used for help with reports.
37 class ttReportHelper {
39 // getWhere prepares a WHERE clause for a report query.
40 static function getWhere($options) {
43 // Prepare dropdown parts.
45 if ($options['client_id'])
46 $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
47 elseif ($user->isClient() && $user->client_id)
48 $dropdown_parts .= ' and l.client_id = '.$user->client_id;
49 if ($options['cf_1_option_id']) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$options['cf_1_option_id'].')';
50 if ($options['project_id']) $dropdown_parts .= ' and l.project_id = '.$options['project_id'];
51 if ($options['task_id']) $dropdown_parts .= ' and l.task_id = '.$options['task_id'];
52 if ($options['billable']=='1') $dropdown_parts .= ' and l.billable = 1';
53 if ($options['billable']=='2') $dropdown_parts .= ' and l.billable = 0';
54 if ($options['invoice']=='1') $dropdown_parts .= ' and l.invoice_id is not NULL';
55 if ($options['invoice']=='2') $dropdown_parts .= ' and l.invoice_id is NULL';
56 if ($options['paid_status']=='1') $dropdown_parts .= ' and l.paid = 1';
57 if ($options['paid_status']=='2') $dropdown_parts .= ' and l.paid = 0';
59 // Prepare sql query part for user list.
60 $userlist = $options['users'] ? $options['users'] : '-1';
61 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
62 $user_list_part = " and l.user_id in ($userlist)";
64 $user_list_part = " and l.user_id = ".$user->id;
65 $user_list_part .= " and l.group_id = ".$user->getActiveGroup();
67 // Prepare sql query part for where.
68 if ($options['period'])
69 $period = new Period($options['period'], new DateAndTime($user->date_format));
71 $period = new Period();
73 new DateAndTime($user->date_format, $options['period_start']),
74 new DateAndTime($user->date_format, $options['period_end']));
76 $where = " where l.status = 1 and l.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and l.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
77 " $user_list_part $dropdown_parts";
81 // getExpenseWhere prepares WHERE clause for expenses query in a report.
82 static function getExpenseWhere($options) {
85 // Prepare dropdown parts.
87 if ($options['client_id'])
88 $dropdown_parts .= ' and ei.client_id = '.$options['client_id'];
89 elseif ($user->isClient() && $user->client_id)
90 $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
91 if ($options['project_id']) $dropdown_parts .= ' and ei.project_id = '.$options['project_id'];
92 if ($options['invoice']=='1') $dropdown_parts .= ' and ei.invoice_id is not NULL';
93 if ($options['invoice']=='2') $dropdown_parts .= ' and ei.invoice_id is NULL';
94 if ($options['paid_status']=='1') $dropdown_parts .= ' and ei.paid = 1';
95 if ($options['paid_status']=='2') $dropdown_parts .= ' and ei.paid = 0';
97 // Prepare sql query part for user list.
98 $userlist = $options['users'] ? $options['users'] : '-1';
99 if ($user->can('view_reports') || $user->can('view_all_reports') || $user->isClient())
100 $user_list_part = " and ei.user_id in ($userlist)";
102 $user_list_part = " and ei.user_id = ".$user->id;
103 $user_list_part .= " and ei.group_id = ".$user->getActiveGroup();
105 // Prepare sql query part for where.
106 if ($options['period'])
107 $period = new Period($options['period'], new DateAndTime($user->date_format));
109 $period = new Period();
111 new DateAndTime($user->date_format, $options['period_start']),
112 new DateAndTime($user->date_format, $options['period_end']));
114 $where = " where ei.status = 1 and ei.date >= '".$period->getStartDate(DB_DATEFORMAT)."' and ei.date <= '".$period->getEndDate(DB_DATEFORMAT)."'".
115 " $user_list_part $dropdown_parts";
119 // getItems retrieves all items associated with a report.
120 // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
121 // Expense items use the "note" field for item name.
122 static function getItems($options) {
124 $mdb2 = getConnection();
126 // Determine these once as they are used in multiple places in this function.
127 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
128 $isClient = $user->isClient();
130 $grouping = ttReportHelper::grouping($options);
131 $grouping_by_date = ($options['group_by1'] == 'date'|| $options['group_by2'] == 'date' || $options['group_by3'] == 'date');
132 $grouping_by_client = ($options['group_by1'] == 'client'|| $options['group_by2'] == 'client' || $options['group_by3'] == 'client');
133 $grouping_by_project = ($options['group_by1'] == 'project'|| $options['group_by2'] == 'project' || $options['group_by3'] == 'project');
134 $grouping_by_task = ($options['group_by1'] == 'task'|| $options['group_by2'] == 'task' || $options['group_by3'] == 'task');
135 $grouping_by_user = ($options['group_by1'] == 'user'|| $options['group_by2'] == 'user' || $options['group_by3'] == 'user');
136 $grouping_by_cf_1 = ($options['group_by1'] == 'cf_1'|| $options['group_by2'] == 'cf_1' || $options['group_by3'] == 'cf_1');
138 $group_by_option = $options['group_by1'];
139 $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
141 // Prepare a query for time items in tt_log table.
142 $fields = array(); // An array of fields for database query.
143 array_push($fields, 'l.id as id');
144 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
145 array_push($fields, 'l.date as date');
146 if($canViewReports || $isClient)
147 array_push($fields, 'u.name as user');
148 // Add client name if it is selected.
149 if ($options['show_client'] || $grouping_by_client)
150 array_push($fields, 'c.name as client');
151 // Add project name if it is selected.
152 if ($options['show_project'] || $grouping_by_project)
153 array_push($fields, 'p.name as project');
154 // Add task name if it is selected.
155 if ($options['show_task'] || $grouping_by_task)
156 array_push($fields, 't.name as task');
158 $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
160 $custom_fields = new CustomFields($user->group_id);
161 $cf_1_type = $custom_fields->fields[0]['type'];
162 if ($cf_1_type == CustomFields::TYPE_TEXT) {
163 array_push($fields, 'cfl.value as cf_1');
164 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
165 array_push($fields, 'cfo.value as cf_1');
169 if ($options['show_start']) {
170 array_push($fields, "l.start as unformatted_start");
171 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
174 if ($options['show_end'])
175 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
177 if ($options['show_duration'])
178 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
180 if ($options['show_work_units']) {
181 if ($user->unit_totals_only)
182 array_push($fields, "null as units");
184 array_push($fields, "if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit)) as units");
187 if ($options['show_note'])
188 array_push($fields, 'l.comment as note');
190 $includeCost = $options['show_cost'];
192 if (MODE_TIME == $user->tracking_mode)
193 array_push($fields, "cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2)) as cost"); // Use default user rate.
195 array_push($fields, "cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2)) as cost"); // Use project rate for user.
196 array_push($fields, "null as expense");
199 if ($canViewReports && $options['show_paid'])
200 array_push($fields, 'l.paid as paid');
202 if ($canViewReports && $options['show_ip']) {
203 array_push($fields, 'l.created as created');
204 array_push($fields, 'l.created_ip as created_ip');
205 array_push($fields, 'l.modified as modified');
206 array_push($fields, 'l.modified_ip as modified_ip');
208 // Add invoice name if it is selected.
209 if (($canViewReports || $isClient) && $options['show_invoice'])
210 array_push($fields, 'i.name as invoice');
212 // Prepare sql query part for left joins.
214 if ($options['show_client'] || $grouping_by_client)
215 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
216 if (($canViewReports || $isClient) && $options['show_invoice'])
217 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
218 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
219 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
220 if ($options['show_project'] || $grouping_by_project)
221 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
222 if ($options['show_task'] || $grouping_by_task)
223 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
225 if ($cf_1_type == CustomFields::TYPE_TEXT)
226 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
227 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
228 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
229 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
232 if ($includeCost && MODE_TIME != $user->tracking_mode)
233 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
235 $where = ttReportHelper::getWhere($options);
237 // Construct sql query for tt_log items.
238 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
239 // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
240 // with an exception of sorting part, that is added in the end.
242 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
243 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
245 $fields = array(); // An array of fields for database query.
246 array_push($fields, 'ei.id');
247 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
248 array_push($fields, 'ei.date');
249 if($canViewReports || $isClient)
250 array_push($fields, 'u.name as user');
251 // Add client name if it is selected.
252 if ($options['show_client'] || $grouping_by_client)
253 array_push($fields, 'c.name as client');
254 // Add project name if it is selected.
255 if ($options['show_project'] || $grouping_by_project)
256 array_push($fields, 'p.name as project');
257 if ($options['show_task'] || $grouping_by_task)
258 array_push($fields, 'null'); // null for task name. We need to match column count for union.
259 if ($options['show_custom_field_1'] || $grouping_by_cf_1)
260 array_push($fields, 'null'); // null for cf_1.
261 if ($options['show_start']) {
262 array_push($fields, 'null'); // null for unformatted_start.
263 array_push($fields, 'null'); // null for start.
265 if ($options['show_end'])
266 array_push($fields, 'null'); // null for finish.
267 if ($options['show_duration'])
268 array_push($fields, 'null'); // null for duration.
269 if ($options['show_work_units'])
270 array_push($fields, 'null as units'); // null for work units.
271 // Use the note field to print item name.
272 if ($options['show_note'])
273 array_push($fields, 'ei.name as note');
274 array_push($fields, 'ei.cost as cost');
275 array_push($fields, 'ei.cost as expense');
277 if ($canViewReports && $options['show_paid'])
278 array_push($fields, 'ei.paid as paid');
280 if ($canViewReports && $options['show_ip']) {
281 array_push($fields, 'ei.created as created');
282 array_push($fields, 'ei.created_ip as created_ip');
283 array_push($fields, 'ei.modified as modified');
284 array_push($fields, 'ei.modified_ip as modified_ip');
286 // Add invoice name if it is selected.
287 if (($canViewReports || $isClient) && $options['show_invoice'])
288 array_push($fields, 'i.name as invoice');
290 // Prepare sql query part for left joins.
292 if ($canViewReports || $isClient)
293 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
294 if ($options['show_client'] || $grouping_by_client)
295 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
296 if ($options['show_project'] || $grouping_by_project)
297 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
298 if (($canViewReports || $isClient) && $options['show_invoice'])
299 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
301 $where = ttReportHelper::getExpenseWhere($options);
303 // Construct sql query for expense items.
304 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
306 // Construct a union.
307 $sql = "($sql) union all ($sql_for_expense_items)";
310 // Determine sort part.
311 $sort_part = ' order by ';
313 $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
314 $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
315 $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
316 if (!$grouping_by_date) $sort_part2 .= ', date';
317 $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
319 $sort_part .= 'date';
321 if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
322 $sort_part .= ', user, type';
323 if ($options['show_start'])
324 $sort_part .= ', unformatted_start';
325 $sort_part .= ', id';
328 // By now we are ready with sql.
330 // Obtain items for report.
331 $res = $mdb2->query($sql);
332 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
334 while ($val = $res->fetchRow()) {
335 if ($convertTo12Hour) {
336 if($val['start'] != '')
337 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
338 if($val['finish'] != '')
339 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
341 if (isset($val['cost'])) {
342 if ('.' != $user->decimal_mark)
343 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
345 if (isset($val['expense'])) {
346 if ('.' != $user->decimal_mark)
347 $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
350 if ($grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
351 $val['date'] = ttDateToUserFormat($val['date']);
353 $report_items[] = $val;
356 return $report_items;
359 // putInSession stores tt_log and tt_expense_items ids from a report in user session
360 // as 2 comma-separated lists.
361 static function putInSession($report_items) {
362 unset($_SESSION['report_item_ids']);
363 unset($_SESSION['report_item_expense_ids']);
365 // Iterate through records and build 2 comma-separated lists.
366 foreach($report_items as $item) {
367 if ($item['type'] == 1)
368 $report_item_ids .= ','.$item['id'];
369 else if ($item['type'] == 2)
370 $report_item_expense_ids .= ','.$item['id'];
372 $report_item_ids = trim($report_item_ids, ',');
373 $report_item_expense_ids = trim($report_item_expense_ids, ',');
375 // The lists are reqdy. Put them in session.
376 if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
377 if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
380 // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
381 static function getFromSession() {
383 $report_item_ids = $_SESSION['report_item_ids'];
384 if ($report_item_ids)
385 $items['report_item_ids'] = explode(',', $report_item_ids);
386 $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
387 if ($report_item_expense_ids)
388 $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
392 // getSubtotals calculates report items subtotals when a report is grouped by.
393 // Without expenses, it's a simple select with group by.
394 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
395 static function getSubtotals($options) {
398 $group_fields = ttReportHelper::makeGroupByFieldsPart($options);
399 if (!$group_fields) return null;
401 $mdb2 = getConnection();
403 $concat_part = ttReportHelper::makeConcatPart($options);
404 $join_part = ttReportHelper::makeJoinPart($options);
405 $where = ttReportHelper::getWhere($options);
406 $group_by_part = ttReportHelper::makeGroupByPart($options);
407 if ($options['show_cost']) {
408 if (MODE_TIME == $user->tracking_mode) {
409 if (!ttReportHelper::groupingByUser($options))
410 $left_join = 'left join tt_users u on (l.user_id = u.id)';
411 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
412 if ($options['show_work_units']) {
413 if ($user->unit_totals_only)
414 $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
416 $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
418 $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
419 null as expenses from tt_log l
420 $join_part $left_join $where $group_by_part";
422 // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
423 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
424 if ($options['show_work_units']) {
425 if ($user->unit_totals_only)
426 $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
428 $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
430 $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
431 null as expenses from tt_log l
433 left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where $group_by_part";
436 // $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
437 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
438 if ($options['show_work_units']) {
439 if ($user->unit_totals_only)
440 $sql .= ", if (sum(l.billable * time_to_sec(l.duration)/60) < $user->first_unit_threshold, 0, ceil(sum(l.billable * time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
442 $sql .= ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
444 $sql .= ", null as expenses from tt_log l
445 $join_part $where $group_by_part";
447 // By now we have sql for time items.
449 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
450 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
452 $concat_part = ttReportHelper::makeConcatExpensesPart($options);
453 $join_part = ttReportHelper::makeJoinExpensesPart($options);
454 $where = ttReportHelper::getExpenseWhere($options);
455 $group_by_part = ttReportHelper::makeGroupByExpensesPart($options);
456 $sql_for_expenses = "select $concat_part, null as time";
457 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
458 $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $join_part $where $group_by_part";
460 // Create a combined query.
461 $combined = "select group_field, sum(time) as time";
462 if ($options['show_work_units']) $combined .= ", sum(units) as units";
463 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
468 $res = $mdb2->query($sql);
469 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
470 while ($val = $res->fetchRow()) {
471 // TODO: consider writing a function that properly formats a date part in a multi-part key.
473 // if ('date' == $group_by_option) {
474 // $val['group_field'] = ttDateToUserFormat($val['group_field']);
476 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
477 $rowLabel = ttReportHelper::makeGroupByLabel($val['group_field'], $options);
478 if ($options['show_cost']) {
479 if ('.' != $user->decimal_mark) {
480 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
481 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
483 $subtotals[$val['group_field']] = array('name'=>$rowLabel,'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
485 $subtotals[$val['group_field']] = array('name'=>$rowLabel,'time'=>$time, 'units'=> $val['units']);
491 // getTotals calculates total hours and cost for all report items.
492 static function getTotals($options)
496 $mdb2 = getConnection();
498 $where = ttReportHelper::getWhere($options);
501 $time_part = "sum(time_to_sec(l.duration)) as time";
502 if ($options['show_work_units']) {
503 $units_part = $user->unit_totals_only ? ", null as units" : ", sum(if(l.billable = 0 or time_to_sec(l.duration)/60 < $user->first_unit_threshold, 0, ceil(time_to_sec(l.duration)/60/$user->minutes_in_unit))) as units";
505 if ($options['show_cost']) {
506 if (MODE_TIME == $user->tracking_mode)
507 $cost_part = ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost, null as expenses";
509 $cost_part = ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost, null as expenses";
511 $cost_part = ", null as cost, null as expenses";
513 if ($options['show_cost']) {
514 if (MODE_TIME == $user->tracking_mode) {
515 $left_joins = "left join tt_users u on (l.user_id = u.id)";
517 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
520 // Prepare a query for time items.
521 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
523 // If we have expenses, query becomes a bit more complex.
524 if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
525 $where = ttReportHelper::getExpenseWhere($options);
526 $sql_for_expenses = "select null as time";
527 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
528 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
530 // Create a combined query.
531 $combined = "select sum(time) as time";
532 if ($options['show_work_units']) $combined .= ", sum(units) as units";
533 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
538 $res = $mdb2->query($sql);
539 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
541 $val = $res->fetchRow();
542 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
543 if ($options['show_cost']) {
544 $total_cost = $val['cost'];
545 if (!$total_cost) $total_cost = '0.00';
546 if ('.' != $user->decimal_mark)
547 $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
548 $total_expenses = $val['expenses'];
549 if (!$total_expenses) $total_expenses = '0.00';
550 if ('.' != $user->decimal_mark)
551 $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
554 if ($options['period'])
555 $period = new Period($options['period'], new DateAndTime($user->date_format));
557 $period = new Period();
559 new DateAndTime($user->date_format, $options['period_start']),
560 new DateAndTime($user->date_format, $options['period_end']));
563 $totals['start_date'] = $period->getStartDate();
564 $totals['end_date'] = $period->getEndDate();
565 $totals['time'] = $total_time;
566 $totals['units'] = $val['units'];
567 $totals['cost'] = $total_cost;
568 $totals['expenses'] = $total_expenses;
573 // The assignToInvoice assigns a set of records to a specific invoice.
574 static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
576 $mdb2 = getConnection();
578 $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
579 " where id in(".join(', ', $time_log_ids).")";
580 $affected = $mdb2->exec($sql);
581 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
583 if ($expense_item_ids) {
584 $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
585 " where id in(".join(', ', $expense_item_ids).")";
586 $affected = $mdb2->exec($sql);
587 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
591 // The markPaid marks a set of records as either paid or unpaid.
592 static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
594 $mdb2 = getConnection();
595 $paid_val = (int) $paid;
597 $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
598 $affected = $mdb2->exec($sql);
599 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
601 if ($expense_item_ids) {
602 $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
603 $affected = $mdb2->exec($sql);
604 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
608 // prepareReportBody - prepares an email body for report.
609 static function prepareReportBody($options, $comment = null)
614 // Determine these once as they are used in multiple places in this function.
615 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
616 $isClient = $user->isClient();
618 $items = ttReportHelper::getItems($options);
619 $group_by = $options['group_by1'];
620 if ($group_by && 'no_grouping' != $group_by)
621 $subtotals = ttReportHelper::getSubtotals($options);
622 $totals = ttReportHelper::getTotals($options);
624 // Use custom fields plugin if it is enabled.
625 if ($user->isPluginEnabled('cf'))
626 $custom_fields = new CustomFields($user->group_id);
628 // Define some styles to use in email.
629 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
630 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
631 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
632 $rowItem = 'background-color: #ffffff;';
633 $rowItemAlt = 'background-color: #f5f5f5;';
634 $rowSubtotal = 'background-color: #e0e0e0;';
635 $cellLeftAligned = 'text-align: left; vertical-align: top;';
636 $cellRightAligned = 'text-align: right; vertical-align: top;';
637 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
638 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
640 // Start creating email body.
642 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
646 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
649 if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
651 if ($options['show_totals_only']) {
652 // Totals only report. Output subtotals.
654 // Determine group_by header.
655 if ('cf_1' == $group_by)
656 $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
658 $key = 'label.'.$group_by;
659 $group_by_header = $i18n->get($key);
662 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
664 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
665 if ($options['show_duration'])
666 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
667 if ($options['show_work_units'])
668 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
669 if ($options['show_cost'])
670 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
672 foreach($subtotals as $subtotal) {
673 $body .= '<tr style="'.$rowSubtotal.'">';
674 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
675 if ($options['show_duration']) {
676 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
677 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
680 if ($options['show_work_units']) {
681 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
682 $body .= $subtotal['units'];
685 if ($options['show_cost']) {
686 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
687 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
694 $body .= '<tr><td> </td></tr>';
695 $body .= '<tr style="'.$rowSubtotal.'">';
696 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
697 if ($options['show_duration']) {
698 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
699 if ($totals['time'] <> '0:00') $body .= $totals['time'];
702 if ($options['show_work_units']) {
703 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
704 $body .= $totals['units'];
707 if ($options['show_cost']) {
708 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
709 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
718 // Print table header.
719 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
721 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
722 if ($canViewReports || $isClient)
723 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
724 if ($options['show_client'])
725 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
726 if ($options['show_project'])
727 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
728 if ($options['show_task'])
729 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
730 if ($options['show_custom_field_1'])
731 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
732 if ($options['show_start'])
733 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
734 if ($options['show_end'])
735 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
736 if ($options['show_duration'])
737 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
738 if ($options['show_work_units'])
739 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
740 if ($options['show_note'])
741 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
742 if ($options['show_cost'])
743 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
744 if ($options['show_paid'])
745 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
746 if ($options['show_ip'])
747 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
748 if ($options['show_invoice'])
749 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
752 // Initialize variables to print subtotals.
753 if ($items && 'no_grouping' != $group_by) {
754 $print_subtotals = true;
756 $prev_grouped_by = '';
757 $cur_grouped_by = '';
759 // Initialize variables to alternate color of rows for different dates.
762 $row_style = $rowItem;
764 // Print report items.
765 if (is_array($items)) {
766 foreach ($items as $record) {
767 $cur_date = $record['date'];
768 // Print a subtotal row after a block of grouped items.
769 if ($print_subtotals) {
770 $cur_grouped_by = $record['grouped_by'];
771 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
772 $body .= '<tr style="'.$rowSubtotal.'">';
773 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
774 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
775 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
776 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
777 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
778 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
779 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
780 if ($options['show_start']) $body .= '<td></td>';
781 if ($options['show_end']) $body .= '<td></td>';
782 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
783 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
784 if ($options['show_note']) $body .= '<td></td>';
785 if ($options['show_cost']) {
786 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
787 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
790 if ($options['show_paid']) $body .= '<td></td>';
791 if ($options['show_ip']) $body .= '<td></td>';
792 if ($options['show_invoice']) $body .= '<td></td>';
794 $body .= '<tr><td> </td></tr>';
799 // Print a regular row.
800 if ($cur_date != $prev_date)
801 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
802 $body .= '<tr style="'.$row_style.'">';
803 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
804 if ($canViewReports || $isClient)
805 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
806 if ($options['show_client'])
807 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
808 if ($options['show_project'])
809 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
810 if ($options['show_task'])
811 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
812 if ($options['show_custom_field_1'])
813 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
814 if ($options['show_start'])
815 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
816 if ($options['show_end'])
817 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
818 if ($options['show_duration'])
819 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
820 if ($options['show_work_units'])
821 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
822 if ($options['show_note'])
823 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
824 if ($options['show_cost'])
825 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
826 if ($options['show_paid']) {
827 $body .= '<td style="'.$cellRightAligned.'">';
828 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
831 if ($options['show_ip']) {
832 $body .= '<td style="'.$cellRightAligned.'">';
833 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
836 if ($options['show_invoice'])
837 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
840 $prev_date = $record['date'];
841 if ($print_subtotals)
842 $prev_grouped_by = $record['grouped_by'];
846 // Print a terminating subtotal.
847 if ($print_subtotals) {
848 $body .= '<tr style="'.$rowSubtotal.'">';
849 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
850 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
851 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
852 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
853 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
854 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
855 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
856 if ($options['show_start']) $body .= '<td></td>';
857 if ($options['show_end']) $body .= '<td></td>';
858 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
859 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
860 if ($options['show_note']) $body .= '<td></td>';
861 if ($options['show_cost']) {
862 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
863 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
866 if ($options['show_paid']) $body .= '<td></td>';
867 if ($options['show_ip']) $body .= '<td></td>';
868 if ($options['show_invoice']) $body .= '<td></td>';
873 $body .= '<tr><td> </td></tr>';
874 $body .= '<tr style="'.$rowSubtotal.'">';
875 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
876 if ($canViewReports || $isClient) $body .= '<td></td>';
877 if ($options['show_client']) $body .= '<td></td>';
878 if ($options['show_project']) $body .= '<td></td>';
879 if ($options['show_task']) $body .= '<td></td>';
880 if ($options['show_custom_field_1']) $body .= '<td></td>';
881 if ($options['show_start']) $body .= '<td></td>';
882 if ($options['show_end']) $body .= '<td></td>';
883 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
884 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
885 if ($options['show_note']) $body .= '<td></td>';
886 if ($options['show_cost']) {
887 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
888 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
891 if ($options['show_paid']) $body .= '<td></td>';
892 if ($options['show_ip']) $body .= '<td></td>';
893 if ($options['show_invoice']) $body .= '<td></td>';
900 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
901 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
903 // Finish creating email body.
904 $body .= '</body></html>';
909 // checkFavReportCondition - checks whether it is okay to send fav report.
910 static function checkFavReportCondition($options, $condition)
912 $items = ttReportHelper::getItems($options);
914 $condition = trim(str_replace('count', '', $condition));
916 $greater_or_equal = ttStartsWith($condition, '>=');
917 if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
919 $less_or_equal = ttStartsWith($condition, '<=');
920 if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
922 $not_equal = ttStartsWith($condition, '<>');
923 if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
925 $greater = ttStartsWith($condition, '>');
926 if ($greater) $condition = trim(str_replace('>', '', $condition));
928 $less = ttStartsWith($condition, '<');
929 if ($less) $condition = trim(str_replace('<', '', $condition));
931 $equal = ttStartsWith($condition, '=');
932 if ($equal) $condition = trim(str_replace('=', '', $condition));
934 $count_required = (int) $condition;
936 if ($greater && count($items) > $count_required) return true;
937 if ($greater_or_equal && count($items) >= $count_required) return true;
938 if ($less && count($items) < $count_required) return true;
939 if ($less_or_equal && count($items) <= $count_required) return true;
940 if ($equal && count($items) == $count_required) return true;
941 if ($not_equal && count($items) <> $count_required) return true;
946 // sendFavReport - sends a favorite report to a specified email, called from cron.php
947 static function sendFavReport($options, $subject, $email, $cc) {
948 // We are called from cron.php, we have no $bean in session.
949 // cron.php sets global $user and $i18n objects to match our favorite report user.
953 // Prepare report body.
954 $body = ttReportHelper::prepareReportBody($options);
956 import('mail.Mailer');
957 $mailer = new Mailer();
958 $mailer->setCharSet(CHARSET);
959 $mailer->setContentType('text/html');
960 $mailer->setSender(SENDER);
962 $mailer->setReceiverCC($cc);
963 if (!empty($user->bcc_email))
964 $mailer->setReceiverBCC($user->bcc_email);
965 $mailer->setReceiver($email);
966 $mailer->setMailMode(MAIL_MODE);
967 if (empty($subject)) $subject = $options['name'];
968 if (!$mailer->send($subject, $body))
974 // getReportOptions - returns an array of report options constructed from session bean.
976 // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
977 // refactoring to simplify maintenance of report generating functions, as we currently
978 // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
979 // Using options obtained from either db or bean shall allow us to use only one set of functions.
980 static function getReportOptions($bean) {
983 // Prepare an array of report options.
986 // Construct one by one.
987 $options['name'] = null; // No name required.
988 $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
989 $options['client_id'] = $bean->getAttribute('client');
990 $options['cf_1_option_id'] = $bean->getAttribute('option');
991 $options['project_id'] = $bean->getAttribute('project');
992 $options['task_id'] = $bean->getAttribute('task');
993 $options['billable'] = $bean->getAttribute('include_records');
994 $options['invoice'] = $bean->getAttribute('invoice');
995 $options['paid_status'] = $bean->getAttribute('paid_status');
996 if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
997 $options['period'] = $bean->getAttribute('period');
998 $options['period_start'] = $bean->getAttribute('start_date');
999 $options['period_end'] = $bean->getAttribute('end_date');
1000 $options['show_client'] = $bean->getAttribute('chclient');
1001 $options['show_invoice'] = $bean->getAttribute('chinvoice');
1002 $options['show_paid'] = $bean->getAttribute('chpaid');
1003 $options['show_ip'] = $bean->getAttribute('chip');
1004 $options['show_project'] = $bean->getAttribute('chproject');
1005 $options['show_start'] = $bean->getAttribute('chstart');
1006 $options['show_duration'] = $bean->getAttribute('chduration');
1007 $options['show_cost'] = $bean->getAttribute('chcost');
1008 $options['show_task'] = $bean->getAttribute('chtask');
1009 $options['show_end'] = $bean->getAttribute('chfinish');
1010 $options['show_note'] = $bean->getAttribute('chnote');
1011 $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1012 $options['show_work_units'] = $bean->getAttribute('chunits');
1013 $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1014 $options['group_by1'] = $bean->getAttribute('group_by1');
1015 $options['group_by2'] = $bean->getAttribute('group_by2');
1016 $options['group_by3'] = $bean->getAttribute('group_by3');
1020 // verifyBean is a security function to make sure data in bean makes sense for a group.
1021 static function verifyBean($bean) {
1025 $users_in_bean = $bean->getAttribute('users');
1026 if (is_array($users_in_bean)) {
1027 $users_in_group = ttTeamHelper::getUsers();
1028 foreach ($users_in_group as $user_in_group) {
1029 $valid_ids[] = $user_in_group['id'];
1031 foreach ($users_in_bean as $user_in_bean) {
1032 if (!in_array($user_in_bean, $valid_ids)) {
1038 // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1042 // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1043 // (passed in $options) and a row of data ($row obtained from a db query).
1044 static function makeGroupByKey($options, $row) {
1045 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1046 // We have group_by1.
1047 $group_by1 = $options['group_by1'];
1048 $group_by1_value = $row[$group_by1];
1049 //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1050 if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1051 $group_by_key .= ' - '.$group_by1_value;
1053 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1054 // We have group_by2.
1055 $group_by2 = $options['group_by2'];
1056 $group_by2_value = $row[$group_by2];
1057 //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1058 if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1059 $group_by_key .= ' - '.$group_by2_value;
1061 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1062 // We have group_by3.
1063 $group_by3 = $options['group_by3'];
1064 $group_by3_value = $row[$group_by3];
1065 //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1066 if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1067 $group_by_key .= ' - '.$group_by3_value;
1069 $group_by_key = trim($group_by_key, ' -');
1070 return $group_by_key;
1073 // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1074 // group_by2, and group_by3 values passed in $options.
1075 static function makeGroupByPart($options) {
1076 if (!ttReportHelper::grouping($options)) return null;
1078 $group_by1 = $options['group_by1'];
1079 $group_by2 = $options['group_by2'];
1080 $group_by3 = $options['group_by3'];
1082 switch ($group_by1) {
1084 $group_by_parts .= ', l.date';
1087 $group_by_parts .= ', u.name';
1090 $group_by_parts .= ', c.name';
1093 $group_by_parts .= ', p.name';
1096 $group_by_parts .= ', t.name';
1099 $group_by_parts .= ', cfo.value';
1102 switch ($group_by2) {
1104 $group_by_parts .= ', l.date';
1107 $group_by_parts .= ', u.name';
1110 $group_by_parts .= ', c.name';
1113 $group_by_parts .= ', p.name';
1116 $group_by_parts .= ', t.name';
1119 $group_by_parts .= ', cfo.value';
1122 switch ($group_by3) {
1124 $group_by_parts .= ', l.date';
1127 $group_by_parts .= ', u.name';
1130 $group_by_parts .= ', c.name';
1133 $group_by_parts .= ', p.name';
1136 $group_by_parts .= ', t.name';
1139 $group_by_parts .= ', cfo.value';
1142 // Remove garbage from the beginning.
1143 $group_by_parts = ltrim($group_by_parts, ', ');
1144 $group_by_part = "group by $group_by_parts";
1145 return $group_by_part;
1148 // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1149 // group_by1, group_by2, and group_by3 values passed in $options.
1150 static function makeGroupByExpensesPart($options) {
1151 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1152 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1153 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1154 if ($no_grouping) return null;
1156 $group_by1 = $options['group_by1'];
1157 $group_by2 = $options['group_by2'];
1158 $group_by3 = $options['group_by3'];
1160 switch ($group_by1) {
1162 $group_by_parts .= ', ei.date';
1165 $group_by_parts .= ', u.name';
1168 $group_by_parts .= ', c.name';
1171 $group_by_parts .= ', p.name';
1174 switch ($group_by2) {
1176 $group_by_parts .= ', ei.date';
1179 $group_by_parts .= ', u.name';
1182 $group_by_parts .= ', c.name';
1185 $group_by_parts .= ', p.name';
1188 switch ($group_by3) {
1190 $group_by_parts .= ', ei.date';
1193 $group_by_parts .= ', u.name';
1196 $group_by_parts .= ', c.name';
1199 $group_by_parts .= ', p.name';
1202 // Remove garbage from the beginning.
1203 $group_by_parts = ltrim($group_by_parts, ', ');
1204 $group_by_part = "group by $group_by_parts";
1205 return $group_by_part;
1208 // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1209 static function makeConcatPart($options) {
1210 $group_by1 = $options['group_by1'];
1211 $group_by2 = $options['group_by2'];
1212 $group_by3 = $options['group_by3'];
1214 switch ($group_by1) {
1216 $what_to_concat .= ", ' - ', l.date";
1219 $what_to_concat .= ", ' - ', u.name";
1222 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1225 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1228 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1231 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1234 switch ($group_by2) {
1236 $what_to_concat .= ", ' - ', l.date";
1239 $what_to_concat .= ", ' - ', u.name";
1242 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1245 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1248 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1251 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1254 switch ($group_by3) {
1256 $what_to_concat .= ", ' - ', l.date";
1259 $what_to_concat .= ", ' - ', u.name";
1262 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1265 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1268 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1271 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1274 // Remove garbage from both ends.
1275 $what_to_concat = trim($what_to_concat, "', -");
1276 $concat_part = "concat($what_to_concat) as group_field";
1277 $concat_part = trim($concat_part, ' -');
1278 return $concat_part;
1281 // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1282 static function makeConcatExpensesPart($options) {
1283 $group_by1 = $options['group_by1'];
1284 $group_by2 = $options['group_by2'];
1285 $group_by3 = $options['group_by3'];
1287 switch ($group_by1) {
1289 $what_to_concat .= ", ' - ', ei.date";
1292 $what_to_concat .= ", ' - ', u.name";
1295 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1298 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1301 switch ($group_by2) {
1303 $what_to_concat .= ", ' - ', ei.date";
1306 $what_to_concat .= ", ' - ', u.name";
1309 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1312 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1315 switch ($group_by3) {
1317 $what_to_concat .= ", ' - ', ei.date";
1320 $what_to_concat .= ", ' - ', u.name";
1323 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1326 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1329 // Remove garbage from both ends.
1330 $what_to_concat = trim($what_to_concat, "', -");
1331 $concat_part = "concat($what_to_concat) as group_field";
1332 $concat_part = trim($concat_part, ' -');
1333 return $concat_part;
1336 // makeJoinPart builds a left join part for getSubtotals query (for time items).
1337 static function makeJoinPart($options) {
1338 global $custom_fields; // TODO: is it safe to assume the object is there when needed?
1340 $group_by_fields = ttReportHelper::makeGroupByFieldsPart($options); // TODO: refactor this, perhaps?
1341 if (strpos($group_by_fields, 'user') !== false) {
1342 // Grouping by user, add a join on tt_users table.
1343 $join .= ' left join tt_users u on (l.user_id = u.id)';
1345 if (strpos($group_by_fields, 'client') !== false) {
1346 // Grouping by client, add a join on tt_clients table.
1347 $join .= ' left join tt_clients c on (l.client_id = c.id)';
1349 if (strpos($group_by_fields, 'project') !== false) {
1350 // Grouping by project, add a join on tt_projects table.
1351 $join .= ' left join tt_projects p on (l.project_id = p.id)';
1353 if (strpos($group_by_fields, 'task') !== false) {
1354 // Grouping by task, add a join on tt_tasks table.
1355 $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1357 if (strpos($group_by_fields, 'cf_1') !== false) {
1358 // Grouping by custom field 1, add a join for it.
1359 // $custom_fields = new CustomFields($user->group_id);
1360 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1361 $join .= ' left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.value = cfo.id)';
1362 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1363 $join .= ' left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)';
1368 // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1369 static function makeJoinExpensesPart($options) {
1370 $group_by_fields = ttReportHelper::makeGroupByFieldsPart($options); // TODO: refactor this, perhaps?
1371 if (strpos($group_by_fields, 'user') !== false) {
1372 // Grouping by user, add a join on tt_users table.
1373 $join .= ' left join tt_users u on (ei.user_id = u.id)';
1375 if (strpos($group_by_fields, 'client') !== false) {
1376 // Grouping by client, add a join on tt_clients table.
1377 $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1379 if (strpos($group_by_fields, 'project') !== false) {
1380 // Grouping by project, add a join on tt_projects table.
1381 $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1386 // makeGroupByFieldsPart builds a commma-separated list of fields for sql query using group_by1,
1387 // group_by2, and group_by3 values passed in $options.
1388 static function makeGroupByFieldsPart($options) {
1389 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1390 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1391 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1392 if ($no_grouping) return null;
1394 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1395 // We have group_by1.
1396 $group_by_fields .= ', '.$options['group_by1'];
1398 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1399 // We have group_by2.
1400 $group_by_fields .= ', '.$options['group_by2'];
1402 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1403 // We have group_by3.
1404 $group_by_fields .= ', '.$options['group_by3'];
1406 $group_by_fields = ltrim($group_by_fields, ', ');
1407 return $group_by_fields;
1410 // grouping determines if we are grouping the report by either group_by1,
1411 // group_by2, or group_by3 values passed in $options.
1412 static function grouping($options) {
1413 $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1414 ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1415 ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1419 // groupingByUser determines if we are grouping a report by user.
1420 static function groupingByUser($options) {
1421 if ($options['group_by1'] == 'user' || $options['group_by2'] == 'user' || $options['group_by3'] == 'user') return true;
1426 // groupingBy determines if we are grouping a report by a value of $what
1427 // ('user', 'project', etc.) by checking group_by1, group_by2, and group_by3
1428 // values passed in $options.
1429 static function groupingBy($what, $options) {
1430 $grouping = ($options['group_by1'] != null && $options['group_by1'] != $what) ||
1431 ($options['group_by2'] != null && $options['group_by2'] != $what) ||
1432 ($options['group_by3'] != null && $options['group_by3'] != $what);
1436 // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1437 // group_by2, and group_by3 values passed in $options.
1438 static function makeGroupByHeader($options) {
1440 global $custom_fields;
1442 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1443 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1444 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1445 if ($no_grouping) return null;
1447 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1448 // We have group_by1.
1449 $group_by1 = $options['group_by1'];
1450 if ('cf_1' == $group_by1)
1451 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1453 $key = 'label.'.$group_by1;
1454 $group_by_header .= ' - '.$i18n->get($key);
1457 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1458 // We have group_by2.
1459 $group_by2 = $options['group_by2'];
1460 if ('cf_1' == $group_by2)
1461 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1463 $key = 'label.'.$group_by2;
1464 $group_by_header .= ' - '.$i18n->get($key);
1467 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1468 // We have group_by3.
1469 $group_by3 = $options['group_by3'];
1470 if ('cf_1' == $group_by3)
1471 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1473 $key = 'label.'.$group_by3;
1474 $group_by_header .= ' - '.$i18n->get($key);
1477 $group_by_header = ltrim($group_by_header, ' -');
1478 return $group_by_header;
1481 // makeGroupByLabel builds a label for one row in a "Totals only" report of grouped by items.
1482 // It does one thing: if we are grouping by date, the date format is converted for user.
1483 static function makeGroupByLabel($key, $options) {
1484 if (!ttReportHelper::groupingBy('date', $options))
1485 return $key; // No need to format.
1488 if ($user->date_format == DB_DATEFORMAT)
1489 return $key; // No need to format.
1492 if (preg_match('/\d\d\d\d-\d\d-\d\d/', $key, $matches)) {
1493 // Replace the first found match of a date in DB_DATEFORMAT.
1494 // This is not entirely clean but better than nothing for a label in a row.
1495 $userDate = ttDateToUserFormat($matches[0]);
1496 $label = str_replace($matches[0], $userDate, $key);