Example #1
0
    def test_badge_associated_to_user(self):
        badge_type = BadgeType.objects.get(identifier="models_1")
        badge = Badge(proprietary=self.user, badge_type=badge_type)
        badge.save()

        self.assertEqual(1, self.user.badges.count())
        self.assertEqual(badge, self.user.badges.all()[0])
Example #2
0
def user_creates_badge(username, title):
    user = get_user(username)
    badge = Badge(
        title = title, 
        description = "Example description", 
        creator = user
    )
    badge.save()
Example #3
0
    def apply_state_update_badges(self):
        if 'badges' not in settings.INSTALLED_APPS:
            return

        from badges.models import Badge

        # Only touch badges for events in the future
        for badge in self.badges.filter(personnel_class__event__start_time__gte=now()):
            Badge.ensure(person=self, event=badge.personnel_class.event)
Example #4
0
def award_badge(badge_identifier, user, model=None):
    """Create badge object related to user and model."""


    badge_type = BadgeType.objects.get(identifier=badge_identifier)
    badge = Badge(badge_type=badge_type, proprietary=user, model=model)
    try:
        badge.save()
    except Badge.AlreadyExists:
        pass
Example #5
0
    def apply_state_update_badges(self):
        if 'badges' not in settings.INSTALLED_APPS:
            return

        from badges.models import Badge

        # Only touch badges for events in the future
        for badge in self.badges.filter(
                personnel_class__event__start_time__gte=now()):
            Badge.ensure(person=self, event=badge.personnel_class.event)
Example #6
0
    def apply_state_create_badges(self):
        if 'badges' not in settings.INSTALLED_APPS:
            return

        if self.event.badges_event_meta is None:
            return

        from badges.models import Badge

        Badge.ensure(event=self.event, person=self.person)
Example #7
0
    def apply_state_create_badges(self):
        if 'badges' not in settings.INSTALLED_APPS:
            return

        if self.event.badges_event_meta is None:
            return

        from badges.models import Badge

        Badge.ensure(event=self.event, person=self.person)
    def handle(*args, **opts):
        from programme.models import Programme
        from core.models import Event
        from badges.models import Badge

        for event_slug in args[1:]:
            event = Event.objects.get(slug=event_slug)

            for programme in Programme.objects.filter(category__event=event):
                for person in programme.organizers.all():
                    print person
                    Badge.get_or_create(event=event, person=person)
Example #9
0
    def apply_state_create_badges(self, deleted_programme_roles=[]):
        if 'badges' not in settings.INSTALLED_APPS:
            return

        if self.event.badges_event_meta is None:
            return

        from badges.models import Badge

        for person in self.organizers.all():
            Badge.ensure(event=self.event, person=person)

        for deleted_programme_role in deleted_programme_roles:
            Badge.ensure(event=self.event, person=deleted_programme_role.person)
Example #10
0
    def apply_state_create_badges(self, deleted_programme_roles=[]):
        if 'badges' not in settings.INSTALLED_APPS:
            return

        if self.event.badges_event_meta is None:
            return

        from badges.models import Badge

        for person in self.organizers.all():
            Badge.ensure(event=self.event, person=person)

        for deleted_programme_role in deleted_programme_roles:
            Badge.ensure(event=self.event, person=deleted_programme_role.person)
Example #11
0
    def apply_state_create_badges(self):
        if 'badges' not in settings.INSTALLED_APPS:
            return

        if self.event.badges_event_meta is None:
            return

        if not self.is_accepted:
            return

        # TODO revoke badge if one exists but shouldn't

        from badges.models import Badge
        Badge.get_or_create(event=self.event, person=self.person)
    def handle(*args, **opts):
        from programme.models import Programme
        from core.models import Event
        from badges.models import Badge

        for event_slug in args[1:]:
            event = Event.objects.get(slug=event_slug)

            for programme in Programme.objects.filter(category__event=event).exclude(state__in=['rejected', 'cancelled']):
                for person in programme.organizers.all():
                    try:
                        Badge.ensure(event=event, person=person)
                        print person
                    except Badge.MultipleObjectsReturned:
                        print u'WARNING: Multiple badges for', person
