Security fix for invoice view. Also paid status handler for invoice view.
[timetracker.git] / WEB-INF / lib / ttInvoiceHelper.class.php
1 <?php
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.
10 // |
11 // | There are only two ways to violate the license:
12 // |
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).
16 // |
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).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 import('ttClientHelper');
30 import('DateAndTime');
31
32 // Class ttInvoiceHelper is used for help with invoices.
33 class ttInvoiceHelper {
34
35   // insert - inserts an invoice in database.
36   static function insert($fields)
37   {
38     $mdb2 = getConnection();
39
40     $team_id = (int) $fields['team_id'];
41     $name = $fields['name'];
42     if (!$name) return false;
43
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']);
49     }
50
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);
55
56     if (is_a($affected, 'PEAR_Error')) return false;
57
58     $last_id = 0;
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'];
63
64     return $last_id;
65   }
66
67   // getInvoice - obtains invoice data from the database.
68   static function getInvoice($invoice_id) {
69     global $user;
70     $mdb2 = getConnection();
71
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())
76         return $val;
77     }
78     return false;
79   }
80
81   // The getInvoiceByName looks up an invoice by name.
82   static function getInvoiceByName($invoice_name) {
83
84     $mdb2 = getConnection();
85     global $user;
86
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();
91       if ($val['id']) {
92         return $val;
93       }
94     }
95     return false;
96   }
97
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) {
103
104     $mdb2 = getConnection();
105     global $user;
106
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.
113     }
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.
120       else
121         return true; // All time and expense items in invoice are paid.
122     }
123     return false;
124   }
125
126   // markPaid marks invoice items as paid.
127   static function markPaid($invoice_id, $mark_paid = true) {
128
129     global $user;
130     $mdb2 = getConnection();
131
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;
136
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;
140
141     return true;
142   }
143
144   // The getInvoiceItems retrieves tt_log items associated with the invoice. 
145   static function getInvoiceItems($invoice_id) {
146     global $user;
147     $mdb2 = getConnection();
148
149     // At this time only detailed invoice is supported.
150     // It is anticipated to support "totals only" option later on.
151
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";
164     } else {
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";
175     }
176
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";
186
187       // Construct a union.
188       $sql = "($sql) union all ($sql_for_expense_items)";
189
190       $sort_part = " order by date, user_name, type";
191       $sql .= $sort_part;
192     }
193
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);
200         $result[] = $val;
201       }
202     }
203     return $result;
204   }
205
206   // delete - deletes the invoice data from the database.
207   static function delete($invoice_id, $delete_invoice_items) {
208     global $user;
209     $mdb2 = getConnection();
210
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;
216     }
217
218     // Handle time records.
219     if ($delete_invoice_items)
220       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
221     else
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;
225
226     // Handle expense items.
227     if ($delete_invoice_items)
228       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
229     else
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;
233
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'));
237   }
238
239   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
240   static function invoiceableItemsExist($fields) {
241
242     $mdb2 = getConnection();
243     global $user;
244
245     $client_id = (int) $fields['client_id'];
246
247     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
248     $start = $start_date->toString(DB_DATEFORMAT);
249
250     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
251     $end = $end_date->toString(DB_DATEFORMAT);
252
253     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
254
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)."
261         and l.user_id = u.id
262         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
263     } else {
264       // sql part for project id.
265       if ($project_id) $project_part = " and l.project_id = $project_id";
266
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.
277
278         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
279     }
280     $res = $mdb2->query($sql);
281     if (!is_a($res, 'PEAR_Error')) {
282       $val = $res->fetchRow();
283       if ($val['num']) {
284         return true;
285       }
286     }
287
288     // sql part for project id.
289     if ($project_id) $project_part = " and ei.project_id = $project_id";
290
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();
298       if ($val['num']) {
299         return true;
300       }
301     }
302
303     return false;
304   }
305
306   // createInvoice - marks items for invoice as belonging to it (with its reference number).
307   static function createInvoice($fields) {
308
309     $mdb2 = getConnection();
310     global $user;
311
312     $name = $fields['name'];
313     if (!$name) return false;
314
315     $client_id = (int) $fields['client_id'];
316
317     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
318     $date = $invoice_date->toString(DB_DATEFORMAT);
319
320     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
321     $start = $start_date->toString(DB_DATEFORMAT);
322
323     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
324     $end = $end_date->toString(DB_DATEFORMAT);
325
326     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
327
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;
333
334     // Mark associated invoice items with invoice id.
335     $last_id = 0;
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'];
340
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.
350     } else {
351        // sql part for project id.
352       if ($project_id) $project_part = " and l.project_id = $project_id";
353
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.
365
366         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
367     }
368     $affected = $mdb2->exec($sql);
369     if (is_a($affected, 'PEAR_Error'))
370       return false;
371
372     // sql part for project id.
373     if ($project_id) $project_part = " and project_id = $project_id";
374
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'));
379   }
380
381   // prepareInvoiceBody - prepares an email body for invoice.
382   static function prepareInvoiceBody($invoice_id, $comment)
383   {
384     global $user;
385     global $i18n;
386
387     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
388     $client = ttClientHelper::getClient($invoice['client_id'], true);
389     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
390
391     $tax_percent = $client['tax'];
392
393     $subtotal = 0;
394     $tax = 0;
395     foreach($invoice_items as $item)
396       $subtotal += $item['cost'];
397     if ($tax_percent) {
398       $tax_expenses = $user->isPluginEnabled('et');
399       foreach($invoice_items as $item) {
400         if ($item['type'] == 2 && !$tax_expenses)
401           continue;
402         $tax += round($item['cost'] * $tax_percent / 100, 2);
403       }
404     }
405     $total = $subtotal + $tax;
406
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)));
410
411     if ('.' != $user->decimal_mark) {
412       foreach ($invoice_items as &$item) {
413         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
414       }
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
417     }
418
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;';
423
424     // Start creating email body.
425     $body = '<html>';
426     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
427     $body .= '<body>';
428
429     // Output title.
430     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
431
432     // Output comment.
433     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
434
435     // Output invoice info.
436     $body .= '<table>';
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>';
440     $body .= '</table>';
441
442     $body .= '<p></p>';
443
444     // Output invoice items.
445     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
446     $body .= '<tr>';
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>';
456     $body .= '</tr>';
457     foreach ($invoice_items as $item) {
458       $body .= '<tr>';
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>';
468       $body .= '</tr>';
469     }
470     // Output summary.
471     $colspan = 4;
472     if (MODE_PROJECTS == $user->tracking_mode)
473       $colspan++;
474     elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
475       $colspan += 2;
476     $body .= '<tr><td>&nbsp;</td></tr>';
477     if ($tax) {
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>';
480     }
481     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
482     $body .= '</table>';
483
484     // Output footer.
485     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
486       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
487
488     // Finish creating email body.
489     $body .= '</body></html>';
490
491     return $body;
492   }
493 }