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) {
 
 102     $mdb2 = getConnection();
 
 104     // At this time only detailed invoice is supported.
 
 105     // It is anticipated to support "totals only" option later on.
 
 107     // Our query is different depending on tracking mode.
 
 108     if (MODE_TIME == $user->tracking_mode) {
 
 109       // In "time only" tracking mode there is a single user rate.
 
 110       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
 
 111       t.name as task_name, l.comment as note,
 
 112       time_format(l.duration, '%k:%i') as duration,
 
 113       cast(l.billable * u.rate * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost from tt_log l
 
 114       inner join tt_users u on (l.user_id = u.id)
 
 115       left join tt_projects p on (p.id = l.project_id)
 
 116       left join tt_tasks t on (t.id = l.task_id)
 
 117       where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
 
 119       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
 
 120         t.name as task_name, l.comment as note,
 
 121         time_format(l.duration, '%k:%i') as duration,
 
 122         cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost from tt_log l
 
 123         inner join tt_users u on (l.user_id = u.id)
 
 124         left join tt_projects p on (p.id = l.project_id)
 
 125         left join tt_tasks t on (t.id = l.task_id)
 
 126         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
 
 127         where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
 
 130     // If we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 131     if ($user->isPluginEnabled('ex')) {
 
 132       $sql_for_expense_items = "select ei.date as date, 2 as type, u.name as user_name, p.name as project_name,
 
 133         null as task_name, ei.name as note,
 
 134         null as duration, ei.cost as cost from tt_expense_items ei
 
 135         inner join tt_users u on (ei.user_id = u.id)
 
 136         left join tt_projects p on (p.id = ei.project_id)
 
 137         where ei.invoice_id = $invoice_id and ei.status = 1";
 
 139       // Construct a union.
 
 140       $sql = "($sql) union all ($sql_for_expense_items)";
 
 142       $sort_part = " order by date, user_name, type";
 
 146     $res = $mdb2->query($sql);
 
 147     if (!is_a($res, 'PEAR_Error')) {
 
 148       $dt = new DateAndTime(DB_DATEFORMAT);
 
 149       while ($val = $res->fetchRow()) {
 
 150         $dt->parseVal($val['date']);
 
 151         $val['date'] = $dt->toString($user->date_format);
 
 158   // delete - deletes the invoice data from the database.
 
 159   static function delete($invoice_id, $delete_invoice_items) {
 
 161     $mdb2 = getConnection();
 
 163     // Handle custom field log records.
 
 164     if ($delete_invoice_items) {
 
 165       $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)";
 
 166       $affected = $mdb2->exec($sql);
 
 167       if (is_a($affected, 'PEAR_Error')) return false;
 
 170     // Handle time records.
 
 171     if ($delete_invoice_items)
 
 172       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
 
 174       $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
 
 175     $affected = $mdb2->exec($sql);
 
 176     if (is_a($affected, 'PEAR_Error')) return false;
 
 178     // Handle expense items.
 
 179     if ($delete_invoice_items)
 
 180       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
 
 182       $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
 
 183     $affected = $mdb2->exec($sql);
 
 184     if (is_a($affected, 'PEAR_Error')) return false;
 
 186     $sql = "update tt_invoices set status = NULL where id = $invoice_id and team_id = $user->team_id";
 
 187     $affected = $mdb2->exec($sql);
 
 188     return (!is_a($affected, 'PEAR_Error'));
 
 191   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
 
 192   static function invoiceableItemsExist($fields) {
 
 194     $mdb2 = getConnection();
 
 197     $client_id = (int) $fields['client_id'];
 
 199     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 200     $start = $start_date->toString(DB_DATEFORMAT);
 
 202     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 203     $end = $end_date->toString(DB_DATEFORMAT);
 
 205     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 207     // Our query is different depending on tracking mode.
 
 208     if (MODE_TIME == $user->tracking_mode) {
 
 209       // In "time only" tracking mode there is a single user rate.
 
 210       $sql = "select count(*) as num from tt_log l, tt_users u
 
 211         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 212         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 214         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
 
 216       // sql part for project id.
 
 217       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 219       // When we have projects, rates are defined for each project in tt_user_project_binds table.
 
 220       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
 
 221         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 222         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 223         and upb.user_id = l.user_id and upb.project_id = l.project_id
 
 224         and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
 
 225         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
 
 226         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
 
 227         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
 
 228         // the problem becomes obvious.
 
 230         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
 
 232     $res = $mdb2->query($sql);
 
 233     if (!is_a($res, 'PEAR_Error')) {
 
 234       $val = $res->fetchRow();
 
 240     // sql part for project id.
 
 241     if ($project_id) $project_part = " and ei.project_id = $project_id";
 
 243     $sql = "select count(*) as num from tt_expense_items ei
 
 244       where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
 
 245       and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
 
 246       and ei.cost <> 0 and ei.status = 1";
 
 247     $res = $mdb2->query($sql);
 
 248     if (!is_a($res, 'PEAR_Error')) {
 
 249       $val = $res->fetchRow();
 
 258   // createInvoice - marks items for invoice as belonging to it (with its reference number).
 
 259   static function createInvoice($fields) {
 
 261     $mdb2 = getConnection();
 
 264     $name = $fields['name'];
 
 265     if (!$name) return false;
 
 267     $client_id = (int) $fields['client_id'];
 
 269     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
 
 270     $date = $invoice_date->toString(DB_DATEFORMAT);
 
 272     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 273     $start = $start_date->toString(DB_DATEFORMAT);
 
 275     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 276     $end = $end_date->toString(DB_DATEFORMAT);
 
 278     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 280     // Create a new invoice record.
 
 281     $sql = "insert into tt_invoices (team_id, name, date, client_id)
 
 282       values($user->team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
 
 283     $affected = $mdb2->exec($sql);
 
 284     if (is_a($affected, 'PEAR_Error')) return false;
 
 286     // Mark associated invoice items with invoice id.
 
 288     $sql = "select last_insert_id() as last_insert_id";
 
 289     $res = $mdb2->query($sql);
 
 290     $val = $res->fetchRow();
 
 291     $last_id = $val['last_insert_id'];
 
 293     // Our update sql is different depending on tracking mode.
 
 294     if (MODE_TIME == $user->tracking_mode) {
 
 295       // In "time only" tracking mode there is a single user rate.
 
 296       $sql = "update tt_log l
 
 297         left join tt_users u on (u.id = l.user_id)
 
 298         set l.invoice_id = $last_id
 
 299         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 300         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 301         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
 
 303        // sql part for project id.
 
 304       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 306       // When we have projects, rates are defined for each project in tt_user_project_binds.
 
 307       $sql = "update tt_log l
 
 308         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
 
 309         set l.invoice_id = $last_id
 
 310         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 311         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 312         and l.billable = 1"; //  l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
 
 313         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
 
 314         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
 
 315         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
 
 316         // the problem becomes obvious.
 
 318         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
 
 320     $affected = $mdb2->exec($sql);
 
 321     if (is_a($affected, 'PEAR_Error'))
 
 324     // sql part for project id.
 
 325     if ($project_id) $project_part = " and project_id = $project_id";
 
 327     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
 
 328       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
 
 329     $affected = $mdb2->exec($sql);
 
 330     return (!is_a($affected, 'PEAR_Error'));
 
 333   // prepareInvoiceBody - prepares an email body for invoice.
 
 334   static function prepareInvoiceBody($invoice_id, $comment)
 
 339     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
 
 340     $client = ttClientHelper::getClient($invoice['client_id'], true);
 
 341     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
 
 343     $tax_percent = $client['tax'];
 
 347     foreach($invoice_items as $item)
 
 348       $subtotal += $item['cost'];
 
 350       $tax_expenses = $user->isPluginEnabled('et');
 
 351       foreach($invoice_items as $item) {
 
 352         if ($item['type'] == 2 && !$tax_expenses)
 
 354         $tax += round($item['cost'] * $tax_percent / 100, 2);
 
 357     $total = $subtotal + $tax;
 
 359     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
 
 360     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
 
 361     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
 
 363     if ('.' != $user->decimal_mark) {
 
 364       foreach ($invoice_items as &$item) {
 
 365         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
 
 367       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
 
 368                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
 
 371     // Define some styles to use in email.
 
 372     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
 373     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
 374     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
 376     // Start creating email body.
 
 378     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
 382     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
 
 385     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
 387     // Output invoice info.
 
 389     $body .= '<tr><td><b>'.$i18n->getKey('label.date').':</b> '.$invoice['date'].'</td></tr>';
 
 390     $body .= '<tr><td><b>'.$i18n->getKey('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
 
 391     $body .= '<tr><td><b>'.$i18n->getKey('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
 
 396     // Output invoice items.
 
 397     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 399     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.date').'</td>';
 
 400     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('form.invoice.person').'</td>';
 
 401     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 402       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.project').'</td>';
 
 403     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 404       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.task').'</td>';
 
 405     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.note').'</td>';
 
 406     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
 
 407     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
 
 409     foreach ($invoice_items as $item) {
 
 411       $body .= '<td>'.$item['date'].'</td>';
 
 412       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
 
 413       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 414         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
 
 415       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 416         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
 
 417       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
 
 418       $body .= '<td align="right">'.$item['duration'].'</td>';
 
 419       $body .= '<td align="right">'.$item['cost'].'</td>';
 
 424     if (MODE_PROJECTS == $user->tracking_mode)
 
 426     elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 428     $body .= '<tr><td> </td></tr>';
 
 430       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
 
 431       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
 
 433     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
 
 437     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
 438       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
 
 440     // Finish creating email body.
 
 441     $body .= '</body></html>';