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";
88 $res = $mdb2->query($sql);
89 if (!is_a($res, 'PEAR_Error')) {
90 $val = $res->fetchRow();
98 // The isPaid determines if an invoice is paid by looking at the paid status of its items.
99 // If any non-paid item is found, the entire invoice is considered not paid.
100 // Therefore, the paid status of the invoice is a calculated value.
101 // This is because we maintain the paid status on individual item level.
102 static function isPaid($invoice_id) {
104 $mdb2 = getConnection();
107 $sql = "select count(*) as count from tt_log where invoice_id = $invoice_id and status = 1 and paid < 1";
108 $res = $mdb2->query($sql);
109 if (!is_a($res, 'PEAR_Error')) {
110 $val = $res->fetchRow();
111 if ($val['count'] > 0)
112 return false; // A non-paid time item exists.
114 $sql = "select count(*) as count from tt_expense_items where invoice_id = $invoice_id and status = 1 and paid < 1";
115 $res = $mdb2->query($sql);
116 if (!is_a($res, 'PEAR_Error')) {
117 $val = $res->fetchRow();
118 if ($val['count'] > 0)
119 return false; // A non-paid expense item exists.
121 return true; // All time and expense items in invoice are paid.
126 // markPaid marks invoice items as paid.
127 static function markPaid($invoice_id, $mark_paid = true) {
130 $mdb2 = getConnection();
132 $paid_status = $mark_paid ? 1 : 0;
133 $sql = "update tt_log set paid = $paid_status where invoice_id = $invoice_id and status = 1";
134 $affected = $mdb2->exec($sql);
135 if (is_a($affected, 'PEAR_Error')) return false;
137 $sql = "update tt_expense_items set paid = $paid_status where invoice_id = $invoice_id and status = 1";
138 $affected = $mdb2->exec($sql);
139 if (is_a($affected, 'PEAR_Error')) return false;
144 // The getInvoiceItems retrieves tt_log items associated with the invoice.
145 static function getInvoiceItems($invoice_id) {
147 $mdb2 = getConnection();
149 // At this time only detailed invoice is supported.
150 // It is anticipated to support "totals only" option later on.
152 // Our query is different depending on tracking mode.
153 if (MODE_TIME == $user->tracking_mode) {
154 // In "time only" tracking mode there is a single user rate.
155 $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
156 t.name as task_name, l.comment as note,
157 time_format(l.duration, '%k:%i') as duration,
158 cast(l.billable * u.rate * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
159 l.paid as paid from tt_log l
160 inner join tt_users u on (l.user_id = u.id)
161 left join tt_projects p on (p.id = l.project_id)
162 left join tt_tasks t on (t.id = l.task_id)
163 where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
165 $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
166 t.name as task_name, l.comment as note,
167 time_format(l.duration, '%k:%i') as duration,
168 cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
169 l.paid as paid from tt_log l
170 inner join tt_users u on (l.user_id = u.id)
171 left join tt_projects p on (p.id = l.project_id)
172 left join tt_tasks t on (t.id = l.task_id)
173 left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
174 where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
177 // If we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
178 if ($user->isPluginEnabled('ex')) {
179 $sql_for_expense_items = "select ei.date as date, 2 as type, u.name as user_name, p.name as project_name,
180 null as task_name, ei.name as note,
181 null as duration, ei.cost as cost,
182 ei.paid as paid from tt_expense_items ei
183 inner join tt_users u on (ei.user_id = u.id)
184 left join tt_projects p on (p.id = ei.project_id)
185 where ei.invoice_id = $invoice_id and ei.status = 1";
187 // Construct a union.
188 $sql = "($sql) union all ($sql_for_expense_items)";
190 $sort_part = " order by date, user_name, type";
194 $res = $mdb2->query($sql);
195 if (!is_a($res, 'PEAR_Error')) {
196 $dt = new DateAndTime(DB_DATEFORMAT);
197 while ($val = $res->fetchRow()) {
198 $dt->parseVal($val['date']);
199 $val['date'] = $dt->toString($user->date_format);
206 // delete - deletes the invoice data from the database.
207 static function delete($invoice_id, $delete_invoice_items) {
209 $mdb2 = getConnection();
211 // Handle custom field log records.
212 if ($delete_invoice_items) {
213 $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)";
214 $affected = $mdb2->exec($sql);
215 if (is_a($affected, 'PEAR_Error')) return false;
218 // Handle time records.
219 if ($delete_invoice_items)
220 $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
222 $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
223 $affected = $mdb2->exec($sql);
224 if (is_a($affected, 'PEAR_Error')) return false;
226 // Handle expense items.
227 if ($delete_invoice_items)
228 $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
230 $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
231 $affected = $mdb2->exec($sql);
232 if (is_a($affected, 'PEAR_Error')) return false;
234 $sql = "update tt_invoices set status = NULL where id = $invoice_id and team_id = $user->team_id";
235 $affected = $mdb2->exec($sql);
236 return (!is_a($affected, 'PEAR_Error'));
239 // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
240 static function invoiceableItemsExist($fields) {
242 $mdb2 = getConnection();
245 $client_id = (int) $fields['client_id'];
247 $start_date = new DateAndTime($user->date_format, $fields['start_date']);
248 $start = $start_date->toString(DB_DATEFORMAT);
250 $end_date = new DateAndTime($user->date_format, $fields['end_date']);
251 $end = $end_date->toString(DB_DATEFORMAT);
253 if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
255 // Our query is different depending on tracking mode.
256 if (MODE_TIME == $user->tracking_mode) {
257 // In "time only" tracking mode there is a single user rate.
258 $sql = "select count(*) as num from tt_log l, tt_users u
259 where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
260 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
262 and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
264 // sql part for project id.
265 if ($project_id) $project_part = " and l.project_id = $project_id";
267 // When we have projects, rates are defined for each project in tt_user_project_binds table.
268 $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
269 where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
270 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
271 and upb.user_id = l.user_id and upb.project_id = l.project_id
272 and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
273 // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
274 // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
275 // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
276 // the problem becomes obvious.
278 // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
280 $res = $mdb2->query($sql);
281 if (!is_a($res, 'PEAR_Error')) {
282 $val = $res->fetchRow();
288 // sql part for project id.
289 if ($project_id) $project_part = " and ei.project_id = $project_id";
291 $sql = "select count(*) as num from tt_expense_items ei
292 where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
293 and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
294 and ei.cost <> 0 and ei.status = 1";
295 $res = $mdb2->query($sql);
296 if (!is_a($res, 'PEAR_Error')) {
297 $val = $res->fetchRow();
306 // createInvoice - marks items for invoice as belonging to it (with its reference number).
307 static function createInvoice($fields) {
309 $mdb2 = getConnection();
312 $name = $fields['name'];
313 if (!$name) return false;
315 $client_id = (int) $fields['client_id'];
317 $invoice_date = new DateAndTime($user->date_format, $fields['date']);
318 $date = $invoice_date->toString(DB_DATEFORMAT);
320 $start_date = new DateAndTime($user->date_format, $fields['start_date']);
321 $start = $start_date->toString(DB_DATEFORMAT);
323 $end_date = new DateAndTime($user->date_format, $fields['end_date']);
324 $end = $end_date->toString(DB_DATEFORMAT);
326 if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
328 // Create a new invoice record.
329 $sql = "insert into tt_invoices (team_id, name, date, client_id)
330 values($user->team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
331 $affected = $mdb2->exec($sql);
332 if (is_a($affected, 'PEAR_Error')) return false;
334 // Mark associated invoice items with invoice id.
336 $sql = "select last_insert_id() as last_insert_id";
337 $res = $mdb2->query($sql);
338 $val = $res->fetchRow();
339 $last_id = $val['last_insert_id'];
341 // Our update sql is different depending on tracking mode.
342 if (MODE_TIME == $user->tracking_mode) {
343 // In "time only" tracking mode there is a single user rate.
344 $sql = "update tt_log l
345 left join tt_users u on (u.id = l.user_id)
346 set l.invoice_id = $last_id
347 where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
348 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
349 and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
351 // sql part for project id.
352 if ($project_id) $project_part = " and l.project_id = $project_id";
354 // When we have projects, rates are defined for each project in tt_user_project_binds.
355 $sql = "update tt_log l
356 left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
357 set l.invoice_id = $last_id
358 where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
359 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
360 and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
361 // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
362 // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
363 // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
364 // the problem becomes obvious.
366 // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
368 $affected = $mdb2->exec($sql);
369 if (is_a($affected, 'PEAR_Error'))
372 // sql part for project id.
373 if ($project_id) $project_part = " and project_id = $project_id";
375 $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
376 and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
377 $affected = $mdb2->exec($sql);
378 return (!is_a($affected, 'PEAR_Error'));
381 // prepareInvoiceBody - prepares an email body for invoice.
382 static function prepareInvoiceBody($invoice_id, $comment)
387 $invoice = ttInvoiceHelper::getInvoice($invoice_id);
388 $client = ttClientHelper::getClient($invoice['client_id'], true);
389 $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
391 $tax_percent = $client['tax'];
395 foreach($invoice_items as $item)
396 $subtotal += $item['cost'];
398 $tax_expenses = $user->isPluginEnabled('et');
399 foreach($invoice_items as $item) {
400 if ($item['type'] == 2 && !$tax_expenses)
402 $tax += round($item['cost'] * $tax_percent / 100, 2);
405 $total = $subtotal + $tax;
407 $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
408 if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
409 $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
411 if ('.' != $user->decimal_mark) {
412 foreach ($invoice_items as &$item) {
413 $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
415 unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
416 // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
419 // Define some styles to use in email.
420 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
421 $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
422 $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
424 // Start creating email body.
426 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
430 $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
433 if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
435 // Output invoice info.
437 $body .= '<tr><td><b>'.$i18n->getKey('label.date').':</b> '.$invoice['date'].'</td></tr>';
438 $body .= '<tr><td><b>'.$i18n->getKey('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
439 $body .= '<tr><td><b>'.$i18n->getKey('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
444 // Output invoice items.
445 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
447 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.date').'</td>';
448 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('form.invoice.person').'</td>';
449 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
450 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.project').'</td>';
451 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
452 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.task').'</td>';
453 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.note').'</td>';
454 $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
455 $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
457 foreach ($invoice_items as $item) {
459 $body .= '<td>'.$item['date'].'</td>';
460 $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
461 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
462 $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
463 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
464 $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
465 $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
466 $body .= '<td align="right">'.$item['duration'].'</td>';
467 $body .= '<td align="right">'.$item['cost'].'</td>';
472 if (MODE_PROJECTS == $user->tracking_mode)
474 elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
476 $body .= '<tr><td> </td></tr>';
478 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
479 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
481 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
485 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
486 $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
488 // Finish creating email body.
489 $body .= '</body></html>';