示例#1
0
def forum(request, asset_id):

    errors = []

    # check that the asset ID exists
    # if not a 404 will be thrown
    the_asset = get_object_or_404(Asset, pk=asset_id)

    # ok, so asset exists
    # now check that this user is allowed to view the forum subjects for this asset
    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id):
        # user is linked so fill up the subjects object
        subjects = Subject.objects.all().filter(asset_id=asset_id)

    else:
        # prepare the error message
        errors.append("You are not authorised to view this Forum")
        # set these to empty
        the_asset = []
        subjects = []

    return render(request, 'forum.html', {
        'subjects': subjects,
        'asset': the_asset,
        'errors': errors
    })
示例#2
0
def asset_detail(request, asset_id):

    the_asset = []
    errors = []
    asset_form = []

    #check asset exists
    the_asset = get_object_or_404(Asset, pk=asset_id)

    # check if the user is allowed to view this asset
    my_id = request.user

    is_linked = check_user_linked_to_asset(request.user, asset_id)
    if is_linked == False:

        errors.append("You do not have permission to view this page")

    is_an_owner = assets_extras.is_user_also_owner(request.user, asset_id)
    if is_an_owner == False:

        errors.append("Access restricted")

    return render(request, "assets/asset_detail.html", {
        "asset": the_asset,
        "errors": errors
    })
示例#3
0
def post_detail(request, asset_id, id):

    errors = []
    show_edit = False  # defaults to False

    # this view is of one post
    # need to check user is authorised to view it
    # and if they are the AUTHOR, they will see an edit button

    #  first check does the post exist?
    if blog_post_exists(asset_id, id) == False:

        errors.append("This page does not exist")
        post = []
        the_asset = []

    else:
        # it does exist
        post = Post.objects.get(id=id, asset_ID_id=asset_id)
        the_asset = get_object_or_404(Asset, pk=asset_id)

        # but now check that this user is allowed to view posts for this asset
        my_id = request.user

        if check_user_linked_to_asset(my_id, asset_id) == False:

            # prepare the error message
            errors.append("You are not authorised to view this Post")
            # set these to empty
            the_asset = []
            post = []

        else:
            # it can be viewed so update the counter
            post.num_views += 1
            post.save()

            #is this person the author?
            if check_user_linked_to_blog_post(my_id, asset_id, id):
                show_edit = True

    return render(
        request, "postdetail.html", {
            'post': post,
            'asset': the_asset,
            'errors': errors,
            'asset_id': asset_id,
            'post_id': id,
            'show_edit': show_edit
        })
示例#4
0
def delete_post(request, asset_id, subject_id, thread_id, post_id):

    errors = []
    post = get_object_or_404(Post, pk=post_id)
    thread = get_object_or_404(Thread, pk=thread_id)
    subject = get_object_or_404(Subject, pk=subject_id)
    the_asset = get_object_or_404(Asset, pk=asset_id)

    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id) == False:
        errors.append("You are not authorised to view to this Forum")
        post = []
        thread = []
        subject = []
        the_asset = []

    elif check_subject_exists(asset_id, subject_id) == False:
        errors.append("Sorry this Subject does not exist in this Forum")
        post = []
        thread = []
        subject = []
        the_asset = []

    elif check_thread_exists(subject_id, thread_id) == False:
        errors.append("Thread does not exist")
        post = []
        thread = []
        subject = []
        the_asset = []

    elif check_user_linked_to_forum_post(my_id, post_id) == False:
        errors.append("You are not authorised to edit this Post")
        post = []
        thread = []
        subject = []
        the_asset = []

    else:
        post.delete()

        messages.success(request, "This Post has been deleted")

        return redirect(
            reverse('thread',
                    kwargs={
                        "asset_id": asset_id,
                        "subject_id": subject_id,
                        "thread_id": thread_id
                    }))
示例#5
0
def new_blog_post(request, asset_id):
    errors = []
    the_asset = get_object_or_404(Asset, pk=asset_id)
    form = []
    content_error = ""

    # asset exists, now check user
    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id) == False:
        # user is linked so fill up the posts object
        errors.append("You are not authorised to post on this Blog")
        the_asset = []

    else:
        # check POST or GET
        if request.method == "POST":

            form = BlogPostForm(request.POST, request.FILES)
            if form.is_valid():
                # before saving check the content of the content field
                if len(form.cleaned_data['content']) == 0:
                    # check if content is blank. HTML Field has to be set to required == False
                    # so that the form can submit (to do with the browser trying to focus on the element and not seeing it
                    # so it's possible that it's blank
                    form = BlogPostForm(request.POST)
                    content_error = "Please don't save your new post without some content!"

                else:
                    post = form.save(commit=False)
                    post.author = request.user
                    post.published_date = timezone.now()
                    post.asset_ID_id = asset_id
                    post.save()
                    return redirect(post_detail, asset_id, post.pk)

        else:
            form = BlogPostForm()

    args = {
        'errors': errors,
        'asset': the_asset,
        'form': form,
        'content_error': content_error
    }
    args.update(csrf(request))

    return render(request, 'blogpostform.html', args)
示例#6
0
def asset_detail(request, asset_id):

    the_asset = get_object_or_404(Asset, pk=asset_id)

    errors = []

    # check if the user is allowed to view this asset
    my_id = request.user

    if check_user_linked_to_asset(my_id, asset_id) == False:
        the_asset = []
        errors.append("You are not authorised to view this page")

    return render(request, "asset_detail.html", {
        "asset": the_asset,
        "errors": errors
    })
示例#7
0
def post_list(request, asset_id):

    # this view will return the posts for the given asset_id
    # posts will be ordered by most recent first and
    # only posts with pub date from current date or before

    errors = []

    # check that the asset ID exists
    # if not a 404 will be thrown
    the_asset = get_object_or_404(Asset, pk=asset_id)

    # ok, so asset exists
    # now check that this user is allowed to view posts for this asset
    my_id = request.user

    #if check_user_linked_to_asset(my_id, asset_id):
    if check_user_linked_to_asset(my_id, asset_id):
        # user is linked so fill up the posts object
        posts = Post.objects.filter(
            asset_ID=asset_id,
            published_date__lte=timezone.now()).order_by('-published_date')

    else:
        # prepare the error message
        errors.append("You are not authorised to view this Blog")
        # set these to empty
        the_asset = []
        posts = []

    # save this current asset_id in sessions
    # over-writing what's save already
    request.session['current_asset_id'] = asset_id

    num_linked_assets = request.session['linked_assets']
    j = json.loads(num_linked_assets)

    return render(
        request, "blogposts.html", {
            'posts': posts,
            'asset': the_asset,
            'errors': errors,
            'num_linked_assets': j
        })
示例#8
0
def delete_blog_post(request, asset_id, id):
    errors = []
    content_error = ""
    form = []
    the_asset = []

    #  first check does the post exist?
    if blog_post_exists(asset_id, id) == False:

        errors.append("This page does not exist")

    else:
        # it does exist
        post = Post.objects.get(id=id, asset_ID_id=asset_id)
        the_asset = get_object_or_404(Asset, pk=asset_id)

        # but now check that this user is allowed to view posts for this asset
        my_id = request.user

        if check_user_linked_to_asset(my_id, asset_id) == False:
            # prepare the error message
            errors.append("You are not authorised to delete this Post")
            # set these to empty
            the_asset = []

        # and finally check if the user is the one who CREATED this post
        # only they should be allowed to delete (or the staff)

        if check_user_linked_to_blog_post(my_id, asset_id, id) == False:
            if not request.user.is_staff:
                messages.error(request,
                               "You are not authorised to delete this Post")
                # set these to empty
                the_asset = []

                return redirect(post_detail, asset_id, id)

        post.delete()

        messages.success(request, "This Blog entry has been deleted")

        return redirect(reverse('post_list', kwargs={"asset_id": asset_id}))
示例#9
0
def asset_exception_detail2(request,
                            asset_id,
                            the_year=0,
                            the_month=0,
                            the_day=0):

    the_asset = get_object_or_404(Asset, id=asset_id)
    errors = []
    user_ok = False

    the_year = 2020
    the_month = 6
    the_day = 17

    if check_user_linked_to_asset(request.user, asset_id):

        if assets_extras.is_user_also_owner(request.user, asset_id):

            user_ok = True

        else:

            errors.append("Restricted Access")
            messages.add_message(request, messages.ERROR, "Restricted Access")
            user_ok = False

    else:

        errors.append("You are not authorised to view this page")
        messages.add_message(request, messages.ERROR,
                             "You are not authorised to view this page")
        user_ok = False

    if user_ok:

        True

    return render(request, "assets/asset_exception_date.html", {
        "the_asset": the_asset,
        "errors": errors,
        'user_ok': user_ok
    })
