5c5d7141f67e9392bdcc857ac0b4af2aad2207c4
[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     $group_id = (int) $fields['group_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 (group_id, name, date, client_id $status_f)".
53       " values($group_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     if ($user->isClient()) $client_part = " and client_id = $user->client_id";
73
74     $sql = "select * from tt_invoices where id = $invoice_id and group_id = ".
75             $user->getActiveGroup()."$client_part and status = 1";
76     $res = $mdb2->query($sql);
77     if (!is_a($res, 'PEAR_Error')) {
78       if ($val = $res->fetchRow())
79         return $val;
80     }
81     return false;
82   }
83
84   // The getInvoiceByName looks up an invoice by name.
85   static function getInvoiceByName($invoice_name) {
86
87     $mdb2 = getConnection();
88     global $user;
89
90     $sql = "select id from tt_invoices where group_id = ".
91             $user->getActiveGroup()." and name = ".$mdb2->quote($invoice_name)." and status = 1";
92     $res = $mdb2->query($sql);
93     if (!is_a($res, 'PEAR_Error')) {
94       $val = $res->fetchRow();
95       if ($val['id']) {
96         return $val;
97       }
98     }
99     return false;
100   }
101
102   // The isPaid determines if an invoice is paid by looking at the paid status of its items.
103   // If any non-paid item is found, the entire invoice is considered not paid.
104   // Therefore, the paid status of the invoice is a calculated value.
105   // This is because we maintain the paid status on individual item level.
106   static function isPaid($invoice_id) {
107
108     $mdb2 = getConnection();
109     global $user;
110
111     $sql = "select count(*) as count from tt_log where invoice_id = $invoice_id and status = 1 and paid < 1";
112     $res = $mdb2->query($sql);
113     if (!is_a($res, 'PEAR_Error')) {
114       $val = $res->fetchRow();
115       if ($val['count'] > 0)
116         return false; // A non-paid time item exists.
117     }
118     $sql = "select count(*) as count from tt_expense_items where invoice_id = $invoice_id and status = 1 and paid < 1";
119     $res = $mdb2->query($sql);
120     if (!is_a($res, 'PEAR_Error')) {
121       $val = $res->fetchRow();
122       if ($val['count'] > 0)
123         return false; // A non-paid expense item exists.
124       else
125         return true; // All time and expense items in invoice are paid.
126     }
127     return false;
128   }
129
130   // markPaid marks invoice items as paid.
131   static function markPaid($invoice_id, $mark_paid = true) {
132
133     global $user;
134     $mdb2 = getConnection();
135
136     $paid_status = $mark_paid ? 1 : 0;
137     $sql = "update tt_log 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     $sql = "update tt_expense_items set paid = $paid_status where invoice_id = $invoice_id and status = 1";
142     $affected = $mdb2->exec($sql);
143     if (is_a($affected, 'PEAR_Error')) return false;
144
145     return true;
146   }
147
148   // The getInvoiceItems retrieves tt_log items associated with the invoice. 
149   static function getInvoiceItems($invoice_id) {
150     global $user;
151     $mdb2 = getConnection();
152
153     // At this time only detailed invoice is supported.
154     // It is anticipated to support "totals only" option later on.
155
156     // Our query is different depending on tracking mode.
157     if (MODE_TIME == $user->tracking_mode) {
158       // In "time only" tracking mode there is a single user rate.
159       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
160       t.name as task_name, l.comment as note,
161       time_format(l.duration, '%k:%i') as duration,
162       cast(l.billable * u.rate * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
163       l.paid as paid from tt_log l
164       inner join tt_users u on (l.user_id = u.id)
165       left join tt_projects p on (p.id = l.project_id)
166       left join tt_tasks t on (t.id = l.task_id)
167       where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
168     } else {
169       $sql = "select l.date as date, 1 as type, u.name as user_name, p.name as project_name,
170         t.name as task_name, l.comment as note,
171         time_format(l.duration, '%k:%i') as duration,
172         cast(l.billable * coalesce(upb.rate, 0) * time_to_sec(l.duration)/3600 as decimal(10, 2)) as cost,
173         l.paid as paid from tt_log l
174         inner join tt_users u on (l.user_id = u.id)
175         left join tt_projects p on (p.id = l.project_id)
176         left join tt_tasks t on (t.id = l.task_id)
177         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
178         where l.status = 1 and l.billable = 1 and l.invoice_id = $invoice_id order by l.date, u.name";
179     }
180
181     // If we have expenses, we need to do a union with a separate query for expense items from tt_expense_items table.
182     if ($user->isPluginEnabled('ex')) {
183       $sql_for_expense_items = "select ei.date as date, 2 as type, u.name as user_name, p.name as project_name,
184         null as task_name, ei.name as note,
185         null as duration, ei.cost as cost,
186         ei.paid as paid from tt_expense_items ei
187         inner join tt_users u on (ei.user_id = u.id)
188         left join tt_projects p on (p.id = ei.project_id)
189         where ei.invoice_id = $invoice_id and ei.status = 1";
190
191       // Construct a union.
192       $sql = "($sql) union all ($sql_for_expense_items)";
193
194       $sort_part = " order by date, user_name, type";
195       $sql .= $sort_part;
196     }
197
198     $res = $mdb2->query($sql);
199     if (!is_a($res, 'PEAR_Error')) {
200       $dt = new DateAndTime(DB_DATEFORMAT);
201       while ($val = $res->fetchRow()) {
202         $dt->parseVal($val['date']);
203         $val['date'] = $dt->toString($user->date_format);
204         $result[] = $val;
205       }
206     }
207     return $result;
208   }
209
210   // delete - deletes the invoice data from the database.
211   static function delete($invoice_id, $delete_invoice_items) {
212     global $user;
213     $mdb2 = getConnection();
214
215     // Handle custom field log records.
216     if ($delete_invoice_items) {
217       $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)";
218       $affected = $mdb2->exec($sql);
219       if (is_a($affected, 'PEAR_Error')) return false;
220     }
221
222     // Handle time records.
223     if ($delete_invoice_items)
224       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
225     else
226       $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
227     $affected = $mdb2->exec($sql);
228     if (is_a($affected, 'PEAR_Error')) return false;
229
230     // Handle expense items.
231     if ($delete_invoice_items)
232       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
233     else
234       $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
235     $affected = $mdb2->exec($sql);
236     if (is_a($affected, 'PEAR_Error')) return false;
237
238     $sql = "update tt_invoices set status = NULL where id = $invoice_id and group_id = ".$user->getActiveGroup();
239     $affected = $mdb2->exec($sql);
240     return (!is_a($affected, 'PEAR_Error'));
241   }
242
243   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
244   static function invoiceableItemsExist($fields) {
245
246     $mdb2 = getConnection();
247     global $user;
248
249     $client_id = (int) $fields['client_id'];
250
251     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
252     $start = $start_date->toString(DB_DATEFORMAT);
253
254     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
255     $end = $end_date->toString(DB_DATEFORMAT);
256
257     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
258
259     // Our query is different depending on tracking mode.
260     if (MODE_TIME == $user->tracking_mode) {
261       // In "time only" tracking mode there is a single user rate.
262       $sql = "select count(*) as num from tt_log l, tt_users u
263         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
264         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
265         and l.user_id = u.id
266         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
267     } else {
268       // sql part for project id.
269       if ($project_id) $project_part = " and l.project_id = $project_id";
270
271       // When we have projects, rates are defined for each project in tt_user_project_binds table.
272       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
273         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
274         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
275         and upb.user_id = l.user_id and upb.project_id = l.project_id
276         and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
277         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
278         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
279         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
280         // the problem becomes obvious.
281
282         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
283     }
284     $res = $mdb2->query($sql);
285     if (!is_a($res, 'PEAR_Error')) {
286       $val = $res->fetchRow();
287       if ($val['num']) {
288         return true;
289       }
290     }
291
292     // sql part for project id.
293     if ($project_id) $project_part = " and ei.project_id = $project_id";
294
295     $sql = "select count(*) as num from tt_expense_items ei
296       where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
297       and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
298       and ei.cost <> 0 and ei.status = 1";
299     $res = $mdb2->query($sql);
300     if (!is_a($res, 'PEAR_Error')) {
301       $val = $res->fetchRow();
302       if ($val['num']) {
303         return true;
304       }
305     }
306
307     return false;
308   }
309
310   // createInvoice - marks items for invoice as belonging to it (with its reference number).
311   static function createInvoice($fields) {
312
313     $mdb2 = getConnection();
314     global $user;
315
316     $name = $fields['name'];
317     if (!$name) return false;
318
319     $client_id = (int) $fields['client_id'];
320
321     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
322     $date = $invoice_date->toString(DB_DATEFORMAT);
323
324     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
325     $start = $start_date->toString(DB_DATEFORMAT);
326
327     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
328     $end = $end_date->toString(DB_DATEFORMAT);
329
330     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
331
332     // Create a new invoice record.
333     $sql = "insert into tt_invoices (group_id, name, date, client_id) values(".
334             $user->getActiveGroup().", ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
335     $affected = $mdb2->exec($sql);
336     if (is_a($affected, 'PEAR_Error')) return false;
337
338     // Mark associated invoice items with invoice id.
339     $last_id = 0;
340     $sql = "select last_insert_id() as last_insert_id";
341     $res = $mdb2->query($sql);
342     $val = $res->fetchRow();
343     $last_id = $val['last_insert_id'];
344
345     // Our update sql is different depending on tracking mode.
346     if (MODE_TIME == $user->tracking_mode) {
347       // In "time only" tracking mode there is a single user rate.
348       $sql = "update tt_log l
349         left join tt_users u on (u.id = l.user_id)
350         set l.invoice_id = $last_id
351         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
352         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
353         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
354     } else {
355        // sql part for project id.
356       if ($project_id) $project_part = " and l.project_id = $project_id";
357
358       // When we have projects, rates are defined for each project in tt_user_project_binds.
359       $sql = "update tt_log l
360         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
361         set l.invoice_id = $last_id
362         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
363         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
364         and l.billable = 1"; //  l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
365         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
366         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
367         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
368         // the problem becomes obvious.
369
370         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
371     }
372     $affected = $mdb2->exec($sql);
373     if (is_a($affected, 'PEAR_Error'))
374       return false;
375
376     // sql part for project id.
377     if ($project_id) $project_part = " and project_id = $project_id";
378
379     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
380       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
381     $affected = $mdb2->exec($sql);
382     return (!is_a($affected, 'PEAR_Error'));
383   }
384
385   // prepareInvoiceBody - prepares an email body for invoice.
386   static function prepareInvoiceBody($invoice_id, $comment)
387   {
388     global $user;
389     global $i18n;
390
391     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
392     $client = ttClientHelper::getClient($invoice['client_id'], true);
393     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
394
395     $tax_percent = $client['tax'];
396
397     $subtotal = 0;
398     $tax = 0;
399     foreach($invoice_items as $item)
400       $subtotal += $item['cost'];
401     if ($tax_percent) {
402       $tax_expenses = $user->isPluginEnabled('et');
403       foreach($invoice_items as $item) {
404         if ($item['type'] == 2 && !$tax_expenses)
405           continue;
406         $tax += round($item['cost'] * $tax_percent / 100, 2);
407       }
408     }
409     $total = $subtotal + $tax;
410
411     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
412     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
413     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
414
415     if ('.' != $user->decimal_mark) {
416       foreach ($invoice_items as &$item) {
417         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
418       }
419       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
420                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
421     }
422
423     // Define some styles to use in email.
424     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
425     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
426     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
427
428     // Start creating email body.
429     $body = '<html>';
430     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
431     $body .= '<body>';
432
433     // Output title.
434     $body .= '<p style="'.$style_title.'">'.$i18n->get('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
435
436     // Output comment.
437     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
438
439     // Output invoice info.
440     $body .= '<table>';
441     $body .= '<tr><td><b>'.$i18n->get('label.date').':</b> '.$invoice['date'].'</td></tr>';
442     $body .= '<tr><td><b>'.$i18n->get('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
443     $body .= '<tr><td><b>'.$i18n->get('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
444     $body .= '</table>';
445
446     $body .= '<p></p>';
447
448     // Output invoice items.
449     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
450     $body .= '<tr>';
451     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.date').'</td>';
452     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('form.invoice.person').'</td>';
453     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
454       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.project').'</td>';
455     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
456       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.task').'</td>';
457     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.note').'</td>';
458     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
459     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
460     $body .= '</tr>';
461     foreach ($invoice_items as $item) {
462       $body .= '<tr>';
463       $body .= '<td>'.$item['date'].'</td>';
464       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
465       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
466         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
467       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
468         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
469       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
470       $body .= '<td align="right">'.$item['duration'].'</td>';
471       $body .= '<td align="right">'.$item['cost'].'</td>';
472       $body .= '</tr>';
473     }
474     // Output summary.
475     $colspan = 4;
476     if (MODE_PROJECTS == $user->tracking_mode)
477       $colspan++;
478     elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
479       $colspan += 2;
480     $body .= '<tr><td>&nbsp;</td></tr>';
481     if ($tax) {
482       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
483       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
484     }
485     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
486     $body .= '</table>';
487
488     // Output footer.
489     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
490       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
491
492     // Finish creating email body.
493     $body .= '</body></html>';
494
495     return $body;
496   }
497 }