Example #13
0
    def apply_state_create_badges(self):
        if 'badges' not in settings.INSTALLED_APPS:
            return

        if self.event.badges_event_meta is None:
            return

        if not self.is_accepted:
            return

        # TODO revoke badge if one exists but shouldn't

        from badges.models import Badge
        badge, created = Badge.get_or_create(event=self.event, person=self.person)

        # Update job title if it is not too late
        if (
            # Just a short-circuit optimization – the job title cannot change if the badge was just created
            not created

            # Don't touch badges of other apps (for example, programme)
            and badge.personnel_class.app_label == 'labour'

            # Don't touch badges that are already printed (XXX should revoke and re-create)
            and badge.batch is None

            # Finally, check if the job title needs update
            and badge.job_title != signup.job_title
        ):
            badge.job_title = signup.job_title
            badge.save()
Example #14
0
 def setUp(self):
     self.c = Client()
     
     # Create the test badge.
     self.b = Badge( name = "The Super Badge",
                     shortname = "superbadge",
                     description = "This badge is quite super.",
                     graphic = "superbadge" )
     self.b.save()
     
     # Create some test users.
     self.u1 = User.objects.create_user("ishara",
                                        "*****@*****.**",
                                        "ishararulz")
     self.u2 = User.objects.create_user("alexis",
                                        "*****@*****.**",
                                        "alexisrulz")
     self.s1 = Student( user=self.u1 )
     self.s2 = Student( user=self.u2 )
     self.s1.save()
     self.s2.save()
     
     # Award the badge to s1
     self.b.awarded_to.add( self.s2 )
     self.b.save()
     
     # Give the test users memorable names.
     self.ishara = self.s1
     self.alexis = self.s2
Example #15
0
def helper_saved(sender, instance, using, **kwargs):
    """ Add badge and gifts to helper if necessary.

    This is a signal handler, that is called, when a helper is saved. It
    adds the badge if badge creation is enabled and it is not there already.
    """
    if instance.event:
        if instance.event.badges and not hasattr(instance, 'badge'):
            badge = Badge()
            badge.helper = instance
            badge.save()

        if instance.event.gifts and not hasattr(instance, 'gifts'):
            gifts = HelpersGifts()
            gifts.helper = instance
            gifts.save()
Example #16
0
def event_saved(sender, instance, using, **kwargs):
    """ Add badge settings, badges and gifts if necessary.

    This is a signal handler, that is called, when a event is saved. It
    adds the badge settings if badge creation is enabled and it is not
    there already. It also adds badge defaults to all jobs and badges to all
    helpers and coordinators if necessary.
    """
    if instance.badges:
        # badge settings for event
        if not instance.badge_settings:
            settings = BadgeSettings()
            settings.event = instance
            settings.save()

        # badge defaults for jobs
        for job in instance.job_set.all():
            if not job.badge_defaults:
                defaults = BadgeDefaults()
                defaults.save()

                job.badge_defaults = defaults
                job.save()

        # badge for helpers
        for helper in instance.helper_set.all():
            if not hasattr(helper, 'badge'):
                badge = Badge()
                badge.helper = helper
                badge.save()

    if instance.gifts:
        for helper in instance.helper_set.all():
            if not hasattr(helper, 'gifts'):
                gifts = HelpersGifts()
                gifts.helper = helper
                gifts.save()

    if instance.inventory:
        if not instance.inventory_settings:
            InventorySettings.objects.create(event=instance)
Example #17
0
    def _setup_badge_settings(self):
        """
        Set up badges for all jobs and helpers (called from post_save handler).

        It adds the badge settings if badge creation is enabled and it is not there already.
        It also adds badge defaults to all jobs and badges to all helpers and coordinators if necessary.
        """
        # badge settings for event
        if not self.badge_settings:
            settings = BadgeSettings()
            settings.event = self
            settings.save()

        # badge defaults for jobs
        for job in self.job_set.all():
            if not job.badge_defaults:
                defaults = BadgeDefaults()
                defaults.save()

                job.badge_defaults = defaults
                job.save()

        # badge for helpers
        for helper in self.helper_set.all():
            if not hasattr(helper, 'badge'):
                badge = Badge()
                badge.event = self
                badge.helper = helper
                badge.save()
