Beispiel #1
0
def add_task(request, list_id):
    list_object = get_object_or_404(List, id=list_id)

    thedate = datetime.datetime.now()
    created_date = "%s/%s/%s" % (thedate.month, thedate.day, thedate.year)

    if request.POST:
        form = AddItemForm(list_object, request.POST, initial={
            'assigned_to': request.user.id,
            'priority': 999,
        })

        if form.is_valid():
            new_task = form.save()

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            if "notify" in request.POST and new_task.assigned_to != request.user:
                send_notify_mail(request, new_task)

            messages.success(request, "Задачу \"{t}\" було успішно створено!".format(t=new_task.title))
            return HttpResponseRedirect(request.path)
    else:
        form = AddItemForm(list_object, initial={
            'assigned_to': request.user.id,
            'priority': 999,
            'due_date': created_date,
        })
    return render(request, 'todo/add_task.html', locals())
Beispiel #2
0
def test_send_notify_mail_myself(todo_setup, django_user_model, email_backend_setup):
    """Assign a task to myself, no mail should be sent.
    """

    u1 = django_user_model.objects.get(username="******")
    task = Task.objects.filter(created_by=u1).first()
    task.assigned_to = u1
    task.save()
    send_notify_mail(task)
    assert len(mail.outbox) == 0
Beispiel #3
0
def test_send_notify_mail_myself(todo_setup, django_user_model,
                                 email_backend_setup):
    """Assign a task to myself, no mail should be sent.
    """

    u1 = django_user_model.objects.get(username="******")
    task = Task.objects.filter(created_by=u1).first()
    task.assigned_to = u1
    task.save()
    send_notify_mail(task)
    assert len(mail.outbox) == 0
Beispiel #4
0
def test_send_notify_mail_not_me(todo_setup, django_user_model, email_backend_setup):
    """Assign a task to someone else, mail should be sent.
    TODO: Future tests could check for email contents.
    """

    u1 = django_user_model.objects.get(username="******")
    u2 = django_user_model.objects.get(username="******")

    task = Task.objects.filter(created_by=u1).first()
    task.assigned_to = u2
    task.save()
    send_notify_mail(task)
    assert len(mail.outbox) == 1
Beispiel #5
0
def test_send_notify_mail_myself(todo_setup, django_user_model,
                                 email_backend_setup):
    """Assign a task to myself, no mail should be sent.

    Назначьте задачу самому себе, никакая почта не должна отправляться.
    """

    u1 = django_user_model.objects.get(username="******")
    task = Task.objects.filter(created_by=u1).first()
    task.assigned_to = u1
    task.save()
    send_notify_mail(task)
    assert len(mail.outbox) == 0
Beispiel #6
0
def test_send_notify_mail_not_me(todo_setup, django_user_model, email_backend_setup):
    """Assign a task to someone else, mail should be sent.
    TODO: Future tests could check for email contents.
    """

    u1 = django_user_model.objects.get(username="******")
    u2 = django_user_model.objects.get(username="******")

    task = Task.objects.filter(created_by=u1).first()
    task.assigned_to = u2
    task.save()
    send_notify_mail(task)
    assert len(mail.outbox) == 1
Beispiel #7
0
def test_send_notify_mail_not_me(todo_setup, django_user_model,
                                 email_backend_setup):
    """Assign a task to someone else, mail should be sent.
    TODO: Future tests could check for email contents.

    Назначьте задачу кому-то другому, почта должна быть отправлена.
    TODO: Будущие тесты могут проверять содержимое электронной почты.
    """

    u1 = django_user_model.objects.get(username="******")
    u2 = django_user_model.objects.get(username="******")

    task = Task.objects.filter(created_by=u1).first()
    task.assigned_to = u2
    task.save()
    send_notify_mail(task)
    assert len(mail.outbox) == 1
