]> wagnertech.de Git - timetracker.git/blobdiff - WEB-INF/lib/ttReportHelper.class.php
A bit more refactoring in reports.
[timetracker.git] / WEB-INF / lib / ttReportHelper.class.php
index 224d7f1777e102585788b380c834584deccd1cb5..e0993525cea5dd3e876bbf70a3bb141abcf62dc1 100644 (file)
@@ -37,13 +37,14 @@ require_once(dirname(__FILE__).'/../../plugins/CustomFields.class.php');
 class ttReportHelper {
 
   // getWhere prepares a WHERE clause for a report query.
-  static function getWhere($bean) {
+  // Note: $options is a future replacement of $bean, which is work in progress.
+  static function getWhere($bean, $options) {
     global $user;
 
     // Prepare dropdown parts.
     $dropdown_parts = '';
-    if ($bean->getAttribute('client'))
-      $dropdown_parts .= ' and l.client_id = '.$bean->getAttribute('client');
+    if ($options['client_id'])
+      $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
     elseif ($user->isClient() && $user->client_id)
       $dropdown_parts .= ' and l.client_id = '.$user->client_id;
     if ($bean->getAttribute('option')) $dropdown_parts .= ' and l.id in(select log_id from tt_custom_field_log where status = 1 and option_id = '.$bean->getAttribute('option').')';
@@ -135,13 +136,13 @@ class ttReportHelper {
   }
 
   // getExpenseWhere prepares WHERE clause for expenses query in a report.
-  static function getExpenseWhere($bean) {
+  static function getExpenseWhere($bean, $options) {
     global $user;
 
     // Prepare dropdown parts.
     $dropdown_parts = '';
-    if ($bean->getAttribute('client'))
-      $dropdown_parts .= ' and ei.client_id = '.$bean->getAttribute('client');
+    if ($options['client_id'])
+      $dropdown_parts .= ' and l.client_id = '.$options['client_id'];
     elseif ($user->isClient() && $user->client_id)
       $dropdown_parts .= ' and ei.client_id = '.$user->client_id;
     if ($bean->getAttribute('project')) $dropdown_parts .= ' and ei.project_id = '.$bean->getAttribute('project');
@@ -227,7 +228,7 @@ class ttReportHelper {
   // getItems retrieves all items associated with a report.
   // It combines tt_log and tt_expense_items in one array for presentation in one table using mysql union all.
   // Expense items use the "note" field for item name.
-  static function getItems($bean) {
+  static function getItems($bean, $options) {
     global $user;
     $mdb2 = getConnection();
 
@@ -276,6 +277,13 @@ class ttReportHelper {
     // Add duration.
     if ($bean->getAttribute('chduration'))
       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
+    // Add work units.
+    if ($bean->getAttribute('chunits')) {
+      if ($user->unit_totals_only)
+        array_push($fields, "null as units");
+      else
+       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");
+    }
     // Add note.
     if ($bean->getAttribute('chnote'))
       array_push($fields, 'l.comment as note');
@@ -303,10 +311,6 @@ class ttReportHelper {
     if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
       array_push($fields, 'i.name as invoice');
 
-    // Add work units.
-    if ($bean->getAttribute('chunits'))
-      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");
-
     // Prepare sql query part for left joins.
     $left_joins = null;
     if ($bean->getAttribute('chclient') || 'client' == $group_by_option)
@@ -330,7 +334,7 @@ class ttReportHelper {
     if ($includeCost && MODE_TIME != $user->tracking_mode)
       $left_joins .= " left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
 
-    $where = ttReportHelper::getWhere($bean);
+    $where = ttReportHelper::getWhere($bean, $options);
 
     // Construct sql query for tt_log items.
     $sql = "select ".join(', ', $fields)." from tt_log l $left_joins $where";
@@ -364,6 +368,9 @@ class ttReportHelper {
         array_push($fields, 'null'); // null for finish.
       if ($bean->getAttribute('chduration'))
         array_push($fields, 'null'); // null for duration.
+      // Add work units.
+      if ($bean->getAttribute('chunits'))
+        array_push($fields, 'null as units'); // null for work units.
       // Use the note field to print item name.
       if ($bean->getAttribute('chnote'))
         array_push($fields, 'ei.name as note');
@@ -384,10 +391,6 @@ class ttReportHelper {
       if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
         array_push($fields, 'i.name as invoice');
 
-      // Add work units.
-      if ($bean->getAttribute('chunits'))
-        array_push($fields, 'null'); // null for work units.
-
       // Prepare sql query part for left joins.
       $left_joins = null;
       if ($canViewReports || $isClient)
@@ -399,7 +402,7 @@ class ttReportHelper {
       if (($canViewReports || $isClient) && $bean->getAttribute('chinvoice'))
         $left_joins .= " left join tt_invoices i on (i.id = ei.invoice_id and i.status = 1)";
 
-      $where = ttReportHelper::getExpenseWhere($bean);
+      $where = ttReportHelper::getExpenseWhere($bean, $options);
 
       // Construct sql query for expense items.
       $sql_for_expense_items = "select ".join(', ', $fields)." from tt_expense_items ei $left_joins $where";
@@ -549,6 +552,14 @@ class ttReportHelper {
     // Add duration.
     if ($report['show_duration'])
       array_push($fields, "TIME_FORMAT(l.duration, '%k:%i') as duration");
+    // Add work units.
+    if ($report['show_work_units']) {
+      if ($user->unit_totals_only)
+        array_push($fields, "null as units");
+      else
+        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");
+    }
+
     // Add note.
     if ($report['show_note'])
       array_push($fields, 'l.comment as note');
@@ -632,6 +643,8 @@ class ttReportHelper {
         array_push($fields, 'null'); // null for finish.
       if ($report['show_duration'])
         array_push($fields, 'null'); // null for duration.
+      if ($report['show_work_units'])
+        array_push($fields, 'null as units'); // null for work units.
       // Use the note field to print item name.
       if ($report['show_note'])
         array_push($fields, 'ei.name as note');
@@ -730,7 +743,7 @@ class ttReportHelper {
   // getSubtotals calculates report items subtotals when a report is grouped by.
   // Without expenses, it's a simple select with group by.
   // With expenses, it becomes a select with group by from a combined set of records obtained with "union all".
-  static function getSubtotals($bean) {
+  static function getSubtotals($bean, $options) {
     global $user;
 
     $group_by_option = $bean->getAttribute('group_by');
@@ -772,29 +785,44 @@ class ttReportHelper {
         break;
     }
 
-    $where = ttReportHelper::getWhere($bean);
+    $where = ttReportHelper::getWhere($bean, $options);
     if ($bean->getAttribute('chcost')) {
       if (MODE_TIME == $user->tracking_mode) {
         if ($group_by_option != 'user')
           $left_join = 'left join tt_users u on (l.user_id = u.id)';
-        $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time,
-          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,
-          sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
+        $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
+        if ($bean->getAttribute('chunits')) {
+          if ($user->unit_totals_only)
+            $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";
+          else
+            $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";
+        }
+        $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
           null as expenses from tt_log l
           $group_join $left_join $where group by $group_field";
       } else {
         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
-        $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time,
-          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,
-          sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
+        $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
+        if ($bean->getAttribute('chunits')) {
+          if ($user->unit_totals_only)
+            $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";
+          else
+            $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";
+        }
+        $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
           null as expenses from tt_log l
           $group_join
           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
       }
     } else {
-      $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time,
-        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,
-        null as expenses from tt_log l
+      $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
+      if ($bean->getAttribute('chunits')) {
+        if ($user->unit_totals_only)
+          $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";
+        else
+          $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";
+      }
+      $sql .= ", null as expenses from tt_log l
         $group_join $where group by $group_field";
     }
     // By now we have sql for time items.
@@ -824,14 +852,18 @@ class ttReportHelper {
           break;
       }
 
-      $where = ttReportHelper::getExpenseWhere($bean);
-      $sql_for_expenses = "select $group_field as group_field, null as time, null as units, sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei 
-        $group_join $where";
+      $where = ttReportHelper::getExpenseWhere($bean, $options);
+      $sql_for_expenses = "select $group_field as group_field, null as time";
+      if ($bean->getAttribute('chunits')) $sql_for_expenses .= ", null as units";
+      $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
       // Add a "group by" clause if we are grouping.
       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
 
       // Create a combined query.
-      $sql = "select group_field, sum(time) as time, sum(units) as units, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
+      $combined = "select group_field, sum(time) as time";
+      if ($bean->getAttribute('chunits')) $combined .= ", sum(units) as units";
+      $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
+      $sql = $combined;
     }
 
     // Execute query.
@@ -909,21 +941,41 @@ class ttReportHelper {
       if (MODE_TIME == $user->tracking_mode) {
         if ($group_by_option != 'user')
           $left_join = 'left join tt_users u on (l.user_id = u.id)';
-        $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
-          sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
+          $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
+          if ($report['show_work_units']) {
+            if ($user->unit_totals_only)
+              $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";
+            else
+              $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";
+          }
+          $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";
+          $sql .= ", sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2))) as cost,
           null as expenses from tt_log l
           $group_join $left_join $where group by $group_field";
       } else {
         // If we are including cost and tracking projects, our query (the same as above) needs to join the tt_user_project_binds table.
-        $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, 
-          sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
+        $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
+        if ($report['show_work_units']) {
+          if ($user->unit_totals_only)
+            $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";
+          else
+            $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";
+        }
+        $sql .= ", sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
           null as expenses from tt_log l 
           $group_join
           left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where group by $group_field";
       }
     } else {
-      $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time, null as expenses from tt_log l 
-         $group_join $where group by $group_field";
+      $sql = "select $group_field as group_field, sum(time_to_sec(l.duration)) as time";
+      if ($report['show_work_units']) {
+        if ($user->unit_totals_only)
+          $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";
+        else
+          $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";
+      }
+      $sql .= ", null as expenses from tt_log l 
+        $group_join $where group by $group_field";
     }
     // By now we have sql for time items.
 
@@ -953,13 +1005,17 @@ class ttReportHelper {
       }
 
       $where = ttReportHelper::getFavExpenseWhere($report);
-      $sql_for_expenses = "select $group_field as group_field, null as time, sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei 
-        $group_join $where";
+      $sql_for_expenses = "select $group_field as group_field, null as time";
+      if ($report['show_work_units']) $sql_for_expenses .= ", null as units";
+      $sql_for_expenses .= ", sum(ei.cost) as cost, sum(ei.cost) as expenses from tt_expense_items ei $group_join $where";
       // Add a "group by" clause if we are grouping.
       if ('null' != $group_field) $sql_for_expenses .= " group by $group_field";
 
       // Create a combined query.
-      $sql = "select group_field, sum(time) as time, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
+      $combined = "select group_field, sum(time) as time";
+      if ($report['show_work_units']) $combined .= ", sum(units) as units";
+      $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t group by group_field";
+      $sql = $combined;
     }
 
     // Execute query.
@@ -979,54 +1035,58 @@ class ttReportHelper {
           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
           $val['expenses'] = str_replace('.', $user->decimal_mark, $val['expenses']);
         }
-        $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time,'cost'=>$val['cost'],'expenses'=>$val['expenses']);
+        $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units'], 'cost'=>$val['cost'],'expenses'=>$val['expenses']);
       } else
-        $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time);
+        $subtotals[$val['group_field']] = array('name'=>$val['group_field'],'time'=>$time, 'units'=> $val['units']);
     }
 
     return $subtotals;
   }
 
   // getTotals calculates total hours and cost for all report items.
-  static function getTotals($bean)
+  static function getTotals($bean, $options)
   {
     global $user;
 
     $mdb2 = getConnection();
 
-    $where = ttReportHelper::getWhere($bean);
+    $where = ttReportHelper::getWhere($bean, $options);
 
-    // TODO: build query in parts so the work units inclusion is conditional.
-
-    // Start with a query for time items.
+    // Prepare parts.
+    $time_part = "sum(time_to_sec(l.duration)) as time";
+    if ($bean->getAttribute('chunits')) {
+      $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";
+    }
+    if ($bean->getAttribute('chcost')) {
+      if (MODE_TIME == $user->tracking_mode)
+        $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";
+      else
+        $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";
+    } else {
+      $cost_part = ", null as cost, null as expenses";
+    }
     if ($bean->getAttribute('chcost')) {
       if (MODE_TIME == $user->tracking_mode) {
-        $sql = "select sum(time_to_sec(l.duration)) as time,
-          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,
-          sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
-          null as expenses 
-          from tt_log l
-          left join tt_users u on (l.user_id = u.id) $where";
+        $left_joins = "left join tt_users u on (l.user_id = u.id)";
       } else {
-        $sql = "select sum(time_to_sec(l.duration)) as time,
-          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,
-          sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
-          null as expenses
-          from tt_log l
-          left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where";
+        $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
       }
-    } else
-      $sql = "select sum(time_to_sec(l.duration)) as time,"
-            ." 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,"
-            ." null as cost, null as expenses from tt_log l $where";
+    }
+    // Prepare a query for time items.
+    $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
 
     // If we have expenses, query becomes a bit more complex.
     if ($bean->getAttribute('chcost') && $user->isPluginEnabled('ex')) {
-      $where = ttReportHelper::getExpenseWhere($bean);
-      $sql_for_expenses = "select null as time, null as units, sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
+      $where = ttReportHelper::getExpenseWhere($bean, $options);
+      $sql_for_expenses = "select null as time";
+      if ($bean->getAttribute('chunits')) $sql_for_expenses .= ", null as units";
+      $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
 
       // Create a combined query.
-      $sql = "select sum(time) as time, sum(units) as units, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
+      $combined = "select sum(time) as time";
+      if ($bean->getAttribute('chunits')) $combined .= ", sum(units) as units";
+      $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
+      $sql = $combined;
     }
 
     // Execute query.
@@ -1074,34 +1134,41 @@ class ttReportHelper {
 
     $where = ttReportHelper::getFavWhere($report);
 
-    // Start with a query for time items.
+    // Prepare parts.
+    $time_part = "sum(time_to_sec(l.duration)) as time";
+    if ($report['show_work_units']) {
+      $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";
+    }
+    if ($report['show_cost']) {
+      if (MODE_TIME == $user->tracking_mode)
+        $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";
+      else
+        $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";
+    } else {
+      $cost_part = ", null as cost, null as expenses";
+    }
     if ($report['show_cost']) {
       if (MODE_TIME == $user->tracking_mode) {
-        $sql = "select sum(time_to_sec(l.duration)) as time,
-          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,
-          sum(cast(l.billable * coalesce(u.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
-          null as expenses 
-          from tt_log l
-          left join tt_users u on (l.user_id = u.id) $where";
+        $left_joins = "left join tt_users u on (l.user_id = u.id)";
       } else {
-        $sql = "select sum(time_to_sec(l.duration)) as time,
-          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,
-          sum(cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10,2))) as cost,
-          null as expenses
-          from tt_log l
-          left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id) $where";
+        $left_joins = "left join tt_user_project_binds upb on (l.user_id = upb.user_id and l.project_id = upb.project_id)";
       }
-    } else
-      $sql = "select sum(time_to_sec(l.duration)) as time,
-        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,
-        null as cost, null as expenses from tt_log l $where";
+    }
+    // Prepare a query for time items.
+    $sql = "select $time_part $units_part $cost_part from tt_log l $left_joins $where";
 
     // If we have expenses, query becomes a bit more complex.
     if ($report['show_cost'] && $user->isPluginEnabled('ex')) {
       $where = ttReportHelper::getFavExpenseWhere($report);
-      $sql_for_expenses = "select null as time, null as units, sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
+      $sql_for_expenses = "select null as time";
+      if ($report['show_work_units']) $sql_for_expenses .= ", null as units";
+      $sql_for_expenses .= ", sum(cost) as cost, sum(cost) as expenses from tt_expense_items ei $where";
+
       // Create a combined query.
-      $sql = "select sum(time) as time, sum(units) as units, sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
+      $combined = "select sum(time) as time";
+      if ($report['show_work_units']) $combined .= ", sum(units) as units";
+      $combined .= ", sum(cost) as cost, sum(expenses) as expenses from (($sql) union all ($sql_for_expenses)) t";
+      $sql = $combined;
     }
 
     // Execute query.
@@ -1184,12 +1251,13 @@ class ttReportHelper {
     // Determine these once as they are used in multiple places in this function.
     $canViewReports = $user->can('view_reports');
     $isClient = $user->isClient();
+    $options = ttReportHelper::getReportOptions($bean);
 
-    $items = ttReportHelper::getItems($bean);
+    $items = ttReportHelper::getItems($bean, $options);
     $group_by = $bean->getAttribute('group_by');
     if ($group_by && 'no_grouping' != $group_by)
-      $subtotals = ttReportHelper::getSubtotals($bean);
-    $totals = ttReportHelper::getTotals($bean);
+      $subtotals = ttReportHelper::getSubtotals($bean, $options);
+    $totals = ttReportHelper::getTotals($bean, $options);
 
     // Use custom fields plugin if it is enabled.
     if ($user->isPluginEnabled('cf'))
@@ -1549,6 +1617,8 @@ class ttReportHelper {
       $body .= '<td style="'.$tableHeader.'">'.$group_by_header.'</td>';
       if ($report['show_duration'])
         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
+      if ($report['show_work_units'])
+        $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
       if ($report['show_cost'])
         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
       $body .= '</tr>';
@@ -1560,6 +1630,11 @@ class ttReportHelper {
           if ($subtotal['time'] <> '0:00') $body .= $subtotal['time'];
           $body .= '</td>';
         }
+        if ($report['show_work_units']) {
+          $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
+          $body .= $subtotal['units'];
+          $body .= '</td>';
+        }
         if ($report['show_cost']) {
           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
           $body .= ($canViewReports || $isClient) ? $subtotal['cost'] : $subtotal['expenses'];
@@ -1577,6 +1652,11 @@ class ttReportHelper {
         if ($totals['time'] <> '0:00') $body .= $totals['time'];
         $body .= '</td>';
       }
+      if ($report['show_work_units']) {
+        $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
+        $body .= $totals['units'];
+        $body .= '</td>';
+      }
       if ($report['show_cost']) {
         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
         $body .= ($canViewReports || $isClient) ? $totals['cost'] : $totals['expenses'];
@@ -1608,6 +1688,8 @@ class ttReportHelper {
         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.finish').'</td>';
       if ($report['show_duration'])
         $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
+      if ($report['show_work_units'])
+        $body .= '<td style="'.$tableHeaderCentered.'" width="5%">'.$i18n->get('label.work_units_short').'</td>';
       if ($report['show_note'])
         $body .= '<td style="'.$tableHeader.'">'.$i18n->get('label.note').'</td>';
       if ($report['show_cost'])
@@ -1651,6 +1733,7 @@ class ttReportHelper {
               if ($report['show_start']) $body .= '<td></td>';
               if ($report['show_end']) $body .= '<td></td>';
               if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['time'].'</td>';
+              if ($report['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$prev_grouped_by]['units'].'</td>';
               if ($report['show_note']) $body .= '<td></td>';
               if ($report['show_cost']) {
                 $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
@@ -1687,6 +1770,8 @@ class ttReportHelper {
             $body .= '<td nowrap style="'.$cellRightAligned.'">'.$record['finish'].'</td>';
           if ($report['show_duration'])
             $body .= '<td style="'.$cellRightAligned.'">'.$record['duration'].'</td>';
+          if ($report['show_work_units'])
+            $body .= '<td style="'.$cellRightAligned.'">'.$record['units'].'</td>';
           if ($report['show_note'])
             $body .= '<td style="'.$cellLeftAligned.'">'.htmlspecialchars($record['note']).'</td>';
           if ($report['show_cost'])
@@ -1724,6 +1809,7 @@ class ttReportHelper {
         if ($report['show_start']) $body .= '<td></td>';
         if ($report['show_end']) $body .= '<td></td>';
         if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['time'].'</td>';
+        if ($report['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$subtotals[$cur_grouped_by]['units'].'</td>';
         if ($report['show_note']) $body .= '<td></td>';
         if ($report['show_cost']) {
           $body .= '<td style="'.$cellRightAlignedSubtotal.'">';
@@ -1748,6 +1834,7 @@ class ttReportHelper {
       if ($report['show_start']) $body .= '<td></td>';
       if ($report['show_end']) $body .= '<td></td>';
       if ($report['show_duration']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['time'].'</td>';
+      if ($report['show_work_units']) $body .= '<td style="'.$cellRightAlignedSubtotal.'">'.$totals['units'].'</td>';
       if ($report['show_note']) $body .= '<td></td>';
       if ($report['show_cost']) {
         $body .= '<td nowrap style="'.$cellRightAlignedSubtotal.'">'.htmlspecialchars($user->currency).' ';
@@ -1799,4 +1886,56 @@ class ttReportHelper {
 
     return true;
   }
+
+  // getReportOptions - returns an array of report options constructed from session bean.
+  //
+  // Note: similarly to ttFavReportHelper::getReportOptions, this function is a part of
+  // refactoring to simplify maintenance of report generating functions, as we currently
+  // have 2 sets: normal reporting (from bean), and fav report emailing (from db fields).
+  // Using options obtained from either db or bean shall allow us to use only one set of functions.
+  static function getReportOptions($bean) {
+    global $user;
+
+    // Prepare an array of report options.
+    $options = array();
+
+    // Construct one by one.
+    $options['name'] = null; // No name required.
+    $options['user_id'] = $user->id; // Not sure if we need user_id here. Fav reports use it to recycle $user object in cron.php.
+    $options['client_id'] = $bean->getAttribute('client');
+
+/*
+ * TODO: remaining fields to fill in...
+  `client_id` int(11) default NULL,                      # client id (if selected)
+  `cf_1_option_id` int(11) default NULL,                 # custom field 1 option id (if selected)
+  `project_id` int(11) default NULL,                     # project id (if selected)
+  `task_id` int(11) default NULL,                        # task id (if selected)
+  `billable` tinyint(4) default NULL,                    # whether to include billable, not billable, or all records
+  `invoice` tinyint(4) default NULL,                     # whether to include invoiced, not invoiced, or all records
+  `paid_status` tinyint(4) default NULL,                 # whether to include paid, not paid, or all records
+  `users` text default NULL,                             # Comma-separated list of user ids. Nothing here means "all" users.
+  `period` tinyint(4) default NULL,                      # selected period type for report
+  `period_start` date default NULL,                      # period start
+  `period_end` date default NULL,                        # period end
+  `show_client` tinyint(4) NOT NULL default 0,           # whether to show client column
+  `show_invoice` tinyint(4) NOT NULL default 0,          # whether to show invoice column
+  `show_paid` tinyint(4) NOT NULL default 0,             # whether to show paid column
+  `show_ip` tinyint(4) NOT NULL default 0,               # whether to show ip column
+  `show_project` tinyint(4) NOT NULL default 0,          # whether to show project column
+  `show_start` tinyint(4) NOT NULL default 0,            # whether to show start field
+  `show_duration` tinyint(4) NOT NULL default 0,         # whether to show duration field
+  `show_cost` tinyint(4) NOT NULL default 0,             # whether to show cost field
+  `show_task` tinyint(4) NOT NULL default 0,             # whether to show task column
+  `show_end` tinyint(4) NOT NULL default 0,              # whether to show end field
+  `show_note` tinyint(4) NOT NULL default 0,             # whether to show note column
+  `show_custom_field_1` tinyint(4) NOT NULL default 0,   # whether to show custom field 1
+  `show_work_units` tinyint(4) NOT NULL default 0,       # whether to show work units
+  `show_totals_only` tinyint(4) NOT NULL default 0,      # whether to show totals only
+  `group_by` varchar(20) default NULL,                   # group by field
+  `status` tinyint(4) default 1,                         # favorite report status
+  PRIMARY KEY (`id`)
+);
+     */
+    return $options;
+  }
 }