def add_fish(request):
    context = RequestContext(request)
    
    if request.method == 'POST':
        # get data from input form
        input_comp      = request.POST.get("comp")
        input_user      = request.POST.get("user")
        input_species   = request.POST.get("species")
        input_weight    = request.POST.get("weight")
        input_lat       = float(request.POST.get("lat"))
        input_lon       = float(request.POST.get("lon"))
        
        user            = User.objects.get(username = input_user)                
        comp            = Tournament.objects.get(pk=input_comp)
        standings_query = Standings.objects.filter(tournament=comp).filter(discipline__name='Fiskning')
        
        if not standings_query:
            # make new standings object if it does not exist
            disc        = Discipline.objects.get(name='Fiskning')
            standings   = Standings(discipline = disc,
                                  tournament = comp)
            standings.save()
        else:
            standings = standings_query.all()
            
        # create points for new fish in DB
        p = Points(points       = input_weight, 
                   user         = user,
                   standings    = standings,
                   score        = 4)
        p.save()
        # create  fish in DB
        f = Fish(species    = input_species,
                 weight     = input_weight,
                 lat        = input_lat,
                 lon        = input_lon,
                 points     = p)        
        f.save()
        
        fishes = Fish.objects.all()
        coord = []
        for fish in fishes:
            coord.append([fish.lat, fish.lon])
        return render_to_response('fish_list.html', {'request':request,
                                                  'fishes': fishes,
                                                  'coord':coord}, context)

    else:
        comps = Tournament.objects.all()
        users = User.objects.all()
        return render(request, 'new_fish.html', {'request':request,
                                              'comps': comps,
                                              'users': users})
def award(request, *args, **kwargs):
    if request.method == 'POST':
        form = AwardForm(request.POST)
        if form.is_valid():
            user = get_object_or_404(User, username=kwargs['username'])
            projectbadge = ProjectBadge.objects.get(pk=request.POST['award_id'])
            points = Points(user=user,projectbadge=projectbadge,value=request.POST['points'],description=request.POST['comment'])
            points.save()
            return HttpResponseRedirect('/users/%s/projects/%s/badges' % (kwargs['username'], kwargs['projectname']))

    else:
        form = AwardForm()

    return render(request, 'core/award.html', { 'form': form, })
def insert_points(uid, rid):
    """
    Inserts a 0 points entry into Points table for a given user and restaurant.

    Args:
        uid: A user ID that corresponds to a user in the User
          table. A integer.
        rid: A restaurant ID that corresponds to a restaurant in the Restaurant
          table. A integer.

    Returns:
        Points if entry was successfully added to the Points table, a list of
        error messages otherwise.
    """
    errmsg = []

    points = Points.query.filter(Points.uid == uid).filter(
        Points.rid == rid).first()
    if points:
        errmsg.append(
            "Points entry already exists for given user at this restaurant.")

    if not errmsg:
        points = Points(uid=uid, rid=rid, points=0)
        db.session.add(points)
        db.session.commit()
        return None
    return errmsg
Beispiel #4
0
    def test_insert_duplicate_uid_and_rid_points_entry(self):
        """
        Test insert a normal points with same uid and rid. Expect an error message as well as data in database remains unchanged.
        """
        points = Points(uid=1, rid=12, points=10)
        db.session.add(points)
        errmsg = pointshelper.insert_points(1, 12)
        self.assertEqual(
            errmsg,
            ["Points entry already exists for given user at this restaurant."])

        points = Points.query.filter_by(uid=1, rid=12)
        self.assertEqual(points.count(), 1)
        self.assertEqual(points.first().pid, 1)
        self.assertEqual(points.first().uid, 1)
        self.assertEqual(points.first().rid, 12)
        self.assertEqual(points.first().points, 10)
 def test_get_nonexistent_points_entry_duplicate_rid(self):
     """
     Test get a point entry with invalid uid. Expect return none.
     """
     newEntry = Points(uid=1, rid=13, points=10)
     db.session.add(newEntry)
     db.session.commit()
     points = pointshelper.get_points(2, 13)
     self.assertEqual(points, None)
Beispiel #6
0
 def test_update_nonexistent_points_entry(self):
     """
     Test update a non exist point entry. Expect an error message.
     """
     points = Points(uid=1, rid=13, points=10)
     db.session.add(points)
     db.session.commit()
     errmsg = pointshelper.update_points(1, 12, 10)
     self.assertEqual(errmsg, [
         "Points entry does not exist for the given user ID and restaurant ID."
     ])
 def test_get_existing_points_entry(self):
     """
     Test get a point entry by given valid input. Expect output to match correct data.
     """
     newEntry = Points(uid=1, rid=12, points=10)
     db.session.add(newEntry)
     db.session.commit()
     points = pointshelper.get_points(1, 12)
     self.assertNotEqual(points, None)
     self.assertEqual(points.pid, 1)
     self.assertEqual(points.uid, 1)
     self.assertEqual(points.rid, 12)
     self.assertEqual(points.points, 10)