示例#10
0
def thread(request, asset_id, subject_id, thread_id):

    # this view shows the one thread only
    errors = []
    content_error = ""
    thread = get_object_or_404(Thread, pk=thread_id)
    subject = get_object_or_404(Subject, pk=subject_id)
    the_asset = get_object_or_404(Asset, pk=asset_id)

    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id) == False:
        errors.append("You are not authorised to view to this Forum")
        thread = []
        subject = []
        the_asset = []

    if check_subject_exists(asset_id, subject_id) == False:
        errors.append("Sorry this Subject does not exist in this Forum")
        thread = []
        subject = []
        the_asset = []

    if check_thread_exists(subject_id, thread_id) == False:
        errors.append("Thread does not exist")
        thread = []
        subject = []
        the_asset = []
    else:
        # it can be viewed so update the counter
        thread.num_views += 1
        thread.save()

    args = {
        'thread': thread,
        'errors': errors,
        'subject': subject,
        'asset': the_asset,
    }
    args.update(csrf(request))

    return render(request, 'thread.html', args)
示例#11
0
def threads(request, asset_id, subject_id):

    # this view shows all threads for a given subject
    errors = []
    subject = get_object_or_404(Subject, pk=subject_id)
    the_asset = get_object_or_404(Asset, pk=asset_id)

    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id) == False:
        errors.append("You are not authorised to view this Forum")
        subject = []
        the_asset = []

    if check_subject_exists(asset_id, subject_id) == False:
        errors.append("Sorry this Subject does not exist in this Forum")
        subject = []
        the_asset = []

    return render(request, "threads.html", {
        'subject': subject,
        'asset': the_asset,
        'errors': errors
    })
示例#12
0
def booking_detail_BEFORE_FORMS(request, booking_id, new=""):
    the_booking = get_object_or_404(Booking, pk=booking_id)
    errors = []
    asset = []
    booking_detail = []
    if new != "new":
        new = ""

    # get the asset id (from the booking)
    asset_id = the_booking.asset_ID_id

    # anyone linked to the Asset can view the booking
    # but only the requestor can edit the booking (once it is a Confirmed Booking)
    # only the Owner can edit the booking (while it is in Pending mode)
    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id):

        # check the status of the overall booking
        booking_pending = is_booking_pending(booking_id)
        booking_confirmed = is_booking_confirmed(booking_id)

        asset = Asset.objects.get(pk=asset_id)
        booking_detail = BookingDetail.objects.select_related().filter(
            booking_id_id=booking_id).order_by("booking_date")

    else:
        errors.append("You are not authorised to view this booking")

    return render(
        request, "booking_detail.html", {
            "booking": the_booking,
            "booking_detail": booking_detail,
            "asset": asset,
            "errors": errors,
            "new": new
        })
示例#13
0
def edit_blog_post(request, asset_id, id):

    errors = []
    content_error = ""
    form = []
    the_asset = []

    #  first check does the post exist?
    if blog_post_exists(asset_id, id) == False:

        errors.append("This page does not exist")

    else:
        # it does exist
        post = Post.objects.get(id=id, asset_ID_id=asset_id)
        the_asset = get_object_or_404(Asset, pk=asset_id)

        # but now check that this user is allowed to view posts for this asset
        my_id = request.user

        if check_user_linked_to_asset(my_id, asset_id) == False:
            # prepare the error message
            errors.append("You are not authorised to edit this Post")
            # set these to empty
            the_asset = []

        # and finally check if the user is the one who CREATED this post
        # only they should be allowed to edit (or the staff)

        if check_user_linked_to_blog_post(
                my_id, asset_id,
                id) == False and request.user.is_staff == False:
            errors.append("You are not authorised to edit this Post")
            # set these to empty
            the_asset = []

        if request.method == "POST":
            form = BlogPostForm(request.POST, request.FILES, instance=post)

            if form.is_valid():
                if len(form.cleaned_data['content']) == 0:
                    # check if content is blank. HTML Field has to be set to required == False
                    # so that the form can submit (to do with the browser trying to focus on the element and not seeing it
                    # so it's possible that it's blank
                    post = Post.objects.get(id=id, asset_ID_id=asset_id)
                    form = BlogPostForm(instance=post)
                    content_error = "Please don't save a your post without some content!"

                else:

                    post = form.save(commit=False)
                    post.author = request.user
                    post.last_edited_date = timezone.now()
                    post.asset_ID_id = asset_id
                    post.save()
                    return redirect(post_detail, asset_id, post.pk)

        else:
            form = BlogPostForm(instance=post)

    args = {
        'errors': errors,
        'asset': the_asset,
        'form': form,
        'content_error': content_error
    }
    args.update(csrf(request))

    return render(request, 'blogpostform.html', args)
示例#14
0
def delete_a_member(request, asset_id, member_id):

    code_message = ""
    errors = []
    #check asset exists
    the_asset = get_object_or_404(Asset, id=asset_id)

    #check if the current user is the same as the member_id
    #no one can delete a user/mapping except the user themselves
    #owners can 'deactivate' members only

    if not member_id == request.user.id:

        code_message = "You are not authorised to do this"
        messages.add_message(request, messages.ERROR, code_message)
        errors.append("You are not authorised to do this")

    else:
        #check if the member id is linked to this asset
        member_linked = check_user_linked_to_asset(member_id, asset_id)

        if member_linked:

            the_member = Asset_User_Mapping.objects.get(asset_ID=asset_id,
                                                        user_ID=member_id)

            if request.method == "POST":

                #user has confirmed
                the_member.delete()
                #delete all bookings for that user
                Booking.objects.filter(
                    asset_ID=asset_id,
                    requested_by_user_ID=member_id).delete()

                messages.add_message(
                    request, messages.SUCCESS, "You have been removed from " +
                    the_asset.asset_display_name)
                return redirect('my_details')

            else:

                return render(request,
                              "assets/asset_user_mapping_confirm_delete.html",
                              {
                                  "asset_mapping": the_member,
                                  "asset": the_asset
                              })

        else:

            code_message = "This is not a valid membership ID"
            messages.add_message(request, messages.ERROR, code_message)

            return render(request, "assets/asset_user_mapping_detail.html",
                          {"asset": the_asset})

    return render(request, "assets/asset_user_mapping_detail.html", {
        "asset": the_asset,
        "errors": errors
    })
示例#15
0
def edit_post(request, asset_id, subject_id, thread_id, post_id):
    # this sends user to the post_form.html mentioned in the new_post view (for editing)
    # and to thread.html for viewing after editing
    errors = []
    content_error = ""
    post = get_object_or_404(Post, pk=post_id)
    thread = get_object_or_404(Thread, pk=thread_id)
    subject = get_object_or_404(Subject, pk=subject_id)
    the_asset = get_object_or_404(Asset, pk=asset_id)
    form = PostForm(instance=post)

    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id) == False:
        errors.append("You are not authorised to view to this Forum")
        post = []
        thread = []
        subject = []
        the_asset = []

    elif check_subject_exists(asset_id, subject_id) == False:
        errors.append("Sorry this Subject does not exist in this Forum")
        post = []
        thread = []
        subject = []
        the_asset = []

    elif check_thread_exists(subject_id, thread_id) == False:
        errors.append("Thread does not exist")
        post = []
        thread = []
        subject = []
        the_asset = []

    elif check_user_linked_to_forum_post(my_id, post_id) == False:
        if not request.user.is_staff:
            errors.append("You are not authorised to edit this Post")
            post = []
            thread = []
            subject = []
            the_asset = []

    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            # before saving check the content of the comment field
            if len(form.cleaned_data['comment']) == 0:
                post = get_object_or_404(Post, pk=post_id)
                form = PostForm(instance=post)
                content_error = "Please don't save a blank post!"
            else:
                form.save()
                messages.success(request, "This Post has been updated")

                return redirect(
                    reverse('thread',
                            kwargs={
                                "asset_id": asset_id,
                                "subject_id": subject_id,
                                "thread_id": thread.pk
                            }))

    else:
        form = PostForm(instance=post)

    args = {
        'thread':
        thread,
        'errors':
        errors,
        'subject':
        subject,
        'asset':
        the_asset,
        'form':
        form,
        'form_action':
        reverse('edit_post',
                kwargs={
                    'asset_id': asset_id,
                    "subject_id": subject_id,
                    "thread_id": thread_id,
                    "post_id": post_id
                }),
        'button_text':
        "Update Post",
        'content_error':
        content_error,
    }
    args.update(csrf(request))

    return render(request, 'post_form.html', args)
示例#16
0
def new_post(request, asset_id, subject_id, thread_id):

    # this view allows the user to add a post to a thread
    errors = []
    content_error = ""
    thread = get_object_or_404(Thread, pk=thread_id)
    subject = get_object_or_404(Subject, pk=subject_id)
    the_asset = get_object_or_404(Asset, pk=asset_id)
    # set this here so that it is assigned
    form = PostForm()

    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id) == False:
        errors.append("You are not authorised to view to this Forum")
        thread = []
        subject = []
        the_asset = []

    elif check_subject_exists(asset_id, subject_id) == False:
        errors.append("Sorry this Subject does not exist in this Forum")
        thread = []
        subject = []
        the_asset = []

    elif check_thread_exists(subject_id, thread_id) == False:
        errors.append("Thread does not exist")
        thread = []
        subject = []
        the_asset = []

    else:
        if request.method == "POST":
            form = PostForm(request.POST)
            if form.is_valid():

                # before saving check the content of the comment field
                if len(form.cleaned_data['comment']) == 0:
                    form = PostForm(request.POST)
                    content_error = "Please don't save a blank post!"
                else:
                    post = form.save(False)
                    post.thread = thread
                    post.user = request.user
                    post.save()

                    messages.success(
                        request,
                        "Your post has been added to %s" % thread.name)

                    return redirect(
                        reverse('thread',
                                kwargs={
                                    "asset_id": asset_id,
                                    "subject_id": subject_id,
                                    "thread_id": thread.pk
                                }))

            else:
                form = PostForm()

    args = {
        'thread':
        thread,
        'errors':
        errors,
        'subject':
        subject,
        'asset':
        the_asset,
        'form':
        form,
        'form_action':
        reverse('new_post',
                kwargs={
                    "asset_id": asset_id,
                    "subject_id": subject_id,
                    "thread_id": thread.id
                }),
        'button_text':
        "Update Post",
        'content_error':
        content_error,
    }
    args.update(csrf(request))

    return render(request, 'post_form.html', args)
