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 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
131 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
132 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
133 $grouping_by_date = ($options['group_by1'] == 'date'|| $options['group_by2'] == 'date' || $options['group_by3'] == 'date');
134 $grouping_by_client = ($options['group_by1'] == 'client'|| $options['group_by2'] == 'client' || $options['group_by3'] == 'client');
135 $grouping_by_project = ($options['group_by1'] == 'project'|| $options['group_by2'] == 'project' || $options['group_by3'] == 'project');
136 $grouping_by_task = ($options['group_by1'] == 'task'|| $options['group_by2'] == 'task' || $options['group_by3'] == 'task');
137 $grouping_by_user = ($options['group_by1'] == 'user'|| $options['group_by2'] == 'user' || $options['group_by3'] == 'user');
138 $grouping_by_cf_1 = ($options['group_by1'] == 'cf_1'|| $options['group_by2'] == 'cf_1' || $options['group_by3'] == 'cf_1');
140 $group_by_option = $options['group_by1'];
141 $convertTo12Hour = ('%I:%M %p' == $user->time_format) && ($options['show_start'] || $options['show_end']);
143 // Prepare a query for time items in tt_log table.
144 $fields = array(); // An array of fields for database query.
145 array_push($fields, 'l.id as id');
146 array_push($fields, '1 as type'); // Type 1 is for tt_log entries.
147 array_push($fields, 'l.date as date');
148 if($canViewReports || $isClient)
149 array_push($fields, 'u.name as user');
150 // Add client name if it is selected.
151 if ($options['show_client'] || $grouping_by_client)
152 array_push($fields, 'c.name as client');
153 // Add project name if it is selected.
154 if ($options['show_project'] || $grouping_by_project)
155 array_push($fields, 'p.name as project');
156 // Add task name if it is selected.
157 if ($options['show_task'] || $grouping_by_task)
158 array_push($fields, 't.name as task');
160 $include_cf_1 = $options['show_custom_field_1'] || $grouping_by_cf_1;
162 $custom_fields = new CustomFields($user->group_id);
163 $cf_1_type = $custom_fields->fields[0]['type'];
164 if ($cf_1_type == CustomFields::TYPE_TEXT) {
165 array_push($fields, 'cfl.value as cf_1');
166 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
167 array_push($fields, 'cfo.value as cf_1');
171 if ($options['show_start']) {
172 array_push($fields, "l.start as unformatted_start");
173 array_push($fields, "TIME_FORMAT(l.start, '%k:%i') as start");
176 if ($options['show_end'])
177 array_push($fields, "TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish");
179 if ($options['show_duration'])
180 array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
182 if ($options['show_work_units']) {
183 if ($user->unit_totals_only)
184 array_push($fields, "null as units");
186 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");
189 if ($options['show_note'])
190 array_push($fields, 'l.comment as note');
192 $includeCost = $options['show_cost'];
194 if (MODE_TIME == $user->tracking_mode)
195 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.
197 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.
198 array_push($fields, "null as expense");
201 if ($canViewReports && $options['show_paid'])
202 array_push($fields, 'l.paid as paid');
204 if ($canViewReports && $options['show_ip']) {
205 array_push($fields, 'l.created as created');
206 array_push($fields, 'l.created_ip as created_ip');
207 array_push($fields, 'l.modified as modified');
208 array_push($fields, 'l.modified_ip as modified_ip');
210 // Add invoice name if it is selected.
211 if (($canViewReports || $isClient) && $options['show_invoice'])
212 array_push($fields, 'i.name as invoice');
214 // Prepare sql query part for left joins.
216 if ($options['show_client'] || $grouping_by_client)
217 $left_joins .= " left join tt_clients c on (c.id = l.client_id)";
218 if (($canViewReports || $isClient) && $options['show_invoice'])
219 $left_joins .= " left join tt_invoices i on (i.id = l.invoice_id and i.status = 1)";
220 if ($canViewReports || $isClient || $user->isPluginEnabled('ex'))
221 $left_joins .= " left join tt_users u on (u.id = l.user_id)";
222 if ($options['show_project'] || $grouping_by_project)
223 $left_joins .= " left join tt_projects p on (p.id = l.project_id)";
224 if ($options['show_task'] || $grouping_by_task)
225 $left_joins .= " left join tt_tasks t on (t.id = l.task_id)";
227 if ($cf_1_type == CustomFields::TYPE_TEXT)
228 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
229 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
230 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
231 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
234 if ($includeCost && MODE_TIME != $user->tracking_mode)
235 $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
237 $where = ttReportHelper::getWhere($options);
239 // Construct sql query for tt_log items.
240 $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
241 // If we don't have expense items (such as when the Expenses plugin is disabled), the above is all sql we need,
242 // with an exception of sorting part, that is added in the end.
244 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
245 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
247 $fields = array(); // An array of fields for database query.
248 array_push($fields, 'ei.id');
249 array_push($fields, '2 as type'); // Type 2 is for tt_expense_items entries.
250 array_push($fields, 'ei.date');
251 if($canViewReports || $isClient)
252 array_push($fields, 'u.name as user');
253 // Add client name if it is selected.
254 if ($options['show_client'] || $grouping_by_client)
255 array_push($fields, 'c.name as client');
256 // Add project name if it is selected.
257 if ($options['show_project'] || $grouping_by_project)
258 array_push($fields, 'p.name as project');
259 if ($options['show_task'] || $grouping_by_task)
260 array_push($fields, 'null'); // null for task name. We need to match column count for union.
261 if ($options['show_custom_field_1'] || $grouping_by_cf_1)
262 array_push($fields, 'null'); // null for cf_1.
263 if ($options['show_start']) {
264 array_push($fields, 'null'); // null for unformatted_start.
265 array_push($fields, 'null'); // null for start.
267 if ($options['show_end'])
268 array_push($fields, 'null'); // null for finish.
269 if ($options['show_duration'])
270 array_push($fields, 'null'); // null for duration.
271 if ($options['show_work_units'])
272 array_push($fields, 'null as units'); // null for work units.
273 // Use the note field to print item name.
274 if ($options['show_note'])
275 array_push($fields, 'ei.name as note');
276 array_push($fields, 'ei.cost as cost');
277 array_push($fields, 'ei.cost as expense');
279 if ($canViewReports && $options['show_paid'])
280 array_push($fields, 'ei.paid as paid');
282 if ($canViewReports && $options['show_ip']) {
283 array_push($fields, 'ei.created as created');
284 array_push($fields, 'ei.created_ip as created_ip');
285 array_push($fields, 'ei.modified as modified');
286 array_push($fields, 'ei.modified_ip as modified_ip');
288 // Add invoice name if it is selected.
289 if (($canViewReports || $isClient) && $options['show_invoice'])
290 array_push($fields, 'i.name as invoice');
292 // Prepare sql query part for left joins.
294 if ($canViewReports || $isClient)
295 $left_joins .= " left join tt_users u on (u.id = ei.user_id)";
296 if ($options['show_client'] || $grouping_by_client)
297 $left_joins .= " left join tt_clients c on (c.id = ei.client_id)";
298 if ($options['show_project'] || $grouping_by_project)
299 $left_joins .= " left join tt_projects p on (p.id = ei.project_id)";
300 if (($canViewReports || $isClient) && $options['show_invoice'])
301 $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
303 $where = ttReportHelper::getExpenseWhere($options);
305 // Construct sql query for expense items.
306 $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
308 // Construct a union.
309 $sql = "($sql) union all ($sql_for_expense_items)";
312 // Determine sort part.
313 $sort_part = ' order by ';
315 $sort_part .= 'date';
317 $sort_part2 .= ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ? ', '.$options['group_by1'] : '';
318 $sort_part2 .= ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ? ', '.$options['group_by2'] : '';
319 $sort_part2 .= ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') ? ', '.$options['group_by3'] : '';
320 if (!$grouping_by_date) $sort_part2 .= ', date';
321 $sort_part .= ltrim($sort_part2, ', '); // Remove leading comma and space.
323 if (($canViewReports || $isClient) && $options['users'] && !$grouping_by_user)
324 $sort_part .= ', user, type';
325 if ($options['show_start'])
326 $sort_part .= ', unformatted_start';
327 $sort_part .= ', id';
330 // By now we are ready with sql.
332 // Obtain items for report.
333 $res = $mdb2->query($sql);
334 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
336 while ($val = $res->fetchRow()) {
337 if ($convertTo12Hour) {
338 if($val['start'] != '')
339 $val['start'] = ttTimeHelper::to12HourFormat($val['start']);
340 if($val['finish'] != '')
341 $val['finish'] = ttTimeHelper::to12HourFormat($val['finish']);
343 if (isset($val['cost'])) {
344 if ('.' != $user->decimal_mark)
345 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
347 if (isset($val['expense'])) {
348 if ('.' != $user->decimal_mark)
349 $val['expense'] = str_replace('.', $user->decimal_mark, $val['expense']);
352 if (!$no_grouping) $val['grouped_by'] = ttReportHelper::makeGroupByKey($options, $val);
353 $val['date'] = ttDateToUserFormat($val['date']);
355 $report_items[] = $val;
358 return $report_items;
361 // putInSession stores tt_log and tt_expense_items ids from a report in user session
362 // as 2 comma-separated lists.
363 static function putInSession($report_items) {
364 unset($_SESSION['report_item_ids']);
365 unset($_SESSION['report_item_expense_ids']);
367 // Iterate through records and build 2 comma-separated lists.
368 foreach($report_items as $item) {
369 if ($item['type'] == 1)
370 $report_item_ids .= ','.$item['id'];
371 else if ($item['type'] == 2)
372 $report_item_expense_ids .= ','.$item['id'];
374 $report_item_ids = trim($report_item_ids, ',');
375 $report_item_expense_ids = trim($report_item_expense_ids, ',');
377 // The lists are reqdy. Put them in session.
378 if ($report_item_ids) $_SESSION['report_item_ids'] = $report_item_ids;
379 if ($report_item_expense_ids) $_SESSION['report_item_expense_ids'] = $report_item_expense_ids;
382 // getFromSession obtains tt_log and tt_expense_items ids stored in user session.
383 static function getFromSession() {
385 $report_item_ids = $_SESSION['report_item_ids'];
386 if ($report_item_ids)
387 $items['report_item_ids'] = explode(',', $report_item_ids);
388 $report_item_expense_ids = $_SESSION['report_item_expense_ids'];
389 if ($report_item_expense_ids)
390 $items['report_item_expense_ids'] = explode(',', $report_item_expense_ids);
394 // getSubtotals calculates report items subtotals when a report is grouped by.
395 // Without expenses, it's a simple select with group by.
396 // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
397 static function getSubtotals($options) {
400 $group_fields = ttReportHelper::makeGroupByFieldsPart($options);
401 if (!$group_fields) return null;
403 $mdb2 = getConnection();
405 $concat_part = ttReportHelper::makeConcatPart($options);
406 $join_part = ttReportHelper::makeJoinPart($options);
407 $where = ttReportHelper::getWhere($options);
408 $group_by_part = ttReportHelper::makeGroupByPart($options);
409 if ($options['show_cost']) {
410 if (MODE_TIME == $user->tracking_mode) {
411 if (!ttReportHelper::groupingByUser($options))
412 $left_join = 'left join tt_users u on (l.user_id = u.id)';
413 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
414 if ($options['show_work_units']) {
415 if ($user->unit_totals_only)
416 $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";
418 $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";
420 $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
421 null as expenses from tt_log l
422 $join_part $left_join $where $group_by_part";
424 // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
425 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
426 if ($options['show_work_units']) {
427 if ($user->unit_totals_only)
428 $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";
430 $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";
432 $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
433 null as expenses from tt_log l
435 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";
438 // $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
439 $sql = "select $concat_part, sum(time_to_sec(l.duration)) as time";
440 if ($options['show_work_units']) {
441 if ($user->unit_totals_only)
442 $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";
444 $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";
446 $sql .= ", null as expenses from tt_log l
447 $join_part $where $group_by_part";
449 // By now we have sql for time items.
451 // However, when we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
452 if ($options['show_cost'] && $user->isPluginEnabled('ex')) { // if ex(penses) plugin is enabled
454 $concat_part = ttReportHelper::makeConcatExpensesPart($options);
455 $join_part = ttReportHelper::makeJoinExpensesPart($options);
456 $where = ttReportHelper::getExpenseWhere($options);
457 $group_by_part = ttReportHelper::makeGroupByExpensesPart($options);
458 $sql_for_expenses = "select $concat_part, null as time";
459 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
460 $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $join_part $where $group_by_part";
462 // Create a combined query.
463 $combined = "select group_field, sum(time) as time";
464 if ($options['show_work_units']) $combined .= ", sum(units) as units";
465 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
470 $res = $mdb2->query($sql);
471 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
472 while ($val = $res->fetchRow()) {
473 // TODO: consider writing a function that properly formats a date part in a multi-part key.
475 // if ('date' == $group_by_option) {
476 // $val['group_field'] = ttDateToUserFormat($val['group_field']);
478 $time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
479 if ($options['show_cost']) {
480 if ('.' != $user->decimal_mark) {
481 $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
482 $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
484 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
486 $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
492 // getTotals calculates total hours and cost for all report items.
493 static function getTotals($options)
497 $mdb2 = getConnection();
499 $where = ttReportHelper::getWhere($options);
502 $time_part = "sum(time_to_sec(l.duration)) as time";
503 if ($options['show_work_units']) {
504 $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";
506 if ($options['show_cost']) {
507 if (MODE_TIME == $user->tracking_mode)
508 $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";
510 $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";
512 $cost_part = ", null as cost, null as expenses";
514 if ($options['show_cost']) {
515 if (MODE_TIME == $user->tracking_mode) {
516 $left_joins = "left join tt_users u on (l.user_id = u.id)";
518 $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
521 // Prepare a query for time items.
522 $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
524 // If we have expenses, query becomes a bit more complex.
525 if ($options['show_cost'] && $user->isPluginEnabled('ex')) {
526 $where = ttReportHelper::getExpenseWhere($options);
527 $sql_for_expenses = "select null as time";
528 if ($options['show_work_units']) $sql_for_expenses .= ", null as units";
529 $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
531 // Create a combined query.
532 $combined = "select sum(time) as time";
533 if ($options['show_work_units']) $combined .= ", sum(units) as units";
534 $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
539 $res = $mdb2->query($sql);
540 if (is_a($res, 'PEAR_Error')) die($res->getMessage());
542 $val = $res->fetchRow();
543 $total_time = $val['time'] ? sec_to_time_fmt_hm($val['time']) : null;
544 if ($options['show_cost']) {
545 $total_cost = $val['cost'];
546 if (!$total_cost) $total_cost = '0.00';
547 if ('.' != $user->decimal_mark)
548 $total_cost = str_replace('.', $user->decimal_mark, $total_cost);
549 $total_expenses = $val['expenses'];
550 if (!$total_expenses) $total_expenses = '0.00';
551 if ('.' != $user->decimal_mark)
552 $total_expenses = str_replace('.', $user->decimal_mark, $total_expenses);
555 if ($options['period'])
556 $period = new Period($options['period'], new DateAndTime($user->date_format));
558 $period = new Period();
560 new DateAndTime($user->date_format, $options['period_start']),
561 new DateAndTime($user->date_format, $options['period_end']));
564 $totals['start_date'] = $period->getStartDate();
565 $totals['end_date'] = $period->getEndDate();
566 $totals['time'] = $total_time;
567 $totals['units'] = $val['units'];
568 $totals['cost'] = $total_cost;
569 $totals['expenses'] = $total_expenses;
574 // The assignToInvoice assigns a set of records to a specific invoice.
575 static function assignToInvoice($invoice_id, $time_log_ids, $expense_item_ids)
577 $mdb2 = getConnection();
579 $sql = "update tt_log set invoice_id = ".$mdb2->quote($invoice_id).
580 " where id in(".join(', ', $time_log_ids).")";
581 $affected = $mdb2->exec($sql);
582 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
584 if ($expense_item_ids) {
585 $sql = "update tt_expense_items set invoice_id = ".$mdb2->quote($invoice_id).
586 " where id in(".join(', ', $expense_item_ids).")";
587 $affected = $mdb2->exec($sql);
588 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
592 // The markPaid marks a set of records as either paid or unpaid.
593 static function markPaid($time_log_ids, $expense_item_ids, $paid = true)
595 $mdb2 = getConnection();
596 $paid_val = (int) $paid;
598 $sql = "update tt_log set paid = $paid_val where id in(".join(', ', $time_log_ids).")";
599 $affected = $mdb2->exec($sql);
600 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
602 if ($expense_item_ids) {
603 $sql = "update tt_expense_items set paid = $paid_val where id in(".join(', ', $expense_item_ids).")";
604 $affected = $mdb2->exec($sql);
605 if (is_a($affected, 'PEAR_Error')) die($affected->getMessage());
609 // prepareReportBody - prepares an email body for report.
610 static function prepareReportBody($options, $comment = null)
615 // Determine these once as they are used in multiple places in this function.
616 $canViewReports = $user->can('view_reports') || $user->can('view_all_reports');
617 $isClient = $user->isClient();
619 $items = ttReportHelper::getItems($options);
620 $group_by = $options['group_by1'];
621 if ($group_by && 'no_grouping' != $group_by)
622 $subtotals = ttReportHelper::getSubtotals($options);
623 $totals = ttReportHelper::getTotals($options);
625 // Use custom fields plugin if it is enabled.
626 if ($user->isPluginEnabled('cf'))
627 $custom_fields = new CustomFields($user->group_id);
629 // Define some styles to use in email.
630 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
631 $tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
632 $tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
633 $rowItem = 'background-color: #ffffff;';
634 $rowItemAlt = 'background-color: #f5f5f5;';
635 $rowSubtotal = 'background-color: #e0e0e0;';
636 $cellLeftAligned = 'text-align: left; vertical-align: top;';
637 $cellRightAligned = 'text-align: right; vertical-align: top;';
638 $cellLeftAlignedSubtotal = 'font-weight: bold; text-align: left; vertical-align: top;';
639 $cellRightAlignedSubtotal = 'font-weight: bold; text-align: right; vertical-align: top;';
641 // Start creating email body.
643 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
647 $body .= '<p style="'.$style_title.'">'.$i18n->get('form.mail.report_subject').': '.$totals['start_date'].' - '.$totals['end_date'].'</p>';
650 if ($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
652 if ($options['show_totals_only']) {
653 // Totals only report. Output subtotals.
655 // Determine group_by header.
656 if ('cf_1' == $group_by)
657 $group_by_header = htmlspecialchars($custom_fields->fields[0]['label']);
659 $key = 'label.'.$group_by;
660 $group_by_header = $i18n->get($key);
663 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
665 $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
666 if ($options['show_duration'])
667 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
668 if ($options['show_work_units'])
669 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
670 if ($options['show_cost'])
671 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
673 foreach($subtotals as $subtotal) {
674 $body .= '<tr style="'.$rowSubtotal.'">';
675 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($subtotal['name'] ? htmlspecialchars($subtotal['name']) : ' ').'</td>';
676 if ($options['show_duration']) {
677 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
678 if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
681 if ($options['show_work_units']) {
682 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
683 $body .= $subtotal['units'];
686 if ($options['show_cost']) {
687 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
688 $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
695 $body .= '<tr><td> </td></tr>';
696 $body .= '<tr style="'.$rowSubtotal.'">';
697 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
698 if ($options['show_duration']) {
699 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
700 if ($totals['time'] <> '0:00') $body .= $totals['time'];
703 if ($options['show_work_units']) {
704 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
705 $body .= $totals['units'];
708 if ($options['show_cost']) {
709 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
710 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
719 // Print table header.
720 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
722 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.date').'</td>';
723 if ($canViewReports || $isClient)
724 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.user').'</td>';
725 if ($options['show_client'])
726 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.client').'</td>';
727 if ($options['show_project'])
728 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.project').'</td>';
729 if ($options['show_task'])
730 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.task').'</td>';
731 if ($options['show_custom_field_1'])
732 $body .= '<td style="'.$tableHeader.'">'.htmlspecialchars($custom_fields->fields[0]['label']).'</td>';
733 if ($options['show_start'])
734 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.start').'</td>';
735 if ($options['show_end'])
736 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
737 if ($options['show_duration'])
738 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
739 if ($options['show_work_units'])
740 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
741 if ($options['show_note'])
742 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
743 if ($options['show_cost'])
744 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
745 if ($options['show_paid'])
746 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.paid').'</td>';
747 if ($options['show_ip'])
748 $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.ip').'</td>';
749 if ($options['show_invoice'])
750 $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.invoice').'</td>';
753 // Initialize variables to print subtotals.
754 if ($items && 'no_grouping' != $group_by) {
755 $print_subtotals = true;
757 $prev_grouped_by = '';
758 $cur_grouped_by = '';
760 // Initialize variables to alternate color of rows for different dates.
763 $row_style = $rowItem;
765 // Print report items.
766 if (is_array($items)) {
767 foreach ($items as $record) {
768 $cur_date = $record['date'];
769 // Print a subtotal row after a block of grouped items.
770 if ($print_subtotals) {
771 $cur_grouped_by = $record['grouped_by'];
772 if ($cur_grouped_by != $prev_grouped_by && !$first_pass) {
773 $body .= '<tr style="'.$rowSubtotal.'">';
774 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
775 $subtotal_name = htmlspecialchars($subtotals[$prev_grouped_by]['name']);
776 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
777 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
778 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
779 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
780 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
781 if ($options['show_start']) $body .= '<td></td>';
782 if ($options['show_end']) $body .= '<td></td>';
783 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
784 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
785 if ($options['show_note']) $body .= '<td></td>';
786 if ($options['show_cost']) {
787 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
788 $body .= ($canViewReports || $isClient) ? $subtotals[$prev_grouped_by]['cost'] : $subtotals[$prev_grouped_by]['expenses'];
791 if ($options['show_paid']) $body .= '<td></td>';
792 if ($options['show_ip']) $body .= '<td></td>';
793 if ($options['show_invoice']) $body .= '<td></td>';
795 $body .= '<tr><td> </td></tr>';
800 // Print a regular row.
801 if ($cur_date != $prev_date)
802 $row_style = ($row_style == $rowItem) ? $rowItemAlt : $rowItem;
803 $body .= '<tr style="'.$row_style.'">';
804 $body .= '<td style="'.$cellLeftAligned.'">'.$record['date'].'</td>';
805 if ($canViewReports || $isClient)
806 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['user']).'</td>';
807 if ($options['show_client'])
808 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['client']).'</td>';
809 if ($options['show_project'])
810 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['project']).'</td>';
811 if ($options['show_task'])
812 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['task']).'</td>';
813 if ($options['show_custom_field_1'])
814 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['cf_1']).'</td>';
815 if ($options['show_start'])
816 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['start'].'</td>';
817 if ($options['show_end'])
818 $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
819 if ($options['show_duration'])
820 $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
821 if ($options['show_work_units'])
822 $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
823 if ($options['show_note'])
824 $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
825 if ($options['show_cost'])
826 $body .= '<td style="'.$cellRightAligned.'">'.$record['cost'].'</td>';
827 if ($options['show_paid']) {
828 $body .= '<td style="'.$cellRightAligned.'">';
829 $body .= $record['paid'] == 1 ? $i18n->get('label.yes') : $i18n->get('label.no');
832 if ($options['show_ip']) {
833 $body .= '<td style="'.$cellRightAligned.'">';
834 $body .= $record['modified'] ? $record['modified_ip'].' '.$record['modified'] : $record['created_ip'].' '.$record['created'];
837 if ($options['show_invoice'])
838 $body .= '<td style="'.$cellRightAligned.'">'.htmlspecialchars($record['invoice']).'</td>';
841 $prev_date = $record['date'];
842 if ($print_subtotals)
843 $prev_grouped_by = $record['grouped_by'];
847 // Print a terminating subtotal.
848 if ($print_subtotals) {
849 $body .= '<tr style="'.$rowSubtotal.'">';
850 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.subtotal').'</td>';
851 $subtotal_name = htmlspecialchars($subtotals[$cur_grouped_by]['name']);
852 if ($canViewReports || $isClient) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'user' ? $subtotal_name : '').'</td>';
853 if ($options['show_client']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'client' ? $subtotal_name : '').'</td>';
854 if ($options['show_project']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'project' ? $subtotal_name : '').'</td>';
855 if ($options['show_task']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'task' ? $subtotal_name : '').'</td>';
856 if ($options['show_custom_field_1']) $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.($group_by == 'cf_1' ? $subtotal_name : '').'</td>';
857 if ($options['show_start']) $body .= '<td></td>';
858 if ($options['show_end']) $body .= '<td></td>';
859 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
860 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
861 if ($options['show_note']) $body .= '<td></td>';
862 if ($options['show_cost']) {
863 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
864 $body .= ($canViewReports || $isClient) ? $subtotals[$cur_grouped_by]['cost'] : $subtotals[$cur_grouped_by]['expenses'];
867 if ($options['show_paid']) $body .= '<td></td>';
868 if ($options['show_ip']) $body .= '<td></td>';
869 if ($options['show_invoice']) $body .= '<td></td>';
874 $body .= '<tr><td> </td></tr>';
875 $body .= '<tr style="'.$rowSubtotal.'">';
876 $body .= '<td style="'.$cellLeftAlignedSubtotal.'">'.$i18n->get('label.total').'</td>';
877 if ($canViewReports || $isClient) $body .= '<td></td>';
878 if ($options['show_client']) $body .= '<td></td>';
879 if ($options['show_project']) $body .= '<td></td>';
880 if ($options['show_task']) $body .= '<td></td>';
881 if ($options['show_custom_field_1']) $body .= '<td></td>';
882 if ($options['show_start']) $body .= '<td></td>';
883 if ($options['show_end']) $body .= '<td></td>';
884 if ($options['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
885 if ($options['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
886 if ($options['show_note']) $body .= '<td></td>';
887 if ($options['show_cost']) {
888 $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
889 $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
892 if ($options['show_paid']) $body .= '<td></td>';
893 if ($options['show_ip']) $body .= '<td></td>';
894 if ($options['show_invoice']) $body .= '<td></td>';
901 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
902 $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
904 // Finish creating email body.
905 $body .= '</body></html>';
910 // checkFavReportCondition - checks whether it is okay to send fav report.
911 static function checkFavReportCondition($options, $condition)
913 $items = ttReportHelper::getItems($options);
915 $condition = trim(str_replace('count', '', $condition));
917 $greater_or_equal = ttStartsWith($condition, '>=');
918 if ($greater_or_equal) $condition = trim(str_replace('>=', '', $condition));
920 $less_or_equal = ttStartsWith($condition, '<=');
921 if ($less_or_equal) $condition = trim(str_replace('<=', '', $condition));
923 $not_equal = ttStartsWith($condition, '<>');
924 if ($not_equal) $condition = trim(str_replace('<>', '', $condition));
926 $greater = ttStartsWith($condition, '>');
927 if ($greater) $condition = trim(str_replace('>', '', $condition));
929 $less = ttStartsWith($condition, '<');
930 if ($less) $condition = trim(str_replace('<', '', $condition));
932 $equal = ttStartsWith($condition, '=');
933 if ($equal) $condition = trim(str_replace('=', '', $condition));
935 $count_required = (int) $condition;
937 if ($greater && count($items) > $count_required) return true;
938 if ($greater_or_equal && count($items) >= $count_required) return true;
939 if ($less && count($items) < $count_required) return true;
940 if ($less_or_equal && count($items) <= $count_required) return true;
941 if ($equal && count($items) == $count_required) return true;
942 if ($not_equal && count($items) <> $count_required) return true;
947 // sendFavReport - sends a favorite report to a specified email, called from cron.php
948 static function sendFavReport($options, $subject, $email, $cc) {
949 // We are called from cron.php, we have no $bean in session.
950 // cron.php sets global $user and $i18n objects to match our favorite report user.
954 // Prepare report body.
955 $body = ttReportHelper::prepareReportBody($options);
957 import('mail.Mailer');
958 $mailer = new Mailer();
959 $mailer->setCharSet(CHARSET);
960 $mailer->setContentType('text/html');
961 $mailer->setSender(SENDER);
963 $mailer->setReceiverCC($cc);
964 if (!empty($user->bcc_email))
965 $mailer->setReceiverBCC($user->bcc_email);
966 $mailer->setReceiver($email);
967 $mailer->setMailMode(MAIL_MODE);
968 if (empty($subject)) $subject = $options['name'];
969 if (!$mailer->send($subject, $body))
975 // getReportOptions - returns an array of report options constructed from session bean.
977 // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
978 // refactoring to simplify maintenance of report generating functions, as we currently
979 // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
980 // Using options obtained from either db or bean shall allow us to use only one set of functions.
981 static function getReportOptions($bean) {
984 // Prepare an array of report options.
987 // Construct one by one.
988 $options['name'] = null; // No name required.
989 $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
990 $options['client_id'] = $bean->getAttribute('client');
991 $options['cf_1_option_id'] = $bean->getAttribute('option');
992 $options['project_id'] = $bean->getAttribute('project');
993 $options['task_id'] = $bean->getAttribute('task');
994 $options['billable'] = $bean->getAttribute('include_records');
995 $options['invoice'] = $bean->getAttribute('invoice');
996 $options['paid_status'] = $bean->getAttribute('paid_status');
997 if (is_array($bean->getAttribute('users'))) $options['users'] = join(',', $bean->getAttribute('users'));
998 $options['period'] = $bean->getAttribute('period');
999 $options['period_start'] = $bean->getAttribute('start_date');
1000 $options['period_end'] = $bean->getAttribute('end_date');
1001 $options['show_client'] = $bean->getAttribute('chclient');
1002 $options['show_invoice'] = $bean->getAttribute('chinvoice');
1003 $options['show_paid'] = $bean->getAttribute('chpaid');
1004 $options['show_ip'] = $bean->getAttribute('chip');
1005 $options['show_project'] = $bean->getAttribute('chproject');
1006 $options['show_start'] = $bean->getAttribute('chstart');
1007 $options['show_duration'] = $bean->getAttribute('chduration');
1008 $options['show_cost'] = $bean->getAttribute('chcost');
1009 $options['show_task'] = $bean->getAttribute('chtask');
1010 $options['show_end'] = $bean->getAttribute('chfinish');
1011 $options['show_note'] = $bean->getAttribute('chnote');
1012 $options['show_custom_field_1'] = $bean->getAttribute('chcf_1');
1013 $options['show_work_units'] = $bean->getAttribute('chunits');
1014 $options['show_totals_only'] = $bean->getAttribute('chtotalsonly');
1015 $options['group_by1'] = $bean->getAttribute('group_by1');
1016 $options['group_by2'] = $bean->getAttribute('group_by2');
1017 $options['group_by3'] = $bean->getAttribute('group_by3');
1021 // verifyBean is a security function to make sure data in bean makes sense for a group.
1022 static function verifyBean($bean) {
1026 $users_in_bean = $bean->getAttribute('users');
1027 if (is_array($users_in_bean)) {
1028 $users_in_group = ttTeamHelper::getUsers();
1029 foreach ($users_in_group as $user_in_group) {
1030 $valid_ids[] = $user_in_group['id'];
1032 foreach ($users_in_bean as $user_in_bean) {
1033 if (!in_array($user_in_bean, $valid_ids)) {
1039 // TODO: add additional checks here. Perhaps do it before saving the bean for consistency.
1043 // makeGroupByKey builds a combined group by key from group_by1, group_by2 and group_by3 values
1044 // (passed in $options) and a row of data ($row obtained from a db query).
1045 static function makeGroupByKey($options, $row) {
1046 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1047 // We have group_by1.
1048 $group_by1 = $options['group_by1'];
1049 $group_by1_value = $row[$group_by1];
1050 //if ($group_by1 == 'date') $group_by1_value = ttDateToUserFormat($group_by1_value);
1051 if (empty($group_by1_value)) $group_by1_value = 'Null'; // To match what comes out of makeConcatPart.
1052 $group_by_key .= ' - '.$group_by1_value;
1054 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1055 // We have group_by2.
1056 $group_by2 = $options['group_by2'];
1057 $group_by2_value = $row[$group_by2];
1058 //if ($group_by2 == 'date') $group_by2_value = ttDateToUserFormat($group_by2_value);
1059 if (empty($group_by2_value)) $group_by2_value = 'Null'; // To match what comes out of makeConcatPart.
1060 $group_by_key .= ' - '.$group_by2_value;
1062 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1063 // We have group_by3.
1064 $group_by3 = $options['group_by3'];
1065 $group_by3_value = $row[$group_by3];
1066 //if ($group_by3 == 'date') $group_by3_value = ttDateToUserFormat($group_by3_value);
1067 if (empty($group_by3_value)) $group_by3_value = 'Null'; // To match what comes out of makeConcatPart.
1068 $group_by_key .= ' - '.$group_by3_value;
1070 $group_by_key = trim($group_by_key, ' -');
1071 return $group_by_key;
1074 // makeGroupByPart builds a combined group by part for sql query for time items using group_by1,
1075 // group_by2, and group_by3 values passed in $options.
1076 static function makeGroupByPart($options) {
1077 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1078 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1079 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1080 if ($no_grouping) return null;
1082 $group_by1 = $options['group_by1'];
1083 $group_by2 = $options['group_by2'];
1084 $group_by3 = $options['group_by3'];
1086 switch ($group_by1) {
1088 $group_by_parts .= ', l.date';
1091 $group_by_parts .= ', u.name';
1094 $group_by_parts .= ', c.name';
1097 $group_by_parts .= ', p.name';
1100 $group_by_parts .= ', t.name';
1103 $group_by_parts .= ', cfo.value';
1106 switch ($group_by2) {
1108 $group_by_parts .= ', l.date';
1111 $group_by_parts .= ', u.name';
1114 $group_by_parts .= ', c.name';
1117 $group_by_parts .= ', p.name';
1120 $group_by_parts .= ', t.name';
1123 $group_by_parts .= ', cfo.value';
1126 switch ($group_by3) {
1128 $group_by_parts .= ', l.date';
1131 $group_by_parts .= ', u.name';
1134 $group_by_parts .= ', c.name';
1137 $group_by_parts .= ', p.name';
1140 $group_by_parts .= ', t.name';
1143 $group_by_parts .= ', cfo.value';
1146 // Remove garbage from the beginning.
1147 $group_by_parts = ltrim($group_by_parts, ', ');
1148 $group_by_part = "group by $group_by_parts";
1149 return $group_by_part;
1152 // makeGroupByExpensesPart builds a combined group by part for sql query for expense items using
1153 // group_by1, group_by2, and group_by3 values passed in $options.
1154 static function makeGroupByExpensesPart($options) {
1155 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1156 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1157 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1158 if ($no_grouping) return null;
1160 $group_by1 = $options['group_by1'];
1161 $group_by2 = $options['group_by2'];
1162 $group_by3 = $options['group_by3'];
1164 switch ($group_by1) {
1166 $group_by_parts .= ', ei.date';
1169 $group_by_parts .= ', u.name';
1172 $group_by_parts .= ', c.name';
1175 $group_by_parts .= ', p.name';
1178 switch ($group_by2) {
1180 $group_by_parts .= ', ei.date';
1183 $group_by_parts .= ', u.name';
1186 $group_by_parts .= ', c.name';
1189 $group_by_parts .= ', p.name';
1192 switch ($group_by3) {
1194 $group_by_parts .= ', ei.date';
1197 $group_by_parts .= ', u.name';
1200 $group_by_parts .= ', c.name';
1203 $group_by_parts .= ', p.name';
1206 // Remove garbage from the beginning.
1207 $group_by_parts = ltrim($group_by_parts, ', ');
1208 $group_by_part = "group by $group_by_parts";
1209 return $group_by_part;
1212 // makeConcatPart builds a concatenation part for getSubtotals query (for time items).
1213 static function makeConcatPart($options) {
1214 $group_by1 = $options['group_by1'];
1215 $group_by2 = $options['group_by2'];
1216 $group_by3 = $options['group_by3'];
1218 switch ($group_by1) {
1220 $what_to_concat .= ", ' - ', l.date";
1223 $what_to_concat .= ", ' - ', u.name";
1226 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1229 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1232 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1235 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1238 switch ($group_by2) {
1240 $what_to_concat .= ", ' - ', l.date";
1243 $what_to_concat .= ", ' - ', u.name";
1246 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1249 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1252 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1255 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1258 switch ($group_by3) {
1260 $what_to_concat .= ", ' - ', l.date";
1263 $what_to_concat .= ", ' - ', u.name";
1266 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1269 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1272 $what_to_concat .= ", ' - ', coalesce(t.name, 'Null')";
1275 $what_to_concat .= ", ' - ', coalesce(cfo.value, 'Null')";
1278 // Remove garbage from both ends.
1279 $what_to_concat = trim($what_to_concat, "', -");
1280 $concat_part = "concat($what_to_concat) as group_field";
1281 $concat_part = trim($concat_part, ' -');
1282 return $concat_part;
1285 // makeConcatPart builds a concatenation part for getSubtotals query (for expense items).
1286 static function makeConcatExpensesPart($options) {
1287 $group_by1 = $options['group_by1'];
1288 $group_by2 = $options['group_by2'];
1289 $group_by3 = $options['group_by3'];
1291 switch ($group_by1) {
1293 $what_to_concat .= ", ' - ', ei.date";
1296 $what_to_concat .= ", ' - ', u.name";
1299 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1302 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1305 switch ($group_by2) {
1307 $what_to_concat .= ", ' - ', ei.date";
1310 $what_to_concat .= ", ' - ', u.name";
1313 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1316 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1319 switch ($group_by3) {
1321 $what_to_concat .= ", ' - ', ei.date";
1324 $what_to_concat .= ", ' - ', u.name";
1327 $what_to_concat .= ", ' - ', coalesce(c.name, 'Null')";
1330 $what_to_concat .= ", ' - ', coalesce(p.name, 'Null')";
1333 // Remove garbage from both ends.
1334 $what_to_concat = trim($what_to_concat, "', -");
1335 $concat_part = "concat($what_to_concat) as group_field";
1336 $concat_part = trim($concat_part, ' -');
1337 return $concat_part;
1340 // makeJoinPart builds a left join part for getSubtotals query (for time items).
1341 static function makeJoinPart($options) {
1342 global $custom_fields; // TODO: is it safe to assume the object is there when needed?
1344 $group_by_fields = ttReportHelper::makeGroupByFieldsPart($options); // TODO: refactor this, perhaps?
1345 if (strpos($group_by_fields, 'user') !== false) {
1346 // Grouping by user, add a join on tt_users table.
1347 $join .= ' left join tt_users u on (l.user_id = u.id)';
1349 if (strpos($group_by_fields, 'client') !== false) {
1350 // Grouping by client, add a join on tt_clients table.
1351 $join .= ' left join tt_clients c on (l.client_id = c.id)';
1353 if (strpos($group_by_fields, 'project') !== false) {
1354 // Grouping by project, add a join on tt_projects table.
1355 $join .= ' left join tt_projects p on (l.project_id = p.id)';
1357 if (strpos($group_by_fields, 'task') !== false) {
1358 // Grouping by task, add a join on tt_tasks table.
1359 $join .= ' left join tt_tasks t on (l.task_id = t.id)';
1361 if (strpos($group_by_fields, 'cf_1') !== false) {
1362 // Grouping by custom field 1, add a join for it.
1363 // $custom_fields = new CustomFields($user->group_id);
1364 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1365 $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)';
1366 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1367 $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)';
1372 // makeJoinExpensesPart builds a left join part for getSubtotals query for expense items.
1373 static function makeJoinExpensesPart($options) {
1374 $group_by_fields = ttReportHelper::makeGroupByFieldsPart($options); // TODO: refactor this, perhaps?
1375 if (strpos($group_by_fields, 'user') !== false) {
1376 // Grouping by user, add a join on tt_users table.
1377 $join .= ' left join tt_users u on (ei.user_id = u.id)';
1379 if (strpos($group_by_fields, 'client') !== false) {
1380 // Grouping by client, add a join on tt_clients table.
1381 $join .= ' left join tt_clients c on (ei.client_id = c.id)';
1383 if (strpos($group_by_fields, 'project') !== false) {
1384 // Grouping by project, add a join on tt_projects table.
1385 $join .= ' left join tt_projects p on (ei.project_id = p.id)';
1390 // makeGroupByFieldsPart builds a commma-separated list of fields for sql query using group_by1,
1391 // group_by2, and group_by3 values passed in $options.
1392 static function makeGroupByFieldsPart($options) {
1393 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1394 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1395 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1396 if ($no_grouping) return null;
1398 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1399 // We have group_by1.
1400 $group_by_fields .= ', '.$options['group_by1'];
1402 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1403 // We have group_by2.
1404 $group_by_fields .= ', '.$options['group_by2'];
1406 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1407 // We have group_by3.
1408 $group_by_fields .= ', '.$options['group_by3'];
1410 $group_by_fields = ltrim($group_by_fields, ', ');
1411 return $group_by_fields;
1414 // grouping determines if we are grooping the project by either group_by1,
1415 // group_by2, or group_by3 values passed in $options.
1416 static function grouping($options) {
1417 $grouping = ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') ||
1418 ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') ||
1419 ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping');
1423 // groupingByUser determines if we are grouping a report by user.
1424 static function groupingByUser($options) {
1425 if ($options['group_by1'] == 'user' || $options['group_by2'] == 'user' || $options['group_by3'] == 'user') return true;
1430 // makeGroupByHeader builds a column header for a totals-only report using group_by1,
1431 // group_by2, and group_by3 values passed in $options.
1432 static function makeGroupByHeader($options) {
1434 global $custom_fields;
1436 $no_grouping = ($options['group_by1'] == null || $options['group_by1'] == 'no_grouping') &&
1437 ($options['group_by2'] == null || $options['group_by2'] == 'no_grouping') &&
1438 ($options['group_by3'] == null || $options['group_by3'] == 'no_grouping');
1439 if ($no_grouping) return null;
1441 if ($options['group_by1'] != null && $options['group_by1'] != 'no_grouping') {
1442 // We have group_by1.
1443 $group_by1 = $options['group_by1'];
1444 if ('cf_1' == $group_by1)
1445 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1447 $key = 'label.'.$group_by1;
1448 $group_by_header .= ' - '.$i18n->get($key);
1451 if ($options['group_by2'] != null && $options['group_by2'] != 'no_grouping') {
1452 // We have group_by2.
1453 $group_by2 = $options['group_by2'];
1454 if ('cf_1' == $group_by2)
1455 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1457 $key = 'label.'.$group_by2;
1458 $group_by_header .= ' - '.$i18n->get($key);
1461 if ($options['group_by3'] != null && $options['group_by3'] != 'no_grouping') {
1462 // We have group_by3.
1463 $group_by3 = $options['group_by3'];
1464 if ('cf_1' == $group_by3)
1465 $group_by_header .= ' - '.$custom_fields->fields[0]['label'];
1467 $key = 'label.'.$group_by3;
1468 $group_by_header .= ' - '.$i18n->get($key);
1471 $group_by_header = ltrim($group_by_header, ' -');
1472 return $group_by_header;