Beispiel #8
0
def list_detail(request,
                list_id=None,
                list_slug=None,
                view_completed=False) -> HttpResponse:
    """Display and manage tasks in a todo list.
    """

    # Defaults
    task_list = None
    form = None

    # Which tasks to show on this list view?
    if list_slug == "mine":
        tasks = Task.objects.filter(assigned_to=request.user)

    else:
        # Show a specific list, ensuring permissions.
        task_list = get_object_or_404(TaskList, id=list_id)
        if task_list.group not in request.user.groups.all(
        ) and not request.user.is_superuser:
            raise PermissionDenied
        tasks = Task.objects.filter(task_list=task_list.id)

    # Additional filtering
    if view_completed:
        tasks = tasks.filter(completed=True)
    else:
        tasks = tasks.filter(completed=False)

    # ######################
    #  Add New Task Form
    # ######################

    if request.POST.getlist("add_edit_task"):
        form = AddEditTaskForm(
            request.user,
            request.POST,
            initial={
                "assigned_to": request.user.id,
                "priority": 999,
                "task_list": task_list
            },
        )

        if form.is_valid():
            new_task = form.save(commit=False)
            new_task.created_by = request.user
            new_task.note = bleach.clean(form.cleaned_data["note"], strip=True)
            form.save()

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            if ("notify" in request.POST and new_task.assigned_to
                    and new_task.assigned_to != request.user):
                send_notify_mail(new_task)

            messages.success(
                request,
                'New task "{t}" has been added.'.format(t=new_task.title))
            return redirect(request.path)
    else:
        # Don't allow adding new tasks on some views
        if list_slug not in ["mine", "recent-add", "recent-complete"]:
            form = AddEditTaskForm(
                request.user,
                initial={
                    "assigned_to": request.user.id,
                    "priority": 999,
                    "task_list": task_list
                },
            )

    context = {
        "list_id": list_id,
        "list_slug": list_slug,
        "task_list": task_list,
        "form": form,
        "tasks": tasks,
        "view_completed": view_completed,
    }

    return render(request, "todo/list_detail.html", context)
Beispiel #9
0
def list_detail(request,
                list_id=None,
                list_slug=None,
                view_completed=False) -> HttpResponse:
    """Display and manage tasks in a todo list.

    Отображение задач и управление ими в списке задач.
    """

    # Defaults
    task_list = None
    form = None

    # Which tasks to show on this list view?
    # Какие задачи отображать в этом представлении списка?
    if list_slug == "mine":
        tasks = Task.objects.filter(assigned_to=request.user)

    else:
        # Show a specific list, ensuring permissions.
        # Показать определенный список, гарантирующий разрешения.
        task_list = get_object_or_404(TaskList, id=list_id)
        if task_list.group not in request.user.groups.all(
        ) and not request.user.is_superuser:
            raise PermissionDenied
        tasks = Task.objects.filter(task_list=task_list.id)

    # Additional filtering
    # Дополнительная фильтрация
    if view_completed:
        tasks = tasks.filter(completed=True)
    else:
        tasks = tasks.filter(completed=False)

    # ######################
    #  Add New Task Form
    # ######################

    if request.POST.getlist("add_edit_task"):
        form = AddEditTaskForm(
            request.user,
            request.POST,
            initial={
                "assigned_to": request.user.id,
                "priority": 999,
                "task_list": task_list
            },
        )

        if form.is_valid():
            new_task = form.save(commit=False)
            new_task.created_by = request.user
            new_task.note = bleach.clean(form.cleaned_data["note"], strip=True)
            form.save()

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            # Отправлять оповещение по электронной почте только в том случае, если установлен флажок Уведомлять
            # и получатель не совпадает с отправителем
            if ("notify" in request.POST and new_task.assigned_to
                    and new_task.assigned_to != request.user):
                send_notify_mail(new_task)

            messages.success(
                request,
                'New task "{t}" has been added.'.format(t=new_task.title))
            return redirect(request.path)
    else:
        # Don't allow adding new tasks on some views
        # Не разрешать добавлять новые задачи в некоторые представления
        if list_slug not in ["mine", "recent-add", "recent-complete"]:
            form = AddEditTaskForm(
                request.user,
                initial={
                    "assigned_to": request.user.id,
                    "priority": 999,
                    "task_list": task_list
                },
            )

    context = {
        "list_id": list_id,
        "list_slug": list_slug,
        "task_list": task_list,
        "form": form,
        "tasks": tasks,
        "view_completed": view_completed,
    }

    return render(request, "todo/list_detail.html", context)
