Exemplo n.º 1
0
def view_piece_of_news(request, piece_of_news_name_slug):
    notify.send(request.user, actor=request.user, recipient=request.user, verb="BREAKING NEWS - Donuts are free for Chicago Police officers!")
    context = {}
    if request.method == "GET":
        piece_of_news = News.objects.get(slug=piece_of_news_name_slug)
        context['piece_of_news'] = piece_of_news
    return render(request, 'pss/piece_of_news.html',context)
Exemplo n.º 2
0
def add_friend_to_list(request, pk):
    friend = get_object_or_404(Profile, pk=pk)
    if request.method == 'POST':
        form = MakeFriendForm(request.POST)
        if form.is_valid():
            user_friend_list = form.save(commit=False)
            user_friend_list.friend = friend
            user_friend_list.user = request.user
            if_obj_exists = Friend.objects.filter(
                friend=friend, user__exact=request.user).exists()
            if if_obj_exists:
                messages.warning(
                    request,
                    '{} ya esta en tu lista de amigos!'.format(friend))
                return redirect('accounts:detail', pk=pk)

            else:

                notify.send(sender=request.user,
                            actor=request.user,
                            recipient=friend.user,
                            verb='te agrego a la lista de amigos',
                            nf_type='followed_by_one_user')

                messages.success(
                    request, '{} fue agregado a tus amigos!'.format(friend))
                user_friend_list.save()
                return redirect('accounts:detail', pk=pk)
Exemplo n.º 3
0
def add_comment_to_comment(request, comment_id):
    comment = get_object_or_404(AgricultureComment, pk=comment_id)
    post = comment.post
    user = post.user

    if request.method == 'POST':
        form = AgricultureCommentForm(request.POST)
        if form.is_valid():
            recomment = form.save(commit=False)
            recomment.post = post
            recomment.parent = comment.id
            recomment.depth = 1
            recomment.user = request.user.username
            recomment.save()

            if request.user != user:
                notify.send(request.user,
                            recipient=user,
                            actor=request.user,
                            description='agriculture',
                            verb='add recomment your comment : ' + post.title,
                            target=post,
                            nf_type='add_comment')

            return redirect('agriculture:detail', post.id)
Exemplo n.º 4
0
def group_invite(request, slug):
    group = get_object_or_404(GroupProfile, slug=slug)

    if not group.can_invite(request.user):
        raise Http404()

    form = GroupInviteForm(request.POST)

    if form.is_valid():
        for user in form.cleaned_data["invite_user_identifiers"].split("\n"):
            group.invite(
                user,
                request.user,
                role=form.cleaned_data["invite_role"],
            )

            # notify user that he/she is invited by the group
            try:
                requested_user = Profile.objects.get(email=user)
            except:
                pass
            else:
                notify.send(request.user, recipient=requested_user, actor=request.user,
                verb='invited you to join')

    return redirect("group_members", slug=group.slug)
Exemplo n.º 5
0
def create_plan(request, username):
    '''create new plan'''
    if request.user.is_superuser:
        user = User.objects.get(username=username)
        form = PlanForm(request.POST or None)
        if form.is_valid():
            subtitle = form.cleaned_data.get('subtitle')
            date = form.cleaned_data.get('date')
            new_plan = Plan.objects.create(user=user,
                                           subtitle=subtitle,
                                           date=date)
            messages.success(request, 'Plan Added!')
            notify.send(request.user,
                        recipient=user,
                        actor=request.user,
                        verb='Added a new plan.',
                        nf_type='plan_by_one_user',
                        target=new_plan)

            return HttpResponseRedirect(
                reverse("nutrition:list", kwargs={"username": username}))
        context = {
            "form": form,
        }
        return render(request, 'nutrition/create_plan.html', context)
    else:
        return HttpResponse("Only authorized user can add nutrition meals")
Exemplo n.º 6
0
def add_workshop(request):
    workshops = Workshop.objects.all().order_by('-pk')
    if request.method == 'POST':
        form = WorkshopForm(request.POST, request.FILES)
        if form.is_valid():
            workshop = form.save(commit=False)
            workshop.added_by = request.user
            workshop.save()

            # notify
            training = workshop
            author = User.objects.get(username=request.user)
            author_friend = author.friend_set.all()
            friends = []
            for follower in author_friend:
                friend = follower.current_user
                friends.append(friend)

            followers = list(friends)

            if len(followers) >= 1:
                notify.send(request.user,
                            recipient_list=followers,
                            actor=training,
                            verb='posted',
                            nf_type='all')
            else:
                pass

            return render(request, 'Marketplace/workshop.html',
                          {'workshops': workshops})
    else:
        form = WorkshopForm()

    return render(request, 'Marketplace/add_workshop.html', {'form': form})
Exemplo n.º 7
0
 def test_single_user_notify(self):
     notify.send(User, recipient=self.recipient, actor=self.actor,
                 verb='poked you')
     notification = Notification.objects.get(pk=1)
     self.assertEqual(notification.recipient_id, self.recipient.id)
     timedelta = timezone.now() - notification.created
     self.assertLessEqual(timedelta.seconds, 60)
Exemplo n.º 8
0
def map_publish(request, map_pk):
    if request.method == 'POST':
        try:
            map = Map.objects.get(id=map_pk)
        except Map.DoesNotExist:
            return Http404("Map does not exist")
        else:
            if request.user != map.owner:
                return HttpResponse(
                        loader.render_to_string(
                            '401.html', RequestContext(
                            request, {
                            'error_message': _("You are not allowed to publish this map.")})), status=401)
                # return HttpResponse('you are not allowed to publish this map')
            group = map.group
            map.status = 'PENDING'
            map.current_iteration += 1
            map.save()

            # notify organization admins about the new published map
            managers = list( group.get_managers())
            notify.send(request.user, recipient_list = managers, actor=request.user,
                        verb='pushed a new map for approval', target=map)

            map_submission_activity = MapSubmissionActivity(map=map, group=group, iteration=map.current_iteration)
            map_submission_activity.save()

            # set all the permissions for all the managers of the group for this map
            map.set_managers_permissions()

            messages.info(request, 'Pushed map succesfully')
            return HttpResponseRedirect(reverse('member-workspace-map'))
    else:
        return HttpResponseRedirect(reverse('member-workspace-map'))
Exemplo n.º 9
0
def edit_purchase(request, purchase_id):
    if request.user.is_anonymous:
        return render(request,
                      "registration/login.html",
                      context={"anonymous": True})

    purchase = Purchase.objects.get(pk=purchase_id)
    edit_form = EditPurchaseForm(request.POST or None, request.FILES)
    if request.method == 'POST':
        if edit_form.is_valid():
            purchase.price = edit_form.cleaned_data['price']
            purchase.description = edit_form.cleaned_data['description']
            purchase.available = edit_form.cleaned_data['available']
            purchase.phone = edit_form.cleaned_data['phone']
            purchase.save()
            following_users = [u.user for u in purchase.subscribers.all()]
            notify.send(request.user,
                        recipient_list=following_users,
                        actor=purchase,
                        verb='modified',
                        nf_type='edit_purchase')
            return HttpResponseRedirect(
                reverse('pet:my purchases',
                        kwargs={
                            'filter_type': 'timeCreate',
                            'pet_type': 'all'
                        }))
        else:
            messages.error(request, "Error")
    context = {'form': edit_form, 'purchase': purchase}
    return render(request, "edit_purchase.html", context)