示例#17
0
def asset_exception_detail(request, asset_id):

    # this function is called when user wants to add or edit an exception on the date provided
    # the exception date (year, month, day) should be in the session
    # if not then send the user back to re-select

    the_asset = []
    the_exception = []
    errors = []
    asset_exception_form = []
    user_ok = False
    the_values = ""
    exception_date = ""
    is_a_weekday = False

    #check asset exists
    the_asset = get_object_or_404(Asset, pk=asset_id)

    # check if the user is allowed to view this asset
    my_id = request.user

    if check_user_linked_to_asset(request.user, asset_id):

        if assets_extras.is_user_also_owner(request.user, asset_id):

            user_ok = True

        else:

            errors.append("Access restricted")
            user_ok = False

    else:

        errors.append("You do not have permission to view this page")
        user_ok = False

    if user_ok:

        #sessions variables must exist

        #variables from the session
        if 'exception_year_cal' in request.session:
            year = (request.session['exception_year_cal'])

        if 'exception_month_cal' in request.session:
            month = (request.session['exception_month_cal'])

        if 'exception_day_cal' in request.session:
            day = (request.session['exception_day_cal'])

        try:
            #create the datetime object from the given parameters
            the_values = "%s - %s - %s" % (year, month, day)
            exception_date = datetime.date(int(year), int(month), int(day))
            show_date_format = exception_date.strftime("%A, %d %B")
            is_a_weekday = booking_extras.is_date_a_weekday(exception_date)

        except:

            code_message = "There was a problem with the date. Please re-select from the calendar and try again." + the_values
            messages.add_message(request, messages.ERROR, code_message)
            return redirect(
                reverse_lazy('venue_calendar_admin',
                             kwargs={"asset_id": the_asset.id}))

        else:

            #check if the exception exists
            exception_record = assets_extras.get_exception_record(
                the_asset.id, exception_date)

            if request.method == "POST":

                if exception_record:
                    #include initial data so new content can be checked
                    #against existing bookings
                    form = AssetExceptionForm(request.POST,
                                              initial=exception_record)

                else:
                    #no initial data so brand new exception
                    form = AssetExceptionForm(request.POST)

                if form.is_valid():

                    cd = form.cleaned_data
                    pass

            else:

                if exception_record:

                    form = AssetExceptionForm(inital=exception_record)

                else:

                    form = AssetExceptionForm(
                        initial={
                            'the_date': show_date_format,
                            'day': day,
                            'year': year,
                            'month': month
                        })

    return render(
        request, "assets/asset_exception_date.html", {
            "asset": the_asset,
            "errors": errors,
            "user_ok": user_ok,
            "form": form,
            "the_date": show_date_format,
            "is_a_weekday": is_a_weekday
        })
示例#18
0
def new_thread(request, asset_id, subject_id):

    errors = []
    content_error = ""
    subject = get_object_or_404(Subject, pk=subject_id)
    the_asset = get_object_or_404(Asset, pk=asset_id)

    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id) == False:
        errors.append("You are not authorised to add to this Forum")
        subject = []
        the_asset = []

    elif check_subject_exists(asset_id, subject_id) == False:
        errors.append("Sorry this Subject does not exist in this Forum")
        subject = []
        the_asset = []

    else:

        if request.method == "POST":
            thread_form = ThreadForm(request.POST)
            post_form = PostForm(request.POST)

            if thread_form.is_valid() and post_form.is_valid():

                # before saving check the content of the comment field
                if len(post_form.cleaned_data['comment']) == 0:
                    thread_form = ThreadForm(request.POST)
                    post_form = PostForm(request.POST)
                    content_error = "Please don't save your new thread without posting a starting comment!"

                else:
                    thread = thread_form.save(False)
                    thread.subject = subject
                    thread.user = request.user
                    thread.save()

                    post = post_form.save(False)
                    post.user = request.user
                    post.thread = thread
                    post.save()

                    messages.success(request, "Thanks for your new Thread")

                    return redirect(
                        reverse('thread',
                                kwargs={
                                    "asset_id": asset_id,
                                    "subject_id": subject_id,
                                    "thread_id": thread.pk
                                }))

        else:
            thread_form = ThreadForm()
            post_form = PostForm(request.POST)

    args = {
        'thread_form': thread_form,
        'post_form': post_form,
        'subject': subject,
        'asset': the_asset,
        'errors': errors,
        'content_error': content_error
    }
    args.update(csrf(request))

    return render(request, 'thread_form.html', args)
示例#19
0
def make_a_booking(request, asset_id):

    the_asset = get_object_or_404(Asset, pk=asset_id)
    errors = []
    owner_date_object = []
    total_days_requested = 0
    booking_form = []
    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id):
        user_ok = True
    else:
        user_ok = False
        errors.append("You are not authorised to view this page")

    if request.method == "POST":
        new_booking_form = BookingForm(request.POST)
        if new_booking_form.is_valid():

            # check if the user has a stripe_id registered and if not point them to register their credit card
            if is_user_stripe_registered(my_id):
                # save it in memory while getting the addition info need to save it to the database
                new_booking = new_booking_form.save(False)
                # get additional info
                new_booking.asset_ID_id = asset_id
                new_booking.requested_by_user_ID = request.user
                # then save
                new_booking.save()

                # now, using the new_booking.pk, save each of the dates in BookingDetail
                new_id = new_booking.pk

                start_date = request.POST['start_date']
                start_date = datetime.datetime.strptime(
                    start_date, '%m/%d/%Y').date()
                end_date = request.POST['end_date']
                end_date = datetime.datetime.strptime(end_date,
                                                      '%m/%d/%Y').date()
                owner_date_object = get_owners_and_dates(
                    asset_id, start_date, end_date)

                print "object count is %s" % len(owner_date_object)

                for item in owner_date_object:

                    owner_id = item.owner_id
                    print "ownerId: %s" % owner_id
                    print "current user: %s" % request.user.id

                    print "the Detail: %s" % item.date_span_available_detail
                    for available_date in item.date_span_available_detail:
                        booking_date = available_date

                        # check if the owner is booking one of their own dates
                        # if so, then set immediately to is_confirmed == True
                        if owner_id == request.user.id:

                            new_record = BookingDetail(
                                booking_date=booking_date,
                                slot_owner_id_id=owner_id,
                                booking_id_id=new_id,
                                is_approved=True,
                                date_approved=timezone.now())
                        else:

                            new_record = BookingDetail(
                                booking_date=booking_date,
                                slot_owner_id_id=owner_id,
                                booking_id_id=new_id,
                                is_pending=True)

                        new_record.save()
                        new = "new"
                # messages.success(request, "New Booking created, thanks")
                return redirect(
                    reverse('booking_detail',
                            kwargs={
                                "booking_id": new_booking.pk,
                                "new": new
                            }))

            else:
                request.session['asset_id_for_stripe'] = asset_id
                request.session['start_date_for_stripe'] = request.POST[
                    'start_date']
                request.session['end_date_for_stripe'] = request.POST[
                    'end_date']
                return redirect(reverse('register_stripe'))

    else:

        #request.method is GET,
        #check which stage of get
        if 'start_date' in request.GET:
            new_booking_form = BookingForm(request.GET)
            if new_booking_form.is_valid():
                start_date = request.GET['start_date']
                start_date = datetime.datetime.strptime(
                    start_date, '%m/%d/%Y').date()

                if 'end_date' in request.GET:
                    end_date = request.GET['end_date']
                    end_date = datetime.datetime.strptime(
                        end_date, '%m/%d/%Y').date()

                if end_date.toordinal() - start_date.toordinal() < 0:
                    errors.append(
                        'Your end date is earlier than your start date - please correct!'
                    )

                    new_booking_form = BookingForm(request.GET)

                elif end_date.toordinal() == start_date.toordinal():
                    errors.append(
                        'Your start and end dates are the same - please correct!'
                    )

                    new_booking_form = BookingForm(request.GET)

                elif end_date.toordinal() - start_date.toordinal() > 60:
                    errors.append(
                        'You cannot request more than 60 days at a time!')

                    new_booking_form = BookingForm(request.GET)

                else:
                    # dates are fine (unless I programme more validation) so now continue with
                    # displaying the ownership for the date range!
                    print "Data to function: %s %s %s" % (asset_id, start_date,
                                                          end_date)
                    owner_date_object = get_owners_and_dates(
                        asset_id, start_date, end_date)

                    new_booking_form = BookingForm(request.GET)
            else:

                new_booking_form = BookingForm(request.GET)
        else:
            # this is first time so just display the form
            new_booking_form = BookingForm()

    args = {
        'booking_form': new_booking_form,
        'the_asset': the_asset,
        'errors': errors,
        'owner_date_object': owner_date_object,
        'user_ok': user_ok,
    }

    args.update(csrf(request))

    return render(request, "new_booking.html", args)