Beispiel #10
0
def list_detail(request,
                list_id=None,
                list_slug=None,
                view_completed=False) -> HttpResponse:

    # Defaults
    completed = False
    book = None
    form = None
    editor_view = False

    editor = Editor.objects.filter(user=request.user).first()
    if editor != None: editor_view = True
    # Which tasks to show on this list view?
    if list_slug == "mine":
        tasks = Task.objects.filter(assigned_to=request.user.user_info)
    else:
        # Show a specific list, ensuring permissions.
        book = get_object_or_404(Book, id=list_id)
        if not user_can_read_book(book, request.user):
            raise PermissionDenied
        tasks = Task.objects.filter(book=book.id)

    # Check if it can be published
    completed = Task.objects.filter(task_type=Task.REVISION,
                                    completed=True).count() > 0

    # Additional filtering
    if view_completed:
        tasks = tasks.filter(completed=True)
    else:
        tasks = tasks.filter(completed=False)

    # ######################
    #  Add New Task Form
    # ######################

    if request.POST.getlist("add_edit_task"):
        form = AddEditTaskForm(
            request.POST,
            initial={
                "priority": 999,
                "book": book
            },
        )

        if form.is_valid():
            new_task = form.save(commit=False)
            new_task.created_by = editor
            if new_task.task_type == Task.WRITING or new_task.task_type == Task.REVISION:
                new_task.assigned_to = UserInfo.objects.filter(
                    user=book.author.user).first()
            new_task.description = bleach.clean(
                form.cleaned_data["description"], strip=True)
            new_task.save()

            send_notify_mail(new_task)

            messages.success(
                request, 'La nueva tarea "{t}" ha sido añadida.'.format(
                    t=new_task.title))
            return redirect(request.path)
        else:
            print(form.errors)

    else:
        # Don't allow adding new tasks on some views
        if list_slug not in ["mine", "recent-add", "recent-complete"]:
            form = AddEditTaskForm(initial={"priority": 999, "book": book}, )

    context = {
        "completed": completed,
        "editor_view": editor_view,
        "list_id": list_id,
        "list_slug": list_slug,
        "book": book,
        "form": form,
        "tasks": tasks,
        "view_completed": view_completed,
    }

    return render(request, "todo/list_detail.html", context)
Beispiel #11
0
def view_list(request, list_id=0, list_slug=None, view_completed=False):
    """
    Display and manage items in a list.
    """

    # Make sure the accessing user has permission to view this list.
    # Always authorize the "mine" view. Admins can view/edit all lists.
    if list_slug == "mine" or list_slug == "recent-add" or list_slug == "recent-complete":
        auth_ok = True
    else:
        list = get_object_or_404(List, id=list_id)
        if list.group in request.user.groups.all(
        ) or request.user.is_staff or list_slug == "mine":
            auth_ok = True
        else:  # User does not belong to the group this list is attached to
            messages.error(
                request, "У вас немає прав на перегляд даної категорії задач")

    # Process all possible list interactions on each submit
    mark_done(request, request.POST.getlist('mark_done'))
    del_tasks(request, request.POST.getlist('del_tasks'))
    undo_completed_task(request, request.POST.getlist('undo_completed_task'))

    thedate = datetime.datetime.now()
    created_date = "%s-%s-%s" % (thedate.year, thedate.month, thedate.day)

    # Get set of items with this list ID, or filter on items assigned to me, or recently added/completed
    if list_slug == "mine":
        task_list = Item.objects.filter(assigned_to=request.user,
                                        completed=False)
        completed_list = Item.objects.filter(assigned_to=request.user,
                                             completed=True)

    elif list_slug == "recent-add":
        # Only show items in lists that are in groups that the current user is also in.
        # Assume this only includes uncompleted items.
        task_list = Item.objects.filter(
            list__group__in=(request.user.groups.all()),
            completed=False).order_by('-created_date')[:50]

    elif list_slug == "recent-complete":
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(
            list__group__in=request.user.groups.all(),
            completed=True).order_by('-completed_date')[:50]

    else:
        task_list = Item.objects.filter(list=list.id, completed=0)
        completed_list = Item.objects.filter(list=list.id, completed=1)

    if request.POST.getlist('add_task'):
        form = AddItemForm(list,
                           request.POST,
                           initial={
                               'assigned_to': request.user.id,
                               'priority': 999,
                           })

        if form.is_valid():
            new_task = form.save()

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            if "notify" in request.POST and new_task.assigned_to != request.user:
                send_notify_mail(request, new_task)

            messages.success(
                request, "Задачу \"{t}\" було успішно створено!".format(
                    t=new_task.title))
            return HttpResponseRedirect(request.path)
    else:
        # Don't allow adding new tasks on some views
        if list_slug != "mine" and list_slug != "recent-add" and list_slug != "recent-complete":
            form = AddItemForm(list,
                               initial={
                                   'assigned_to': request.user.id,
                                   'priority': 999,
                               })

    return render(request, 'todo/view_list.html', locals())
