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;
 
  43         $client_id = (int) $fields['client_id'];
 
  44         $date = $fields['date'];
 
  45     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
 
  46       $status_f = ', status';
 
  47       $status_v = ', '.$mdb2->quote($fields['status']);
 
  50     // Insert a new invoice record.
 
  51     $sql = "insert into tt_invoices (team_id, name, date, client_id $status_f)
 
  52       values($team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id $status_v)"; 
 
  53     $affected = $mdb2->exec($sql);
 
  55     if (is_a($affected, 'PEAR_Error'))
 
  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 (in_array('ex', explode(',', $user->plugins))) { // if ex(penses) plugin is enabled
 
 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'))
 
 172     // Handle time records.
 
 173     if ($delete_invoice_items)
 
 174       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
 
 176       $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
 
 177     $affected = $mdb2->exec($sql);
 
 178         if (is_a($affected, 'PEAR_Error'))
 
 181     // Handle expense items.
 
 182     if ($delete_invoice_items)            
 
 183       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
 
 185       $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
 
 186     $affected = $mdb2->exec($sql);
 
 187         if (is_a($affected, 'PEAR_Error'))
 
 190         $sql = "update tt_invoices set status = NULL where id = $invoice_id and team_id = $user->team_id";
 
 191         $affected = $mdb2->exec($sql);
 
 192     return (!is_a($affected, 'PEAR_Error'));
 
 195   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
 
 196   static function invoiceableItemsExist($fields) {
 
 198         $mdb2 = getConnection();
 
 201     $client_id = (int) $fields['client_id'];
 
 203     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 204     $start = $start_date->toString(DB_DATEFORMAT);
 
 206     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 207     $end = $end_date->toString(DB_DATEFORMAT);
 
 209     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 211     // Our query is different depending on tracking mode.
 
 212     if (MODE_TIME == $user->tracking_mode) {
 
 213       // In "time only" tracking mode there is a single user rate.
 
 214       $sql = "select count(*) as num from tt_log l, tt_users u
 
 215         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
 
 216         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 217         and l.billable * u.rate * time_to_sec(l.duration)/3600 > 0
 
 218         and l.user_id = u.id";
 
 220       // sql part for project id.
 
 221       if ($project_id) $project_part = " and l.project_id = $project_id";
 
 223       // When we have projects, rates are defined for each project in tt_user_project_binds table.
 
 224       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
 
 225         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
 
 226         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
 
 227         and l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
 
 228         and upb.user_id = l.user_id and upb.project_id = l.project_id";
 
 230         $res = $mdb2->query($sql);
 
 231         if (!is_a($res, 'PEAR_Error')) {
 
 232       $val = $res->fetchRow();
 
 238     // sql part for project id.
 
 239     if ($project_id) $project_part = " and ei.project_id = $project_id";
 
 241     $sql = "select count(*) as num from tt_expense_items ei
 
 242       where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
 
 243       and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
 
 244       and ei.cost <> 0 and ei.status = 1";
 
 245     $res = $mdb2->query($sql);
 
 246         if (!is_a($res, 'PEAR_Error')) {
 
 247       $val = $res->fetchRow();
 
 256   // createInvoice - marks items for invoice as belonging to it (with its reference number).
 
 257   static function createInvoice($fields) {
 
 259         $mdb2 = getConnection();
 
 262         $name = $fields['name'];
 
 266         $client_id = (int) $fields['client_id'];
 
 268         $invoice_date = new DateAndTime($user->date_format, $fields['date']);
 
 269     $date = $invoice_date->toString(DB_DATEFORMAT);
 
 271     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
 
 272     $start = $start_date->toString(DB_DATEFORMAT);
 
 274     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
 
 275     $end = $end_date->toString(DB_DATEFORMAT);
 
 277     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
 
 279     // Create a new invoice record.
 
 280     $sql = "insert into tt_invoices (team_id, name, date, client_id)
 
 281       values($user->team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)"; 
 
 282     $affected = $mdb2->exec($sql);
 
 283     if (is_a($affected, 'PEAR_Error'))
 
 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 * u.rate * time_to_sec(l.duration)/3600 > 0";
 
 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 * upb.rate * time_to_sec(l.duration)/3600 > 0";
 
 314     $affected = $mdb2->exec($sql);
 
 315     if (is_a($affected, 'PEAR_Error'))
 
 318     // sql part for project id.
 
 319     if ($project_id) $project_part = " and project_id = $project_id";
 
 321     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
 
 322       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
 
 323     $affected = $mdb2->exec($sql);
 
 324     return (!is_a($affected, 'PEAR_Error'));
 
 327   // prepareInvoiceBody - prepares an email body for invoice.
 
 328   static function prepareInvoiceBody($invoice_id, $comment)
 
 333         $invoice = ttInvoiceHelper::getInvoice($invoice_id);
 
 334         $client = ttClientHelper::getClient($invoice['client_id'], true);
 
 335         $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
 
 337         $tax_percent = $client['tax'];
 
 341     foreach($invoice_items as $item)
 
 342       $subtotal += $item['cost'];
 
 344       $tax_expenses = in_array('et', explode(',', $user->plugins));
 
 345       foreach($invoice_items as $item) {
 
 346             if ($item['type'] == 2 && !$tax_expenses)
 
 348         $tax += round($item['cost'] * $tax_percent / 100, 2);   
 
 351     $total = $subtotal + $tax; 
 
 353     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
 
 354     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
 
 355     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
 
 357     if ('.' != $user->decimal_mark) {
 
 358       foreach ($invoice_items as &$item) {
 
 359         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
 
 361       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
 
 362                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
 
 365     // Define some styles to use in email.
 
 366     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
 
 367     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
 
 368     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
 
 370     // Start creating email body.
 
 372     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
 
 376     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
 
 379     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
 
 381     // Output invoice info.
 
 383     $body .= '<tr><td><b>'.$i18n->getKey('label.date').':</b> '.$invoice['date'].'</td></tr>';
 
 384     $body .= '<tr><td><b>'.$i18n->getKey('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
 
 385     $body .= '<tr><td><b>'.$i18n->getKey('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
 
 390     // Output invoice items.
 
 391     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
 
 393     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.date').'</td>';
 
 394     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('form.invoice.person').'</td>';
 
 395     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 396       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.project').'</td>';
 
 397     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 398       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.task').'</td>';
 
 399     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.note').'</td>';
 
 400     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
 
 401     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
 
 403     foreach ($invoice_items as $item) {
 
 405       $body .= '<td>'.$item['date'].'</td>';
 
 406       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
 
 407       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 408         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
 
 409       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 410         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
 
 411       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
 
 412       $body .= '<td align="right">'.$item['duration'].'</td>';
 
 413       $body .= '<td align="right">'.$item['cost'].'</td>';
 
 418     if (MODE_PROJECTS == $user->tracking_mode)
 
 420     else if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
 
 422     $body .= '<tr><td> </td></tr>';
 
 424       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
 
 425       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
 
 427     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
 
 431     $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
 
 432     // Finish creating email body.
 
 433     $body .= '</body></html>';