Exemplo n.º 10
0
def add_workout(request, username):
    """
    New workout plan
    :param request:
    return
    """
    if request.user.is_superuser:
        user = User.objects.get(username=username)
        form = WorkoutForm(request.POST or None)
        if form.is_valid():

            title = form.cleaned_data.get('title')
            date = form.cleaned_data.get('creation_date')
            workout = Workout.objects.create(user=user,
                                             title=title,
                                             creation_date=date)
            notify.send(request.user,
                        recipient=workout.user,
                        actor=request.user,
                        verb='Added a new workout.',
                        nf_type='plan_by_one_user',
                        target=workout)
            messages.success(request, 'Workout Day Added!')
            return HttpResponseRedirect(
                reverse("workout:overview",
                        kwargs={"username": workout.user.username}))
        context = {
            "form": form,
        }

        return render(request, 'workout/add_workout.html', context)
    else:
        return HttpResponse("Only authorized user can add workout plans")

    return redirect('/')
Exemplo n.º 11
0
def sculpt_save_receiver(sender, instance, created, *args, **kwargs):

    if created and not instance.parent:
        #notify a user.
        user_regex = r'@(?P<username>[\w.@+-]+)'
        usernames = re.findall(user_regex, instance.content)
        # username = usernames[0]
        # print(sender.user.username)
        # print(instance.user)

        # print(created)
        # print(username)

        # send notification to user here.

        hash_regex = r'#(?P<hashtag>[\w\d-]+)'
        hashtags = re.findall(hash_regex, instance.content)
        parsed_hashtags.send(sender=instance.__class__, hashtag_list=hashtags)

        #send hashtag signal to user here

    else:
        if (instance.reply):

            notify.send(instance.user,
                        recipient=instance.parent.user,
                        actor=instance.user,
                        verb='Commented on your post')
Exemplo n.º 12
0
    def get(self, request, pk=None, format=None):
        obj = get_object_or_404(Post, pk=self.kwargs.get("pk"))
        url_ = obj.get_posts_url()
        user = self.request.user
        updated = False
        liked = False
        user_like = Like.objects.filter(post=obj, user=user)
        if user_like:
            liked = False
            user_like.delete()
            #obj.likes.remove(user)
        else:
            liked = True
            #obj.likes.add(user)
            Like.objects.create(user=user, post=obj)
            notify.send(request.user,
                        recipient=obj.user,
                        actor=request.user,
                        verb='Like your post.',
                        nf_type='liked_by_one_user',
                        target=obj)
        updated = True
        data = {"updated": updated, "liked": liked}

        return Response(data)
Exemplo n.º 13
0
def change_friend(request, operation, pk):

    current_user = User.objects.get(username=request.user)
    new_friend = User.objects.get(pk=pk)
    if operation == 'add':
        Friend.add_friend(current_user, new_friend)

        # django notify code
        notify.send(request.user,
                    recipient=new_friend,
                    actor=request.user,
                    verb='followed you.',
                    nf_type='all')

    elif operation == 'remove':
        Friend.remove_friend(current_user, new_friend)

        # django notify code
        notify.send(request.user,
                    recipient=new_friend,
                    actor=request.user,
                    verb='stopped following you.',
                    nf_type='all')

    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Exemplo n.º 14
0
def create_event(request):
    """
    create an event from admin to user
    :param request:
    """
    if request.user.is_superuser:
        form = AppointmentForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data.get('user')

            if (user == request.user):
                context = {
                    'form': form,
                    'error_message': 'You are the meeting creator, Please add guest'
                }
                return render(request, 'create_event.html', context)

            task = form.cleaned_data.get('task')
            date = form.cleaned_data.get('date')
            time = form.cleaned_data.get('time')
            app = Appointment.objects.create(user=user, task=task, time=time, date=date, sender=request.user)
            notify.send(request.user, recipient=app.user, actor=request.user, verb='Added a new Meeting.',
                        nf_type='app_by_one_user', target=app)
            messages.success(request, 'Appointment Added!')
            return HttpResponseRedirect(reverse("appointments:appoint", kwargs={"username": request.user.username}))

        context = {'form': form}
        return render(request, 'create_event.html', context)
    return redirect('home')
Exemplo n.º 15
0
def notifications(user):
    profile = UserProfile.objects.get(user=user)
    if profile.notif_upcoming_event:
        for notif in Notification.objects.filter(recipient=user, read=True):
            event = notif.actor  #the only 'read' notifications are upcoming_event ones, the others are immediately deleted
            event.notifications_sent = -1
            notif.delete()
            event.save()

        for e in Event.objects.attending(user):
            nb_days = (e.date_time() - timezone.now()).days
            nb_minutes = (e.date_time() - timezone.now()).seconds / 60
            nb_hours = nb_minutes / 60

            #print('delay', e.date_time() - timezone.now(), (e.date_time() - timezone.now()).total_seconds())
            seconds_before_event = (e.date_time() -
                                    timezone.now()).total_seconds()

            if (e.notifications_sent != -1) and not(e.has_begun()) and \
            (seconds_before_event < 1/(2**e.notifications_sent)*INITIAL_DELAY_SECONDS) and (seconds_before_event >= 5 * 60):
                e.notifications_sent = math.floor(
                    math.log2(
                        INITIAL_DELAY_SECONDS / seconds_before_event)) + 1
                e.save()
                notify.send(user, recipient = user, actor=e, \
                    verb = 'is in %d hours and %d minutes from now.' % (nb_hours,nb_minutes%60), nf_type = 'upcoming_event')
Exemplo n.º 16
0
    def form_valid(self, form):
        recievers = []
        for user in User.objects.all():
            # if self.request.user.email != user.email:
            recievers.append(user.email)

        users = User.objects.all()
        notify.send(self.request.user, recipient_list=list(users), actor=self.request.user,
                    verb='subvención', obj=form.instance, target=form.instance, nf_type='edit')

        object = form.instance
        html_message = loader.render_to_string(
            'myapp/subv_email_create.html',
            {
                'name_actor': self.request.user.username,
                'name_subv': form.cleaned_data.get('nombre'),
                'object': object
            }
        )

        send_mail('Gestión de subvenciones',
                  '',
                  self.request.user.email,
                  ['*****@*****.**', '*****@*****.**'],#recievers
                  html_message=html_message
        )

        messages.success(self.request, 'Subvención actualizada correctamente!')
        return super(SubvencionUpdateView, self).form_valid(form)
Exemplo n.º 17
0
def unfollow_business(request, business_id):
    business = models.Business.objects.get(pk=business_id)
    if request.user.appuser in business.followers.all():
        business.followers.remove(request.user.appuser)
        managers = models.User.objects.filter(appuser__in=business.managers.all())
        notify.send(request.user, recipient_list=list(managers.all()), actor=request.user.appuser,
                    verb='stopped following your business.', target=business, nf_type='followed_by_one_user')