示例#20
0
def all_asset_bookings(request,
                       asset_id,
                       user_id=0,
                       time_period="all",
                       status="all",
                       owner_id=0):

    # this function returns all the bookings for an asset
    # can provide optional arg with the user id which will return bookings for a particular user only
    # can provide optional arg to return bookings of a particular time period only (future or past)

    # based on the inputs, the page_desc is decided
    page_desc = ""
    the_asset = get_object_or_404(Asset, pk=asset_id)
    this_user_only = False
    time_range = ""
    errors = []
    the_owner = 0
    my_page_display = False

    if request.user.id == int(user_id):
        this_user_only = True
        my_page_display = True

    time_range = time_period

    if time_range != "future" and time_range != "past":
        time_range = ""

    if len(time_range) > 0:
        page_desc = "%s %s" % (page_desc, time_range.capitalize())

    if status == "pending":
        is_pending = True
        is_confirmed = False
        page_desc = "%s %s" % (page_desc, "Pending Requests")
    elif status == "confirming":
        is_confirmed = False
        is_pending = False
        page_desc = "%s %s" % (page_desc, "Requests to be Confirmed")
    elif status == "confirmed":
        is_confirmed = True
        is_pending = False
        page_desc = "%s %s" % (page_desc, "Confirmed Bookings")
    else:
        is_confirmed = ""
        is_pending = ""
        page_desc = "%s %s" % (page_desc, "Bookings")

    if owner_id > 0:
        # an owner_id has been supplied
        # check if this user is linked to this owner
        if check_user_linked_to_owner(request.user, owner_id, asset_id):
            the_owner = owner_id
            the_owner_display_name = get_owner_name_for_user_id_and_asset(
                asset_id, user_id, first_name_only=True)
            page_desc = "%s %s %s" % (page_desc, "to be approved by ",
                                      the_owner_display_name)
            my_page_display = False
        else:
            the_owner = 0

    my_id = request.user
    if check_user_linked_to_asset(my_id, asset_id):

        # optional userID
        if this_user_only:

            all_bookings = get_bookings(asset_id=asset_id,
                                        user_id=request.user.id,
                                        time_period=time_range,
                                        pending=is_pending,
                                        confirming=is_confirmed,
                                        owner_id=the_owner)

        else:

            all_bookings = get_bookings(asset_id=asset_id,
                                        time_period=time_range,
                                        pending=is_pending,
                                        confirming=is_confirmed,
                                        owner_id=the_owner)

    else:
        the_asset = []
        all_bookings = []
        errors.append("You are not authorised to view this Bookings page")

    return render(
        request, "all_bookings.html", {
            "asset": the_asset,
            "bookings": all_bookings,
            "errors": errors,
            "return_page_user": my_page_display,
            "page_name": page_desc
        })
示例#21
0
def my_bookings(request, **kwargs):

    #set all initial values regardless of kwargs

    #start with who has requested this page
    #all bookings returned are requested by this user
    #it doesn't matter if the user is the owner - they will see what all other members see
    #(if they are the owner they can view it through my_venue_bookings view to get special owner view)

    my_id = request.user.id

    booking_requested_by = 0
    errors = []
    booking_id = 0
    booked_date = ""
    asset_id = 0
    the_asset = []
    time_period = "future"  #assume future always unless provided
    future_bookings = []
    past_bookings = []
    num_bookings_future = 0
    num_bookings_past = 0

    # get all bookings for the request.user

    if 'booking_id' in kwargs:
        booking_id = kwargs['booking_id']
        booked_date = get_booking_date(booking_id)

    # used in query - search for all bookings for this particular asset/venue
    # checks the id of the person who called this query to make sure they are linked to it
    if 'asset_id' in kwargs:
        asset_id = kwargs['asset_id']

        #does asset exist?
        the_asset = get_object_or_404(Asset, id=asset_id)

        #is the requestor linked to this asset?
        is_linked = check_user_linked_to_asset(my_id, asset_id)

        #is the requestor activated?
        is_activated = check_user_activated(my_id, asset_id)

        if not is_linked:
            errors.append("You are not authorised to view this Bookings page")

        if not is_activated:
            errors.append("Account deactivated")
    else:

        errors.append("Please provide the Venue details")

    if not errors:
        # used in query - search for all bookings past or future from now
        # time period can be either: 'past' or 'future'
        if 'time_period' in kwargs:
            time_period = kwargs['time_period']

        if len(errors) == 0:

            # if no time_period is provided then this view must return two record sets (past AND future)
            # if time_period is 'past' or 'future', then this view returns just one record set

            if time_period == "future":

                # this is all FUTURE bookings  (>=today and >current time)
                future_bookings = get_bookings(user_id=my_id,
                                               time_period=time_period,
                                               asset_id=asset_id)
                num_bookings_future = len(future_bookings)

            elif time_period == "past":

                # this is all PAST bookings  (<=today and <current_time)
                past_bookings = get_bookings(user_id=my_id,
                                             time_period=time_period,
                                             asset_id=asset_id)
                num_bookings_past = len(past_bookings)

            else:

                #this is ALL bookings (but still in separate past/future objects)
                future_bookings = get_bookings(user_id=my_id,
                                               time_period="future",
                                               asset_id=asset_id)
                num_bookings_future = len(future_bookings)

                past_bookings = get_bookings(user_id=my_id,
                                             time_period="past",
                                             asset_id=asset_id)
                num_bookings_past = len(past_bookings)

    return render(
        request, "booking/bookings.html", {
            "future_bookings": future_bookings,
            "num_bookings_future": num_bookings_future,
            "past_bookings": past_bookings,
            "num_bookings_past": num_bookings_past,
            "booking_id_to_highlight": booking_id,
            "booked_date_to_highlight": booked_date,
            "the_asset": the_asset,
            "errors": errors
        })