Beispiel #12
0
def view_list(request,
              group_pk=None,
              list_id=0,
              list_slug=None,
              view_completed=False):
    """
    Display and manage items in a list.
    """
    #this list is repeated a lot. lets re-factor somehow
    group = get_object_or_404(models.Group, pk=group_pk)
    familygroup = get_object_or_404(FamilyGroup, group_id=group_pk)
    #list = get_object_or_404(List, group_id=group_pk)
    event = familygroup.event
    members = models.User.objects.filter(groups=group)
    profile = request.user.userprofile
    # Make sure the accessing user has permission to view this list.
    # Always authorize the "mine" view. Admins can view/edit all lists.
    if list_slug == "mine" or list_slug == "recent-add" or list_slug == "recent-complete":
        auth_ok = True
    else:
        list = get_object_or_404(List, id=list_id)
        if list.group in request.user.groups.all(
        ) or request.user.is_staff or list_slug == "mine":
            auth_ok = True
        else:  # User does not belong to the group this list is attached to
            messages.error(
                request, "You do not have permission to view/edit this list.")

    # Process all possible list interactions on each submit
    mark_done(request, request.POST.getlist('mark_done'))
    del_tasks(request, request.POST.getlist('del_tasks'))
    undo_completed_task(request, request.POST.getlist('undo_completed_task'))

    thedate = datetime.datetime.now()
    created_date = "%s-%s-%s" % (thedate.year, thedate.month, thedate.day)

    # Get set of items with this list ID, or filter on items assigned to me, or recently added/completed
    if list_slug == "mine":
        task_list = Item.objects.filter(assigned_to=request.user,
                                        completed=False)
        completed_list = Item.objects.filter(assigned_to=request.user,
                                             completed=True)

    elif list_slug == "recent-add":
        # Only show items in lists that are in groups that the current user is also in.
        # Assume this only includes uncompleted items.
        task_list = Item.objects.filter(
            list__group__in=(request.user.groups.all()),
            completed=False).order_by('-created_date')[:50]

    elif list_slug == "recent-complete":
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(
            list__group__in=request.user.groups.all(),
            completed=True).order_by('-completed_date')[:50]

    else:
        task_list = Item.objects.filter(list=list.id, completed=0)
        completed_list = Item.objects.filter(list=list.id, completed=1)

    if request.POST.getlist('add_task'):
        print('got request')

        form = AddItemForm(list,
                           request.POST,
                           initial={
                               'assigned_to': request.user.id,
                               'priority': 999,
                           })
        print('set form variable')
        print(form.errors)
        print(form.is_valid)

        if form.is_valid():
            form.save()
            print('saved')
            new_task = form.save()

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            if "notify" in request.POST and new_task.assigned_to != request.user:
                send_notify_mail(request, new_task)

            messages.success(
                request,
                "New task \"{t}\" has been added.".format(t=new_task.title))
            return HttpResponseRedirect(request.path)
    else:
        # Don't allow adding new tasks on some views
        if list_slug != "mine" and list_slug != "recent-add" and list_slug != "recent-complete":
            form = AddItemForm(list,
                               initial={
                                   'assigned_to': request.user.id,
                                   'priority': 999,
                               })

    return render(request, 'todo/view_list.html', locals())
