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