Beispiel #8
0
    def test_insert_duplicate_rid_points_entry(self):
        """
        Test insert multi normal points with same rid. Expect output to match correct data.
        """
        points = Points(uid=1, rid=12, points=10)
        db.session.add(points)
        errmsg = pointshelper.insert_points(2, 12)
        self.assertEqual(errmsg, None)

        points = Points.query.filter_by(rid=12)
        self.assertEqual(points.count(), 2)

        points = Points.query.filter_by(pid=1).first()
        self.assertNotEqual(points, None)
        self.assertEqual(points.uid, 1)
        self.assertEqual(points.rid, 12)
        self.assertEqual(points.points, 10)

        points = Points.query.filter_by(pid=2).first()
        self.assertNotEqual(points, None)
        self.assertEqual(points.uid, 2)
        self.assertEqual(points.rid, 12)
        self.assertEqual(points.points, 0)
Beispiel #9
0
    def test_update_points_entry_zero_increment(self):
        """
        Test update a normal point entry with zero increment. Expect output to match correct data.
        """
        points = Points(uid=1, rid=12, points=10)
        db.session.add(points)
        db.session.commit()
        errmsg = pointshelper.update_points(1, 12, 0)
        self.assertEqual(errmsg, None)

        points = Points.query.filter_by(uid=1, rid=12).first()
        self.assertNotEqual(points, None)
        self.assertEqual(points.pid, 1)
        self.assertEqual(points.uid, 1)
        self.assertEqual(points.rid, 12)
        self.assertEqual(points.points, 10)
 def test_add_complete(self):
     """
     Test make progress on an achievement and complete the achievement, this is valid.
     """
     ap = Customer_Achievement_Progress(aid=1, uid=3, progress=1, total=2)
     user = User(uid=3, name='cus', password='******', email='test', type=-1)
     points = Points(pid=1, uid=3, rid=1, points=20)
     achievement = Achievements(aid=1, rid=1, name='test', experience=20, points=20, type=0, value='test;10')
     db.session.add(ap)
     db.session.add(user)
     db.session.add(points)
     db.session.add(achievement)
     db.session.commit()
     achievementhelper.add_one_progress_bar(ap, 1, 3)
     self.assertEqual(points.points, 40)
     self.assertEqual(ap.progress, 2)
Beispiel #11
0
    def test_update_points_entry_negative_increment_equal_to_existing_points(
            self):
        """
        Test update a normal point entry with negative but still valid(abs(value)==points) increment. Expect output to match correct data.
        """
        points = Points(uid=1, rid=12, points=10)
        db.session.add(points)
        db.session.commit()
        errmsg = pointshelper.update_points(1, 12, -10)
        self.assertEqual(errmsg, None)

        points = Points.query.filter_by(uid=1, rid=12).first()
        self.assertNotEqual(points, None)
        self.assertEqual(points.pid, 1)
        self.assertEqual(points.uid, 1)
        self.assertEqual(points.rid, 12)
        self.assertEqual(points.points, 0)
 def test_add_type_one(self):
     """
     Test make progress on an achievement and immediately complete, this is valid as some type of achievement 
     only has two situation: not started/completed.
     """
     ap = Customer_Achievement_Progress(aid=1, uid=3, progress=0, total=1)
     user = User(uid=3, name='cus', password='******', email='test', type=-1)
     points = Points(pid=1, uid=3, rid=1, points=20)
     achievement = Achievements(aid=1, rid=1, name='test', experience=20, points=20, type=0, value=';20')
     db.session.add(ap)
     db.session.add(user)
     db.session.add(points)
     db.session.add(achievement)
     db.session.commit()
     achievementhelper.add_one_progress_bar(ap, 1, 3)
     self.assertEqual(points.points, 40)
     self.assertEqual(ap.progress, 1)
Beispiel #13
0
def process_points(lst, question_id):
    all_points = []
    for i, num in enumerate(lst):
        if num:
            if float(num) != 0:
                all_points.append({
                    "id":
                    PlayerDict.id_dict[PlayerDict.player_order[i]],
                    "points":
                    num
                })
    for p in all_points:
        new_points = Points(player_id=p["id"],
                            question_id=question_id,
                            points=p["points"],
                            win=len(all_points) == 1)
        db.session.add(new_points)
        db.session.commit()
Beispiel #14
0
    def test_update_points_entry_negative_increment_greater_than_existing_points(
            self):
        """
        Test update a normal point entry with negative invalid increment. Expect an error message.
        """
        points = Points(uid=1, rid=12, points=10)
        db.session.add(points)
        db.session.commit()
        errmsg = pointshelper.update_points(1, 12, -20)
        self.assertEqual(
            errmsg, ["A points entry cannot have a negative point count."])

        points = Points.query.filter_by(uid=1, rid=12).first()
        self.assertNotEqual(points, None)
        self.assertEqual(points.pid, 1)
        self.assertEqual(points.uid, 1)
        self.assertEqual(points.rid, 12)
        self.assertEqual(points.points, 10)
