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) {
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 ($user->isPluginEnabled('ex')) {
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')) return false;
171 // Handle time records.
172 if ($delete_invoice_items)
173 $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
175 $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
176 $affected = $mdb2->exec($sql);
177 if (is_a($affected, 'PEAR_Error')) return false;
179 // Handle expense items.
180 if ($delete_invoice_items)
181 $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
183 $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
184 $affected = $mdb2->exec($sql);
185 if (is_a($affected, 'PEAR_Error')) return false;
187 $sql = "update tt_invoices set status = NULL where id = $invoice_id and team_id = $user->team_id";
188 $affected = $mdb2->exec($sql);
189 return (!is_a($affected, 'PEAR_Error'));
192 // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
193 static function invoiceableItemsExist($fields) {
195 $mdb2 = getConnection();
198 $client_id = (int) $fields['client_id'];
200 $start_date = new DateAndTime($user->date_format, $fields['start_date']);
201 $start = $start_date->toString(DB_DATEFORMAT);
203 $end_date = new DateAndTime($user->date_format, $fields['end_date']);
204 $end = $end_date->toString(DB_DATEFORMAT);
206 if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
208 // Our query is different depending on tracking mode.
209 if (MODE_TIME == $user->tracking_mode) {
210 // In "time only" tracking mode there is a single user rate.
211 $sql = "select count(*) as num from tt_log l, tt_users u
212 where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
213 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
214 and l.billable * u.rate * time_to_sec(l.duration)/3600 > 0
215 and l.user_id = u.id";
217 // sql part for project id.
218 if ($project_id) $project_part = " and l.project_id = $project_id";
220 // When we have projects, rates are defined for each project in tt_user_project_binds table.
221 $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
222 where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
223 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
224 and l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
225 and upb.user_id = l.user_id and upb.project_id = l.project_id";
227 $res = $mdb2->query($sql);
228 if (!is_a($res, 'PEAR_Error')) {
229 $val = $res->fetchRow();
235 // sql part for project id.
236 if ($project_id) $project_part = " and ei.project_id = $project_id";
238 $sql = "select count(*) as num from tt_expense_items ei
239 where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
240 and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
241 and ei.cost <> 0 and ei.status = 1";
242 $res = $mdb2->query($sql);
243 if (!is_a($res, 'PEAR_Error')) {
244 $val = $res->fetchRow();
253 // createInvoice - marks items for invoice as belonging to it (with its reference number).
254 static function createInvoice($fields) {
256 $mdb2 = getConnection();
259 $name = $fields['name'];
260 if (!$name) return false;
262 $client_id = (int) $fields['client_id'];
264 $invoice_date = new DateAndTime($user->date_format, $fields['date']);
265 $date = $invoice_date->toString(DB_DATEFORMAT);
267 $start_date = new DateAndTime($user->date_format, $fields['start_date']);
268 $start = $start_date->toString(DB_DATEFORMAT);
270 $end_date = new DateAndTime($user->date_format, $fields['end_date']);
271 $end = $end_date->toString(DB_DATEFORMAT);
273 if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
275 // Create a new invoice record.
276 $sql = "insert into tt_invoices (team_id, name, date, client_id)
277 values($user->team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
278 $affected = $mdb2->exec($sql);
279 if (is_a($affected, 'PEAR_Error')) return false;
281 // Mark associated invoice items with invoice id.
283 $sql = "select last_insert_id() as last_insert_id";
284 $res = $mdb2->query($sql);
285 $val = $res->fetchRow();
286 $last_id = $val['last_insert_id'];
288 // Our update sql is different depending on tracking mode.
289 if (MODE_TIME == $user->tracking_mode) {
290 // In "time only" tracking mode there is a single user rate.
291 $sql = "update tt_log l
292 left join tt_users u on (u.id = l.user_id)
293 set l.invoice_id = $last_id
294 where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
295 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
296 and l.billable * u.rate * time_to_sec(l.duration)/3600 > 0";
298 // sql part for project id.
299 if ($project_id) $project_part = " and l.project_id = $project_id";
301 // When we have projects, rates are defined for each project in tt_user_project_binds.
302 $sql = "update tt_log l
303 left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
304 set l.invoice_id = $last_id
305 where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
306 and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
307 and l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
309 $affected = $mdb2->exec($sql);
310 if (is_a($affected, 'PEAR_Error'))
313 // sql part for project id.
314 if ($project_id) $project_part = " and project_id = $project_id";
316 $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
317 and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
318 $affected = $mdb2->exec($sql);
319 return (!is_a($affected, 'PEAR_Error'));
322 // prepareInvoiceBody - prepares an email body for invoice.
323 static function prepareInvoiceBody($invoice_id, $comment)
328 $invoice = ttInvoiceHelper::getInvoice($invoice_id);
329 $client = ttClientHelper::getClient($invoice['client_id'], true);
330 $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
332 $tax_percent = $client['tax'];
336 foreach($invoice_items as $item)
337 $subtotal += $item['cost'];
339 $tax_expenses = $user->isPluginEnabled('et');
340 foreach($invoice_items as $item) {
341 if ($item['type'] == 2 && !$tax_expenses)
343 $tax += round($item['cost'] * $tax_percent / 100, 2);
346 $total = $subtotal + $tax;
348 $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
349 if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
350 $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
352 if ('.' != $user->decimal_mark) {
353 foreach ($invoice_items as &$item) {
354 $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
356 unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
357 // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
360 // Define some styles to use in email.
361 $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
362 $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
363 $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
365 // Start creating email body.
367 $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
371 $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
374 if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
376 // Output invoice info.
378 $body .= '<tr><td><b>'.$i18n->getKey('label.date').':</b> '.$invoice['date'].'</td></tr>';
379 $body .= '<tr><td><b>'.$i18n->getKey('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
380 $body .= '<tr><td><b>'.$i18n->getKey('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
385 // Output invoice items.
386 $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
388 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.date').'</td>';
389 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('form.invoice.person').'</td>';
390 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
391 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.project').'</td>';
392 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
393 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.task').'</td>';
394 $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.note').'</td>';
395 $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
396 $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
398 foreach ($invoice_items as $item) {
400 $body .= '<td>'.$item['date'].'</td>';
401 $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
402 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
403 $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
404 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
405 $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
406 $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
407 $body .= '<td align="right">'.$item['duration'].'</td>';
408 $body .= '<td align="right">'.$item['cost'].'</td>';
413 if (MODE_PROJECTS == $user->tracking_mode)
415 elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
417 $body .= '<tr><td> </td></tr>';
419 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
420 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
422 $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
426 if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
427 $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
429 // Finish creating email body.
430 $body .= '</body></html>';