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