示例#22
0
def booking_detail(request, booking_id, new=""):

    # this view shows the booking in detail, a list of all the dates in the booking
    # with a summary on top

    # depending on the booking status and the user who is viewing, the view can return
    # a formset which allows the user to edit the booking or returns just a record set for display

    the_booking = get_object_or_404(Booking, pk=booking_id)
    errors = []
    asset = []
    booking_detail = []
    # this 'new' is here to indicate that we got to this page from entering a NEW BOOKING REQUEST
    # it will determine the link to show
    if new != "new":
        new = ""

    # set these to False to start with
    booking_pending = False
    booking_confirmed = False
    user_is_requestor = False
    user_is_owner = False
    booking_in_future = False
    include_delete_booking_button = False

    # set the formsets to empty to start with
    formset_owner = []
    formset_requestor_to_confirm = []
    formset_requestor_confirmed_or_pending = []

    # get the asset id (from the booking)
    asset_id = the_booking.asset_ID_id

    # anyone linked to the Asset can view the booking
    # but only the requestor can edit the booking (once it is a Confirmed Booking)
    # only the Owner can edit the booking (while it is in Pending mode)
    my_id = request.user

    if check_user_linked_to_asset(my_id, asset_id):

        asset = Asset.objects.get(pk=asset_id)
        #this booking_detail will get returned if no editing is needed on this booking
        booking_detail = BookingDetail.objects.select_related().filter(
            booking_id_id=booking_id).order_by("booking_date")

        # check the status of the overall booking
        booking_pending = is_booking_pending(booking_id)
        booking_confirmed = is_booking_confirmed(booking_id)

        # check if this is a future booking
        # if not, then display page without any forms regardless of who is looking at it
        if get_booking_end_date(booking_id) > datetime.date.today():
            booking_in_future = True

        # check the status of the user_id
        # are they the original requestor or an owner of this asset?
        is_requestor = get_booking_requestor(booking_id, return_id=True)
        if is_requestor == request.user.id:
            user_is_requestor = True
        user_is_owner = check_if_user_is_an_owner(my_id, asset_id)

        # depending on the above checks, show the booking detail with different formsets
        if (user_is_owner or user_is_requestor) and booking_in_future:

            # REQUESTOR OR OWNER AND FUTURE BOOKING
            # so check further
            if user_is_requestor:

                # USER IS REQUESTOR
                print "User is the Requestor"

                if booking_confirmed or booking_pending:

                    print "booking is confirmed or pending"
                    # the form only needs to give the Requestor the option to delete individual dates when it is a
                    # confirmed booking or a pending booking
                    # also gives option to delete the ENTIRE booking

                    include_delete_booking_button = True

                    BookingDetailFormSet = modelformset_factory(
                        BookingDetail,
                        form=
                        BookingDetailForm_for_Requestor_Confirmed_or_Pending,
                        max_num=1,
                        can_delete=True)

                    booking_detail_for_requestor = BookingDetail.objects.select_related(
                    ).filter(booking_id_id=booking_id,
                             booking_id__requested_by_user_ID=request.user.id
                             ).order_by("booking_date")

                    formset_requestor_confirmed_or_pending = BookingDetailFormSet(
                        queryset=booking_detail_for_requestor)

                    if request.method == 'POST':

                        formset_requestor_confirmed_or_pending = BookingDetailFormSet(
                            request.POST,
                            request.FILES,
                            queryset=booking_detail_for_requestor)

                        delete_count = len(
                            formset_requestor_confirmed_or_pending.
                            deleted_forms)
                        form_count = len(
                            formset_requestor_confirmed_or_pending)

                        if delete_count > 0:

                            if delete_count == form_count:
                                print "all dates are to be deleted"
                                # then this is the full booking to be delete, so just call the delete_booking view
                                return redirect(
                                    reverse('delete_booking',
                                            kwargs={"booking_id": booking_id}))

                            else:

                                print "some dates are to be deleted"
                                # don't save to db yet have to check if dates are still consecutive
                                instances = formset_requestor_confirmed_or_pending.save(
                                    commit=False)

                                # it's ok to delete the dates set to delete
                                for obj in formset_requestor_confirmed_or_pending.deleted_objects:
                                    obj.delete()

                                # run code to break up the booking into separate consecutive date bookings IF IT IS REQUIRED
                                num_extra_bookings = make_the_split(booking_id)

                                if num_extra_bookings > 0:
                                    messages.success(
                                        request,
                                        "This Booking (ref %s) has been split into %s Bookings with consecutive dates ranges"
                                        % (booking_id, num_extra_bookings + 1))
                                    return redirect(
                                        reverse('all_asset_bookings',
                                                kwargs={
                                                    "asset_id": asset_id,
                                                    "user_id": request.user.id
                                                }))

                                else:
                                    if delete_count > 1:
                                        messages.success(
                                            request,
                                            "%s dates have been removed from this booking."
                                            % delete_count)
                                    else:
                                        messages.success(
                                            request,
                                            "%s date has been removed from this booking."
                                            % delete_count)
                                    return redirect(
                                        reverse(
                                            'booking_detail',
                                            kwargs={"booking_id": booking_id}))

                        else:
                            # nothing was sent for the form to delete so send it right back
                            print formset_requestor_confirmed_or_pending.errors
                            messages.error(
                                request,
                                "Want to amend the booking? Please set Remove to 'Yes' on each date you want to remove."
                            )
                            formset_requestor_confirmed_or_pending = BookingDetailFormSet(
                                queryset=booking_detail_for_requestor)

                elif booking_confirmed == False:
                    # the booking is not confirmed but is it also not pending, so this means that the user needs to
                    # look at the approved/denied dates and CONFIRM the booking
                    # they do this by selecting either delete, or confirm on each date that is set to 'Approved'
                    # and the MUST select 'Delete' for all dates that are set to 'Denied'
                    # they can also delete the ENTIRE BOOKING
                    print "booking is not confirmed yet"
                    BookingDetailFormSet = modelformset_factory(
                        BookingDetail,
                        form=BookingDetailForm_for_Requestor_to_Confirm,
                        max_num=1,
                        can_delete=True)

                    booking_detail_for_requestor = BookingDetail.objects.select_related(
                    ).filter(booking_id_id=booking_id,
                             booking_id__requested_by_user_ID=request.user.id
                             ).order_by("booking_date")

                    formset_requestor_to_confirm = BookingDetailFormSet(
                        queryset=booking_detail_for_requestor)

                    include_delete_booking_button = True

                    if request.method == 'POST':
                        formset_requestor_to_confirm = BookingDetailFormSet(
                            request.POST,
                            request.FILES,
                            queryset=booking_detail_for_requestor)

                        if formset_requestor_to_confirm.is_valid():
                            print "it is valid"
                            # don't save to db yet
                            total_forms = len(formset_requestor_to_confirm)
                            instances = formset_requestor_to_confirm.save(
                                commit=False)
                            delete_count = len(
                                formset_requestor_to_confirm.deleted_forms)
                            form_count = total_forms

                            print "TOTAL FORMS %s" % total_forms
                            print "DELETED INSTANCES %s" % delete_count

                            is_confirmed_count = 0

                            for instance in instances:
                                confirmed = instance.is_confirmed
                                if confirmed:
                                    is_confirmed_count += 1

                            print "Confirmed: %s Deleted: %s Form Count: %s" % (
                                is_confirmed_count, delete_count, form_count)

                            if is_confirmed_count + delete_count == form_count:

                                # it's ok to update the instance now
                                # had to wait until now because I was updating is_approved in the instance
                                # and it was affecting the form if the code had to return because of count not matching
                                is_confirmed_count = 0
                                for instance in instances:
                                    confirmed = instance.is_confirmed
                                    if confirmed:
                                        is_confirmed_count += 1
                                        instance.date_confirmed = timezone.now(
                                        )
                                        # update this in the table to False
                                        instance.is_approved = 0
                                print "confirmed count after ok: %s" % is_confirmed_count
                                # it's ok to delete the dates set to delete
                                for obj in formset_requestor_to_confirm.deleted_objects:
                                    obj.delete()
                                # and update the other dates
                                formset_requestor_to_confirm.save()

                                # run code to break up the booking into separate consecutive date bookings IF IT IS REQUIRED
                                num_extra_bookings = make_the_split(booking_id)

                                if num_extra_bookings > 0:
                                    messages.success(
                                        request,
                                        "Thank you for confirming this booking. Just so you are aware, this Booking (ref %s) has been split into %s Bookings with consecutive date ranges"
                                        % (booking_id, num_extra_bookings + 1))
                                    return redirect(
                                        reverse('all_asset_bookings',
                                                kwargs={
                                                    "asset_id": asset_id,
                                                    "user_id": request.user.id
                                                }))

                                else:
                                    messages.success(
                                        request,
                                        "Thank you for confirming this booking."
                                    )
                                    return redirect(
                                        reverse(
                                            'booking_detail',
                                            kwargs={"booking_id": booking_id}))

                            else:

                                messages.error(
                                    request,
                                    "Oops! To confirm your Booking, all dates (approved or denied) have to be set to 'Yes'"
                                )
                                formset_requestor_to_confirm = []
                                formset_requestor_to_confirm = BookingDetailFormSet(
                                    queryset=booking_detail_for_requestor)

                        else:
                            print formset_requestor_to_confirm.errors
                            messages.error(
                                request,
                                "Oops! Form not valid. Please check that 'Confirm' is selected for all Approved date and 'Remove' is selected for each Denied date"
                            )
                            formset_requestor_to_confirm = BookingDetailFormSet(
                                queryset=booking_detail_for_requestor)

            else:
                #user is the owner
                print "The user is the owner of some (or all) dates in the booking"
                if booking_pending:
                    BookingDetailFormSet = modelformset_factory(
                        BookingDetail,
                        form=BookingDetailForm_for_Owner,
                        max_num=1)
                    booking_detail_for_owner = BookingDetail.objects.select_related(
                    ).filter(booking_id_id=booking_id,
                             slot_owner_id_id=request.user.id).order_by(
                                 "booking_date")
                    formset_owner = BookingDetailFormSet(
                        queryset=booking_detail_for_owner)

                    if request.method == 'POST':
                        formset_owner = BookingDetailFormSet(
                            request.POST,
                            request.FILES,
                            queryset=booking_detail_for_owner)

                        if formset_owner.is_valid():
                            print "it is valid"
                            # don't save to db yet
                            instances = formset_owner.save(commit=False)
                            total_forms = len(formset_owner)

                            is_approved_count = 0
                            is_denied_count = 0
                            both_count = 0
                            form_count = total_forms

                            for instance in instances:

                                approved = instance.is_approved
                                if approved:
                                    is_approved_count += 1
                                    instance.date_approved = timezone.now()

                                denied = instance.is_denied
                                if denied:
                                    is_denied_count += 1
                                    instance.date_denied = timezone.now()

                                if approved and denied:
                                    both_count += 1

                            print "Approved: %s Denied: %s Form Count: %s" % (
                                is_approved_count, is_denied_count, form_count)
                            if (is_approved_count + is_denied_count
                                    == form_count) and both_count == 0:
                                formset_owner.save()

                                messages.success(
                                    request,
                                    "Thank you for updating these dates.")
                                return redirect(
                                    reverse('booking_detail',
                                            kwargs={"booking_id": booking_id}))

                            else:
                                messages.error(
                                    request,
                                    "Oops! Please check that (only one of) 'Approved' or 'Denied' is set to Yes for each date requested"
                                )
                                formset_owner = BookingDetailFormSet(
                                    queryset=booking_detail_for_owner)
                        else:
                            print formset_owner.errors
                            messages.error(
                                request,
                                "Oops! Please check that (only one of) 'Approved' or 'Denied' is set to Yes for each date requested"
                            )
                            formset_owner = BookingDetailFormSet(
                                queryset=booking_detail_for_owner)

    else:
        errors.append("You are not authorised to view this booking")

    args = {
        'booking': the_booking,
        'booking_detail': booking_detail,
        'asset': asset,
        'errors': errors,
        'new': new,
        'formset_owner': formset_owner,
        'formset_requestor_confirmed_or_pending':
        formset_requestor_confirmed_or_pending,
        'formset_requestor_to_confirm': formset_requestor_to_confirm,
        'include_delete_booking_button': include_delete_booking_button,
    }
    args.update(csrf(request))

    return render(request, "booking_detail.html", args)
