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