Replacing else if with elseif
[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         $client_id = (int) $fields['client_id'];
44         $date = $fields['date'];
45     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
46       $status_f = ', status';
47       $status_v = ', '.$mdb2->quote($fields['status']);
48     }
49     
50     // Insert a new invoice record.
51     $sql = "insert into tt_invoices (team_id, name, date, client_id $status_f)
52       values($team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id $status_v)"; 
53     $affected = $mdb2->exec($sql);
54     
55     if (is_a($affected, 'PEAR_Error'))
56       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 (in_array('ex', explode(',', $user->plugins))) { // if ex(penses) plugin is enabled
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'))
169             return false;
170     }
171     
172     // Handle time records.
173     if ($delete_invoice_items)
174       $sql = "update tt_log set status = NULL where invoice_id = $invoice_id";
175     else
176       $sql = "update tt_log set invoice_id = NULL where invoice_id = $invoice_id";
177     $affected = $mdb2->exec($sql);
178         if (is_a($affected, 'PEAR_Error'))
179           return false;
180
181     // Handle expense items.
182     if ($delete_invoice_items)            
183       $sql = "update tt_expense_items set status = NULL where invoice_id = $invoice_id";
184     else          
185       $sql = "update tt_expense_items set invoice_id = NULL where invoice_id = $invoice_id";
186     $affected = $mdb2->exec($sql);
187         if (is_a($affected, 'PEAR_Error'))
188           return false;
189  
190         $sql = "update tt_invoices set status = NULL where id = $invoice_id and team_id = $user->team_id";
191         $affected = $mdb2->exec($sql);
192     return (!is_a($affected, 'PEAR_Error'));
193   }
194
195   // The invoiceableItemsExist determines whether invoiceable records exist in the specified period.
196   static function invoiceableItemsExist($fields) {
197         
198         $mdb2 = getConnection();
199     global $user;
200
201     $client_id = (int) $fields['client_id'];
202    
203     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
204     $start = $start_date->toString(DB_DATEFORMAT);
205     
206     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
207     $end = $end_date->toString(DB_DATEFORMAT);
208     
209     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
210     
211     // Our query is different depending on tracking mode.
212     if (MODE_TIME == $user->tracking_mode) {
213       // In "time only" tracking mode there is a single user rate.
214       $sql = "select count(*) as num from tt_log l, tt_users u
215         where l.status = 1 and l.client_id = $client_id and l.invoice_id is NULL
216         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
217         and l.billable * u.rate * time_to_sec(l.duration)/3600 > 0
218         and l.user_id = u.id";
219     } else {
220       // sql part for project id.
221       if ($project_id) $project_part = " and l.project_id = $project_id";
222                 
223       // When we have projects, rates are defined for each project in tt_user_project_binds table.
224       $sql = "select count(*) as num from tt_log l, tt_user_project_binds upb
225         where l.status = 1 and l.client_id = $client_id $project_part and l.invoice_id is NULL
226         and l.date >= ".$mdb2->quote($start)." and l.date <= ".$mdb2->quote($end)."
227         and l.billable * upb.rate * time_to_sec(l.duration)/3600 > 0
228         and upb.user_id = l.user_id and upb.project_id = l.project_id";
229     }
230         $res = $mdb2->query($sql);
231         if (!is_a($res, 'PEAR_Error')) {
232       $val = $res->fetchRow();
233           if ($val['num']) {
234         return true;
235       }
236     }
237     
238     // sql part for project id.
239     if ($project_id) $project_part = " and ei.project_id = $project_id";
240     
241     $sql = "select count(*) as num from tt_expense_items ei
242       where ei.client_id = $client_id $project_part and ei.invoice_id is NULL
243       and ei.date >= ".$mdb2->quote($start)." and ei.date <= ".$mdb2->quote($end)."
244       and ei.cost <> 0 and ei.status = 1";
245     $res = $mdb2->query($sql);
246         if (!is_a($res, 'PEAR_Error')) {
247       $val = $res->fetchRow();
248           if ($val['num']) {
249         return true;
250       }
251     }
252       
253     return false;
254   }
255   
256   // createInvoice - marks items for invoice as belonging to it (with its reference number).
257   static function createInvoice($fields) {
258         
259         $mdb2 = getConnection();
260     global $user;
261         
262         $name = $fields['name'];
263         if (!$name)
264           return false;
265
266         $client_id = (int) $fields['client_id'];
267
268         $invoice_date = new DateAndTime($user->date_format, $fields['date']);
269     $date = $invoice_date->toString(DB_DATEFORMAT);
270         
271     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
272     $start = $start_date->toString(DB_DATEFORMAT);
273     
274     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
275     $end = $end_date->toString(DB_DATEFORMAT);
276     
277     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
278     
279     // Create a new invoice record.
280     $sql = "insert into tt_invoices (team_id, name, date, client_id)
281       values($user->team_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id)"; 
282     $affected = $mdb2->exec($sql);
283     if (is_a($affected, 'PEAR_Error'))
284       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 * u.rate * time_to_sec(l.duration)/3600 > 0";
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 * upb.rate * time_to_sec(l.duration)/3600 > 0";
313     }
314     $affected = $mdb2->exec($sql);
315     if (is_a($affected, 'PEAR_Error'))
316       return false;
317       
318     // sql part for project id.
319     if ($project_id) $project_part = " and project_id = $project_id";
320     
321     $sql = "update tt_expense_items set invoice_id = $last_id where client_id = $client_id $project_part and invoice_id is NULL
322       and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end)." and cost <> 0 and status = 1";
323     $affected = $mdb2->exec($sql);
324     return (!is_a($affected, 'PEAR_Error'));
325   }
326   
327   // prepareInvoiceBody - prepares an email body for invoice.
328   static function prepareInvoiceBody($invoice_id, $comment)
329   {
330         global $user;
331         global $i18n;
332         
333         $invoice = ttInvoiceHelper::getInvoice($invoice_id);
334         $client = ttClientHelper::getClient($invoice['client_id'], true);
335         $invoice_items = ttInvoiceHelper::getInvoiceItems($invoice_id);
336         
337         $tax_percent = $client['tax'];
338         
339         $subtotal = 0;
340     $tax = 0;
341     foreach($invoice_items as $item)
342       $subtotal += $item['cost'];
343     if ($tax_percent) {
344       $tax_expenses = in_array('et', explode(',', $user->plugins));
345       foreach($invoice_items as $item) {
346             if ($item['type'] == 2 && !$tax_expenses)
347               continue;
348         $tax += round($item['cost'] * $tax_percent / 100, 2);   
349       }
350     }
351     $total = $subtotal + $tax; 
352     
353     $subtotal = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($subtotal, 2)));
354     if ($tax) $tax = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($tax, 2)));
355     $total = htmlspecialchars($user->currency).' '.str_replace('.', $user->decimal_mark, sprintf('%8.2f', round($total, 2)));
356     
357     if ('.' != $user->decimal_mark) {
358       foreach ($invoice_items as &$item) {
359         $item['cost'] = str_replace('.', $user->decimal_mark, $item['cost']);
360       }
361       unset($item); // Unset the reference. If we don't, the foreach loop below modifies the array while printing.
362                     // See http://stackoverflow.com/questions/8220399/php-foreach-pass-by-reference-last-element-duplicating-bug
363     }
364     
365     // Define some styles to use in email.
366     $style_title = 'text-align: center; font-size: 15pt; font-family: Arial, Helvetica, sans-serif;';
367     $style_tableHeader = 'font-weight: bold; background-color: #a6ccf7; text-align: left;';
368     $style_tableHeaderCentered = 'font-weight: bold; background-color: #a6ccf7; text-align: center;';
369     
370     // Start creating email body.
371     $body = '<html>';
372     $body .= '<head><meta http-equiv="content-type" content="text/html; charset='.CHARSET.'"></head>';
373     $body .= '<body>';
374     
375     // Output title.
376     $body .= '<p style="'.$style_title.'">'.$i18n->getKey('title.invoice').' '.htmlspecialchars($invoice['name']).'</p>';
377     
378     // Output comment.
379     if($comment) $body .= '<p>'.htmlspecialchars($comment).'</p>';
380     
381     // Output invoice info.
382     $body .= '<table>';
383     $body .= '<tr><td><b>'.$i18n->getKey('label.date').':</b> '.$invoice['date'].'</td></tr>';
384     $body .= '<tr><td><b>'.$i18n->getKey('label.client').':</b> '.htmlspecialchars($client['name']).'</td></tr>';
385     $body .= '<tr><td><b>'.$i18n->getKey('label.client_address').':</b> '.htmlspecialchars($client['address']).'</td></tr>';
386     $body .= '</table>';
387     
388     $body .= '<p></p>';
389     
390     // Output invoice items.
391     $body .= '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
392     $body .= '<tr>';
393     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.date').'</td>';
394     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('form.invoice.person').'</td>';
395     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
396       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.project').'</td>';
397     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
398       $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.task').'</td>';
399     $body .= '<td style="'.$style_tableHeader.'">'.$i18n->getKey('label.note').'</td>';
400     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.duration').'</td>';
401     $body .= '<td style="'.$style_tableHeaderCentered.'" width="5%">'.$i18n->getKey('label.cost').'</td>';
402     $body .= '</tr>';
403     foreach ($invoice_items as $item) {
404       $body .= '<tr>';
405       $body .= '<td>'.$item['date'].'</td>';
406       $body .= '<td>'.htmlspecialchars($item['user_name']).'</td>';
407       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
408         $body .= '<td>'.htmlspecialchars($item['project_name']).'</td>';
409       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
410         $body .= '<td>'.htmlspecialchars($item['task_name']).'</td>';
411       $body .= '<td>'.htmlspecialchars($item['note']).'</td>';
412       $body .= '<td align="right">'.$item['duration'].'</td>';
413       $body .= '<td align="right">'.$item['cost'].'</td>';
414       $body .= '</tr>';
415     }
416     // Output summary.
417     $colspan = 4;
418     if (MODE_PROJECTS == $user->tracking_mode)
419       $colspan++;
420     elseif (MODE_PROJECTS_AND_TASKS == $user->tracking_mode)
421       $colspan += 2;
422     $body .= '<tr><td>&nbsp;</td></tr>';
423     if ($tax) {
424       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.subtotal').':</b></td><td nowrap align="right">'.$subtotal.'</td></tr>';
425       $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.tax').':</b></td><td nowrap align="right">'.$tax.'</td></tr>';
426     }
427     $body .= '<tr><td colspan="'.$colspan.'" align="right"><b>'.$i18n->getKey('label.total').':</b></td><td nowrap align="right">'.$total.'</td></tr>';
428     $body .= '</table>';
429   
430     // Output footer.
431     $body .= '<p style="text-align: center;">'.$i18n->getKey('form.mail.footer').'</p>';
432     // Finish creating email body.
433     $body .= '</body></html>';
434
435     return $body;
436   }
437 }