Exemplo n.º 18
0
def approve_request(request, cast: Cast, username: str):
    """
    Approves a cast membership request
    """
    user = get_object_or_404(User, username=username)
    try:
        cast.remove_member_request(user.profile)
    except ValueError as exc:
        messages.error(request, str(exc))
    else:
        try:
            cast.add_member(user.profile)
        except ValueError as exc:
            messages.error(request, str(exc))
        else:
            notify.send(request.user,
                        recipient=user,
                        actor=request.user,
                        verb='approved',
                        obj=user,
                        target=cast,
                        nf_type='cast_member_result')
            messages.success(request,
                             f'{user.profile.name} is now a member of {cast}')
    return redirect('cast_member_requests', slug=cast.slug)
Exemplo n.º 19
0
def layer_remove(request, layername, template='layers/layer_remove.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.delete_resourcebase',
        _PERMISSION_MSG_DELETE)

    if (request.method == 'GET'):
        return render_to_response(template, RequestContext(request, {
            "layer": layer
        }))
    if (request.method == 'POST'):
        try:
            with transaction.atomic():
                delete_layer.delay(object_id=layer.id)

                # notify layer owner that someone have deleted the layer
                if request.user != layer.owner:
                    recipient = layer.owner
                    notify.send(request.user, recipient=recipient, actor=request.user,
                    target=layer, verb='deleted your layer')
        except Exception as e:
            message = '{0}: {1}.'.format(_('Unable to delete layer'), layer.typename)

            if 'referenced by layer group' in getattr(e, 'message', ''):
                message = _('This layer is a member of a layer group, you must remove the layer from the group '
                            'before deleting.')

            messages.error(request, message)
            return render_to_response(template, RequestContext(request, {"layer": layer}))
        return HttpResponseRedirect(reverse("layer_browse"))
    else:
        return HttpResponse("Not allowed", status=403)
Exemplo n.º 20
0
def add_friend_to_list(request, pk):
    friend = get_object_or_404(Profile, pk=pk)
    if request.method == 'POST':
        form = MakeFriendForm(request.POST)
        if form.is_valid():
            user_friend_list = form.save(commit=False)
            user_friend_list.friend = friend
            user_friend_list.user = request.user
            if_obj_exists = Friend.objects.filter(
                friend=friend, user__exact=request.user).exists()
            if if_obj_exists:
                messages.warning(
                    request,
                    '{} is already in your friends list!'.format(friend))
                return redirect('accounts:detail', pk=pk)

            else:

                notify.send(sender=request.user,
                            actor=request.user,
                            recipient=friend.user,
                            verb='added you to his friends list',
                            nf_type='followed_by_one_user')

                messages.success(
                    request,
                    '{} was added to your friends list!'.format(friend))
                user_friend_list.save()
                return redirect('accounts:detail', pk=pk)
Exemplo n.º 21
0
def layer_publish(request, layer_pk):
    if request.method == 'POST':
        try:
            layer = Layer.objects.get(id=layer_pk)
        except Layer.DoesNotExist:
            return Http404("Layer does not exist")
        else:
            if request.user != layer.owner:
                return HttpResponse(
                        loader.render_to_string(
                            '401.html', RequestContext(
                            request, {
                            'error_message': _("You are not allowed to publish this layer.")})), status=401)
                # return HttpResponse('you are not allowed to publish this layer')
            group = layer.group
            layer.status = 'PENDING'
            layer.current_iteration += 1
            layer.save()
            layer_submission_activity = LayerSubmissionActivity(layer=layer, group=group, iteration=layer.current_iteration)
            layer_submission_activity.save()

            # notify organization admins about the new published layer
            managers = list( group.get_managers())
            notify.send(request.user, recipient_list = managers, actor=request.user,
                        verb='pushed a new layer for approval', target=layer)

            # set all the permissions for all the managers of the group for this layer
            layer.set_managers_permissions()

            messages.info(request, 'Pushed layer succesfully for approval')
            return HttpResponseRedirect(reverse('member-workspace-layer'))
    else:
        return HttpResponseRedirect(reverse('member-workspace-layer'))
Exemplo n.º 22
0
def dispute_create(request):
    form = forms.DisputeForm(request.POST or None)
    try:
        order = request.user.appuser.user_orders.get(pk=request.GET.get('order_id'))
        appointment = None
    except:
        order = None
        appointment = request.user.appuser.user_appointments.get(pk=request.GET.get('appointment_id'))
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user.appuser
        if order:
            instance.order = order
            instance.business = order.business
        else:
            instance.appointment = appointment
            instance.business = appointment.business
        create_conversation(instance, instance.business, instance.user)
        instance.save()
        managers = models.User.objects.filter(appuser__in=instance.business.managers.all())
        notify.send(request.user, recipient_list=list(managers.all()), actor=request.user.appuser,
                    verb='created new dispute.', target=instance, nf_type='create')
        return redirect('my user dispute list')

    context = {
        'form': form
    }
    return render(request, 'BaseApp/Dispute/create.html', context)
Exemplo n.º 23
0
 def test_render_template_tag(self):
     notify.send(User, recipient=self.user,
                 actor_text='Joe', verb='followed you')
     nf_list = Notification.objects.filter(recipient=self.user).active()
     rendered = self.RENDER_TEMPLATE.render(
         Context({'notifications': nf_list}))
     self.assertIn('followed you', rendered)
Exemplo n.º 24
0
 def test_single_user_notify(self):
     notify.send(User, recipient=self.recipient, actor=self.actor,
                 verb='poked you')
     notification = Notification.objects.get(pk=1)
     self.assertEqual(notification.recipient_id, self.recipient.id)
     timedelta = timezone.now() - notification.created
     self.assertLessEqual(timedelta.seconds, 60)
Exemplo n.º 25
0
 def test_render_template_tag(self):
     notify.send(User, recipient=self.user,
                 actor_text='Joe', verb='followed you')
     nf_list = Notification.objects.filter(recipient=self.user).active()
     rendered = self.RENDER_TEMPLATE.render(
         Context({'notifications': nf_list}))
     self.assertIn('followed you', rendered)
Exemplo n.º 26
0
def ticket(request, ticket_id):
    ticket = get_object_or_404(Ticket, pk=ticket_id)
    form = AnswerForm()
    if request.method == "POST":
        resolution = request.POST.get('resolution', '')
        ticket.resolution = resolution
        ticket.ticketState = Ticket.RESOLVED_STATUS
        ticket.staff = request.user
        ticket.resolved = datetime.now()
        ticket.save()
        notify.send(request.user,
                    recipient=ticket.user,
                    actor=request.user,
                    verb='followed you.',
                    nf_type='followed_by_one_user')
        return HttpResponseRedirect(reverse('helpdesk:tickets'))
    # if not _has_access_to_queue(request.user, ticket.queue):
    #     raise PermissionDenied()
    return render(
        request,
        'helpdesk/ticket_staff.html',
        {
            'ticket': ticket,
            'form': form,
            # 'form': form,
        })
