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   // getInvoice - obtains invoice data from the database.
 
  36   static function getInvoice($invoice_id) {
 
  38     $mdb2 = getConnection();
 
  40     if ($user->isClient()) $client_part = " and client_id = $user->client_id";
 
  42     $sql = "select * from tt_invoices where id = $invoice_id and group_id = ".
 
  43             $user->getGroup()."$client_part and status = 1";
 
  44     $res = $mdb2->query($sql);
 
  45     if (!is_a($res, 'PEAR_Error')) {
 
  46       if ($val = $res->fetchRow())
 
  52   // The getInvoiceByName looks up an invoice by name.
 
  53   static function getInvoiceByName($invoice_name) {
 
  55     $mdb2 = getConnection();
 
  58     $sql = "select id from tt_invoices where group_id = ".
 
  59             $user->getGroup()." and name = ".$mdb2->quote($invoice_name)." and status = 1";
 
  60     $res = $mdb2->query($sql);
 
  61     if (!is_a($res, 'PEAR_Error')) {
 
  62       $val = $res->fetchRow();
 
  70   // The isPaid determines if an invoice is paid by looking at the paid status of its items.
 
  71   // If any non-paid item is found, the entire invoice is considered not paid.
 
  72   // Therefore, the paid status of the invoice is a calculated value.
 
  73   // This is because we maintain the paid status on individual item level.
 
  74   static function isPaid($invoice_id) {
 
  76     $mdb2 = getConnection();
 
  79     $sql = "select count(*) as count from tt_log where invoice_id = $invoice_id and status = 1 and paid < 1";
 
  80     $res = $mdb2->query($sql);
 
  81     if (!is_a($res, 'PEAR_Error')) {
 
  82       $val = $res->fetchRow();
 
  83       if ($val['count'] > 0)
 
  84         return false; // A non-paid time item exists.
 
  86     $sql = "select count(*) as count from tt_expense_items where invoice_id = $invoice_id and status = 1 and paid < 1";
 
  87     $res = $mdb2->query($sql);
 
  88     if (!is_a($res, 'PEAR_Error')) {
 
  89       $val = $res->fetchRow();
 
  90       if ($val['count'] > 0)
 
  91         return false; // A non-paid expense item exists.
 
  93         return true; // All time and expense items in invoice are paid.
 
  98   // markPaid marks invoice items as paid.
 
  99   static function markPaid($invoice_id, $mark_paid = true) {
 
 102     $mdb2 = getConnection();
 
 104     $paid_status = $mark_paid ? 1 : 0;
 
 105     $sql = "update tt_log set paid = $paid_status where invoice_id = $invoice_id and status = 1";
 
 106     $affected = $mdb2->exec($sql);
 
 107     if (is_a($affected, 'PEAR_Error')) return false;
 
 109     $sql = "update tt_expense_items set paid = $paid_status where invoice_id = $invoice_id and status = 1";
 
 110     $affected = $mdb2->exec($sql);
 
 111     if (is_a($affected, 'PEAR_Error')) return false;
 
 116   // The getInvoiceItems retrieves tt_log items associated with the invoice. 
 
 117   static function getInvoiceItems($invoice_id) {
 
 119     $mdb2 = getConnection();
 
 121     // At this time only detailed invoice is supported.
 
 122     // It is anticipated to support "totals only" option later on.
 
 124     // Our query is different depending on tracking mode.
 
 125     if (MODE_TIME == $user->getTrackingMode()) {
 
 126       // In "time only" tracking mode there is a single user rate.
 
 127       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
 
 128       t.name as task_name, l.comment as note,
 
 129       time_format(l.duration, '%k:%i') as duration,
 
 130       cast(l.billable * u.rate * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
 
 131       l.paid as paid from tt_log l
 
 132       inner join tt_users u on (l.user_id = u.id)
 
 133       left join tt_projects p on (p.id = l.project_id)
 
 134       left join tt_tasks t on (t.id = l.task_id)
 
 135       where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
 
 137       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
 
 138         t.name as task_name, l.comment as note,
 
 139         time_format(l.duration, '%k:%i') as duration,
 
 140         cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
 
 141         l.paid as paid from tt_log l
 
 142         inner join tt_users u on (l.user_id = u.id)
 
 143         left join tt_projects p on (p.id = l.project_id)
 
 144         left join tt_tasks t on (t.id = l.task_id)
 
 145         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
 
 146         where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
 
 149     // If we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 150     if ($user->isPluginEnabled('ex')) {
 
 151       $sql_for_expense_items = "select ei.date as date, 2 as type, u.name as user_name, p.name as project_name,
 
 152         null as task_name, ei.name as note,
 
 153         null as duration, ei.cost as cost,
 
 154         ei.paid as paid from tt_expense_items ei
 
 155         inner join tt_users u on (ei.user_id = u.id)
 
 156         left join tt_projects p on (p.id = ei.project_id)
 
 157         where ei.invoice_id = $invoice_id and ei.status = 1";
 
 159       // Construct a union.
 
 160       $sql = "($sql) union all ($sql_for_expense_items)";
 
 162       $sort_part = " order by date, user_name, type";
 
 166     $res = $mdb2->query($sql);
 
 167     if (!is_a($res, 'PEAR_Error')) {
 
 168       $dt = new DateAndTime(DB_DATEFORMAT);
 
 169       while ($val = $res->fetchRow()) {
 
 170         $dt->parseVal($val['date']);
 
 171         $val['date'] = $dt->toString($user->date_format);
 
 178   // delete - deletes the invoice data from the database.
 
 179   static function delete($invoice_id, $delete_invoice_items) {
 
 181     $mdb2 = getConnection();
 
 183     // Handle custom field log records.
 
 184     if ($delete_invoice_items) {
 
 185       $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)";
 
 186       $affected = $mdb2->exec($sql);
 
 187       if (is_a($affected, 'PEAR_Error')) return false;
 
 190     // Handle time records.
 
 191     if ($delete_invoice_items)
 
 192       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
 
 194       $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
 
 195     $affected = $mdb2->exec($sql);
 
 196     if (is_a($affected, 'PEAR_Error')) return false;
 
 198     // Handle expense items.
 
 199     if ($delete_invoice_items)
 
 200       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
 
 202       $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
 
 203     $affected = $mdb2->exec($sql);
 
 204     if (is_a($affected, 'PEAR_Error')) return false;
 
 206     $sql = "update tt_invoices set status = NULL where id = $invoice_id and group_id = ".$user->getGroup();
 
 207     $affected = $mdb2->exec($sql);
 
 208     return (!is_a($affected, 'PEAR_Error'));
 
 211   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
 
 212   static function invoiceableItemsExist($fields) {
 
 214     $mdb2 = getConnection();
 
 217     $client_id = (int) $fields['client_id'];
 
 219     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 220     $start = $start_date->toString(DB_DATEFORMAT);
 
 222     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 223     $end = $end_date->toString(DB_DATEFORMAT);
 
 225     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 227     // Our query is different depending on tracking mode.
 
 228     if (MODE_TIME == $user->getTrackingMode()) {
 
 229       // In "time only" tracking mode there is a single user rate.
 
 230       $sql = "select count(*) as num from tt_log l, tt_users u
 
 231         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 232         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 234         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
 
 236       // sql part for project id.
 
 237       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 239       // When we have projects, rates are defined for each project in tt_user_project_binds table.
 
 240       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
 
 241         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 242         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 243         and upb.user_id = l.user_id and upb.project_id = l.project_id
 
 244         and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
 
 245         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
 
 246         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
 
 247         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
 
 248         // the problem becomes obvious.
 
 250         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
 
 252     $res = $mdb2->query($sql);
 
 253     if (!is_a($res, 'PEAR_Error')) {
 
 254       $val = $res->fetchRow();
 
 260     // sql part for project id.
 
 261     if ($project_id) $project_part = " and ei.project_id = $project_id";
 
 263     $sql = "select count(*) as num from tt_expense_items ei
 
 264       where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
 
 265       and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
 
 266       and ei.cost <> 0 and ei.status = 1";
 
 267     $res = $mdb2->query($sql);
 
 268     if (!is_a($res, 'PEAR_Error')) {
 
 269       $val = $res->fetchRow();
 
 278   // createInvoice - marks items for invoice as belonging to it (with its reference number).
 
 279   static function createInvoice($fields) {
 
 281     $mdb2 = getConnection();
 
 284     $name = $fields['name'];
 
 285     if (!$name) return false;
 
 287     $client_id = (int) $fields['client_id'];
 
 289     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
 
 290     $date = $invoice_date->toString(DB_DATEFORMAT);
 
 292     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 293     $start = $start_date->toString(DB_DATEFORMAT);
 
 295     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 296     $end = $end_date->toString(DB_DATEFORMAT);
 
 298     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 300     // Create a new invoice record.
 
 301     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id) values(".
 
 302       $user->getGroup().", $user->org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
 
 303     $affected = $mdb2->exec($sql);
 
 304     if (is_a($affected, 'PEAR_Error')) return false;
 
 306     // Mark associated invoice items with invoice id.
 
 307     $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
 
 309     // Our update sql is different depending on tracking mode.
 
 310     if (MODE_TIME == $user->getTrackingMode()) {
 
 311       // In "time only" tracking mode there is a single user rate.
 
 312       $sql = "update tt_log l
 
 313         left join tt_users u on (u.id = l.user_id)
 
 314         set l.invoice_id = $last_id
 
 315         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 316         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 317         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
 
 319        // sql part for project id.
 
 320       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 322       // When we have projects, rates are defined for each project in tt_user_project_binds.
 
 323       $sql = "update tt_log l
 
 324         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
 
 325         set l.invoice_id = $last_id
 
 326         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 327         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 328         and l.billable = 1"; //  l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
 
 329         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
 
 330         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
 
 331         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
 
 332         // the problem becomes obvious.
 
 334         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
 
 336     $affected = $mdb2->exec($sql);
 
 337     if (is_a($affected, 'PEAR_Error'))
 
 340     // sql part for project id.
 
 341     if ($project_id) $project_part = " and project_id = $project_id";
 
 343     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
 
 344       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
 
 345     $affected = $mdb2->exec($sql);
 
 346     return (!is_a($affected, 'PEAR_Error'));
 
 349   // prepareInvoiceBody - prepares an email body for invoice.
 
 350   static function prepareInvoiceBody($invoice_id, $comment)
 
 355     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
 
 356     $client = ttClientHelper::getClient($invoice['client_id'], true);
 
 357     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
 
 359     $tax_percent = $client['tax'];
 
 363     foreach($invoice_items as $item)
 
 364       $subtotal += $item['cost'];
 
 366       $tax_expenses = $user->isPluginEnabled('et');
 
 367       foreach($invoice_items as $item) {
 
 368         if ($item['type'] == 2 && !$tax_expenses)
 
 370         $tax += round($item['cost'] * $tax_percent / 100, 2);
 
 373     $total = $subtotal + $tax;
 
 375     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
 
 376     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
 
 377     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
 
 379     if ('.' != $user->decimal_mark) {
 
 380       foreach ($invoice_items as &$item) {
 
 381         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
 
 383       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
 
 384                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
 
 387     // Define some styles to use in email.
 
 388     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
 389     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
 390     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
 392     // Determine tracking mode once for multiple reuse below.
 
 393     $trackingMode = $user->getTrackingMode();
 
 395     // Start creating email body.
 
 397     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
 401     $body .= '<p style="'.$style_title.'">'.$i18n->get('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
 
 404     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
 406     // Output invoice info.
 
 408     $body .= '<tr><td><b>'.$i18n->get('label.date').':</b> '.$invoice['date'].'</td></tr>';
 
 409     $body .= '<tr><td><b>'.$i18n->get('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
 
 410     $body .= '<tr><td><b>'.$i18n->get('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
 
 415     // Output invoice items.
 
 416     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 418     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.date').'</td>';
 
 419     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('form.invoice.person').'</td>';
 
 420     if (MODE_PROJECTS == $trackingMode || MODE_PROJECTS_AND_TASKS == $trackingMode)
 
 421       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.project').'</td>';
 
 422     if (MODE_PROJECTS_AND_TASKS == $trackingMode)
 
 423       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.task').'</td>';
 
 424     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.note').'</td>';
 
 425     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
 
 426     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
 
 428     foreach ($invoice_items as $item) {
 
 430       $body .= '<td>'.$item['date'].'</td>';
 
 431       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
 
 432       if (MODE_PROJECTS == $trackingMode || MODE_PROJECTS_AND_TASKS == $trackingMode)
 
 433         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
 
 434       if (MODE_PROJECTS_AND_TASKS == $trackingMode)
 
 435         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
 
 436       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
 
 437       $body .= '<td align="right">'.$item['duration'].'</td>';
 
 438       $body .= '<td align="right">'.$item['cost'].'</td>';
 
 443     if (MODE_PROJECTS == $trackingMode)
 
 445     elseif (MODE_PROJECTS_AND_TASKS == $trackingMode)
 
 447     $body .= '<tr><td> </td></tr>';
 
 449       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
 
 450       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
 
 452     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
 
 456     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
 457       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
 
 459     // Finish creating email body.
 
 460     $body .= '</body></html>';