Beispiel #13
0
def view_list(request, list_id=0, list_slug=None, view_completed=False):
    """
    Display and manage items in a list.
    """

    # Make sure the accessing user has permission to view this list.
    # Always authorize the "mine" view. Admins can view/edit all lists.
    if list_slug == "mine" or list_slug == "recent-add" or list_slug == "recent-complete":
        auth_ok = True
    else:
        list = get_object_or_404(List, id=list_id)
        if list.group in request.user.groups.all() or request.user.is_staff or list_slug == "mine":
            auth_ok = True
        else:  # User does not belong to the group this list is attached to
            messages.error(request, "You do not have permission to view/edit this list.")

    # Process all possible list interactions on each submit
    mark_done(request, request.POST.getlist('mark_done'))
    del_tasks(request, request.POST.getlist('del_tasks'))
    undo_completed_task(request, request.POST.getlist('undo_completed_task'))

    thedate = datetime.datetime.now()
    created_date = "%s-%s-%s" % (thedate.year, thedate.month, thedate.day)

    # Get set of items with this list ID, or filter on items assigned to me, or recently added/completed
    if list_slug == "mine":
        task_list = Item.objects.filter(assigned_to=request.user, completed=False)
        completed_list = Item.objects.filter(assigned_to=request.user, completed=True)

    elif list_slug == "recent-add":
        # Only show items in lists that are in groups that the current user is also in.
        # Assume this only includes uncompleted items.
        task_list = Item.objects.filter(
            list__group__in=(request.user.groups.all()),
            completed=False).order_by('-created_date')[:50]

    elif list_slug == "recent-complete":
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(
            list__group__in=request.user.groups.all(),
            completed=True).order_by('-completed_date')[:50]

    else:
        task_list = Item.objects.filter(list=list.id, completed=0)
        completed_list = Item.objects.filter(list=list.id, completed=1)

    if request.POST.getlist('add_task'):
        form = AddItemForm(list, request.POST, initial={
            'assigned_to': request.user.id,
            'priority': 999,
        })

        if form.is_valid():
            new_task = form.save()

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            if "notify" in request.POST and new_task.assigned_to != request.user:
                send_notify_mail(request, new_task)

            messages.success(request, "New task \"{t}\" has been added.".format(t=new_task.title))
            return HttpResponseRedirect(request.path)
    else:
        # Don't allow adding new tasks on some views
        if list_slug != "mine" and list_slug != "recent-add" and list_slug != "recent-complete":
            form = AddItemForm(list, initial={
                'assigned_to': request.user.id,
                'priority': 999,
            })

    return render(request, 'todo/view_list.html', locals())
