def browse_task_files(request, task_id): try: res = { 'status': 'Ok', 'data': [], } task = Task.objects.get(pk=task_id) if ACL.canViewTask(request.user, task): #task = Task.objects.get(pk=int(task_id)) if task.hasPermissions(request.user): files = TaskAttachment.objects.filter(task=task) #res = [] for f in files: res['data'].append({ 'id': f.pk, 'name':os.path.basename(f.task_attachment_file.name), 'url':f.task_attachment_file.url, 'size': sizeof_fmt(f.task_attachment_file.size) }) else: res['data'] = [] else: raise Exception('Permission denied') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls = DjangoJSONEncoder) return HttpResponse(data, content_type = 'application/json')
def browse_task_reminders(request, task_id): try: task = Task.objects.get(pk=task_id) #res = [] res = { 'status': 'Ok', 'data': {} } if ACL.canViewTask(request.user, task): task = Task.objects.get(pk=task_id) res['data'] = { 'emails': task.usersEmails(), 'reminders': task.taskReminders(), } else: raise Exception('Permission denied') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls = DjangoJSONEncoder) return HttpResponse(data, content_type = 'application/json')
def browse_task_predecessors(request): res = {} try: res = { 'status': 'Ok', 'message': '', 'data': [], } t = Task.objects.get(pk=request.POST.get('task_id')) if ACL.canViewTask(request.user, t): #t = Task.objects.get(pk = request.GET.get('task_id')) for p in t.task_predecessors.all(): res['data'].append({ 'task_id': p.task_id, 'task_name': p.task_name, 'task_start_date': p.task_start_date.strftime(settings.DATETIME_FORMAT) }) else: raise Exception('Permission denied') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls=DjangoJSONEncoder) return HttpResponse(data, content_type='application/json')
def add_task_predecessor(request, task_id, pred_id): res = {} try: res = { 'status': 'Ok', 'data': { 'task_id': task_id }, } t = Task.objects.get(pk=task_id) p = Task.objects.get(pk=pred_id) if ACL.canUpdateTask(request.user, t): if (task_id != pred_id): # Receives the current task to assign predecessors to #t = Task.objects.get(pk = task_id) #p = Task.objects.get(pk = pred_id) # If predecessor already inserted, do nothing if p not in t.task_predecessors.all(): t.task_predecessors.add(p) else: raise Exception('Permission denied') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls=DjangoJSONEncoder) return HttpResponse(data, content_type='application/json')
def browse_observation(request, task_id): try: res = { 'status': 'Ok', 'data': [], } task = Task.objects.get(pk=int(task_id)) if ACL.canViewTask(request.user, task): if task.hasPermissions(request.user): objs = Observation.objects.filter(task=task) for obj in objs: res['data'].append({ 'id': obj.pk, 'msg': obj.observation_msg, 'date': obj.observation_date.strftime( settings.DATETIME_FORMAT), 'user': obj.user.username }) else: raise Exception('Permission denied') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls=DjangoJSONEncoder) return HttpResponse(data, content_type='application/json')
def add_observation(request, task_id): try: res = { 'status': 'Ok', } task = Task.objects.get(pk=int(task_id)) msg = request.POST.get('observation', '') if ACL.canUpdateTask(request.user, task): if task.hasPermissions(request.user) and msg != '': obj = Observation(observation_msg=msg, user=request.user, task=task) obj.save() else: raise Exception('No permissions or message empty') else: raise Exception('No permissions or message empty') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls=DjangoJSONEncoder) return HttpResponse(data, content_type='application/json')
def add_task_label(request, task_id): try: res = { 'status': 'Ok', } label_id = request.GET.get('label_id') task = Task.objects.get(pk=task_id) if ACL.canUpdateTask(request.user, task): label = TaskLabel.objects.get(pk=label_id) if (request.user==label.user or request.user in label.users.all()) and \ label not in task.tasklabels.all(): task.tasklabels.add(label) else: res = { 'status': 'Error', 'message': 'No permissions to update', } except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls = DjangoJSONEncoder) return HttpResponse(data, content_type = 'application/json')
def del_task(request, task_id): res = {} try: task = Task.objects.get(pk=task_id) labels = task.tasklabels.all() labels = labels.filter(Q(user=request.user)) """ if len(labels)>0: #labels = labels.filter(pk__in=task).distinct() #labels = labels.filter(pk__in=[task.task_id]).distinct() labels = labels.distinct() """ labels = labels.distinct() if ACL.canDeleteTask(request.user, task): if task.hasPermissions( request.user): #TODO: Check if this is necessary task.delete() res = {'status': 'Ok'} else: res = {'status': 'Error', 'message': 'Permission denied'} else: res = {'status': 'Error', 'message': 'Permission denied'} except Exception as e: res = {'status': 'Error', 'message': str(e)} data = json.dumps(res, cls=DjangoJSONEncoder) return HttpResponse(data, content_type='application/json')
def label_print(request, label_id): label = TaskLabel.objects.get(pk=label_id) tasks = Task.objects.filter(tasklabels=label) tasks = tasks.order_by('task_start_date', 'task_name').distinct() res = [task for task in tasks if ACL.canViewTask(request.user, task)] project = None template = 'ptmTemplates/label_print.html' if label.project_set.count() > 0: project = label.project_set.all()[0] if hasattr(project, 'grantproject'): template = 'ptmTemplates/grantproject_print.html' project = project.grantproject else: template = 'ptmTemplates/project_print.html' response = render_to_response(template, { 'label': label, 'project': project, 'tasks': res, 'datetime': datetime.datetime.now() }, context_instance=RequestContext(request)) return response
def get_task_reminder(request, reminder_id): try: res = { 'status': 'Ok', 'data': {} } reminder = Reminder.objects.get(pk=reminder_id) task = reminder.task if ACL.canViewTask(request.user, task) : #reminder = Reminder.objects.get(pk=reminder_id) res['data'] = { 'reminder_id': reminder.reminder_id, 'reminder_subject': reminder.reminder_subject, 'reminder_msg': reminder.reminder_msg, 'reminder_recipients': reminder.reminder_recipients, 'reminder_date': reminder.reminder_date.strftime( settings.DATE_FORMAT ), 'task_id': reminder.task.task_id, 'reminder_non_validated': reminder.reminder_non_validated } else: raise Exception('Permission denied') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls = DjangoJSONEncoder) return HttpResponse(data, content_type = 'application/json')
def upload(request): task_id = request.POST.get('task_id', None) task = Task.objects.get(pk=int(task_id)) if ACL.canUpdateTask(request.user, task): if task.hasPermissions(request.user): file_dict = {'task_id': task_id} if task_id!=None: file = upload_receive( request ) task = Task.objects.get(pk=int(task_id)) instance = TaskAttachment( task_attachment_file = file, task=task ) instance.save() basename = os.path.basename( instance.task_attachment_file.path ) file_dict = { 'name' : basename, 'size' : instance.task_attachment_file.size, 'url': settings.MEDIA_URL + str(instance.task_attachment_file), 'thumbnailUrl': '/static/file_thumb.png', 'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }), 'deleteType': 'POST', } else: file_dict = {} else: raise Exception('Permission denied') return UploadResponse( request, file_dict )
def user_rss(request): tasks = Task.objects.filter(task_users=request.user) tasks = tasks.filter(task_is_complete=False) tasks = tasks.order_by('task_start_date').distinct() tasks = [task for task in tasks if ACL.canViewTask(request.user, task)] return render_to_response('ptmTemplates/user_rss.xml', { 'tasks': tasks, 'datetime': datetime.datetime.now() }, context_instance=RequestContext(request), mimetype='application/xml')
def add_task_reminders(request, task_id): try: res = { 'status': 'Ok', } task = Task.objects.get(pk=task_id) if ACL.canUpdateTask(request.user, task): taskid = request.POST.get('task_id', task_id ) if taskid.strip()=='': taskid=task_id #task = Task.objects.get(pk=taskid) if request.user in task.task_users.all(): reminder_id = request.POST.get('reminder_id', None ) if reminder_id.strip()=='': reminder_id=None reminder_subject = request.POST.get('reminder_subject', None ) reminder_msg = request.POST.get('reminder_msg', None ) reminder_recipients = request.POST.get('reminder_recipients', None ) reminder_date = request.POST.get('reminder_date', None ) reminder_non_validated = request.POST.get('reminder_non_validated') #reminder_date = datetime.datetime.strptime(reminder_date, settings.DATE_FORMAT) reminder = Reminder( reminder_id=reminder_id, reminder_subject=reminder_subject, reminder_msg=reminder_msg, reminder_recipients=reminder_recipients, reminder_date=reminder_date, reminder_non_validated = True if reminder_non_validated=='true' else False, task = task ) reminder.save() else: raise Exception("User doesn't have permissions") else: raise Exception('Permission denied') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls = DjangoJSONEncoder) return HttpResponse(data, content_type = 'application/json')
def label_ical(request, label_id): label = TaskLabel.objects.get(pk=label_id) tasks = Task.objects.filter(tasklabels=label) tasks = tasks.order_by('task_start_date').distinct() res = [task for task in tasks if ACL.canViewTask(request.user, task)] response = render_to_response('ptmTemplates/user_ical.ics', { 'label': label, 'tasks': res, 'datetime': datetime.datetime.now() }, context_instance=RequestContext(request), mimetype='application/ics') response['Content-Disposition'] = 'attachment; filename="%s - %s.ical"' % ( label.tasklabel_name, datetime.datetime.now()) return response
def upload_delete( request, pk ): try: instance = TaskAttachment.objects.get( pk = pk ) task = instance.task if ACL.canUpdateTask(request.user, task): #instance = TaskAttachment.objects.get( pk = pk ) #task = instance.task if task.hasPermissions(request.user): os.unlink( instance.task_attachment_file.path ) instance.delete() success = True else: success = False else: raise Exception('Permission denied') except TaskAttachment.DoesNotExist: success = False return JFUResponse( request, success )
def del_task_predecessor(request, task_id, pred_id): res = {} try: res = { 'status': 'Ok', } t = Task.objects.get(pk=task_id) p = Task.objects.get(pk=pred_id) if ACL.canUpdateTask(request.user, t): if p in t.task_predecessors.all(): t.task_predecessors.remove(p) else: raise Exception('Permission denied') except Exception as e: res = {'status': 'Error'} data = json.dumps(res, cls=DjangoJSONEncoder) return HttpResponse(data, content_type='application/json')
def del_task_reminder(request, reminder_id): try: res = { 'status': 'Ok', } reminder = Reminder.objects.get(pk=reminder_id) task = reminder.task if ACL.canUpdateTask(request.user, task): #reminder = Reminder.objects.get(pk=reminder_id) reminder.delete() else: raise Exception('Permission <denied></denied>') except Exception as e: res = { 'status': 'Error', } data = json.dumps(res, cls = DjangoJSONEncoder) return HttpResponse(data, content_type = 'application/json')
def del_observation(request, observation_id): try: res = { 'status': 'Ok', } obj = Observation.objects.get(pk=observation_id) task = obj.task if ACL.canUpdateTask(request.user, task): if task.hasPermissions(request.user): obj.delete() else: raise Exception('No permissions or message empty') except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls=DjangoJSONEncoder) return HttpResponse(data, content_type='application/json')
def add_task(request, task_id=None): #try: res = {'status': 'Ok'} is_complete = "true" == request.GET.get("task_is_complete").lower() is_important = "true" == request.GET.get("task_is_important").lower() is_title = "true" == request.GET.get("task_is_title").lower() task_name = request.GET.get("task_name") task_start_date = request.GET.get("task_start_date") task_end_date = request.GET.get("task_end_date") clone_from = request.GET.get("clone_from", None) # Eventual future request: Do not allow to remove the complete status of a task if the 'master' task is marked as complete # Only allow a task to be complete if ALL its predecessors are also complete if task_id != None and is_complete: t = Task.objects.get(pk=task_id) for p in t.task_predecessors.all(): if p.task_is_complete == False: raise Exception( 'There are still predecessors tasks to complete') # Convert ISO string dates to datetime objects task_start_date = dateutil.parser.parse(task_start_date) task_end_date = dateutil.parser.parse(task_end_date) #correct the dates if start dat > end date if task_start_date > task_end_date and task_id != None: task = Task.objects.get(pk=task_id) diff_dates = task_end_date - task.task_start_date task_end_date = task_start_date + diff_dates if task_start_date > task_end_date: raise Exception('Start date has to be lower than the end date.') # ACL ############################################################## labelsToInsert = [] if task_id == None and clone_from != '-1': clone = Task.objects.get(pk=clone_from) addLabelTo = False for l in clone.tasklabels.all(): if ACL.canCreateInLabel(request.user, l): labelsToInsert.append(l) addLabelTo = True if not addLabelTo: tasklabel_id = request.GET.get("label_id") label = TaskLabel.objects.get(pk=tasklabel_id) if ACL.canCreateInLabel(request.user, label): labelsToInsert.append(label) if len(labelsToInsert) == 0: raise Exception('No permissions') elif task_id != None: task = Task.objects.get(pk=task_id) if not ACL.canUpdateTask(request.user, task): raise Exception('No permissions') else: member_id = request.GET.get("label_id") label = TaskLabelMembership.objects.get(pk=member_id).child if not ACL.canCreateInLabel(request.user, label): raise Exception('No permissions') ################################################################### task = Task( task_id=task_id, task_is_complete=is_complete, task_is_important=is_important, task_is_title=is_title, task_name=task_name, task_start_date=task_start_date, task_end_date=task_end_date, user=request.user if is_complete else None, ) task.save() try: for t in task.task_set.filter(task_is_title=True): changed = False if t.task_start_date > task.task_start_date: t.task_start_date = task.task_start_date changed = True if t.task_end_date < task.task_end_date: t.task_end_date = task.task_end_date changed = True if changed: t.save() except Task.DoesNotExist: pass if task_id == None: if clone_from != None and clone_from != '-1': for u in clone.task_users.all(): task.task_users.add(u) for l in labelsToInsert: task.tasklabels.add(l) else: member_id = request.GET.get("label_id") label = TaskLabelMembership.objects.get(pk=member_id).child task.tasklabels.add(label) task.task_users.add(request.user) users = [] for user in task.task_users.all(): try: a, b = user.first_name[0], user.last_name[0] except: a, b = '', '' users.append([user.pk, user.username, (a + b).upper()]) labels = [] for label in task.tasklabels.all(): labels.append({ 'id': label.pk, 'label': label.tasklabel_name, 'color': "#%s" % label.tasklabel_color }) res['data'] = { 'task_id': task.pk, 'task_is_title': task.task_is_title, 'task_is_complete': task.task_is_complete, 'task_is_important': task.task_is_important, 'task_name': task.task_name, 'task_start_date': task.task_start_date, 'task_end_date': task.task_end_date, 'completed_by_user_id': task.user.id if task.task_is_complete else None, 'users': users, 'labels': labels, } """ except Exception as e: res = { 'status': 'Error', 'message': str(e) }""" data = json.dumps(res, cls=DjangoJSONEncoder) return HttpResponse(data, content_type='application/json')
def browse_tasks_by_label(request, label_id=None): try: res = { 'status': 'Ok', 'message': '', 'data': [] } members = request.GET.get('ids', label_id) members = members.split(',') members = TaskLabelMembership.objects.filter(pk__in=members, user=request.user) label_ids = [x.child.pk for x in members] labels = TaskLabel.objects.all() labels = labels.filter(pk__in=label_ids).distinct() #only_labels = [x for x in labels if x.project_set.count()==0] #project_labels = [x for x in labels if x.project_set.count()>0] filter_codes = request.GET.get('filters', '') filter_codes = filter_codes.split(',') # E.g. sort=-task_name (sort descending for Task name/description column) # E.g. sort=task_name (sort ascending for Task name/description column) sort = request.GET.get('sort', None) tasks = Task.objects query = request.GET.get('query', '') queries = query.split(' ') for query in queries: if query.startswith('after:'): after_date = query.split(':')[1] after_date += ' 00:00:00' after_date = datetime.datetime.strptime(after_date, '%Y-%m-%d %H:%M:%S') tz = pytz.timezone('UTC') after_date = tz.localize(after_date) tasks = tasks.filter(task_start_date__gte = after_date) elif query.startswith('before:'): before_date = query.split(':')[1] before_date += ' 23:59:59' before_date = datetime.datetime.strptime(before_date, '%Y-%m-%d %H:%M:%S') tz = pytz.timezone('UTC') before_date = tz.localize(before_date) tasks = tasks.filter(task_end_date__lte = before_date) # The user's tasks elif query=='q:my': tasks = tasks.filter( task_users=request.user ) # Today tasks (i.e. between start data, including, and end date, including) elif query=='q:today': tasks = tasks.filter( ( # Include complete and not complete tasks Q(task_start_date__lte = datetime.datetime.today()) \ & Q(task_end_date__gte = datetime.datetime.today()) \ ) | ( # Expired tasks (overdue) Q(task_end_date__lte = datetime.datetime.today()) \ & Q(task_is_complete = False) ) ) # Tasks within the next 7 days elif query=='q:next': tasks = tasks.filter( ( Q(task_start_date__lte = datetime.datetime.today()) & Q(task_end_date__lte = datetime.datetime.today() + datetime.timedelta(days = 7)) ) | ( Q(task_end_date__lte = datetime.datetime.today() + datetime.timedelta(days = 7)) \ & Q(task_is_complete = False) ) ) # Exclude tasks that have already expired (overdue tasks) elif query=='q:nooverdue': tasks = tasks.exclude(task_end_date__lt = datetime.datetime.today()) # Exclude tasks that are complete elif query=='q:nocomplete': tasks = tasks.exclude(task_is_complete = True) # Non validated reminders in the next seven days # all reminders -> fk is label_id -> non validated elif query=='q:unconfirmed': tasks = tasks.filter( Q(reminder__reminder_non_validated=False) \ & Q(reminder__reminder_date__lte = datetime.datetime.today() + datetime.timedelta(days = 7)) ) # important tasks elif query=='q:important': tasks = tasks.filter(task_is_important = True) # elif len(query.strip())>0: tasks = tasks.filter(task_name__contains=query) tasks = tasks.filter(tasklabels=labels) #if len(only_labels)>0: tasks = tasks.filter(tasklabels__in=only_labels) #if len(project_labels)>0: tasks = tasks.filter(tasklabels__in=project_labels) # Column sorting order_by = [] tasks = tasks.distinct() if sort!=None: order_by.append(sort) else: order_by.append('task_start_date') order_by.append('task_name') tasks = tasks.order_by(*order_by) clearanceList = ACL.canViewOthersTasks(request.user,labels) for taskIndex, t in enumerate(tasks): users = [] labelUsers = t.task_users.all().distinct() for user in labelUsers: try: a, b = user.first_name[0], user.last_name[0] except: a,b = '','' users.append({ 'user_id': user.pk, 'user_name': user.username, 'user_initials': (a+b).upper(), 'completed_task': t.user==user }) labels=[] for membership in TaskLabelMembership.objects.filter(user=request.user).filter(child__in=t.tasklabels.all()).distinct(): label = membership.child labels.append({ 'id':label.pk, 'label':label.tasklabel_name, 'color': "#%s" % label.tasklabel_color }) #Correct this because of the naive datetime style = 'todo' if t.task_is_complete!=True and t.task_end_date <= timezone.now() else '' #Check user permissions showTask = False if request.user in labelUsers: showTask = True else: for label in t.tasklabels.all(): if label in clearanceList: showTask = True; break if showTask: res['data'].append({ 'task_id': t.task_id, 'task_is_complete': t.task_is_complete, 'task_is_important': t.task_is_important, 'task_is_title': t.task_is_title, 'task_name': t.task_name, 'task_start_date': t.task_start_date, 'task_end_date': t.task_end_date, 'users': users, 'labels': labels, 'style': style }) if sort==None: try: parent = t.task_set.all().earliest('task_start_date') orderkey = parent.task_start_date.strftime('%Y%m%d %H:%M-')+str(parent.pk) orderkey += 'c' if parent.task_is_title else 'a' res['data'][-1]['parentTitle'] = parent.pk if parent.task_is_title else None except Task.DoesNotExist: orderkey = t.task_start_date.strftime('%Y%m%d %H:%M-')+str(t.pk)+'b' res['data'][-1]['parentTitle'] = None res['data'][-1]['order'] = orderkey if sort==None: res['data'] = sorted(res['data'], key=lambda x: x['order']) data = res['data'] for i in range( len(data)-1 ): if data[i]['parentTitle']!=None and data[i]['parentTitle']!=data[i+1]['parentTitle']: data[i]['style'] += ' from-group last-from-group' elif data[i]['parentTitle']!=None and data[i]['parentTitle']==data[i+1]['parentTitle']: data[i]['style'] += ' from-group' except Exception as e: res = { 'status': 'Error', 'message': str(e), } data = json.dumps(res, cls = DjangoJSONEncoder) return HttpResponse(data, content_type = 'application/json')