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 // Class ttInvoiceHelper is used for help with invoices.
 
  33 class ttInvoiceHelper {
 
  35   // insert - inserts an invoice in database.
 
  36   static function insert($fields)
 
  38     $mdb2 = getConnection();
 
  40     $team_id = (int) $fields['team_id'];
 
  41     $name = $fields['name'];
 
  42     if (!$name) return false;
 
  44     $client_id = (int) $fields['client_id'];
 
  45     $date = $fields['date'];
 
  46     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
 
  47       $status_f = ', status';
 
  48       $status_v = ', '.$mdb2->quote($fields['status']);
 
  51     // Insert a new invoice record.
 
  52     $sql = "insert into tt_invoices (team_id, name, date, client_id $status_f)
 
  53       values($team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id $status_v)"; 
 
  54     $affected = $mdb2->exec($sql);
 
  56     if (is_a($affected, 'PEAR_Error')) return false;
 
  59     $sql = "select last_insert_id() as last_insert_id";
 
  60     $res = $mdb2->query($sql);
 
  61     $val = $res->fetchRow();
 
  62     $last_id = $val['last_insert_id'];
 
  67   // getInvoice - obtains invoice data from the database.
 
  68   static function getInvoice($invoice_id) {
 
  70     $mdb2 = getConnection();
 
  72     $sql = "select * from tt_invoices where id = $invoice_id and team_id = $user->team_id and status = 1";
 
  73     $res = $mdb2->query($sql);
 
  74     if (!is_a($res, 'PEAR_Error')) {
 
  75       if ($val = $res->fetchRow())
 
  81   // The getInvoiceByName looks up an invoice by name.
 
  82   static function getInvoiceByName($invoice_name) {
 
  84     $mdb2 = getConnection();
 
  87     $sql = "select id from tt_invoices where team_id = $user->team_id and name = ".$mdb2->quote($invoice_name)." and status = 1";
 
  89     $res = $mdb2->query($sql);
 
  90     if (!is_a($res, 'PEAR_Error')) {
 
  91       $val = $res->fetchRow();
 
  99   // The getInvoiceItems retrieves tt_log items associated with the invoice. 
 
 100   static function getInvoiceItems($invoice_id) {
 
 103     $mdb2 = getConnection();
 
 105     // At this time only detailed invoice is supported.
 
 106     // It is anticipated to support "totals only" option later on.
 
 108     // Our query is different depending on tracking mode.
 
 109     if (MODE_TIME == $user->tracking_mode) {
 
 110       // In "time only" tracking mode there is a single user rate.
 
 111       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
 
 112       t.name as task_name, l.comment as note,
 
 113       time_format(l.duration, '%k:%i') as duration,
 
 114       cast(l.billable * u.rate * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost from tt_log l
 
 115       inner join tt_users u on (l.user_id = u.id)
 
 116       left join tt_projects p on (p.id = l.project_id)
 
 117       left join tt_tasks t on (t.id = l.task_id)
 
 118       where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
 
 120       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
 
 121         t.name as task_name, l.comment as note,
 
 122         time_format(l.duration, '%k:%i') as duration,
 
 123         cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost from tt_log l
 
 124         inner join tt_users u on (l.user_id = u.id)
 
 125         left join tt_projects p on (p.id = l.project_id)
 
 126         left join tt_tasks t on (t.id = l.task_id)
 
 127         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
 
 128         where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
 
 131     // If we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 132     if ($user->isPluginEnabled('ex')) {
 
 133       $sql_for_expense_items = "select ei.date as date, 2 as type, u.name as user_name, p.name as project_name,
 
 134         null as task_name, ei.name as note,
 
 135         null as duration, ei.cost as cost from tt_expense_items ei
 
 136         inner join tt_users u on (ei.user_id = u.id)
 
 137         left join tt_projects p on (p.id = ei.project_id)
 
 138         where ei.invoice_id = $invoice_id and ei.status = 1";
 
 140       // Construct a union.
 
 141       $sql = "($sql) union all ($sql_for_expense_items)";
 
 143       $sort_part = " order by date, user_name, type";
 
 147     $res = $mdb2->query($sql);
 
 148     if (!is_a($res, 'PEAR_Error')) {
 
 149       $dt = new DateAndTime(DB_DATEFORMAT);
 
 150       while ($val = $res->fetchRow()) {
 
 151         $dt->parseVal($val['date']);
 
 152         $val['date'] = $dt->toString($user->date_format);
 
 159   // delete - deletes the invoice data from the database.
 
 160   static function delete($invoice_id, $delete_invoice_items) {
 
 162     $mdb2 = getConnection();
 
 164     // Handle custom field log records.
 
 165     if ($delete_invoice_items) {
 
 166       $sql = "update tt_custom_field_log set status = NULL where log_id in (select id from tt_log where invoice_id = $invoice_id and status = 1)";
 
 167       $affected = $mdb2->exec($sql);
 
 168       if (is_a($affected, 'PEAR_Error')) return false;
 
 171     // Handle time records.
 
 172     if ($delete_invoice_items)
 
 173       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
 
 175       $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
 
 176     $affected = $mdb2->exec($sql);
 
 177     if (is_a($affected, 'PEAR_Error')) return false;
 
 179     // Handle expense items.
 
 180     if ($delete_invoice_items)
 
 181       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
 
 183       $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
 
 184     $affected = $mdb2->exec($sql);
 
 185     if (is_a($affected, 'PEAR_Error')) return false;
 
 187     $sql = "update tt_invoices set status = NULL where id = $invoice_id and team_id = $user->team_id";
 
 188     $affected = $mdb2->exec($sql);
 
 189     return (!is_a($affected, 'PEAR_Error'));
 
 192   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
 
 193   static function invoiceableItemsExist($fields) {
 
 195     $mdb2 = getConnection();
 
 198     $client_id = (int) $fields['client_id'];
 
 200     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 201     $start = $start_date->toString(DB_DATEFORMAT);
 
 203     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 204     $end = $end_date->toString(DB_DATEFORMAT);
 
 206     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 208     // Our query is different depending on tracking mode.
 
 209     if (MODE_TIME == $user->tracking_mode) {
 
 210       // In "time only" tracking mode there is a single user rate.
 
 211       $sql = "select count(*) as num from tt_log l, tt_users u
 
 212         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 213         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 215         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
 
 217       // sql part for project id.
 
 218       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 220       // When we have projects, rates are defined for each project in tt_user_project_binds table.
 
 221       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
 
 222         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 223         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 224         and upb.user_id = l.user_id and upb.project_id = l.project_id
 
 225         and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
 
 226         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
 
 227         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
 
 228         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
 
 229         // the problem becomes obvious.
 
 231         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
 
 233     $res = $mdb2->query($sql);
 
 234     if (!is_a($res, 'PEAR_Error')) {
 
 235       $val = $res->fetchRow();
 
 241     // sql part for project id.
 
 242     if ($project_id) $project_part = " and ei.project_id = $project_id";
 
 244     $sql = "select count(*) as num from tt_expense_items ei
 
 245       where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
 
 246       and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
 
 247       and ei.cost <> 0 and ei.status = 1";
 
 248     $res = $mdb2->query($sql);
 
 249     if (!is_a($res, 'PEAR_Error')) {
 
 250       $val = $res->fetchRow();
 
 259   // createInvoice - marks items for invoice as belonging to it (with its reference number).
 
 260   static function createInvoice($fields) {
 
 262     $mdb2 = getConnection();
 
 265     $name = $fields['name'];
 
 266     if (!$name) return false;
 
 268     $client_id = (int) $fields['client_id'];
 
 270     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
 
 271     $date = $invoice_date->toString(DB_DATEFORMAT);
 
 273     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 274     $start = $start_date->toString(DB_DATEFORMAT);
 
 276     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 277     $end = $end_date->toString(DB_DATEFORMAT);
 
 279     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 281     // Create a new invoice record.
 
 282     $sql = "insert into tt_invoices (team_id, name, date, client_id)
 
 283       values($user->team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
 
 284     $affected = $mdb2->exec($sql);
 
 285     if (is_a($affected, 'PEAR_Error')) return false;
 
 287     // Mark associated invoice items with invoice id.
 
 289     $sql = "select last_insert_id() as last_insert_id";
 
 290     $res = $mdb2->query($sql);
 
 291     $val = $res->fetchRow();
 
 292     $last_id = $val['last_insert_id'];
 
 294     // Our update sql is different depending on tracking mode.
 
 295     if (MODE_TIME == $user->tracking_mode) {
 
 296       // In "time only" tracking mode there is a single user rate.
 
 297       $sql = "update tt_log l
 
 298         left join tt_users u on (u.id = l.user_id)
 
 299         set l.invoice_id = $last_id
 
 300         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 301         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 302         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
 
 304        // sql part for project id.
 
 305       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 307       // When we have projects, rates are defined for each project in tt_user_project_binds.
 
 308       $sql = "update tt_log l
 
 309         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
 
 310         set l.invoice_id = $last_id
 
 311         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 312         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 313         and l.billable = 1"; //  l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
 
 314         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
 
 315         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
 
 316         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
 
 317         // the problem becomes obvious.
 
 319         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
 
 321     $affected = $mdb2->exec($sql);
 
 322     if (is_a($affected, 'PEAR_Error'))
 
 325     // sql part for project id.
 
 326     if ($project_id) $project_part = " and project_id = $project_id";
 
 328     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
 
 329       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
 
 330     $affected = $mdb2->exec($sql);
 
 331     return (!is_a($affected, 'PEAR_Error'));
 
 334   // prepareInvoiceBody - prepares an email body for invoice.
 
 335   static function prepareInvoiceBody($invoice_id, $comment)
 
 340     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
 
 341     $client = ttClientHelper::getClient($invoice['client_id'], true);
 
 342     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
 
 344     $tax_percent = $client['tax'];
 
 348     foreach($invoice_items as $item)
 
 349       $subtotal += $item['cost'];
 
 351       $tax_expenses = $user->isPluginEnabled('et');
 
 352       foreach($invoice_items as $item) {
 
 353         if ($item['type'] == 2 && !$tax_expenses)
 
 355         $tax += round($item['cost'] * $tax_percent / 100, 2);
 
 358     $total = $subtotal + $tax;
 
 360     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
 
 361     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
 
 362     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
 
 364     if ('.' != $user->decimal_mark) {
 
 365       foreach ($invoice_items as &$item) {
 
 366         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
 
 368       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
 
 369                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
 
 372     // Define some styles to use in email.
 
 373     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
 374     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
 375     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
 377     // Start creating email body.
 
 379     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
 383     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
 
 386     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
 388     // Output invoice info.
 
 390     $body .= '<tr><td><b>'.$i18n->getKey('label.date').':</b> '.$invoice['date'].'</td></tr>';
 
 391     $body .= '<tr><td><b>'.$i18n->getKey('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
 
 392     $body .= '<tr><td><b>'.$i18n->getKey('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
 
 397     // Output invoice items.
 
 398     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 400     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.date').'</td>';
 
 401     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('form.invoice.person').'</td>';
 
 402     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 403       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.project').'</td>';
 
 404     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 405       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.task').'</td>';
 
 406     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.note').'</td>';
 
 407     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
 
 408     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
 
 410     foreach ($invoice_items as $item) {
 
 412       $body .= '<td>'.$item['date'].'</td>';
 
 413       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
 
 414       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 415         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
 
 416       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 417         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
 
 418       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
 
 419       $body .= '<td align="right">'.$item['duration'].'</td>';
 
 420       $body .= '<td align="right">'.$item['cost'].'</td>';
 
 425     if (MODE_PROJECTS == $user->tracking_mode)
 
 427     elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 429     $body .= '<tr><td> </td></tr>';
 
 431       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
 
 432       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
 
 434     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
 
 438     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
 439       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
 
 441     // Finish creating email body.
 
 442     $body .= '</body></html>';