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