a00b4b7a86dbffdf99ddeef5834918cba13a6dfc
[timetracker.git] / WEB-INF / lib / ttTimesheetHelper.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('ttUserHelper');
30
31 // Class ttTimesheetHelper is used to help with project related tasks.
32 class ttTimesheetHelper {
33
34   // The getTimesheetByName looks up a project by name.
35   static function getTimesheetByName($name) {
36     global $user;
37     $mdb2 = getConnection();
38
39     $user_id = $user->getUser();
40     $group_id = $user->getGroup();
41     $org_id = $user->org_id;
42
43     $sql = "select id from tt_timesheets".
44       " where group_id = $group_id and org_id = $org_id and user_id = $user_id and name = ".$mdb2->quote($name).
45       " and status is not null";
46     $res = $mdb2->query($sql);
47     if (!is_a($res, 'PEAR_Error')) {
48       $val = $res->fetchRow();
49       if ($val && $val['id'])
50         return $val;
51     }
52     return false;
53   }
54
55   // createTimesheet function creates a new timesheet.
56   static function createTimesheet($fields)
57   {
58     // Create a new timesheet entry.
59     global $user;
60     $mdb2 = getConnection();
61
62     $user_id = $user->getUser();
63     $group_id = $user->getGroup();
64     $org_id = $user->org_id;
65
66     $client_id = $fields['client_id'];
67     $project_id = $fields['project_id'];
68     $name = $fields['name'];
69     $comment = $fields['comment'];
70
71     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
72     $start = $start_date->toString(DB_DATEFORMAT);
73
74     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
75     $end = $end_date->toString(DB_DATEFORMAT);
76
77     $created_part = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
78
79     $sql = "insert into tt_timesheets (user_id, group_id, org_id, client_id, project_id, name, comment,".
80       " start_date, end_date, created, created_ip, created_by)".
81       " values ($user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).", ".$mdb2->quote($name).
82       ", ".$mdb2->quote($comment).", ".$mdb2->quote($start).", ".$mdb2->quote($end).$created_part.")";
83     $affected = $mdb2->exec($sql);
84     if (is_a($affected, 'PEAR_Error'))
85       return false;
86
87     $last_id = $mdb2->lastInsertID('tt_timesheets', 'id');
88
89     // Associate tt_log items with timesheet.
90     if (isset($fields['client'])) $client_id = (int) $fields['client_id'];
91     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
92     // sql parts.
93     if ($client_id) $client_part = " and client_id = $client_id";
94     if ($project_id) $project_part = " and project_id = $project_id";
95
96     $sql = "update tt_log set timesheet_id = $last_id".
97       " where status = 1 $client_part $project_part and timesheet_id is null".
98       " and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end).
99       " and user_id = $user_id and group_id = $group_id and org_id = $org_id";
100     $affected = $mdb2->exec($sql);
101     if (is_a($affected, 'PEAR_Error'))
102       return false;
103
104     return $last_id;
105   }
106
107   // The getActiveTimesheets obtains active timesheets for a user.
108   static function getActiveTimesheets()
109   {
110     global $user;
111     $mdb2 = getConnection();
112
113     $user_id = $user->getUser();
114     $group_id = $user->getGroup();
115     $org_id = $user->org_id;
116
117     $result = array();
118     $sql = "select ts.id, ts.name, ts.client_id, c.name as client_name,".
119       " ts.submit_status, ts.approve_status from tt_timesheets ts".
120       " left join tt_clients c on (c.id = ts.client_id)".
121       " where ts.status = 1 and ts.group_id = $group_id and ts.org_id = $org_id and ts.user_id = $user_id".
122       " order by ts.name";
123     $res = $mdb2->query($sql);
124     $result = array();
125     if (!is_a($res, 'PEAR_Error')) {
126       while ($val = $res->fetchRow()) {
127         $result[] = $val;
128       }
129     }
130     return $result;
131   }
132
133   // The getInactiveTimesheets obtains inactive timesheets for a user.
134   static function getInactiveTimesheets()
135   {
136     global $user;
137     $mdb2 = getConnection();
138
139     $user_id = $user->getUser();
140     $group_id = $user->getGroup();
141     $org_id = $user->org_id;
142
143     $result = array();
144     $sql = "select ts.id, ts.name, ts.client_id, c.name as client_name,".
145       " ts.submit_status, ts.approve_status from tt_timesheets ts".
146       " left join tt_clients c on (c.id = ts.client_id)".
147       " where ts.status = 0 and ts.group_id = $group_id and ts.org_id = $org_id and ts.user_id = $user_id".
148       " order by ts.name";
149     $res = $mdb2->query($sql);
150     $result = array();
151     if (!is_a($res, 'PEAR_Error')) {
152       while ($val = $res->fetchRow()) {
153         $result[] = $val;
154       }
155     }
156     return $result;
157   }
158
159   // getTimesheet - obtains timesheet data from the database.
160   static function getTimesheet($timesheet_id) {
161     global $user;
162     $mdb2 = getConnection();
163
164     $user_id = $user->getUser();
165     $group_id = $user->getGroup();
166     $org_id = $user->org_id;
167
168     $sql = "select ts.*, u.name as user_name, c.name as client_name,".
169       " p.name as project_name from tt_timesheets ts".
170       " left join tt_users u on (ts.user_id = u.id)".
171       " left join tt_clients c on (ts.client_id = c.id)".
172       " left join tt_projects p on (ts.project_id = p.id)".
173       " where ts.id = $timesheet_id and ts.user_id = $user_id and ts.group_id = $group_id and ts.org_id = $org_id and ts.status is not null";
174     $res = $mdb2->query($sql);
175     if (!is_a($res, 'PEAR_Error')) {
176       if ($val = $res->fetchRow())
177         return $val;
178     }
179     return false;
180   }
181
182   // delete - deletes timesheet from the database.
183   static function delete($timesheet_id) {
184     global $user;
185     $mdb2 = getConnection();
186
187     $user_id = $user->getUser();
188     $group_id = $user->getGroup();
189     $org_id = $user->org_id;
190
191     // Handle tt_log records.
192     $sql = "update tt_log set timesheet_id = null".
193       " where timesheet_id = $timesheet_id and user_id = $user_id and group_id = $group_id and org_id = $org_id";
194     $affected = $mdb2->exec($sql);
195     if (is_a($affected, 'PEAR_Error')) return false;
196
197     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
198
199     // Delete timesheet.
200     $sql = "update tt_timesheets set status = null".$modified_part.
201       " where id = $timesheet_id and user_id = $user_id and group_id = $group_id and org_id = $org_id";
202     $affected = $mdb2->exec($sql);
203     return (!is_a($affected, 'PEAR_Error'));
204   }
205
206   // update function - updates the timesheet in database.
207   static function update($fields) {
208     global $user;
209     $mdb2 = getConnection();
210
211     $user_id = $user->getUser();
212     $group_id = $user->getGroup();
213     $org_id = $user->org_id;
214
215     $timesheet_id = $fields['id']; // Timesheet we are updating.
216     $name = $fields['name']; // Timesheet name.
217     $comment = $fields['comment'];
218     $status = $fields['status']; // Timesheet status.
219
220     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
221
222     $sql = "update tt_timesheets set name = ".$mdb2->quote($name).
223       ", comment = ".$mdb2->quote($comment).$modified_part.
224       ", status = ".$mdb2->quote($status).
225       " where id = $timesheet_id and user_id = $user_id and group_id = $group_id and org_id = $org_id";
226     $affected = $mdb2->exec($sql);
227     return (!is_a($affected, 'PEAR_Error'));
228   }
229
230   // getReportOptions prepares $options array to be used with ttReportHelper
231   // to obtain items for timesheet view.
232   static function getReportOptions($timesheet) {
233     global $user;
234     $group_by_client = $user->isPluginEnabled('cl') && !$timesheet['client_id'];
235     $trackingMode = $user->getTrackingMode();
236     $group_by_project = MODE_PROJECTS == $trackingMode || MODE_PROJECTS_AND_TASKS == $trackingMode;
237
238     $options['timesheet_id'] = $timesheet['id'];
239     $options['group_by1'] = 'date';
240     if ($group_by_client || $group_by_project) {
241       $options['group_by2'] = $group_by_client ? 'client' : 'project';
242     }
243     if ($options['group_by2'] && $options['group_by2'] != 'project' && $group_by_project) {
244       $options['group_by3'] = 'project';
245     }
246     return $options;
247   }
248
249   // getApprovers obtains a list of users who can approve a timesheet for a given user
250   // and also have an email to receive a notification about it.
251   static function getApprovers() {
252     global $user;
253     $mdb2 = getConnection();
254
255     $user_id = $user->getUser();
256     $group_id = $user->getGroup();
257     $org_id = $user->org_id;
258
259     $approvers = array();
260     $rank = ttUserHelper::getUserRank($user_id);
261     $sql = "select u.id, u.name, u.email".
262       " from tt_users u".
263       " left join tt_roles r on (r.id = u.role_id)".
264       " where u.status = 1 and u.email is not null and u.group_id = $group_id and u.org_id = $org_id".
265       " and (r.rank > $rank and r.rights like '%approve_timesheets%')";
266     $res = $mdb2->query($sql);
267     if (!is_a($res, 'PEAR_Error')) {
268       while ($val = $res->fetchRow()) {
269         $approvers[] = $val;
270       }
271     }
272     return $approvers;
273   }
274
275   // getApprover obtains approver properties such as name and email.
276   static function getApprover($user_id) {
277     global $user;
278     $mdb2 = getConnection();
279
280     $group_id = $user->getGroup();
281     $org_id = $user->org_id;
282
283     $rank = ttUserHelper::getUserRank($user->getUser());
284     $sql = "select u.name, u.email".
285       " from tt_users u".
286       " left join tt_roles r on (r.id = u.role_id)".
287       " where u.id = $user_id and u.status = 1 and u.email is not null and u.group_id = $group_id and u.org_id = $org_id".
288       " and (r.rank > $rank and r.rights like '%approve_timesheets%')";
289     $res = $mdb2->query($sql);
290     if (!is_a($res, 'PEAR_Error')) {
291       if ($val = $res->fetchRow()) {
292         return $val;
293       }
294     }
295     return false;
296   }
297
298   // markSubmitted marks a timesheet as submitted.
299   static function markSubmitted($fields) {
300     global $user;
301     $mdb2 = getConnection();
302
303     $user_id = $user->getUser();
304     $group_id = $user->getGroup();
305     $org_id = $user->org_id;
306
307     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
308
309     $timesheet_id = $fields['timesheet_id'];
310     $sql = "update tt_timesheets set submit_status = 1".$modified_part.
311       " where id = $timesheet_id and user_id = $user_id and group_id = $group_id and org_id = $org_id";
312     $affected = $mdb2->exec($sql);
313     return (!is_a($affected, 'PEAR_Error'));
314   }
315
316   // sendSubmitEmail sends a notification to an approver about a timesheet submit.
317   static function sendSubmitEmail($fields) {
318     global $i18n;
319     global $user;
320
321     // Send email to a selected approver.
322     if (!$fields['approver_id']) return true; // No approver, nothing to do.
323
324     $approver = ttTimesheetHelper::getApprover($fields['approver_id']);
325     if (!$approver) return false; // Invalid approver id.
326
327     $fields['to'] = $approver['email'];
328     $fields['subject'] = $i18n->get('form.timesheet_view.submit_subject');
329     $fields['body'] = sprintf($i18n->get('form.timesheet_view.submit_body'), $user->getName());
330
331     return ttTimesheetHelper::sendEmail($fields);
332   }
333
334   // sendApprovedEmail sends a notification to user about a timesheet approval.
335   static function sendApprovedEmail($fields) {
336     global $i18n;
337     global $user;
338
339     // Obtain user email.
340     $user_details = $user->getUserDetails($fields['user_id']);
341     $email = $user_details['email'];
342     if (!$email) return true; // No email to send to, nothing to do.
343
344     $fields['to'] = $email;
345     $fields['subject'] = $i18n->get('form.timesheet_view.approve_subject');
346     $fields['body'] = sprintf($i18n->get('form.timesheet_view.approve_body'), htmlspecialchars($fields['name']), htmlspecialchars($fields['comment']));
347
348     return ttTimesheetHelper::sendEmail($fields);
349   }
350
351   // sendDisapprovedEmail sends a notification to user about a timesheet disapproval.
352   static function sendDisapprovedEmail($fields) {
353     global $i18n;
354     global $user;
355
356     // Obtain user email.
357     $user_details = $user->getUserDetails($fields['user_id']);
358     $email = $user_details['email'];
359     if (!$email) return true; // No email to send to, nothing to do.
360
361     $fields['to'] = $email;
362     $fields['subject'] = $i18n->get('form.timesheet_view.disapprove_subject');
363     $fields['body'] = sprintf($i18n->get('form.timesheet_view.disapprove_body'), htmlspecialchars($fields['name']), htmlspecialchars($fields['comment']));
364
365     return ttTimesheetHelper::sendEmail($fields);
366   }
367
368   // sendEmail is a generic finction that sends a timesheet related email.
369   // TODO: perhaps make it even more generic for the entire application.
370   static function sendEmail($fields, $html = true) {
371     global $i18n;
372     global $user;
373
374     // Send email.
375     import('mail.Mailer');
376     $mailer = new Mailer();
377     $mailer->setCharSet(CHARSET);
378     if ($html)
379       $mailer->setContentType('text/html');
380     $mailer->setSender(SENDER);
381     $mailer->setReceiver($fields['to']);
382     if (!empty($user->bcc_email))
383       $mailer->setReceiverBCC($user->bcc_email);
384     $mailer->setMailMode(MAIL_MODE);
385     if (!$mailer->send($fields['subject'], $fields['body']))
386       return false;
387
388     return true;
389   }
390
391   // markApproved marks a timesheet as approved.
392   static function markApproved($fields) {
393     global $user;
394     $mdb2 = getConnection();
395
396     $user_id = $user->getUser();
397     $group_id = $user->getGroup();
398     $org_id = $user->org_id;
399
400     $timesheet_id = $fields['timesheet_id'];
401     $comment = $fields['comment'];
402
403     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
404
405     $sql = "update tt_timesheets set approve_status = 1, approve_comment = ".$mdb2->quote($comment).$modified_part.
406       " where id = $timesheet_id and submit_status = 1 and user_id = $user_id and group_id = $group_id and org_id = $org_id";
407     $affected = $mdb2->exec($sql);
408     return (!is_a($affected, 'PEAR_Error'));
409   }
410
411   // markDisapproved marks a timesheet as not approved.
412   static function markDisapproved($fields) {
413     global $user;
414     $mdb2 = getConnection();
415
416     $user_id = $user->getUser();
417     $group_id = $user->getGroup();
418     $org_id = $user->org_id;
419
420     $timesheet_id = $fields['timesheet_id'];
421     $comment = $fields['comment'];
422
423     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
424
425     $sql = "update tt_timesheets set approve_status = 0, approve_comment = ".$mdb2->quote($comment).$modified_part.
426       " where id = $timesheet_id and submit_status = 1 and user_id = $user_id and group_id = $group_id and org_id = $org_id";
427     $affected = $mdb2->exec($sql);
428     return (!is_a($affected, 'PEAR_Error'));
429   }
430
431   // The timesheetItemsExist determines whether tt_log records exist in the specified period
432   // for inclusion in a new timesheet.
433   static function timesheetItemsExist($fields) {
434     global $user;
435     $mdb2 = getConnection();
436
437     $user_id = $user->getUser();
438     $group_id = $user->getGroup();
439     $org_id = $user->org_id;
440
441     if (isset($fields['client_id'])) $client_id = (int) $fields['client_id'];
442     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
443
444     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
445     $start = $start_date->toString(DB_DATEFORMAT);
446
447     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
448     $end = $end_date->toString(DB_DATEFORMAT);
449
450     // sql parts.
451     if ($client_id) $client_part = " and client_id = $client_id";
452     if ($project_id) $project_part = " and project_id = $project_id";
453
454     $sql = "select count(*) as num from tt_log".
455       " where status = 1 $client_part $project_part and timesheet_id is null".
456       " and date >= ".$mdb2->quote($start)." and date <= ".$mdb2->quote($end).
457       " and user_id = $user_id and group_id = $group_id and org_id = $org_id";
458     $res = $mdb2->query($sql);
459     if (!is_a($res, 'PEAR_Error')) {
460       $val = $res->fetchRow();
461       if ($val['num']) {
462         return true;
463       }
464     }
465
466     return false;
467   }
468
469   // The overlaps function determines if a new timesheet overlaps with
470   // an already existing timesheet.
471   static function overlaps($fields) {
472     global $user;
473     $mdb2 = getConnection();
474
475     $user_id = $user->getUser();
476     $group_id = $user->getGroup();
477     $org_id = $user->org_id;
478
479     if (isset($fields['client_id'])) $client_id = (int) $fields['client_id'];
480     if (isset($fields['project_id'])) $project_id = (int) $fields['project_id'];
481
482     $start_date = new DateAndTime($user->date_format, $fields['start_date']);
483     $start = $start_date->toString(DB_DATEFORMAT);
484     $quoted_start = $mdb2->quote($start);
485
486     $end_date = new DateAndTime($user->date_format, $fields['end_date']);
487     $end = $end_date->toString(DB_DATEFORMAT);
488     $quoted_end = $mdb2->quote($end);
489
490     // sql parts.
491     if ($client_id) $client_part = " and client_id = $client_id";
492     if ($project_id) $project_part = " and project_id = $project_id";
493
494     $sql = "select id from tt_timesheets".
495       " where status is not null $client_part $project_part".
496       " and (($quoted_start >= start_date and $quoted_start <= end_date)".
497       "   or ($quoted_end >= start_date and $quoted_end <= end_date))".
498       " and user_id = $user_id and group_id = $group_id and org_id = $org_id";
499     $res = $mdb2->query($sql);
500     if (!is_a($res, 'PEAR_Error')) {
501       $val = $res->fetchRow();
502       if ($val['id']) {
503         return true;
504       }
505     }
506     return false;
507   }
508
509   // The getMatchingTimesheets function retrieves a timesheet that "matches"
510   // a report for an option to assign report items to it.
511   //
512   // Condition: report range is fully enclosed in an existing timesheet with
513   // matching client_id and project_id and null approved_status.
514   static function getMatchingTimesheets($options) {
515     global $user;
516     $mdb2 = getConnection();
517
518     $user_id = $user->getUser();
519     $group_id = $user->getGroup();
520     $org_id = $user->org_id;
521
522     // Check users.
523     if (isset($options['users'])) {
524       $comma_separated = $options['users'];
525       $users = explode(',', $comma_separated);
526       if (count($users) > 1 || $users[0] != $user->getUser())
527         return false;
528     }
529
530     // No timesheets for expenses.
531     if ($options['show_cost'] && $user->isPluginEnabled('ex')) return false;
532     
533     // Parts for client and project.
534     if ($options['client_id']) $client_part = ' and (client_id is null or client_id = '.(int)$options['client_id'].')';
535     if ($options['project_id']) $project_part = ' and (project_id is null or project_id = '.(int)$options['project_id'].')';
536
537     // Determine start and end dates.
538     $dateFormat = $user->getDateFormat();
539     if ($options['period'])
540       $period = new Period($options['period'], new DateAndTime($dateFormat));
541     else {
542       $period = new Period();
543       $period->setPeriod(
544         new DateAndTime($dateFormat, $options['period_start']),
545         new DateAndTime($dateFormat, $options['period_end']));
546     }
547     $start = $period->getStartDate(DB_DATEFORMAT);
548     $end = $period->getEndDate(DB_DATEFORMAT);
549
550     $result = false;
551     $sql = "select id, name from tt_timesheets".
552       " where ".$mdb2->quote($start)." >= start_date and ".$mdb2->quote($end)." <= end_date".
553       "$client_part $project_part".
554       " and user_id = $user_id and group_id = $group_id and org_id = $org_id".
555       " and approve_status is null and status is not null";
556     $res = $mdb2->query($sql);
557     if (!is_a($res, 'PEAR_Error')) {
558       while ($val = $res->fetchRow()) {
559         $result[] = $val;
560       }
561     }
562     return $result;
563   }
564 }