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) {
83 $mdb2 = getConnection();
85 $sql = "select id from tt_invoices where team_id = $user->team_id and name = ".$mdb2->quote($invoice_name)." and status = 1";
86 $res = $mdb2->query($sql);
87 if (!is_a($res, 'PEAR_Error')) {
88 $val = $res->fetchRow();
96 // The isPaid determines if an invoice is paid by looking at the paid status of its items.
97 // If any non-paid item is found, the entire invoice is considered not paid.
98 // Therefore, the paid status of the invoice is a calculated value.
99 // This is because we maintain the paid status on individual item level.
100 static function isPaid($invoice_id) {
102 $mdb2 = getConnection();
105 $sql = "select count(*) as count from tt_log where invoice_id = $invoice_id and status = 1 and paid < 1";
106 $res = $mdb2->query($sql);
107 if (!is_a($res, 'PEAR_Error')) {
108 $val = $res->fetchRow();
109 if ($val['count'] > 0)
110 return false; // A non-paid time item exists.
112 $sql = "select count(*) as count from tt_expense_items 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 expense item exists.
119 return true; // All time and expense items in invoice are paid.
124 // The getInvoiceItems retrieves tt_log items associated with the invoice.
125 static function getInvoiceItems($invoice_id) {
127 $mdb2 = getConnection();
129 // At this time only detailed invoice is supported.
130 // It is anticipated to support "totals only" option later on.
132 // Our query is different depending on tracking mode.
133 if (MODE_TIME == $user->tracking_mode) {
134 // In "time only" tracking mode there is a single user rate.
135 $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
136 t.name as task_name, l.comment as note,
137 time_format(l.duration, '%k:%i') as duration,
138 cast(l.billable * u.rate * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
139 l.paid as paid from tt_log l
140 inner join tt_users u on (l.user_id = u.id)
141 left join tt_projects p on (p.id = l.project_id)
142 left join tt_tasks t on (t.id = l.task_id)
143 where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
145 $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
146 t.name as task_name, l.comment as note,
147 time_format(l.duration, '%k:%i') as duration,
148 cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
149 l.paid as paid from tt_log l
150 inner join tt_users u on (l.user_id = u.id)
151 left join tt_projects p on (p.id = l.project_id)
152 left join tt_tasks t on (t.id = l.task_id)
153 left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
154 where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
157 // If we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
158 if ($user->isPluginEnabled('ex')) {
159 $sql_for_expense_items = "select ei.date as date, 2 as type, u.name as user_name, p.name as project_name,
160 null as task_name, ei.name as note,
161 null as duration, ei.cost as cost,
162 ei.paid as paid from tt_expense_items ei
163 inner join tt_users u on (ei.user_id = u.id)
164 left join tt_projects p on (p.id = ei.project_id)
165 where ei.invoice_id = $invoice_id and ei.status = 1";
167 // Construct a union.
168 $sql = "($sql) union all ($sql_for_expense_items)";
170 $sort_part = " order by date, user_name, type";
174 $res = $mdb2->query($sql);
175 if (!is_a($res, 'PEAR_Error')) {
176 $dt = new DateAndTime(DB_DATEFORMAT);
177 while ($val = $res->fetchRow()) {
178 $dt->parseVal($val['date']);
179 $val['date'] = $dt->toString($user->date_format);
186 // delete - deletes the invoice data from the database.
187 static function delete($invoice_id, $delete_invoice_items) {
189 $mdb2 = getConnection();
191 // Handle custom field log records.
192 if ($delete_invoice_items) {
193 $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)";
194 $affected = $mdb2->exec($sql);
195 if (is_a($affected, 'PEAR_Error')) return false;
198 // Handle time records.
199 if ($delete_invoice_items)
200 $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
202 $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
203 $affected = $mdb2->exec($sql);
204 if (is_a($affected, 'PEAR_Error')) return false;
206 // Handle expense items.
207 if ($delete_invoice_items)
208 $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
210 $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
211 $affected = $mdb2->exec($sql);
212 if (is_a($affected, 'PEAR_Error')) return false;
214 $sql = "update tt_invoices set status = NULL where id = $invoice_id and team_id = $user->team_id";
215 $affected = $mdb2->exec($sql);
216 return (!is_a($affected, 'PEAR_Error'));
219 // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
220 static function invoiceableItemsExist($fields) {
222 $mdb2 = getConnection();
225 $client_id = (int) $fields['client_id'];
227 $start_date = new DateAndTime($user->date_format, $fields['start_date']);
228 $start = $start_date->toString(DB_DATEFORMAT);
230 $end_date = new DateAndTime($user->date_format, $fields['end_date']);
231 $end = $end_date->toString(DB_DATEFORMAT);
233 if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
235 // Our query is different depending on tracking mode.
236 if (MODE_TIME == $user->tracking_mode) {
237 // In "time only" tracking mode there is a single user rate.
238 $sql = "select count(*) as num from tt_log l, tt_users u
239 where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
240 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
242 and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
244 // sql part for project id.
245 if ($project_id) $project_part = " and l.project_id = $project_id";
247 // When we have projects, rates are defined for each project in tt_user_project_binds table.
248 $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
249 where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
250 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
251 and upb.user_id = l.user_id and upb.project_id = l.project_id
252 and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
253 // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
254 // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
255 // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
256 // the problem becomes obvious.
258 // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
260 $res = $mdb2->query($sql);
261 if (!is_a($res, 'PEAR_Error')) {
262 $val = $res->fetchRow();
268 // sql part for project id.
269 if ($project_id) $project_part = " and ei.project_id = $project_id";
271 $sql = "select count(*) as num from tt_expense_items ei
272 where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
273 and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
274 and ei.cost <> 0 and ei.status = 1";
275 $res = $mdb2->query($sql);
276 if (!is_a($res, 'PEAR_Error')) {
277 $val = $res->fetchRow();
286 // createInvoice - marks items for invoice as belonging to it (with its reference number).
287 static function createInvoice($fields) {
289 $mdb2 = getConnection();
292 $name = $fields['name'];
293 if (!$name) return false;
295 $client_id = (int) $fields['client_id'];
297 $invoice_date = new DateAndTime($user->date_format, $fields['date']);
298 $date = $invoice_date->toString(DB_DATEFORMAT);
300 $start_date = new DateAndTime($user->date_format, $fields['start_date']);
301 $start = $start_date->toString(DB_DATEFORMAT);
303 $end_date = new DateAndTime($user->date_format, $fields['end_date']);
304 $end = $end_date->toString(DB_DATEFORMAT);
306 if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
308 // Create a new invoice record.
309 $sql = "insert into tt_invoices (team_id, name, date, client_id)
310 values($user->team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
311 $affected = $mdb2->exec($sql);
312 if (is_a($affected, 'PEAR_Error')) return false;
314 // Mark associated invoice items with invoice id.
316 $sql = "select last_insert_id() as last_insert_id";
317 $res = $mdb2->query($sql);
318 $val = $res->fetchRow();
319 $last_id = $val['last_insert_id'];
321 // Our update sql is different depending on tracking mode.
322 if (MODE_TIME == $user->tracking_mode) {
323 // In "time only" tracking mode there is a single user rate.
324 $sql = "update tt_log l
325 left join tt_users u on (u.id = l.user_id)
326 set l.invoice_id = $last_id
327 where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
328 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
329 and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
331 // sql part for project id.
332 if ($project_id) $project_part = " and l.project_id = $project_id";
334 // When we have projects, rates are defined for each project in tt_user_project_binds.
335 $sql = "update tt_log l
336 left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
337 set l.invoice_id = $last_id
338 where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
339 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
340 and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
341 // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
342 // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
343 // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
344 // the problem becomes obvious.
346 // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
348 $affected = $mdb2->exec($sql);
349 if (is_a($affected, 'PEAR_Error'))
352 // sql part for project id.
353 if ($project_id) $project_part = " and project_id = $project_id";
355 $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
356 and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
357 $affected = $mdb2->exec($sql);
358 return (!is_a($affected, 'PEAR_Error'));
361 // prepareInvoiceBody - prepares an email body for invoice.
362 static function prepareInvoiceBody($invoice_id, $comment)
367 $invoice = ttInvoiceHelper::getInvoice($invoice_id);
368 $client = ttClientHelper::getClient($invoice['client_id'], true);
369 $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
371 $tax_percent = $client['tax'];
375 foreach($invoice_items as $item)
376 $subtotal += $item['cost'];
378 $tax_expenses = $user->isPluginEnabled('et');
379 foreach($invoice_items as $item) {
380 if ($item['type'] == 2 && !$tax_expenses)
382 $tax += round($item['cost'] * $tax_percent / 100, 2);
385 $total = $subtotal + $tax;
387 $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
388 if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
389 $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
391 if ('.' != $user->decimal_mark) {
392 foreach ($invoice_items as &$item) {
393 $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
395 unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
396 // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
399 // Define some styles to use in email.
400 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
401 $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
402 $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
404 // Start creating email body.
406 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
410 $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
413 if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
415 // Output invoice info.
417 $body .= '<tr><td><b>'.$i18n->getKey('label.date').':</b> '.$invoice['date'].'</td></tr>';
418 $body .= '<tr><td><b>'.$i18n->getKey('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
419 $body .= '<tr><td><b>'.$i18n->getKey('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
424 // Output invoice items.
425 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
427 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.date').'</td>';
428 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('form.invoice.person').'</td>';
429 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
430 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.project').'</td>';
431 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
432 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.task').'</td>';
433 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.note').'</td>';
434 $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
435 $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
437 foreach ($invoice_items as $item) {
439 $body .= '<td>'.$item['date'].'</td>';
440 $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
441 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
442 $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
443 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
444 $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
445 $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
446 $body .= '<td align="right">'.$item['duration'].'</td>';
447 $body .= '<td align="right">'.$item['cost'].'</td>';
452 if (MODE_PROJECTS == $user->tracking_mode)
454 elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
456 $body .= '<tr><td> </td></tr>';
458 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
459 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
461 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
465 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
466 $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
468 // Finish creating email body.
469 $body .= '</body></html>';