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