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