示例#23
0
def review_a_booking(request, asset_id):

    bookingform = BookingForm()
    user_ok = False
    the_asset = get_object_or_404(Asset, id=asset_id)

    #check user is linked to the asset provided
    if check_user_linked_to_asset(request.user, asset_id):

        #is the requestor activated?
        if check_user_activated(request.user, asset_id):

            user_ok = True

        else:

            user_ok = False
            messages.add_message(request, messages.ERROR,
                                 "Account Deactivated")

    else:

        user_ok = False
        messages.add_message(request, messages.ERROR,
                             "You are not authorised to view this page")

    if user_ok:

        #sessions variables must exist

        #variables from the session
        if 'selected_day_cal' in request.session:
            day = (request.session['selected_day_cal'])

        if 'selected_month_cal' in request.session:
            month = (request.session['selected_month_cal'])

        if 'selected_year_cal' in request.session:
            year = (request.session['selected_year_cal'])

        if 'selected_hour_cal' in request.session:
            hour = (request.session['selected_hour_cal'])

        if 'selected_minute_cal' in request.session:
            minute = (request.session['selected_minute_cal'])

        try:

            the_values = "%s - %s - %s - %s - %s" % (year, month, day, hour,
                                                     minute)
            url_date = datetime.datetime(int(year), int(month), int(day),
                                         int(hour), int(minute))

        except:

            clear_date_and_time_from_session
            code_message = "There was a problem with the date, please re-select from the booking calendar " + the_values
            messages.add_message(request, messages.ERROR, code_message)
            return redirect(
                reverse_lazy('make_a_booking',
                             kwargs={"asset_id": the_asset.id}))

        else:

            show_date_format = url_date.strftime("%A, %d %B")
            show_time_format = url_date.strftime("%H:%M")

            if request.method == "POST":

                form = BookingForm(request.POST)

                if form.is_valid():

                    cd = form.cleaned_data

                    hour = int(cd['hour'])
                    minute = int(cd['minute'])
                    day = int(cd['day'])
                    month = int(cd['month'])
                    year = int(cd['year'])
                    url_date = datetime.datetime(year, month, day, hour,
                                                 minute)
                    the_request_date = datetime.datetime(year, month, day)
                    the_request_time = datetime.time(hour, minute)

                    #check things about the date first here before saving
                    #the date has already been checked before being saved to the session
                    #check if the time-slot is still available (could be a delay with confirming the booking)

                    new_booking = Booking(
                        requested_by_user_ID=request.user,
                        asset_ID=the_asset,
                        requested_date=the_request_date,
                        requested_start_time=the_request_time)

                    try:
                        new_booking.save()
                        new_id = new_booking.pk
                        #redirect to bookings page

                        clear_date_and_time_from_session
                        #send email to user
                        user_email = request.user.email

                        current_site = get_current_site(request)
                        domain = current_site.domain
                        delete_link = "%s/%s/%s/" % (domain, "booking/delete",
                                                     new_id)
                        message_body = "Here are the details of your recent booking: " + show_date_format + " at " + show_time_format
                        message_body += "  To delete this booking at any time, click <a href='" + delete_link + "'>here</a>"

                        con = get_connection()
                        send_mail("Count Me In = booking",
                                  message_body,
                                  "*****@*****.**",
                                  ['*****@*****.**', user_email],
                                  connection=con)

                        return redirect(
                            reverse_lazy('my_bookings',
                                         kwargs={
                                             "asset_id": the_asset.id,
                                             "booking_id": new_id
                                         }))

                    except IntegrityError as code_message:

                        code_message = "You have already booked that particular time slot, please choose another"
                        messages.add_message(request, messages.ERROR,
                                             code_message)

                        clear_date_and_time_from_session

                        #redirect to bookings page
                        return redirect(
                            reverse_lazy('make_a_booking',
                                         kwargs={"asset_id": the_asset.id}))

                else:

                    print(form.errors)

                    #form not valid

            else:

                bookingform = BookingForm(
                    initial={
                        'requested_date': show_date_format,
                        'requested_start_time': show_time_format,
                        'hour': hour,
                        'minute': minute,
                        'day': day,
                        'year': year,
                        'month': month
                    })

    return render(
        request, "booking/confirm_booking.html", {
            "asset": the_asset,
            'bookingform': bookingform,
            'request_date': show_date_format,
            'request_time': show_time_format,
            "user_ok": user_ok
        })
示例#24
0
def member_detail_edit(request, asset_id, member_id):

    #to edit a member, must be the owner of the asset
    #check asset exists
    the_asset = get_object_or_404(Asset, pk=asset_id)
    errors = []
    the_member_form = []
    the_member_detail = []
    initial_data = ""

    # check if the user is allowed to view this asset
    my_id = request.user
    is_an_owner = assets_extras.is_user_also_owner(my_id, asset_id)

    if is_an_owner == False:

        messages.add_message(request, messages.ERROR,
                             "You are not authorised to view this page")
        errors.append("You are not authorised to view this page")

    else:

        #check validity of the member they want to edit
        is_linked = check_user_linked_to_asset(member_id, asset_id)

        if is_linked == False:
            messages.add_message(request, messages.ERROR,
                                 "That is not a valid Member ID")
            errors.append("That is not a valid Member ID")

        else:
            the_member_detail = Asset_User_Mapping.objects.get(
                asset_ID=asset_id, user_ID=member_id)
            initial_data = {
                'is_activated': the_member_detail.is_activated,
                'is_owner': the_member_detail.is_owner,
                'asset_membership_ID': the_member_detail.asset_membership_ID,
                'asset_swipe_ID': the_member_detail.asset_swipe_ID,
                'admin_notes': the_member_detail.admin_notes
            }

            #for validation after form is POSTED, will need to know if the user_id submitting is the same as the member_id
            if my_id == the_member_detail.user_ID:

                owner_user_same_person = True

            else:

                owner_user_same_person = False

        if len(errors) == 0:  #no errors

            if request.method == "POST":

                form = AssetMemberForm(request.POST, initial=initial_data)

                if form.is_valid():

                    cd = form.cleaned_data

                    is_staff = cd['is_owner']
                    is_activated = cd['is_activated']
                    membership_ID = cd['asset_membership_ID']
                    swipe_ID = cd['asset_swipe_ID']
                    notes = cd['admin_notes']

                    if form.has_changed():

                        if ('is_owner' in form.changed_data
                                or 'is_activated' in form.changed_data
                            ) and owner_user_same_person:

                            # check that the current user hasn't changed their own is_staff status to False
                            # if they have send back a warning (or else they will not be able to view the Owner pages)
                            code_message = "You cannot edit your own staff status. Another staff member must do this on your behalf."
                            messages.add_message(request, messages.WARNING,
                                                 code_message)
                            return redirect(
                                reverse_lazy('member_detail',
                                             kwargs={"asset_id": asset_id}))

                        elif is_staff and not is_activated:

                            code_message = "To deactivate a staff member, you must first remove their staff status"
                            messages.add_message(request, messages.WARNING,
                                                 code_message)
                            errors.append(code_message)
                            return redirect(
                                reverse_lazy('member_detail',
                                             kwargs={"asset_id": asset_id}))

                        else:

                            try:
                                Asset_User_Mapping.objects.filter(
                                    user_ID=member_id,
                                    asset_ID=asset_id).update(
                                        is_owner=is_staff,
                                        is_activated=is_activated,
                                        asset_membership_ID=membership_ID,
                                        asset_swipe_ID=swipe_ID,
                                        admin_notes=notes)
                                code_message = "Member " + the_member_detail.user_ID.first_name + " " + the_member_detail.user_ID.last_name + " has been edited"
                                messages.add_message(request, messages.INFO,
                                                     code_message)
                                #send back to Membership page
                                return redirect(
                                    reverse_lazy('member_detail',
                                                 kwargs={"asset_id":
                                                         asset_id}))

                            except Error:

                                code_message = "There was a problem, can you please try that again?"
                                messages.add_message(request, messages.ERROR,
                                                     code_message)

                    return redirect(
                        reverse_lazy('member_detail',
                                     kwargs={"asset_id": asset_id}))

                else:

                    print(form.errors)

            else:  #not POST

                the_member_form = AssetMemberForm(initial=initial_data)

        else:  #there are errors

            the_member_form = []

    return render(
        request, "assets/asset_user_mapping_detail_edit.html", {
            "asset": the_asset,
            "form": the_member_form,
            "member": the_member_detail,
            "errors": errors
        })