Example #18
0
def create_badge_for_comment(request, comment_id):
    comment = get_object_or_404(Comment, id=comment_id)
    if comment.is_deleted:
        raise BadRequest(
            title="😵 Комментарий удалён",
            message="Нельзя выдавать награды за удалённые комменты")
    if comment.author.deleted_at:
        raise BadRequest(title="😵 Пользователь удалился",
                         message="Нельзя выдавать награды удалённым юзерам")
    if comment.author == request.me:
        raise BadRequest(title="😵 Это же ты",
                         message="Нельзя выдавать награды самому себе")
    if request.method != "POST":
        if request.me.membership_days_left(
        ) < settings.MIN_DAYS_TO_GIVE_BADGES:
            return render(request, "badges/messages/insufficient_funds.html")

        return render(request, "badges/create.html", {
            "comment": comment,
            "badges": Badge.visible_objects().all(),
        })

    badge_code = request.POST.get("badge_code")
    badge = Badge.objects.filter(code=badge_code).first()
    if not badge or not badge.is_visible:
        raise BadRequest(title="🙅‍♀️ Бейджик недоступен",
                         message="Данную награду пока нельзя выдавать")

    note = (request.POST.get("note") or "")[:1000]
    user_badge = UserBadge.create_user_badge(
        badge=badge,
        from_user=request.me,
        to_user=comment.author,
        comment=comment,
        note=note,
    )

    # bump post on home page by updating its last_activity_at
    Post.objects.filter(id=comment.post_id).update(
        last_activity_at=datetime.utcnow())

    # show insufficient funds warning if < 3 months
    show_funds_warning = request.me.membership_days_left() - \
        user_badge.badge.price_days < settings.MIN_DAYS_TO_GIVE_BADGES * 3

    return render(request, "badges/messages/success.html", {
        "user_badge": user_badge,
        "show_funds_warning": show_funds_warning,
    })
Example #19
0
    def create(self, request):
        """POST to create a new badge"""
        data = request.data

        if 'title' not in data:
            resp = rc.BAD_REQUEST
            resp.write('title required')
            return resp

        new_badge = Badge(
            creator=request.user,
            updated_at=datetime.now(),
            title = data['title'], 
            slug = slugify(data['title']),
            description = data.get('description', ''),
            autoapprove = data.get('autoapprove', False),
            only_creator_can_nominate = 
                data.get('only_creator_can_nominate', False),
        )

        try:
            new_badge.validate_unique()
        except ValidationError, e:
            return rc.DUPLICATE_ENTRY
Example #20
0
def create_badge_for_post(request, post_slug):
    post = get_object_or_404(Post, slug=post_slug)
    if post.deleted_at:
        raise BadRequest(title="😵 Пост удалён",
                         message="Нельзя давать награды за удалённые посты")

    if request.method != "POST":
        if request.me.membership_days_left(
        ) < settings.MIN_DAYS_TO_GIVE_BADGES:
            return render(request, "badges/messages/insufficient_funds.html")

        return render(request, "badges/create.html", {
            "post": post,
            "badges": Badge.visible_objects().all(),
        })

    badge_code = request.POST.get("badge_code")
    badge = Badge.objects.filter(code=badge_code).first()
    if not badge or not badge.is_visible:
        raise BadRequest(title="🙅‍♀️ Бейджик недоступен",
                         message="Данную награду пока нельзя выдавать")

    note = (request.POST.get("note") or "")[:1000]
    user_badge = UserBadge.create_user_badge(
        badge=badge,
        from_user=request.me,
        to_user=post.author,
        post=post,
        note=note,
    )

    # bump post on home page by updating its last_activity_at
    Post.objects.filter(id=post.id).update(last_activity_at=datetime.utcnow())

    # show insufficient funds warning if < 3 months
    show_funds_warning = request.me.membership_days_left() - \
        user_badge.badge.price_days < settings.MIN_DAYS_TO_GIVE_BADGES * 3

    return render(request, "badges/messages/success.html", {
        "user_badge": user_badge,
        "show_funds_warning": show_funds_warning,
    })
