93d272b43fea5ba92f0e84b956fc04f115ff6b68
[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
242     $mdb2 = getConnection();
243     global $user;
244
245     $client_id = (int) $fields['client_id'];
246
247     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
248     $start = $start_date->toString(DB_DATEFORMAT);
249
250     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
251     $end = $end_date->toString(DB_DATEFORMAT);
252
253     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
254
255     // Our query is different depending on tracking mode.
256     if (MODE_TIME == $user->getTrackingMode()) {
257       // In "time only" tracking mode there is a single user rate.
258       $sql = "select count(*) as num from tt_log l, tt_users u
259         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
260         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
261         and l.user_id = u.id
262         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0 // See explanation below.
263     } else {
264       // sql part for project id.
265       if ($project_id) $project_part = " and l.project_id = $project_id";
266
267       // When we have projects, rates are defined for each project in tt_user_project_binds table.
268       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
269         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
270         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
271         and upb.user_id = l.user_id and upb.project_id = l.project_id
272         and l.billable = 1"; // l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
273         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
274         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
275         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
276         // the problem becomes obvious.
277
278         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
279     }
280     $res = $mdb2->query($sql);
281     if (!is_a($res, 'PEAR_Error')) {
282       $val = $res->fetchRow();
283       if ($val['num']) {
284         return true;
285       }
286     }
287
288     if ($user->isPluginEnabled('ex')) {
289       // sql part for project id.
290       if ($project_id) $project_part = " and ei.project_id = $project_id";
291
292       $sql = "select count(*) as num from tt_expense_items ei
293         where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
294         and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
295         and ei.cost <> 0 and ei.status = 1";
296       $res = $mdb2->query($sql);
297       if (!is_a($res, 'PEAR_Error')) {
298         $val = $res->fetchRow();
299         if ($val['num']) {
300           return true;
301         }
302       }
303     }
304
305     return false;
306   }
307
308   // createInvoice - marks items for invoice as belonging to it (with its reference number).
309   static function createInvoice($fields) {
310
311     $mdb2 = getConnection();
312     global $user;
313
314     $name = $fields['name'];
315     if (!$name) return false;
316
317     $client_id = (int) $fields['client_id'];
318
319     $invoice_date = new DateAndTime($user->date_format, $fields['date']);
320     $date = $invoice_date->toString(DB_DATEFORMAT);
321
322     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
323     $start = $start_date->toString(DB_DATEFORMAT);
324
325     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
326     $end = $end_date->toString(DB_DATEFORMAT);
327
328     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
329
330     // Create a new invoice record.
331     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id) values(".
332       $user->getGroup().", $user->org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)";
333     $affected = $mdb2->exec($sql);
334     if (is_a($affected, 'PEAR_Error')) return false;
335
336     // Mark associated invoice items with invoice id.
337     $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
338
339     // Our update sql is different depending on tracking mode.
340     if (MODE_TIME == $user->getTrackingMode()) {
341       // In "time only" tracking mode there is a single user rate.
342       $sql = "update tt_log l
343         left join tt_users u on (u.id = l.user_id)
344         set l.invoice_id = $last_id
345         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
346         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
347         and l.billable = 1"; // l.billable * u.rate * time_to_sec(l.duration)/3600 > 0"; // See explanation below.
348     } else {
349        // sql part for project id.
350       if ($project_id) $project_part = " and l.project_id = $project_id";
351
352       // When we have projects, rates are defined for each project in tt_user_project_binds.
353       $sql = "update tt_log l
354         left join tt_user_project_binds upb on (upb.user_id = l.user_id and upb.project_id = l.project_id)
355         set l.invoice_id = $last_id
356         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
357         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
358         and l.billable = 1"; //  l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0";
359         // Users with a lot of clients and projects (Jaro) may forget to set user rates properly.
360         // Specifically, user rate may be set to 0 on a project, by mistake. This leads to error.no_invoiceable_items
361         // and increased support cost. Commenting out allows us to include 0 cost items in invoices so that
362         // the problem becomes obvious.
363
364         // TODO: If the above turns out useful, rework the query to simplify it by removing left join.
365     }
366     $affected = $mdb2->exec($sql);
367     if (is_a($affected, 'PEAR_Error'))
368       return false;
369
370     // sql part for project id.
371     if ($project_id) $project_part = " and project_id = $project_id";
372
373     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
374       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
375     $affected = $mdb2->exec($sql);
376     return (!is_a($affected, 'PEAR_Error'));
377   }
378
379   // prepareInvoiceBody - prepares an email body for invoice.
380   static function prepareInvoiceBody($invoice_id, $comment)
381   {
382     global $user;
383     global $i18n;
384
385     $invoice = ttInvoiceHelper::getInvoice($invoice_id);
386     $client = ttClientHelper::getClient($invoice['client_id'], true);
387     $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
388
389     $tax_percent = $client['tax'];
390
391     $subtotal = 0;
392     $tax = 0;
393     foreach($invoice_items as $item)
394       $subtotal += $item['cost'];
395     if ($tax_percent) {
396       $tax_expenses = $user->isPluginEnabled('et');
397       foreach($invoice_items as $item) {
398         if ($item['type'] == 2 && !$tax_expenses)
399           continue;
400         $tax += round($item['cost'] * $tax_percent / 100, 2);
401       }
402     }
403     $total = $subtotal + $tax;
404
405     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
406     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
407     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
408
409     if ('.' != $user->decimal_mark) {
410       foreach ($invoice_items as &$item) {
411         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
412       }
413       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
414                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
415     }
416
417     // Define some styles to use in email.
418     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
419     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
420     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
421
422     // Determine tracking mode once for multiple reuse below.
423     $trackingMode = $user->getTrackingMode();
424
425     // Start creating email body.
426     $body = '<html>';
427     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
428     $body .= '<body>';
429
430     // Output title.
431     $body .= '<p style="'.$style_title.'">'.$i18n->get('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
432
433     // Output comment.
434     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
435
436     // Output invoice info.
437     $body .= '<table>';
438     $body .= '<tr><td><b>'.$i18n->get('label.date').':</b> '.$invoice['date'].'</td></tr>';
439     $body .= '<tr><td><b>'.$i18n->get('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
440     $body .= '<tr><td><b>'.$i18n->get('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
441     $body .= '</table>';
442
443     $body .= '<p></p>';
444
445     // Output invoice items.
446     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
447     $body .= '<tr>';
448     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.date').'</td>';
449     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('form.invoice.person').'</td>';
450     if (MODE_PROJECTS == $trackingMode || MODE_PROJECTS_AND_TASKS == $trackingMode)
451       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.project').'</td>';
452     if (MODE_PROJECTS_AND_TASKS == $trackingMode)
453       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.task').'</td>';
454     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->get('label.note').'</td>';
455     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->get('label.duration').'</td>';
456     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->get('label.cost').'</td>';
457     $body .= '</tr>';
458     foreach ($invoice_items as $item) {
459       $body .= '<tr>';
460       $body .= '<td>'.$item['date'].'</td>';
461       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
462       if (MODE_PROJECTS == $trackingMode || MODE_PROJECTS_AND_TASKS == $trackingMode)
463         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
464       if (MODE_PROJECTS_AND_TASKS == $trackingMode)
465         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
466       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
467       $body .= '<td align="right">'.$item['duration'].'</td>';
468       $body .= '<td align="right">'.$item['cost'].'</td>';
469       $body .= '</tr>';
470     }
471     // Output summary.
472     $colspan = 4;
473     if (MODE_PROJECTS == $trackingMode)
474       $colspan++;
475     elseif (MODE_PROJECTS_AND_TASKS == $trackingMode)
476       $colspan += 2;
477     $body .= '<tr><td>&nbsp;</td></tr>';
478     if ($tax) {
479       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
480       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
481     }
482     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->get('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
483     $body .= '</table>';
484
485     // Output footer.
486     if (!defined('REPORT_FOOTER') || !(REPORT_FOOTER == false))
487       $body .= '<p style="text-align: center;">'.$i18n->get('form.mail.footer').'</p>';
488
489     // Finish creating email body.
490     $body .= '</body></html>';
491
492     return $body;
493   }
494 }