示例#25
0
def venue_calendar_admin(request, asset_id):

    the_asset = get_object_or_404(Asset, id=asset_id)
    errors = []
    user_ok = False
    cal_data = {}
    dates_to_show = set()

    if check_user_linked_to_asset(request.user, asset_id):

        if is_user_also_owner(request.user, asset_id):

            user_ok = True

        else:

            errors.append("Restricted Access")
            messages.add_message(request, messages.ERROR, "Restricted Access")
            user_ok = False

    else:

        errors.append("You are not authorised to view this page")
        messages.add_message(request, messages.ERROR,
                             "You are not authorised to view this page")
        user_ok = False

    if user_ok:

        #remove any selected dates/times from the session in case they exist already
        #empty session variables
        booking_extras.clear_exception_date_from_session

        # each day there are bookings, the calendar shows "Bookings <the number>"
        # and a link with "add an exception"
        # if the date is already in the exception table, the link will say "edit exception" (or something like that)
        # unlike the calendar for users (make_a_booking view), there are no modals on this calendar - each item on the date will be a separate link

        # create the object that the calendar needs (cal_data)
        # this is a series of dates and links

        #distict query below is not allowed in sqlite3 so will get individual dates by populating a set() which can only have unique values
        #dates_to_show = Bookings.objects.all().filter(asset_ID = the_asset.id, requested_date__gte=datetime.date.today()).order_by('requested_date').distinct('asset_ID', 'requested_date')

        #there will be multiple bookings per date so to get individual dates put into a set()
        all_future_bookings = Booking.objects.all().filter(
            asset_ID=the_asset.id, requested_date__gte=datetime.date.today())

        if all_future_bookings:

            for item in all_future_bookings:
                # print(item.requested_date)
                dates_to_show.add(item.requested_date)

            if dates_to_show:

                for item in dates_to_show:

                    num_future_bookings = get_total_bookings_venue(
                        the_asset.id, selected_date=item)
                    todays_date = datetime.date(datetime.datetime.now().year,
                                                datetime.datetime.now().month,
                                                datetime.datetime.now().day)

                    is_exception_date = assets_extras.is_date_in_exception_table(
                        the_asset.id, item)

                    entry_date_str = item.strftime("%m-%d-%Y")

                    if is_exception_date:
                        click_link = onclick = 'UpdateExceptionDate(this," + str(entry_date.day) + "," + the_asset.id + ")'
                        href_link = "%s%s/" % ("/asset/exception/", asset_id)
                        exception_link = "<a style='background-color:#f44336; font-size:12px;border-radius: 25px;padding:4px 6px 4px 6px;' href='" + href_link + "'>View Exception Details</a>"

                    else:

                        exception_link = ""

                    if num_future_bookings == 1:
                        text_desc = "Booking"
                    else:
                        text_desc = "Bookings"

                    cal_data[
                        entry_date_str] = "<div>%s %s</div> <div>%s</div>" % (
                            num_future_bookings, text_desc, exception_link)

                print(cal_data)

        else:

            #no dates to show, so empty calendar!
            messages.add_message(request, messages.INFO,
                                 "Click on any date to add an exception")

    return render(
        request, "booking/booking_calendar_venue.html", {
            "the_asset": the_asset,
            "errors": errors,
            "cal_data": cal_data,
            'user_ok': user_ok
        })
示例#26
0
def make_a_booking(request, asset_id):

    clear_date_and_time_from_session
    user_ok = False

    the_asset = get_object_or_404(Asset, id=asset_id)
    errors = []
    asset_booking_dates = []
    asset_booking_dates_times = []
    cal_data = {}
    the_modals = []

    year = datetime.date.today().year
    month = datetime.date.today().month
    month_name = calendar.month_name[month]

    if check_user_linked_to_asset(request.user, asset_id):

        #is the requestor activated?
        if check_user_activated(request.user, asset_id):

            user_ok = True

            #remove any selected dates/times from the session in case they exist already
            #empty session variables
            request.session['selected_year_cal'] = []
            request.session['selected_month_cal'] = []
            request.session['selected_day_cal'] = []
            request.session['selected_hour_cal'] = []
            request.session['selected_minute_cal'] = []

        else:

            user_ok = False
            messages.add_message(request, messages.ERROR,
                                 "Account deactivated")

    else:
        user_ok = False
        errors.append("You are not authorised to view this page")
        messages.add_message(request, messages.ERROR,
                             "You are not authorised to view this page")

    if user_ok:

        time_period_to_display = get_display_time_period_for_booking(asset_id)

        #create the object that the calendar needs (cal_data)
        #this is a series of dates and links
        #also create the MODAL object (the_modals)
        #this is the set of booking links that will pop up when the user clicks on the calendar date
        #both of these need to only show the dates that the venue has set
        #so this could be 5, 6 or 7 day weeks (and not EVERY DAY)
        #so cal_dat and the_modals may not have consecutive dates

        asset_booking_dates = get_asset_booking_dates_for_display(asset_id)

        for entry_date in asset_booking_dates:

            #------prepare the cal_data------#

            entry_date_index = asset_booking_dates.index(entry_date)
            entry_date_str = entry_date.strftime("%m-%d-%Y")

            #------prepare the cal_data end------#

            #------prepare the_modals start------#

            header_message = "Available times on " + entry_date.strftime(
                "%A %d %b")

            the_modal_start = "<div class='modal fade bs-example-modal-lg' id='myTimeModal" + str(
                entry_date_index) + "' role='dialog'>"
            the_modal_start += "<div class='modal-dialog modal-lg'>"
            the_modal_start += "<div class= 'modal-content'>"
            the_modal_start += "<div class= 'modal-header'>"
            the_modal_start += "<h3 class='modal-title'>" + header_message + "</h3>"
            the_modal_start += "<button type='button' class='close' data-dismiss='modal'>&times;</button>"
            the_modal_start += "</div>"
            the_modal_start += "<div class='modal-body'>"

            asset_booking_dates_times = get_asset_booking_time_links(
                asset_id, entry_date)
            num_items = len(asset_booking_dates_times)

            #only run the rest of this function if there are times provided
            #(someone could be looking at the site after-hours)
            if num_items > 0:

                the_modal_middle = ""
                the_count = 0
                for item in asset_booking_dates_times:
                    #print ("%s: %s" % ("the", item))
                    #need to display all the items except last one
                    #last time-slot should be closing time, so it can't be booked
                    the_count += 1

                    if the_count < num_items:
                        # print ("%s:%s" %(item.hour, item.minute))
                        display_time = datetime.datetime.strftime(
                            item, "%H:%M")
                        extend_url = "review/"

                        #if fully booked, don't include a link ***STILL TO CODE MH ***
                        if time_slot_fully_booked(asset_id, entry_date, item):

                            the_modal_middle += "%s%s%s" % (
                                "<type='button' onclick='alert('This slot is fully booked')' class='btn-dark btn-sm' disabled='disabled' href='#'>",
                                display_time, "</button>")

                        else:

                            the_modal_middle += "%s%s%s" % (
                                "<a type='button' onclick='updateDateAndTime(this,"
                                + str(entry_date.day) +
                                ")' class='button button-dark button-circle btn-lg' href='review/'>",
                                display_time, "</a>")

                the_modal_end = "</div>"
                the_modal_end += "<div class='modal-footer'>"
                the_modal_end += "<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>"
                the_modal_end += "</div></div></div></div>"

                the_modal = the_modal_start + the_modal_middle + the_modal_end

                the_modals.append({"detail": the_modal})

                #------prepare the modal end------#

                #------populate the cal_data------#

                the_first_slot = "%s" % (datetime.datetime.strftime(
                    asset_booking_dates_times[0], "%H:%M"))
                the_last_slot = "%s" % (datetime.datetime.strftime(
                    asset_booking_dates_times[len(asset_booking_dates_times) -
                                              1], "%H:%M"))
                opening_times_for_display = "%s to %s" % (the_first_slot,
                                                          the_last_slot)

                # issue with button on calendar in large view if date is TODAY - model doesn't open (3rd party code)
                # so changing entry text for TODAY only to an <a> tag and styling like a button
                # all other dates work
                if entry_date_index == 0:
                    entry_message = "<a style='background-color:#f44336; font-size:16px;border-radius: 25px;padding:8px 12px 8px 12px;' data-toggle='modal' data-target='#myTimeModal" + str(
                        entry_date_index
                    ) + "'>" + opening_times_for_display + "</a>"
                else:
                    entry_message = "<button type='button' style='border-radius: 25px;'class='btn btn-primary' data-toggle='modal' data-target='#myTimeModal" + str(
                        entry_date_index
                    ) + "'>" + opening_times_for_display + "</button>"

                #populate cal_data
                cal_data[entry_date_str] = entry_message

                #------populate the cal_data end--#

    args = {
        'the_asset': the_asset,
        'errors': errors,
        'user_ok': user_ok,
        'cal_data': cal_data,
        'the_modals': the_modals
    }

    #args.update(csrf(request))

    return render(request, "booking/new_booking.html", args)
