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