Exemplo n.º 27
0
def comment_question_ajax(request, pk):
    question = get_object_or_404(Question, pk=pk)
    last_comment = Comment.objects.filter(question_comments=question).last()
    response_data = {}

    if request.method == 'POST':
        comment_text = request.POST.get('text')
        new_comment = highlight(strip_tags(comment_text))
        comment = Comment(content_object=question,
                          text=new_comment,
                          posted_by=request.user)
        comment.save()

        send_notify(request, question, 'answer', comment_text)

        if question.asked_by != request.user:
            notify.send(request.user,
                        recipient=question.asked_by,
                        actor=request.user,
                        verb='commented on your question',
                        obj=question,
                        nf_type='question_commented_on')

        response_data['id'] = comment.pk
        response_data['text_html'] = urlize(new_comment)
        response_data['posted_by'] = comment.posted_by.username
        response_data['posted_by_id'] = comment.posted_by.id
        response_data['posted_on'] = shorten_naturaltime(
            naturaltime(comment.posted_on))
        if last_comment is None:
            response_data['last_comment'] = "null"
        else:
            response_data['last_comment'] = last_comment.id

        return JsonResponse(response_data)
Exemplo n.º 28
0
def document_publish(request, document_pk):
    if request.method == 'POST':
        try:
            document = Document.objects.get(id=document_pk)
        except Document.DoesNotExist:
            return Http404("Document does not exist")
        else:
            if request.user != document.owner:
                return HttpResponse(
                    loader.render_to_string(
                        '401.html', RequestContext(
                        request, {
                        'error_message': _("you are not allowed to publish this document.")})), status=403)
                # return HttpResponse('you are not allowed to publish this document')
            group = document.group
            document.status = 'PENDING'
            document.current_iteration += 1
            document.save()
            document_submission_activity = DocumentSubmissionActivity(document=document, group=group, iteration=document.current_iteration)
            document_submission_activity.save()
            # notify organization admins about the new published document
            managers = list( group.get_managers())
            notify.send(request.user, recipient_list = managers, actor=request.user,
                        verb='pushed a new document for approval', target=document)
            # set all the permissions for all the managers of the group for this documentt
            document.set_managers_permissions()

            messages.info(request, 'Pushed document succesfully for approval')
            return HttpResponseRedirect(reverse('member-workspace-document'))
    else:
        return HttpResponseRedirect(reverse('member-workspace-document'))
Exemplo n.º 29
0
def accept(request, pk):
    if not request.user.is_authenticated:
        return HttpResponse('Not logged in', status=401)

    answer = Answer.objects.get(pk=pk)

    if answer.answered_by == answer.question.asked_by:
        return HttpResponseBadRequest('Answered by question-poster',
                                      status=400)

    if request.method == 'POST':
        accept_type = request.POST.get('accept_type')
        if accept_type == 'accept' and not answer.accepted:
            answer.accepted = True
            answer.save()
            answer.answered_by.accepted_answer()
            notify.send(request.user,
                        recipient=answer.answered_by,
                        actor=request.user,
                        verb='accepted your answer',
                        obj=answer,
                        target=answer.question,
                        nf_type='answer_accepted')
            return JsonResponse({'accept_type': accept_type})
        elif accept_type == 'cancel_accept' and answer.accepted:
            answer.accepted = False
            answer.save()
            answer.answered_by.accepted_answer_cancel()
            return JsonResponse({'accept_type': accept_type})
    else:
        return HttpResponseBadRequest('The request is not POST', status=400)
Exemplo n.º 30
0
def news_feed(request):
    posts = request.session['business'].business_base_posts.all().order_by('-is_important', 'changed_at')[:5]
    form = forms.PostForm((request.POST or None))
    if form.is_valid():
        instance = form.save(commit=False)
        instance.business = request.session['business']
        instance.save()
        followers = models.User.objects.filter(appuser__in=instance.business.followers.all())
        if followers:
            notify.send(request.user, recipient_list=list(followers), actor=instance.business,
                        verb='published new post.',
                        target=instance, nf_type='create')

        return redirect('default')
    if request.GET.get('like'):
        post = models.BasePost.objects.get(pk=request.GET.get('like'))
        post.followers.add(request.user.appuser)
    if request.GET.get('dislike'):
        post = models.BasePost.objects.get(pk=request.GET.get('dislike'))
        post.followers.remove(request.user.appuser)
    context = {
        'form': form,
        'posts': posts,
    }
    return render(request, 'BaseApp/NewsFeed/news_feed.html', context)
Exemplo n.º 31
0
def purchase_detail(request, purchase_id):
    try:
        purchase = Purchase.objects.get(pk=purchase_id)
    except Purchase.DoesNotExist:
        raise Http404("Purchase does not exist")
    comment_form = CommentForm(request.POST or None)

    if request.method == 'POST':
        if comment_form.is_valid():
            new_comment = Comment.objects.create(post=purchase,
                                                 author=request.user)
            new_comment.text = comment_form.cleaned_data['text']
            new_comment.save()
            notify.send(request.user,
                        recipient=purchase.owner.user,
                        actor=request.user,
                        verb='commented on your ',
                        target=purchase,
                        nf_type='comment')
            return render(request, 'purchase_detail.html',
                          {'purchase': purchase})

    return render(request, 'purchase_detail.html', {
        'purchase': purchase,
        'comment_form': comment_form
    })
Exemplo n.º 32
0
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save()
            for item in cart:
                OrderItem.objects.create(
                    order=order,
                    customer=request.user.profile.username,
                    product=item['product'],
                    price=item['price'],
                    calories=item['product'].calories,
                    quantity=item['quantity'])
                import pdb
                pdb.set_trace()
            # clear the cart
            cart.clear()
            order_created(order.id)
            request.session['order_id'] = order.id
            # import pdb
            # pdb.set_trace()
            customer_user = User.objects.get(username='******')
            notify.send(request.user,
                        recipient=customer_user,
                        actor=request.user,
                        verb='placed an order',
                        nf_type='followed_by_one_user')
            # redirect to the payment
            return redirect('shop:product_list')
            # return redirect('payment:process')

    else:
        form = OrderCreateForm()
    return render(request, 'orders/create.html', {'cart': cart, 'form': form})
Exemplo n.º 33
0
def group_invite(request, slug):
    group = get_object_or_404(GroupProfile, slug=slug)

    if not group.can_invite(request.user):
        raise Http404()

    form = GroupInviteForm(request.POST)

    if form.is_valid():
        for user in form.cleaned_data["invite_user_identifiers"].split("\n"):
            group.invite(
                user,
                request.user,
                role=form.cleaned_data["invite_role"],
            )

            # notify user that he/she is invited by the group
            try:
                requested_user = Profile.objects.get(email=user)
            except:
                pass
            else:
                notify.send(request.user, recipient=requested_user, actor=request.user,
                verb='invited you to join')

    return redirect("group_members", slug=group.slug)
