c30776c05abc5b5dee4ba4f18f4d4c68f1c5f110
[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     $mdb2 = getConnection();
84     global $user;
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();
89       if ($val['id']) {
90         return $val;
91       }
92     }
93     return false;
94   }
95
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) {
101
102     $mdb2 = getConnection();
103     global $user;
104
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.
111     }
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.
118       else
119         return true; // All time and expense items in invoice are paid.
120     }
121     return false;
122   }
123
124   // The getInvoiceItems retrieves tt_log items associated with the invoice. 
125   static function getInvoiceItems($invoice_id) {
126     global $user;
127     $mdb2 = getConnection();
128
129     // At this time only detailed invoice is supported.
130     // It is anticipated to support "totals only" option later on.
131
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";
144     } else {
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";
155     }
156
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";
166
167       // Construct a union.
168       $sql = "($sql) union all ($sql_for_expense_items)";
169
170       $sort_part = " order by date, user_name, type";
171       $sql .= $sort_part;
172     }
173
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);
180         $result[] = $val;
181       }
182     }
183     return $result;
184   }
185
186   // delete - deletes the invoice data from the database.
187   static function delete($invoice_id, $delete_invoice_items) {
188     global $user;
189     $mdb2 = getConnection();
190
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;
196     }
197
198     // Handle time records.
199     if ($delete_invoice_items)
200       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
201     else
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;
205
206     // Handle expense items.
207     if ($delete_invoice_items)
208       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
209     else
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;
213
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'));
217   }
218
219   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
220   static function invoiceableItemsExist($fields) {
221
222     $mdb2 = getConnection();
223     global $user;
224
225     $client_id = (int) $fields['client_id'];
226
227     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
228     $start = $start_date->toString(DB_DATEFORMAT);
229
230     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
231     $end = $end_date->toString(DB_DATEFORMAT);
232
233     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
234
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)."
241         and l.user_id = u.id
242         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
243     } else {
244       // sql part for project id.
245       if ($project_id) $project_part = " and l.project_id = $project_id";
246
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.
257
258         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
259     }
260     $res = $mdb2->query($sql);
261     if (!is_a($res, 'PEAR_Error')) {
262       $val = $res->fetchRow();
263       if ($val['num']) {
264         return true;
265       }
266     }
267
268     // sql part for project id.
269     if ($project_id) $project_part = " and ei.project_id = $project_id";
270
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();
278       if ($val['num']) {
279         return true;
280       }
281     }
282
283     return false;
284   }
285
286   // createInvoice - marks items for invoice as belonging to it (with its reference number).
287   static function createInvoice($fields) {
288
289     $mdb2 = getConnection();
290     global $user;
291
292     $name = $fields['name'];
293     if (!$name) return false;
294
295     $client_id = (int) $fields['client_id'];
296
297     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
298     $date = $invoice_date->toString(DB_DATEFORMAT);
299
300     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
301     $start = $start_date->toString(DB_DATEFORMAT);
302
303     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
304     $end = $end_date->toString(DB_DATEFORMAT);
305
306     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
307
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;
313
314     // Mark associated invoice items with invoice id.
315     $last_id = 0;
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'];
320
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.
330     } else {
331        // sql part for project id.
332       if ($project_id) $project_part = " and l.project_id = $project_id";
333
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.
345
346         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
347     }
348     $affected = $mdb2->exec($sql);
349     if (is_a($affected, 'PEAR_Error'))
350       return false;
351
352     // sql part for project id.
353     if ($project_id) $project_part = " and project_id = $project_id";
354
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'));
359   }
360
361   // prepareInvoiceBody - prepares an email body for invoice.
362   static function prepareInvoiceBody($invoice_id, $comment)
363   {
364     global $user;
365     global $i18n;
366
367     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
368     $client = ttClientHelper::getClient($invoice['client_id'], true);
369     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
370
371     $tax_percent = $client['tax'];
372
373     $subtotal = 0;
374     $tax = 0;
375     foreach($invoice_items as $item)
376       $subtotal += $item['cost'];
377     if ($tax_percent) {
378       $tax_expenses = $user->isPluginEnabled('et');
379       foreach($invoice_items as $item) {
380         if ($item['type'] == 2 && !$tax_expenses)
381           continue;
382         $tax += round($item['cost'] * $tax_percent / 100, 2);
383       }
384     }
385     $total = $subtotal + $tax;
386
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)));
390
391     if ('.' != $user->decimal_mark) {
392       foreach ($invoice_items as &$item) {
393         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
394       }
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
397     }
398
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;';
403
404     // Start creating email body.
405     $body = '<html>';
406     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
407     $body .= '<body>';
408
409     // Output title.
410     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
411
412     // Output comment.
413     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
414
415     // Output invoice info.
416     $body .= '<table>';
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>';
420     $body .= '</table>';
421
422     $body .= '<p></p>';
423
424     // Output invoice items.
425     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
426     $body .= '<tr>';
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>';
436     $body .= '</tr>';
437     foreach ($invoice_items as $item) {
438       $body .= '<tr>';
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>';
448       $body .= '</tr>';
449     }
450     // Output summary.
451     $colspan = 4;
452     if (MODE_PROJECTS == $user->tracking_mode)
453       $colspan++;
454     elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
455       $colspan += 2;
456     $body .= '<tr><td>&nbsp;</td></tr>';
457     if ($tax) {
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>';
460     }
461     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
462     $body .= '</table>';
463
464     // Output footer.
465     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
466       $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
467
468     // Finish creating email body.
469     $body .= '</body></html>';
470
471     return $body;
472   }
473 }