示例#27
0
def print_bookings(request, **kwargs):

    asset_id = 0
    my_id = request.user.id
    is_owner = False
    is_linked = False
    time_period = "future"
    selected_date = ""
    year = 0
    month = 0
    day = 0

    #prepare the query
    if 'the_year' in kwargs:
        year = kwargs['the_year']
        print(year)
    if 'the_month' in kwargs:
        month = kwargs['the_month']
        print(month)
    if 'the_day' in kwargs:
        day = kwargs['the_day']
        print(day)
    check = year + month + day
    print(check)
    if check > 0:

        selected_date = datetime.date(year, month, day)
        time_period = ""

    print("date is:")
    print(selected_date)

    #prepare the query
    if 'asset_id' in kwargs:
        asset_id = kwargs['asset_id']

    #prepare the query
    if 'time_period' in kwargs:
        time_period = kwargs['time_period']

    #can only print if an owner
    is_owner = is_user_also_owner(my_id, asset_id)

    #is the requestor linked to this asset?
    is_linked = check_user_linked_to_asset(my_id, asset_id)

    #format file name
    now = datetime.datetime.now()
    format_now_date = now.strftime("%d-%b-%y")
    format_now_time_in_file = now.strftime("%H:%M:%S")
    format_now_time_filename = now.strftime("_%H%M%S")
    format_file_name = "bookings_as_of_" + format_now_date + format_now_time_filename + ".csv"

    if is_owner and is_linked:

        the_output = get_bookings(asset_id=asset_id,
                                  time_period=time_period,
                                  selected_date=selected_date)

        response = HttpResponse(content_type='text/csv')
        response[
            'Content-Disposition'] = 'attachment; filename=' + format_file_name

        writer = csv.writer(response)
        writer.writerow([
            'Venue', 'Booking Date', ' Booking Time', 'First Name', 'Surname',
            'Membership Number', 'Swipe ID'
        ])

        for item in the_output:

            if not type(item.requested_date) is datetime.date:
                print("its not a date")

            format_date = item.requested_date.strftime("%d-%b-%y")

            format_time = item.requested_start_time.strftime("%H:%M")

            user_membership_ID = assets_extras.get_membership_id(
                item.requested_by_user_ID, item.asset_ID)
            user_swipe_ID = assets_extras.get_swipe_id(
                item.requested_by_user_ID, item.asset_ID)

            writer.writerow([
                item.asset_ID.asset_display_name, format_date, format_time,
                item.requested_by_user_ID.first_name,
                item.requested_by_user_ID.last_name, user_membership_ID,
                user_swipe_ID
            ])

        writer.writerow([])
        writer.writerow([])

        writer.writerow(['Printed:', format_now_date])
        writer.writerow(['At:', format_now_time_in_file])

    return response
示例#28
0
def profile(request):

    invitecodeform = InviteCodeForm()
    code_message = ""

    if request.method == "POST":
        form = InviteCodeForm(request.POST)
        if form.is_valid():
            # hard-coding the actions here for purposes of testing the concept of using an invitation code
            cd = form.cleaned_data
            the_date = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
            if cd['invitecode'] == "11111":
                # check if the code has been used
                if check_user_linked_to_asset(request.user, 1) == False:
                    new_mapping = Asset_User_Mapping(user_ID=request.user,
                                                     asset_ID_id=1,
                                                     date_activated=the_date,
                                                     is_owner=0,
                                                     is_activated=True,
                                                     inviter_id=13)
                    new_mapping.save()
                else:
                    code_message = "You have already used that code"

            elif cd['invitecode'] == "22222":
                if check_user_linked_to_asset(request.user, 2) == False:
                    new_mapping = Asset_User_Mapping(user_ID=request.user,
                                                     asset_ID_id=2,
                                                     date_activated=the_date,
                                                     is_owner=0,
                                                     is_activated=True,
                                                     inviter_id=21)
                    new_mapping.save()
                else:
                    code_message = "You have already used that code"

            elif cd['invitecode'] == "33333":
                if check_user_linked_to_asset(request.user, 3) == False:
                    new_mapping = Asset_User_Mapping(user_ID=request.user,
                                                     asset_ID_id=3,
                                                     date_activated=the_date,
                                                     is_owner=0,
                                                     is_activated=True,
                                                     inviter_id=19)
                    new_mapping.save()
                else:
                    code_message = "You have already used that code"

            else:
                code_message = "Code not recognised"
    else:

        invitecodeform = InviteCodeForm()

    # set session values to be used until user logs out
    # store the asset ids they are linked to

    # create empty session list
    request.session['linked_assets'] = []
    linked_asset_count = Asset.objects.all().filter(
        asset_users=request.user).count()

    # want to store a list in the session
    # http://stackoverflow.com/questions/6720121/serializing-result-of-a-queryset-with-json-raises-error
    class LinkedAssets(object):
        def __init__(self, asset_id):
            self.asset_id = asset_id

        def serialize(self):
            return self.__dict__

    if linked_asset_count > 0:
        # fill the linked_assets session list
        linked_assets = serializers.serialize(
            'json',
            Asset.objects.all().filter(asset_users=request.user),
            fields=('id,'))
        request.session['linked_assets'] = linked_assets

    assets = Asset_User_Mapping.objects.all().filter(user_ID=request.user)

    return render(
        request, 'profile.html', {
            'assets': assets,
            'invitecodeform': invitecodeform,
            'code_message': code_message
        })
示例#29
0
def profile(request,**kwargs):

	#'invite_code' will be in kwargs if the user has 
	#requested to be linked to an asset via a URL (they are redirected to this view)
	if 'invite_code' in kwargs: 
		
		invite = kwargs['invite_code']

	else:
		invite=0

	invitecodeform = InviteCodeForm()
	code_message = ""
	
	if request.method == "POST":
		form = InviteCodeForm(request.POST)
		if form.is_valid():
			
			cd = form.cleaned_data
			the_code = cd['invitecode']
			the_date = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
			
			#check if the invitecode is in the Asset table
			#return the AssetID if it is
			the_venue = get_asset_from_invite_code(the_code)

			if the_venue:
				#check if the venue has been activated
				the_venue_activated = is_asset_activated(the_venue.id)
				if the_venue_activated:
				
					the_venue_id = the_venue.id
					the_venue_name = the_venue.asset_display_name

					#check if the user is already linked to this asset  
					if check_user_linked_to_asset(request.user,the_venue_id) == False:
						new_mapping = Asset_User_Mapping(user_ID=request.user,asset_ID=the_venue,is_owner=0,invite_code_used=the_code)
						new_mapping.save()
						code_message = "You have just been counted in to " + the_venue_name + "!"
						messages.add_message(request, messages.SUCCESS, code_message)

					else:
						code_message = "You are already a Member of " + the_venue_name + "!"
						messages.add_message(request, messages.ERROR, code_message)
				else:

					code_message = "This is not a active code. Please confirm the code with your Gym."
					messages.add_message(request, messages.ERROR, code_message)

			else:
				code_message = "This is not a valid code. Please check and try again."
				messages.add_message(request, messages.ERROR, code_message) 
	
	elif invite:

		#user has entered a VALID invite_code via the url, so add them to this asset (if they are not already linked to it)
		#return the AssetID if it is
		the_venue = get_asset_from_invite_code(invite)

		if the_venue:
			#check if the venue has been activated
			the_venue_activated = is_asset_activated(the_venue.id)
			if the_venue_activated:
			
				the_venue_id = the_venue.id
				the_venue_name = the_venue.asset_display_name

				#check if the user is already linked to this asset  
				if check_user_linked_to_asset(request.user,the_venue_id) == False:
					new_mapping = Asset_User_Mapping(user_ID=request.user,asset_ID=the_venue,is_owner=0,invite_code_used=invite)
					new_mapping.save()

					code_message = "You have just been counted in to " + the_venue_name + "!"
					messages.add_message(request, messages.SUCCESS, code_message)

				else:
					code_message = "You are already a Member of " + the_venue_name + "!"
					messages.add_message(request, messages.ERROR, code_message)
			else:

				code_message = "This is not a active code. Please confirm the code with your Gym."
				messages.add_message(request, messages.ERROR, code_message)

		else:
			code_message = "This is not a valid code. Please check and try again."
			messages.add_message(request, messages.ERROR, code_message)

	else:
		
		invitecodeform = InviteCodeForm()


	# set session values to be used until user logs out
	# store the asset ids they are linked to

	# create empty session list
	request.session['linked_assets']=[]
	linked_asset_count = Asset.objects.all().filter(asset_users=request.user).count()

	# want to store a list in the session
	# http://stackoverflow.com/questions/6720121/serializing-result-of-a-queryset-with-json-raises-error
	class LinkedAssets(object):
		def __init__(self,asset_id):
			self.asset_id = asset_id

		def serialize(self):
			return self.__dict__

	if linked_asset_count > 0:
		# fill the linked_assets session list
		linked_assets = serializers.serialize('json',Asset.objects.all().filter(asset_users = request.user), fields=('id,'))
		request.session['linked_assets'] = linked_assets

	assets = Asset_User_Mapping.objects.all().filter(user_ID=request.user, asset_ID_id__is_activated=True)

	return render(request, 'home/profile.html',
				  {'assets': assets, 'invitecodeform': invitecodeform, 'code_message': code_message})