Exemplo n.º 34
0
def return_equipment(request):
    if request.method == "POST":
        Issueance_pk = request.POST.get('Issueance_pk')
        if UserProfile.objects.get(user=request.user).is_admin == True:
            issue = Issueance.objects.get(pk=Issueance_pk)
            equipment = issue.equipmentInstance
            issue.returned = True
            issue.save()
            issue.return_date = timezone.now()
            equipment.is_available = True
            issue.save()
            equipment.save()
            followers = list(equipment.equipment.followers.all())
            notify.send(
                request.user,
                recipient_list=followers,
                actor=equipment,
                verb='is available now!.',
            )
            notification = "equipment returned"
            ctx = {
                'noti': True,
            }
            return HttpResponse(json.dumps(ctx),
                                content_type='application/json')
    ctx = {
        'noti': False,
    }
    return HttpResponse(json.dumps(ctx), content_type='application/json')
Exemplo n.º 35
0
def managers_delete(request, cast: Cast, pk: int):
    """
    Remove a user from cast managers
    """
    user = get_object_or_404(User, pk=pk)
    if cast.managers.count() < 2:
        messages.error(request, 'Casts must have at least one manager')
    elif request.user == user:
        messages.error(request, 'You cannot remove yourself')
    else:
        try:
            cast.remove_manager(user.profile)
        except ValueError as exc:
            messages.error(request, str(exc))
        else:
            notify.send(request.user,
                        recipient_list=cast.managers_as_user + [user],
                        actor=request.user,
                        verb='removed',
                        obj=user,
                        target=cast,
                        nf_type='cast_manager')
            messages.success(request,
                             f'{user.username} is no longer a manager')
    return redirect('cast_managers_edit', slug=cast.slug)
Exemplo n.º 36
0
def addarticle(request):
    if request.method == 'POST':
        form = articleForm(request.POST, request.FILES)
        if form.is_valid():
            article = form.save(commit=False)
            article.added_by = request.user
            article.save()

            # django notify
            post = article
            author = User.objects.get(username=request.user)
            author_friend = author.friend_set.all()
            friends = []
            for follower in author_friend:
                friend = follower.current_user
                friends.append(friend)

            followers = list(friends)

            if len(followers) >= 1:
                notify.send(request.user,
                            recipient_list=followers,
                            actor=post,
                            verb='posted',
                            nf_type='all')
            else:
                pass

            return redirect('articledetail', pk=article.pk)
    else:
        form = articleForm()
    return render(request, 'Marketplace/articleform.html', {'form': form})
Exemplo n.º 37
0
    def save_model(self, request, obj, form, change):
        u = []

        if obj.is_dirty():
            dirty_fields = obj.get_dirty_fields()
            #print(dirty_fields)
            for field in dirty_fields:
                if field == 'image':
                    user = User.objects.filter(is_superuser=False)
                    for x in user:
                        for y in x.profile.selected:
                            if y == obj.id:
                                u.append(x)
                    #print(u)
                    if not u:
                        recipient = user
                    else:
                        recipient = u
                    notify.send(sender=self,
                                target=obj,
                                recipient_list=list(recipient),
                                verb="updated")
                    for person in recipient:
                        subject = 'Notification of update'
                        verb = "updated"
                        message = render_to_string(
                            'darshan/notification_email.html', {
                                'target': obj,
                                'verb': verb
                            })
                        person.email_user(subject, message)
                    obj.save()
Exemplo n.º 38
0
 def test_render_template_tag_for_box(self):
     notify.send(User, recipient=self.user,
                 actor_text='Joe', verb='followed you')
     nf_list = Notification.objects.filter(recipient=self.user).active()
     rendered = self.RENDER_TEMPLATE_FOR_BOX.render(
         Context({'notifications': nf_list}))
     # to make things differentiable we'll use n-rTt-bx as a flag
     # in the default ``box`` template.
     self.assertIn('n-rTt-bx', rendered)
     self.assertIn('followed you', rendered)
Exemplo n.º 39
0
    def test_multiple_user_notify(self):
        notify.send(User, recipient_list=list(self.recipient_list),
                    actor=self.actor, verb='uploaded a new video')
        notifications = Notification.objects.filter(verb__startswith='u')
        self.assertEqual(notifications.count(), self.no_of_users)

        username_list = [u.username for u in self.recipient_list]

        for nf in notifications:
            self.assertIn(nf.recipient.username, username_list)
            timedelta = timezone.now() - nf.created
            self.assertLessEqual(timedelta.seconds, 60)
Exemplo n.º 40
0
def document_remove(request, docid, template='documents/document_remove.html'):
    try:
        document = _resolve_document(
            request,
            docid,
            'base.delete_resourcebase',
            _PERMISSION_MSG_DELETE)

        if request.method == 'GET':
            return render_to_response(template, RequestContext(request, {
                "document": document
            }))

        if request.method == 'POST':

            if getattr(settings, 'SLACK_ENABLED', False):
                slack_message = None
                try:
                    from geonode.contrib.slack.utils import build_slack_message_document
                    slack_message = build_slack_message_document("document_delete", document)
                except:
                    print "Could not build slack message for delete document."

                document.delete()
                # notify document owner that someone have deleted the document
                if request.user != document.owner:
                    recipient = document.owner
                    notify.send(request.user, recipient=recipient, actor=request.user,
                    target=document, verb='deleted your document')

                try:
                    from geonode.contrib.slack.utils import send_slack_messages
                    send_slack_messages(slack_message)
                except:
                    print "Could not send slack message for delete document."
            else:
                document.delete()
                # notify document owner that someone have deleted the document
                if request.user != document.owner:
                    recipient = document.owner
                    notify.send(request.user, recipient=recipient, actor=request.user,
                    target=document, verb='deleted your document')

            return HttpResponseRedirect(reverse("document_browse"))
        else:
            return HttpResponse("Not allowed", status=403)

    except PermissionDenied:
        return HttpResponse(
            loader.render_to_string(
                '401.html', RequestContext(
                    request, {
                        'error_message': _("You are not allowed to delete this document.")})), status=401)
Exemplo n.º 41
0
def userinvitation(request, slug):
    """

    """
    if request.method == 'POST':
        group = get_object_or_404(GroupProfile, slug=slug)
        if group.access == "public-invite":
            user_invitation = UserInvitationModel(user=request.user, group=group, state='pending')
            user_invitation.save()
            managers = list(group.get_managers())
            notify.send(request.user, recipient_list=managers, actor=request.user,
                    target=group, verb='requested to join {}'.format(group.title))
            return redirect("group_detail", slug=slug)
