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     $group_id = (int) $fields['group_id'];
 
  41     $org_id = (int) $fields['org_id'];
 
  42     $name = $fields['name'];
 
  43     if (!$name) return false;
 
  45     $client_id = (int) $fields['client_id'];
 
  46     $date = $fields['date'];
 
  47     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
 
  48       $status_f = ', status';
 
  49       $status_v = ', '.$mdb2->quote($fields['status']);
 
  52     // Insert a new invoice record.
 
  53     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id $status_f)".
 
  54       " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id $status_v)";
 
  55     $affected = $mdb2->exec($sql);
 
  57     if (is_a($affected, 'PEAR_Error')) return false;
 
  60     $sql = "select last_insert_id() as last_insert_id";
 
  61     $res = $mdb2->query($sql);
 
  62     $val = $res->fetchRow();
 
  63     $last_id = $val['last_insert_id'];
 
  68   // getInvoice - obtains invoice data from the database.
 
  69   static function getInvoice($invoice_id) {
 
  71     $mdb2 = getConnection();
 
  73     if ($user->isClient()) $client_part = " and client_id = $user->client_id";
 
  75     $sql = "select * from tt_invoices where id = $invoice_id and group_id = ".
 
  76             $user->getActiveGroup()."$client_part and status = 1";
 
  77     $res = $mdb2->query($sql);
 
  78     if (!is_a($res, 'PEAR_Error')) {
 
  79       if ($val = $res->fetchRow())
 
  85   // The getInvoiceByName looks up an invoice by name.
 
  86   static function getInvoiceByName($invoice_name) {
 
  88     $mdb2 = getConnection();
 
  91     $sql = "select id from tt_invoices where group_id = ".
 
  92             $user->getActiveGroup()." and name = ".$mdb2->quote($invoice_name)." and status = 1";
 
  93     $res = $mdb2->query($sql);
 
  94     if (!is_a($res, 'PEAR_Error')) {
 
  95       $val = $res->fetchRow();
 
 103   // The isPaid determines if an invoice is paid by looking at the paid status of its items.
 
 104   // If any non-paid item is found, the entire invoice is considered not paid.
 
 105   // Therefore, the paid status of the invoice is a calculated value.
 
 106   // This is because we maintain the paid status on individual item level.
 
 107   static function isPaid($invoice_id) {
 
 109     $mdb2 = getConnection();
 
 112     $sql = "select count(*) as count from tt_log where invoice_id = $invoice_id and status = 1 and paid < 1";
 
 113     $res = $mdb2->query($sql);
 
 114     if (!is_a($res, 'PEAR_Error')) {
 
 115       $val = $res->fetchRow();
 
 116       if ($val['count'] > 0)
 
 117         return false; // A non-paid time item exists.
 
 119     $sql = "select count(*) as count from tt_expense_items where invoice_id = $invoice_id and status = 1 and paid < 1";
 
 120     $res = $mdb2->query($sql);
 
 121     if (!is_a($res, 'PEAR_Error')) {
 
 122       $val = $res->fetchRow();
 
 123       if ($val['count'] > 0)
 
 124         return false; // A non-paid expense item exists.
 
 126         return true; // All time and expense items in invoice are paid.
 
 131   // markPaid marks invoice items as paid.
 
 132   static function markPaid($invoice_id, $mark_paid = true) {
 
 135     $mdb2 = getConnection();
 
 137     $paid_status = $mark_paid ? 1 : 0;
 
 138     $sql = "update tt_log set paid = $paid_status where invoice_id = $invoice_id and status = 1";
 
 139     $affected = $mdb2->exec($sql);
 
 140     if (is_a($affected, 'PEAR_Error')) return false;
 
 142     $sql = "update tt_expense_items set paid = $paid_status where invoice_id = $invoice_id and status = 1";
 
 143     $affected = $mdb2->exec($sql);
 
 144     if (is_a($affected, 'PEAR_Error')) return false;
 
 149   // The getInvoiceItems retrieves tt_log items associated with the invoice. 
 
 150   static function getInvoiceItems($invoice_id) {
 
 152     $mdb2 = getConnection();
 
 154     // At this time only detailed invoice is supported.
 
 155     // It is anticipated to support "totals only" option later on.
 
 157     // Our query is different depending on tracking mode.
 
 158     if (MODE_TIME == $user->tracking_mode) {
 
 159       // In "time only" tracking mode there is a single user rate.
 
 160       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
 
 161       t.name as task_name, l.comment as note,
 
 162       time_format(l.duration, '%k:%i') as duration,
 
 163       cast(l.billable * u.rate * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
 
 164       l.paid as paid from tt_log l
 
 165       inner join tt_users u on (l.user_id = u.id)
 
 166       left join tt_projects p on (p.id = l.project_id)
 
 167       left join tt_tasks t on (t.id = l.task_id)
 
 168       where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
 
 170       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
 
 171         t.name as task_name, l.comment as note,
 
 172         time_format(l.duration, '%k:%i') as duration,
 
 173         cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
 
 174         l.paid as paid from tt_log l
 
 175         inner join tt_users u on (l.user_id = u.id)
 
 176         left join tt_projects p on (p.id = l.project_id)
 
 177         left join tt_tasks t on (t.id = l.task_id)
 
 178         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
 
 179         where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
 
 182     // If we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
 
 183     if ($user->isPluginEnabled('ex')) {
 
 184       $sql_for_expense_items = "select ei.date as date, 2 as type, u.name as user_name, p.name as project_name,
 
 185         null as task_name, ei.name as note,
 
 186         null as duration, ei.cost as cost,
 
 187         ei.paid as paid from tt_expense_items ei
 
 188         inner join tt_users u on (ei.user_id = u.id)
 
 189         left join tt_projects p on (p.id = ei.project_id)
 
 190         where ei.invoice_id = $invoice_id and ei.status = 1";
 
 192       // Construct a union.
 
 193       $sql = "($sql) union all ($sql_for_expense_items)";
 
 195       $sort_part = " order by date, user_name, type";
 
 199     $res = $mdb2->query($sql);
 
 200     if (!is_a($res, 'PEAR_Error')) {
 
 201       $dt = new DateAndTime(DB_DATEFORMAT);
 
 202       while ($val = $res->fetchRow()) {
 
 203         $dt->parseVal($val['date']);
 
 204         $val['date'] = $dt->toString($user->date_format);
 
 211   // delete - deletes the invoice data from the database.
 
 212   static function delete($invoice_id, $delete_invoice_items) {
 
 214     $mdb2 = getConnection();
 
 216     // Handle custom field log records.
 
 217     if ($delete_invoice_items) {
 
 218       $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)";
 
 219       $affected = $mdb2->exec($sql);
 
 220       if (is_a($affected, 'PEAR_Error')) return false;
 
 223     // Handle time records.
 
 224     if ($delete_invoice_items)
 
 225       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
 
 227       $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
 
 228     $affected = $mdb2->exec($sql);
 
 229     if (is_a($affected, 'PEAR_Error')) return false;
 
 231     // Handle expense items.
 
 232     if ($delete_invoice_items)
 
 233       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
 
 235       $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
 
 236     $affected = $mdb2->exec($sql);
 
 237     if (is_a($affected, 'PEAR_Error')) return false;
 
 239     $sql = "update tt_invoices set status = NULL where id = $invoice_id and group_id = ".$user->getActiveGroup();
 
 240     $affected = $mdb2->exec($sql);
 
 241     return (!is_a($affected, 'PEAR_Error'));
 
 244   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
 
 245   static function invoiceableItemsExist($fields) {
 
 247     $mdb2 = getConnection();
 
 250     $client_id = (int) $fields['client_id'];
 
 252     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 253     $start = $start_date->toString(DB_DATEFORMAT);
 
 255     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 256     $end = $end_date->toString(DB_DATEFORMAT);
 
 258     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 260     // Our query is different depending on tracking mode.
 
 261     if (MODE_TIME == $user->tracking_mode) {
 
 262       // In "time only" tracking mode there is a single user rate.
 
 263       $sql = "select count(*) as num from tt_log l, tt_users u
 
 264         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 265         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 267         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
 
 269       // sql part for project id.
 
 270       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 272       // When we have projects, rates are defined for each project in tt_user_project_binds table.
 
 273       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
 
 274         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 275         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 276         and upb.user_id = l.user_id and upb.project_id = l.project_id
 
 277         and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
 
 278         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
 
 279         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
 
 280         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
 
 281         // the problem becomes obvious.
 
 283         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
 
 285     $res = $mdb2->query($sql);
 
 286     if (!is_a($res, 'PEAR_Error')) {
 
 287       $val = $res->fetchRow();
 
 293     // sql part for project id.
 
 294     if ($project_id) $project_part = " and ei.project_id = $project_id";
 
 296     $sql = "select count(*) as num from tt_expense_items ei
 
 297       where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
 
 298       and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
 
 299       and ei.cost <> 0 and ei.status = 1";
 
 300     $res = $mdb2->query($sql);
 
 301     if (!is_a($res, 'PEAR_Error')) {
 
 302       $val = $res->fetchRow();
 
 311   // createInvoice - marks items for invoice as belonging to it (with its reference number).
 
 312   static function createInvoice($fields) {
 
 314     $mdb2 = getConnection();
 
 317     $name = $fields['name'];
 
 318     if (!$name) return false;
 
 320     $client_id = (int) $fields['client_id'];
 
 322     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
 
 323     $date = $invoice_date->toString(DB_DATEFORMAT);
 
 325     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 326     $start = $start_date->toString(DB_DATEFORMAT);
 
 328     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 329     $end = $end_date->toString(DB_DATEFORMAT);
 
 331     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 333     // Create a new invoice record.
 
 334     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id) values(".
 
 335       $user->getActiveGroup().", $user->org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
 
 336     $affected = $mdb2->exec($sql);
 
 337     if (is_a($affected, 'PEAR_Error')) return false;
 
 339     // Mark associated invoice items with invoice id.
 
 341     $sql = "select last_insert_id() as last_insert_id";
 
 342     $res = $mdb2->query($sql);
 
 343     $val = $res->fetchRow();
 
 344     $last_id = $val['last_insert_id'];
 
 346     // Our update sql is different depending on tracking mode.
 
 347     if (MODE_TIME == $user->tracking_mode) {
 
 348       // In "time only" tracking mode there is a single user rate.
 
 349       $sql = "update tt_log l
 
 350         left join tt_users u on (u.id = l.user_id)
 
 351         set l.invoice_id = $last_id
 
 352         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 353         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 354         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
 
 356        // sql part for project id.
 
 357       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 359       // When we have projects, rates are defined for each project in tt_user_project_binds.
 
 360       $sql = "update tt_log l
 
 361         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
 
 362         set l.invoice_id = $last_id
 
 363         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 364         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 365         and l.billable = 1"; //  l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
 
 366         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
 
 367         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
 
 368         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
 
 369         // the problem becomes obvious.
 
 371         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
 
 373     $affected = $mdb2->exec($sql);
 
 374     if (is_a($affected, 'PEAR_Error'))
 
 377     // sql part for project id.
 
 378     if ($project_id) $project_part = " and project_id = $project_id";
 
 380     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
 
 381       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
 
 382     $affected = $mdb2->exec($sql);
 
 383     return (!is_a($affected, 'PEAR_Error'));
 
 386   // prepareInvoiceBody - prepares an email body for invoice.
 
 387   static function prepareInvoiceBody($invoice_id, $comment)
 
 392     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
 
 393     $client = ttClientHelper::getClient($invoice['client_id'], true);
 
 394     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
 
 396     $tax_percent = $client['tax'];
 
 400     foreach($invoice_items as $item)
 
 401       $subtotal += $item['cost'];
 
 403       $tax_expenses = $user->isPluginEnabled('et');
 
 404       foreach($invoice_items as $item) {
 
 405         if ($item['type'] == 2 && !$tax_expenses)
 
 407         $tax += round($item['cost'] * $tax_percent / 100, 2);
 
 410     $total = $subtotal + $tax;
 
 412     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
 
 413     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
 
 414     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
 
 416     if ('.' != $user->decimal_mark) {
 
 417       foreach ($invoice_items as &$item) {
 
 418         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
 
 420       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
 
 421                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
 
 424     // Define some styles to use in email.
 
 425     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
 426     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
 427     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
 429     // Start creating email body.
 
 431     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
 435     $body .= '<p style="'.$style_title.'">'.$i18n->get('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
 
 438     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
 440     // Output invoice info.
 
 442     $body .= '<tr><td><b>'.$i18n->get('label.date').':</b> '.$invoice['date'].'</td></tr>';
 
 443     $body .= '<tr><td><b>'.$i18n->get('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
 
 444     $body .= '<tr><td><b>'.$i18n->get('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
 
 449     // Output invoice items.
 
 450     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 452     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.date').'</td>';
 
 453     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('form.invoice.person').'</td>';
 
 454     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 455       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.project').'</td>';
 
 456     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 457       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.task').'</td>';
 
 458     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.note').'</td>';
 
 459     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
 
 460     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
 
 462     foreach ($invoice_items as $item) {
 
 464       $body .= '<td>'.$item['date'].'</td>';
 
 465       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
 
 466       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 467         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
 
 468       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 469         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
 
 470       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
 
 471       $body .= '<td align="right">'.$item['duration'].'</td>';
 
 472       $body .= '<td align="right">'.$item['cost'].'</td>';
 
 477     if (MODE_PROJECTS == $user->tracking_mode)
 
 479     elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 481     $body .= '<tr><td> </td></tr>';
 
 483       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
 
 484       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
 
 486     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
 
 490     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
 
 491       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
 
 493     // Finish creating email body.
 
 494     $body .= '</body></html>';