Beispiel #14
0
def list_detail(request,
                list_id=None,
                list_slug=None,
                view_completed=False) -> HttpResponse:
    """Display and manage tasks in a todo list.
    """

    # Defaults
    task_list = None
    form = None

    # Which tasks to show on this list view?
    if list_slug == "mine":
        tasks = Task.objects.filter(is_active=True).filter(
            Q(assigned_to=request.user)
            | Q(assigned_to__isnull=True,
                task_list__group__in=get_user_groups(request.user)))
    else:
        # pai
        #if task_list.group not in get_user_groups(request.user) and not request.user.is_superuser:
        if staff_check(request.user):
            # Show a specific list, ensuring permissions.
            task_list = get_object_or_404(TaskList, id=list_id)

            tasks = task_list.task_set.filter(is_active=True) \
                                      .prefetch_related('created_by', 'assigned_to')
        else:
            # Show a specific list, ensuring permissions.
            task_list = get_object_or_404(TaskList,
                                          id=list_id,
                                          group__in=get_user_groups(
                                              request.user))

            tasks = get_task_list_tasks(task_list, request.user)

    # Additional filtering
    if view_completed:
        tasks = tasks.filter(completed=True)
    else:
        tasks = tasks.filter(completed=False)

    # ######################
    #  Add New Task Form
    # ######################

    if request.POST.getlist("add_edit_task"):
        form = AddEditTaskForm(
            request.user,
            request.POST,
            initial={
                "assigned_to": request.user.id,
                "priority": 999,
                "task_list": task_list
            },
        )

        if form.is_valid():
            new_task = form.save(commit=False)
            new_task.created_by = request.user
            new_task.note = bleach.clean(form.cleaned_data["note"], strip=True)
            form.save()

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            if ("notify" in request.POST and new_task.assigned_to
                    and new_task.assigned_to != request.user
                    and new_task.assigned_to != new_task.created_by):
                send_notify_mail(new_task)

            messages.success(
                request,
                'New task "{t}" has been added.'.format(t=new_task.title))
            return redirect(request.path)
        else:
            pass
    else:
        # Don't allow adding new tasks on some views
        if list_slug not in ["mine", "recent-add", "recent-complete"]:
            form = AddEditTaskForm(
                request.user,
                initial={
                    "assigned_to": request.user.id,
                    "priority": 999,
                    "task_list": task_list
                },
            )

    # Pagination
    paginator = Paginator(tasks, 20)

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        "list_id": list_id,
        "list_slug": list_slug,
        "task_list": task_list,
        "form": form,
        "tasks": tasks,
        "view_completed": view_completed,
        'page_obj': page_obj
    }

    return render(request, "todo/list_detail.html", context)
Beispiel #15
0
def list_detail(request, list_id=None, list_slug=None, view_completed=False) -> HttpResponse:
    """Display and manage tasks in a todo list.
    """

    # Defaults
    task_list = None
    form = None

    # Which tasks to show on this list view?
    if list_slug == "mine":
        tasks = Task.objects.filter(assigned_to=request.user)

    else:
        # Show a specific list, ensuring permissions.
        task_list = get_object_or_404(TaskList, id=list_id)
        if task_list.group not in request.user.groups.all() and not request.user.is_superuser:
            raise PermissionDenied
        tasks = Task.objects.filter(task_list=task_list.id)

    # Additional filtering
    if view_completed:
        tasks = tasks.filter(completed=True)
    else:
        tasks = tasks.filter(completed=False)

    # ######################
    #  Add New Task Form
    # ######################

    if request.POST.getlist("add_edit_task"):
        form = AddEditTaskForm(
            request.user,
            request.POST,
            initial={"assigned_to": request.user.id, "priority": 999, "task_list": task_list},
        )

        if form.is_valid():
            new_task = form.save(commit=False)
            new_task.created_date = timezone.now()
            new_task.note = bleach.clean(form.cleaned_data["note"], strip=True)
            form.save()

            # Send email alert only if Notify checkbox is checked AND assignee is not same as the submitter
            if (
                "notify" in request.POST
                and new_task.assigned_to
                and new_task.assigned_to != request.user
            ):
                send_notify_mail(new_task)

            messages.success(request, 'New task "{t}" has been added.'.format(t=new_task.title))
            return redirect(request.path)
    else:
        # Don't allow adding new tasks on some views
        if list_slug not in ["mine", "recent-add", "recent-complete"]:
            form = AddEditTaskForm(
                request.user,
                initial={"assigned_to": request.user.id, "priority": 999, "task_list": task_list},
            )

    context = {
        "list_id": list_id,
        "list_slug": list_slug,
        "task_list": task_list,
        "form": form,
        "tasks": tasks,
        "view_completed": view_completed,
    }

    return render(request, "todo/list_detail.html", context)