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