Beispiel #15
0
def showpost(code):
    singlepost = Posts.query.filter_by(post_code=code).first_or_404()
    flash(singlepost.id, "warning")
    user_code = request.args.get('ref')
    remote_addr = request.remote_addr

    db.session.expire_on_commit = False
    singlepost = Posts.query.filter_by(post_code=code).first_or_404()

    if (user_code):
        tup = hashids.decode(user_code)
        try:
            user_code = float(tup[0])
        except:
            user_code = -1

    if (Tracking.query.filter(Tracking.post_ID == singlepost.id).filter(
            Tracking.ip == remote_addr).filter(
                Tracking.user_ID == user_code).scalar() is None):
        newtrack = Tracking(singlepost.id, user_code, remote_addr)
        db.session.add(newtrack)

        if (Points.query.filter(Points.post_ID == singlepost.id).filter(
                Points.user_ID == user_code).scalar() is None):
            newpoint = Points(user_code, singlepost.id, 1)
            db.session.add(newpoint)

        else:
            element = Points.query.filter(
                Points.post_ID == singlepost.id).filter(
                    Points.user_ID == user_code).first()
            element.earned_points += 1
        try:
            db.session.commit()
        except:
            db.session.rollback()
        finally:
            db.session.close()

    return render_template("main/single.html",
                           title="post",
                           singlepost=singlepost)
            point_args['user'] = get_object_or_404(User,username=kwargs['username'])
            project = get_object_or_404(Project,name=kwargs['projectname'])
        except Http404, e:
            context = { 'message' : e.__str__().split()[1] + ' not found' }
            return HttpResponse(json.dumps(context),'application/json',404)
            
        award = request.GET['award']

        try:
            point_args['projectbadge'] = get_object_or_404(ProjectBadge,name=award)
        except Http404, e:
            context = { 'message' : 'Project not found' }
            return HttpResponse(json.dumps(context), 'application/json', 404)

        # award points
        points = Points(**point_args)
        points.save()

        return HttpResponseRedirect('/users/%s/projects/%s' % (point_args['user'], project))

@api_view(('GET',))
@renderer_classes((renderers.TemplateHTMLRenderer,renderers.JSONRenderer))
def master_project_list(request):
    queryset = Project.objects.filter(private=False)

    if request.accepted_renderer.format == 'html':
        actives = []
        non_actives = []
        for project in queryset:
            if project.active:
                actives.append(project)
Beispiel #17
0
def add_points():
    """
    Add points
    """
    data = request.get_json(silent=True)["data"]

    amount = data.get("amount")
    assignee = data["assignee"]
    description = data["description"]
    event_id = None

    # if user's discord id is given, change assignee to discord username
    if "#" in assignee:
        user = User.query.filter_by(name=assignee).first()
    else:
        user = User.query.filter_by(id=assignee).first()
        assignee = user.name

    discord_id = user.id

    if description == "Event":
        event_id = data.get("event_id")
        secret_input = data.get("secret_input")
        if event_id is None:
            return jsonify({
                "success": False,
                "message": "Please specify the event id"
            })
        if secret_input is None:
            return jsonify({
                "success": False,
                "message": "Please input the secret code"
            })

        # Check if points are already claimed for event
        if Points.query.filter_by(event_id=event_id,
                                  assignee=discord_id).first():
            return jsonify({
                "success": False,
                "message": "Event points already claimed"
            })
        else:
            # Check if input matches event secret code
            event = Event.query.filter_by(id=event_id).first()
            if event.secret_code == secret_input:
                amount = event.points_amount
                message = f"{amount} points added to {assignee} for Event {event.name}"
                success = True
            else:
                return jsonify({
                    "success":
                    False,
                    "message":
                    f"The code {secret_input} is incorrect for Event {event.name}",
                })

    elif description == "Discord":
        # Check daily limit of 5 messages is exceeded
        discord_points_today = (Points.query.filter_by(
            description="Discord", assignee=discord_id).filter(
                func.date(Points.timestamp) == func.date(func.now())).all())
        if len(discord_points_today) >= 5:
            return jsonify({
                "success":
                False,
                "message":
                "Daily limit for Discord activity points reached",
            })
        else:
            message = f"{amount } points added to {assignee} for Discord activity"
            success = True
    else:
        message = f"{amount} points added to {assignee} for {description}"
        success = True

    # Create a Points in the points table
    new_point = Points(amount=amount,
                       assignee=discord_id,
                       description=description,
                       event_id=event_id)
    db.session.add(new_point)

    # Add to user's total points
    user.points_total += int(amount)

    db.session.commit()

    return jsonify({
        "success": success,
        "message": message,
        "data": {
            "id": new_point.id,
            "amount": new_point.amount,
            "assignee": new_point.assignee,
            "description": new_point.description,
            "event_id": new_point.event_id,
            "timestamp": new_point.timestamp,
        },
    })