Example #21
0
 def personnel_class_name(self):
     from badges.models import Badge
     badge, unused = Badge.ensure(event=self.event, person=self.person)
     return badge.personnel_class.name if badge else ''
Example #22
0
class BadgeTests(TestCase):
    def setUp(self):
        self.c = Client()
        
        # Create the test badge.
        self.b = Badge( name = "The Super Badge",
                        shortname = "superbadge",
                        description = "This badge is quite super.",
                        graphic = "superbadge" )
        self.b.save()
        
        # Create some test users.
        self.u1 = User.objects.create_user("ishara",
                                           "*****@*****.**",
                                           "ishararulz")
        self.u2 = User.objects.create_user("alexis",
                                           "*****@*****.**",
                                           "alexisrulz")
        self.s1 = Student( user=self.u1 )
        self.s2 = Student( user=self.u2 )
        self.s1.save()
        self.s2.save()
        
        # Award the badge to s1
        self.b.awarded_to.add( self.s2 )
        self.b.save()
        
        # Give the test users memorable names.
        self.ishara = self.s1
        self.alexis = self.s2
    
    # Test the model's "held_by" method.
    def test_held_by(self):
        self.assertFalse( self.b.held_by( self.ishara ) )
        self.assertTrue( self.b.held_by( self.alexis ) )
    
    # When an anonymous user visits the badge list (/badges/) they see the
    # superbadge.
    def test_view_badge_list(self):
        response = self.c.get('/badges/')
        self.assertEqual(response.status_code, 200)
        response = self.c.get('/badges/superbadge/')
        self.assertEqual(response.status_code, 200)
    
    # When you go to a badge that doesn't exist, you get redirected back to
    # '/badges'.
    def test_badge_redirect(self):
        response = self.c.get('/badges/fakebadge/', follow=True)
        self.assertEqual(response.redirect_chain, [(u'http://testserver/badges/', 302)])

    # When Alexis visits the badge list, she sees a check mark next to
    # the superbadge.
    def test_view_badge_list_check(self):
        self.c.login(username="******", password="******")
        response = self.c.get('/badges/')
        self.assertEqual(response.status_code, 200)
        self.assertTrue( '<i class="icon-ok"></i>' in response.content )

    # When Ishara visits the badge list, he doesn't see a check mark next to
    # the superbadge.
    def test_view_badge_list_nocheck(self):
        self.c.login(username="******", password="******")
        response = self.c.get('/badges/')
        self.assertEqual(response.status_code, 200)
        self.assertFalse( '<i class="icon-ok"></i>' in response.content )
    
    # When Alexis visits the badge information, she can add the badge to her
    # backpack.
    def test_badge_backpack_button(self):
        self.c.login(username="******", password="******")
        response = self.c.get('/badges/superbadge/')
        self.assertEqual(response.status_code, 200)
        self.assertTrue( 'http://beta.openbadges.org/issuer.js' in response.content )

    # When Ishara visits the badge information, he can not add the badge to his
    # backpack.
    def test_view_badge_list_nocheck(self):
        self.c.login(username="******", password="******")
        response = self.c.get('/badges/superbadge/')
        self.assertEqual(response.status_code, 200)
        self.assertFalse( 'http://beta.openbadges.org/issuer.js' in response.content )    
    
    # Check to ensure that you get a 404 for the assertion for Ishara and a
    # JSON string for Alexis.
    def test_badge_assertion(self):
        response = self.c.get('/badges/superbadge/ishara/')
        self.assertEqual(response.status_code, 404)
        response = self.c.get('/badges/superbadge/ramen/')
        self.assertEqual(response.status_code, 404)
        response = self.c.get('/badges/superbadge/alexis/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json')