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