Exemplo n.º 42
0
    def setUp(self):
        self.recipient = User.objects.create(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.actor = User.objects.create(username='******',
                                         email='*****@*****.**',
                                         password='******')
        self.nf_count = 10

        self.assertEqual(self.recipient.id, 1)
        self.assertEqual(self.actor.id, 2)

        for x in range(self.nf_count):
            notify.send(User, recipient=self.recipient, actor=self.actor,
                        verb='followed you')
Exemplo n.º 43
0
def document_deny(request, document_pk):
    if request.method == 'POST':
        form = ResourceDenyForm(request.POST)
        if form.is_valid():
            try:
                document = Document.objects.get(id=document_pk)
            except Document.DoesNotExist:
                return Http404("requested document does not exists")
            else:
                group = document.group
                if request.user not in group.get_managers():
                    return HttpResponse(
                        loader.render_to_string(
                            '401.html', RequestContext(
                            request, {
                            'error_message': _("you are not allowed to deny this document.")})), status=401)
                    # return HttpResponse("you are not allowed to deny this document")
                document_submission_activity = DocumentSubmissionActivity.objects.get(document=document, group=group, iteration=document.current_iteration)
                document_audit_activity= DocumentAuditActivity(document_submission_activity=document_submission_activity)
                comment_body = request.POST.get('comment')
                comment_subject = request.POST.get('comment_subject')
                document.status = 'DENIED'
                document.last_auditor = request.user
                document.save()

                # notify document owner that someone have deleted the document
                if request.user != document.owner:
                    recipient = document.owner
                    notify.send(request.user, recipient=recipient, actor=request.user,
                    target=document, verb='deleted your document')

                document_submission_activity.is_audited = True
                document_submission_activity.save()

                document_audit_activity.comment_subject = comment_subject
                document_audit_activity.comment_body = comment_body
                document_audit_activity.result = 'DECLINED'
                document_audit_activity.auditor = request.user
                document_audit_activity.save()

            messages.info(request, 'Denied document successfully')
            return HttpResponseRedirect(reverse('admin-workspace-document'))
        else:
            messages.info(request, 'Please write a deny comment and try again')
            return HttpResponseRedirect(reverse('admin-workspace-document'))

    else:
        return HttpResponseRedirect(reverse('admin-workspace-document'))
Exemplo n.º 44
0
def layer_deny(request, layer_pk):
    if request.method == 'POST':
        form = ResourceDenyForm(data=request.POST)
        if form.is_valid():

            try:
                layer = Layer.objects.get(id=layer_pk)
            except:
                return Http404("requested layer does not exists")
            else:
                group = layer.group
                if request.user not in group.get_managers():
                    return HttpResponse(
                        loader.render_to_string(
                            '401.html', RequestContext(
                            request, {
                            'error_message': _("You are not allowed to deny this layer.")})), status=401)
                    # return HttpResponse("you are not allowed to deny this layer")
                layer_submission_activity = LayerSubmissionActivity.objects.get(layer=layer, group=group, iteration=layer.current_iteration)
                layer_audit_activity = LayerAuditActivity(layer_submission_activity=layer_submission_activity)
                comment_body = request.POST.get('comment')
                comment_subject = request.POST.get('comment_subject')
                layer.status = 'DENIED'
                layer.last_auditor = request.user
                layer.save()

                # notify layer owner that someone have denied the layer
                if request.user != layer.owner:
                    recipient = layer.owner
                    notify.send(request.user, recipient=recipient, actor=request.user,
                    target=layer, verb='denied your layer')

                layer_submission_activity.is_audited = True
                layer_submission_activity.save()

                layer_audit_activity.comment_subject = comment_subject
                layer_audit_activity.comment_body = comment_body
                layer_audit_activity.result = 'DECLINED'
                layer_audit_activity.auditor = request.user
                layer_audit_activity.save()

            messages.info(request, 'layer denied successfully')
            return HttpResponseRedirect(reverse('admin-workspace-layer'))
        else:
            messages.info(request, 'Please write a deny comment and try again')
            return HttpResponseRedirect(reverse('admin-workspace-layer'))
    else:
        return HttpResponseRedirect(reverse('admin-workspace-layer'))
Exemplo n.º 45
0
def appointment_details(request, appointment_id):
    object = get_object_or_404(models.Appointment, pk=appointment_id)
    if request.GET.get('accept'):
        object.status = 'accepted'
        object.save()
        notify.send(request.user, recipient=object.user.user, actor=object.business,
                    verb='accepted your order.', target=object, nf_type='accept')
    elif request.GET.get('reject'):
        object.status = 'rejected'
        object.save()
        notify.send(request.user, recipient=object.user.user, actor=object.business,
                    verb='rejected your order.', target=object, nf_type='reject')
    context = {
        'object': object,
    }
    return render(request, 'BaseApp/Appointment/details.html', context)
Exemplo n.º 46
0
def dispute_details(request, dispute_id):
    object = request.session['business'].business_disputes.get(pk=dispute_id)
    if request.GET.get('accept'):
        object.status = 'accepted'
        object.save()
        notify.send(request.user, recipient=object.user.user, actor=object.business,
                    verb='accepted your order.', target=object, nf_type='accept')
    elif request.GET.get('reject'):
        object.status = 'rejected'
        object.save()
        notify.send(request.user, recipient=object.user.user, actor=object.business,
                    verb='rejected your order.', target=object, nf_type='reject')
    context = {
        "object": object,
    }
    return render(request, 'BaseApp/Dispute/details.html', context)
Exemplo n.º 47
0
    def setUp(self):
        user = User(username='******', email='*****@*****.**')
        user.set_password('pwd@user')
        user.save()

        self.user = User.objects.get(username='******')

        actor = User.objects.create_user('actor', '*****@*****.**',
                                         'pwd@actor')

        for x in range(10):
            notify.send(User, recipient=self.user, actor=actor,
                        verb='followed you', nf_type='followed_you')

        factory = RequestFactory()
        self.request = factory.get('/foobar/')
Exemplo n.º 48
0
def discount_benefit_create(request):
    form = forms.DiscountBenefitForm(request.POST or None)
    items = models.Item.objects.filter(catalog__business__id=request.session['business'].id).exclude(
        itemdiscount__new_price__gte=0)
    services = models.Service.objects.filter(catalog__business__id=request.session['business'].id).exclude(
        servicediscount__new_price__gte=0)
    if form.is_valid():
        instance = form.save(commit=False)
        base_benefit = request.session['BaseBenefit']
        base_benefit.business = request.session['business']
        base_benefit.save()
        instance.benefit = base_benefit
        instance.save()
        if instance.discount_type == 'item_discounts':
            print()
            selected = request.POST.getlist('item_checks')
            for item in items:
                if str(item.id) in selected:
                    item_discount = models.ItemDiscount()
                    item_discount.new_price = item.price * (1 - (instance.discount_percentage / 100))
                    item_discount.item = item
                    item_discount.save()
                    instance.item_discounts.add(item_discount)
        elif instance.discount_type == 'service_discounts':
            selected = request.POST.getlist('service_checks')
            for service in services:
                if str(service.id) in selected:
                    service_discount = models.ServiceDiscount()
                    service_discount.new_price = service.price * (1 - (instance.discount_percentage / 100))
                    service_discount.service = service
                    service_discount.save()
                    instance.service_discounts.add(service_discount)
        else:
            purchase_amount = request.POST.get('purchase_amount')
            instance.purchase_amount_discount = float(purchase_amount)
        instance.save()
        followers = models.User.objects.filter(appuser__in=base_benefit.business.followers.all())
        if followers:
            notify.send(request.user, recipient_list=list(followers), actor=base_benefit.business,
                        verb='created a new discount benefit.', target=instance, nf_type='create')
        return redirect('default')
    context = {
        'form': form,
        'items': items,
        'services': services,
    }
    return render(request, 'BaseApp/BaseBenefit/DiscountBenefit/create.html', context)
Exemplo n.º 49
0
def map_deny(request, map_pk):
    if request.method == 'POST':
        form = ResourceDenyForm(request.POST)
        if form.is_valid():
            try:
                map = Map.objects.get(id=map_pk)
            except:
                return Http404("requested map does not exists")
            else:
                group = map.group
                if request.user not in group.get_managers():
                    return HttpResponse(
                        loader.render_to_string(
                            '401.html', RequestContext(
                            request, {
                            'error_message': _("You are not allowed to deny this map.")})), status=401)
                    # return HttpResponse("you are not allowed to deny this map")
                map_submission_activity = MapSubmissionActivity.objects.get(map=map, group=group, iteration=map.current_iteration)
                map_audit_activity= MapAuditActivity(map_submission_activity=map_submission_activity)
                comment_body = request.POST.get('comment')
                comment_subject = request.POST.get('comment_subject')
                map.status = 'DENIED'
                map.last_auditor = request.user
                map.save()

                # notify map owner that someone have denied the map
                if request.user != map.owner:
                    recipient = map.owner
                    notify.send(request.user, recipient=recipient, actor=request.user,
                    target=map, verb='denied your map')

                map_submission_activity.is_audited = True
                map_submission_activity.save()

                map_audit_activity.comment_subject = comment_subject
                map_audit_activity.comment_body = comment_body
                map_audit_activity.result = 'DECLINED'
                map_audit_activity.auditor = request.user
                map_audit_activity.save()

            messages.info(request, 'Denied map successfully')
            return HttpResponseRedirect(reverse('admin-workspace-map'))
        else:
            messages.info(request, 'Please write an deny comment and try again')
            return HttpResponseRedirect(reverse('admin-workspace-map'))
    else:
        return HttpResponseRedirect(reverse('admin-workspace-map'))
Exemplo n.º 50
0
def order_create(request):
    business_id = request.GET.get('order_business_id')
    business = models.Business.objects.get(pk=business_id)
    items_list = models.Item.objects.all().filter(catalog__business__id=business_id)
    form = forms.OrderForm(request.POST or None)
    address_form = forms.AddressForm(request.POST or None)
    if form.is_valid() & address_form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user.appuser
        business = get_object_or_404(models.Business, id=int(request.GET.get('order_business_id')))
        instance.business = business
        instance.save()
        total = 0
        for item in items_list:
            item_id = 'item_' + str(item.id)
            quantity = int(request.POST[item_id])
            if quantity > 0:
                total += (item.price * quantity)
                item_order = models.ItemOrder()
                item_order.item = item
                item_order.order = instance
                item_order.quantity = quantity
                item_order.save()
        instance.total = total
        address = address_form.save(commit=False)
        print("heloooooooooooooooooooooooooooooooooooooooo"+request.POST.get('address_raw'))
        address.raw = request.POST.get('address_raw')
        address.save()
        instance.address = address
        create_conversation(instance, business, request.user.appuser)
        instance.save()
        get_order_benefits(instance)
        assign_coupons_to_order(request, instance)
        use_order_benefits(instance)

        managers = models.User.objects.filter(appuser__in=business.managers.all())
        notify.send(request.user, recipient_list=list(managers.all()), actor=request.user.appuser,
                    verb='created new order.', target=instance, nf_type='create')
        return redirect('my user order list')
    context = {
        'items_list': items_list,
        'form': form,
        'address_form': address_form,
        'business': business,
    }
    return render(request, 'BaseApp/Order/create.html', context)
Exemplo n.º 51
0
def map_remove(request, mapid, template='maps/map_remove.html'):
    ''' Delete a map, and its constituent layers. '''
    map_obj = _resolve_map(request, mapid, 'base.delete_resourcebase', _PERMISSION_MSG_VIEW)

    if request.method == 'GET':
        return render_to_response(template, RequestContext(request, {
            "map": map_obj
        }))

    elif request.method == 'POST':

        if getattr(settings, 'SLACK_ENABLED', False):

            slack_message = None
            try:
                from geonode.contrib.slack.utils import build_slack_message_map
                slack_message = build_slack_message_map("map_delete", map_obj)
            except:
                print "Could not build slack message for delete map."

            delete_map.delay(object_id=map_obj.id)
            # notify map owner that someone have deleted the map
            if request.user != map_obj.owner:
                recipient = map_obj.owner
                notify.send(request.user, recipient=recipient, actor=request.user,
                target=map_obj, verb='deleted your map')

            try:
                from geonode.contrib.slack.utils import send_slack_messages
                send_slack_messages(slack_message)
            except:
                print "Could not send slack message for delete map."

        else:
            delete_map.delay(object_id=map_obj.id)
            # notify map owner that someone have deleted the map
            if request.user != map_obj.owner:
                recipient = map_obj.owner
                notify.send(request.user, recipient=recipient, actor=request.user,
                target=map_obj, verb='deleted your map')

        return HttpResponseRedirect(reverse("maps_browse"))
Exemplo n.º 52
0
def catalog_create(request, business_id):
    if str(request.session['business'].id) != business_id:
        return redirect('default')
    business = get_object_or_404(models.Business, pk=business_id)
    form = forms.CatalogForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.changed_at = datetime.now()
        instance.business = business
        instance.save()
        followers = models.User.objects.filter(appuser__in=business.followers.all())
        if followers:
            notify.send(request.user, recipient_list=list(followers), actor=business, verb='created a new catalog.',
                        target=instance, nf_type='create')
        return redirect('catalog list', business_id)
    context = {
        'business_id': int(business_id),
        'form': form,
    }
    return render(request, 'BaseApp/Catalog/create.html', context)
Exemplo n.º 53
0
def create_appointment_select_service_and_date(request):
    if request.GET.get('business_id'):
        request.session['appointment_business_id'] = request.GET.get('business_id')

    if request.GET.get('service_id') and request.GET.get('date'):
        request.session['appointment_service_id'] = request.GET.get('service_id')
        request.session['appointment_date'] = request.GET.get('date')
        return create_appointment_select_time(request)

    if request.GET.get('date_time'):
        object = request.GET.get('date_time')
        date_time = datetime.strptime(object, "%d/%m/%Y %H:%M")
        business_id = request.session['appointment_business_id']
        business = models.Business.objects.all().get(pk=business_id)
        service_id = request.session['appointment_service_id']
        service = models.Service.objects.all().get(pk=service_id)
        appointment = models.Appointment()
        appointment.service = service
        appointment.business = business
        appointment.date = date_time
        appointment.user = request.user.appuser
        try:
            appointment.total = service.servicediscount.new_price
        except:
            appointment.total = service.price
        appointment.save()
        create_conversation(appointment, business, request.user.appuser)
        managers = models.User.objects.filter(appuser__in=appointment.business.managers.all())
        notify.send(request.user, recipient_list=list(managers.all()), actor=request.user.appuser,
                    verb='created new appointment.', target=appointment, nf_type='create')
        appointment.save()
        return redirect('my user appointment list')

    service_list = models.Service.objects.all().filter(catalog__business__id=request.session['appointment_business_id'])
    context = {
        'service_list': service_list,
    }
    return render(request, 'BaseApp/Appointment/create_1.html', context)
Exemplo n.º 54
0
def ticket_benefit_create(request):
    form = forms.TicketBenefitForm(request.POST or None)
    items = models.Item.objects.filter(catalog__business__id=request.session['business'].id)
    services = models.Service.objects.filter(catalog__business__id=request.session['business'].id)
    if form.is_valid():
        instance = form.save(commit=False)
        base_benefit = request.session['BaseBenefit']
        base_benefit.business = request.session['business']
        base_benefit.save()
        instance.benefit = base_benefit
        instance.required_punches -= 1
        instance.save()
        if instance.reward_type == 'item_reward':
            selected = request.POST.get('item_checks')
            for item in items:
                if str(item.id) == selected:
                    instance.item_reward = item
        elif instance.reward_type == 'service_reward':
            selected = request.POST.get('service_checks')
            for service in services:
                if str(service.id) == selected:
                    instance.service_reward = service
        else:
            money_reward = request.POST.get('money_reward')
            instance.money_reward = money_reward
        instance.save()
        followers = models.User.objects.filter(appuser__in=base_benefit.business.followers.all())
        if followers:
            notify.send(request.user, recipient_list=list(followers), actor=base_benefit.business,
                        verb='created a new ticket benefit.', target=instance, nf_type='create')
        return redirect('default')
    context = {
        'form': form,
        'items': items,
        'services': services,
    }
    return render(request, 'BaseApp/BaseBenefit/TicketBenefit/create.html', context)
Exemplo n.º 55
0
def post_comment(request, content_type_id, object_id, form_class=CommentForm):
    content_type = get_object_or_404(ContentType, pk=content_type_id)
    obj = get_object_or_404(content_type.model_class(), pk=object_id)
    form = form_class(request.POST, request=request, obj=obj, user=request.user)
    if form.is_valid():
        comment = form.save()
        # notify resource owner that someone have commented on his resource
        if request.user != obj.owner:
            recipient = obj.owner
            notify.send(request.user, recipient=recipient, actor=request.user,
            target=obj, verb='commented on your {0}'.format(content_type.name))

        commented.send(sender=post_comment, comment=comment, request=request)
        if request.is_ajax():
            return HttpResponse(json.dumps({
                "status": "OK",
                "comment": dehydrate_comment(comment),
                "html": render_to_string("dialogos/_comment.html", {
                    "comment": comment
                }, context_instance=RequestContext(request))
            }), content_type="application/json")
    else:
        if request.is_ajax():
            return HttpResponse(json.dumps({
                "status": "ERROR",
                "errors": form.errors,
                "html": render_to_string("dialogos/_form.html", {
                    "form": form,
                    "obj": obj
                }, context_instance=RequestContext(request))
            }), content_type="application/json")
    redirect_to = request.POST.get("next")
    # light security check -- make sure redirect_to isn't garbage.
    if not redirect_to or " " in redirect_to or redirect_to.startswith("http"):
        redirect_to = obj
    return redirect(redirect_to)
Exemplo n.º 56
0
    def setUp(self):
        self.no_of_users = 10

        # Create recipients
        users = []
        for i in range(self.no_of_users):
            u = User(username='******' % i, email='*****@*****.**' % i)
            u.set_password('pwd@user')
            users.append(u)
        User.objects.bulk_create(users)

        # Create actor
        actor = User.objects.create(username='******',
                                    email='*****@*****.**')
        actor.set_password('pwd@actor')
        actor.save()
        self.actor = User.objects.get(username="******")

        self.recipient = User.objects.get(username='******')

        self.recipient_list = User.objects.filter(
            username__startswith='u').order_by('id')

        # Send notifications to all recipients.
        notify.send(User, recipient_list=list(self.recipient_list),
                    actor=self.actor, verb='wrote a new blog post.')

        # Send some more notifications to a specific user.
        self.recipient_nf_count = 11
        for i in range(10):
            notify.send(User, recipient=self.recipient, actor_text='You',
                        verb='reached level %r' % i)

        # Login this recipient
        self.assertTrue(self.client.login(username="******",
                                          password="******"))
Exemplo n.º 57
0
def map_approve(request, map_pk):
    if request.method == 'POST':
        form = ResourceApproveForm(request.POST)
        if form.is_valid():
            try:
                map = Map.objects.get(id=map_pk)
            except Map.DoesNotExist:
                return Http404("requested map does not exists")
            else:
                group = map.group
                if request.user not in group.get_managers():
                    if request.user != map.owner:
                        return HttpResponse(
                        loader.render_to_string(
                            '401.html', RequestContext(
                            request, {
                            'error_message': _("You are not allowed to approve this map.")})), status=401)
                    # return HttpResponse("you are not allowed to approve this map")
                map_submission_activity = MapSubmissionActivity.objects.get(map=map, group=group, iteration=map.current_iteration)
                map_audit_activity = MapAuditActivity(map_submission_activity=map_submission_activity)
                comment_body = request.POST.get('comment')
                comment_subject = request.POST.get('comment_subject')
                map.status = 'ACTIVE'
                map.last_auditor = request.user
                map.save()

                permissions = _perms_info_json(map)
                perm_dict = json.loads(permissions)
                if request.POST.get('view_permission'):
                    if not 'AnonymousUser' in perm_dict['users']:
                        perm_dict['users']['AnonymousUser'] = []
                        perm_dict['users']['AnonymousUser'].append('view_resourcebase')
                    else:
                        if not 'view_resourcebase' in perm_dict['users']['AnonymousUser']:
                            perm_dict['users']['AnonymousUser'].append('view_resourcebase')

                if request.POST.get('download_permission'):
                    if not 'AnonymousUser' in perm_dict['users']:
                        perm_dict['users']['AnonymousUser'] = []
                        perm_dict['users']['AnonymousUser'].append('download_resourcebase')
                    else:
                        if not 'download_resourcebase' in perm_dict['users']['AnonymousUser']:
                            perm_dict['users']['AnonymousUser'].append('download_resourcebase')

                map.set_permissions(perm_dict)



                # notify map owner that someone have approved the map
                if request.user != map.owner:
                    recipient = map.owner
                    notify.send(request.user, recipient=recipient, actor=request.user,
                    target=map, verb='approved your map')

                map_submission_activity.is_audited = True
                map_submission_activity.save()

                map_audit_activity.comment_subject = comment_subject
                map_audit_activity.comment_body = comment_body
                map_audit_activity.result = 'APPROVED'
                map_audit_activity.auditor = request.user
                map_audit_activity.save()

            messages.info(request, 'Approved map succesfully')
            return HttpResponseRedirect(reverse('admin-workspace-map'))
        else:
            messages.info(request, 'Please write an approve comment and try again')
            return HttpResponseRedirect(reverse('admin-workspace-map'))
    else:
        return HttpResponseRedirect(reverse('admin-workspace-map'))