Example #1
0
def redeemed_rewards(pid, uid):
    """Get a list of a user's redeemed rewards, ordered by redeemed_at dates."""
    redeemed = Redeemed.query.join(Redeemed.reward) \
      .filter(Redeemed.user_id == uid, Reward.program_id == pid) \
      .options( \
      joinedload(Redeemed.reward), \
      joinedload(Redeemed.user), \
      joinedload(Redeemed.reward).joinedload(Reward.color), \
      joinedload(Redeemed.reward).joinedload(Reward.stamp) \
      ).order_by(Redeemed.redeemed_at).all()

    redeemed_data = dump_data_list(redeemed, redeemed_schema)
    i = 0
    for reward in redeemed:
        redeemed_data[i]["reward"] = reward_schema.dump(reward.reward)
        redeemed_data[i]["reward"]["color"] = color_schema.dump(
            reward.reward.color)
        redeemed_data[i]["reward"]["stamp"] = stamp_schema.dump(
            reward.reward.stamp)
        if redeemed_data[i]["reward"]["limit_per_member"] < 1:
            redeemed_data[i]["reward"]["limit_per_member"] = "∞"
        if redeemed_data[i]["reward"]["quantity"] < 0:
            redeemed_data[i]["reward"]["quantity"] = "∞"
        i += 1
    print("\n\nREDEEMED REWARDS LIST")
    pprint(redeemed_data)
    return jsonify(redeemed_data)
Example #2
0
def create_habit(pid):
    form = HabitForm()
    form['csrf_token'].data = request.cookies['csrf_token']

    if form.validate():
        newHabit = Habit(
            habit=form.data['habit'],
            description=form.data['description'],
            frequency=str(form.data['frequency']),
            color_id=form.data['color'],
            stamp_id=form.data['stamp'],
            creator_id=request.json['userId'],
            program_id=pid,
        )
        db.session.add(newHabit)
        print(newHabit)
        db.session.commit()
        newHabit = Habit.query.options(joinedload(Habit.stamp),
                                       joinedload(Habit.color)).get(
                                           newHabit.id)
        habit = habit_schema.dump(newHabit)

        habit["color"] = color_schema.dump(newHabit.color)
        habit["stamp"] = stamp_schema.dump(newHabit.stamp)
        print("\n\nNEW HABIT DICTIONARY:", habit)
        return jsonify(habit)
    return "Habit failure"
def member_habits(mid):
    """Get a list of a program member's habits (program-specific)."""
    habits = Habit.query.options(joinedload(Habit.stamp)).all()  # dunno
    habits_data = dump_data_list(habits, habit_schema)
    for i in range(len(habits)):
        habit_stamp = stamp_schema.dump(habits[i].stamp)
        habit_color = color_schema.dump(habits[i].color)
        habits_data[i]["stamp"] = habit_stamp
        habits_data[i]["color"] = habit_color
    return jsonify(habits_data)
Example #4
0
def habit_details(hid, mid):
    """Get a habit's details, including recent history."""
    # TODO Ask TA how to filter joinedload to only return dailystamps of 'member id blah', and filter attributes for each joinedload.
    habit = Habit.query.filter(Habit.id == hid).options( \
      joinedload(Habit.color), \
      joinedload(Habit.stamp), \
      joinedload(Habit.program), \
      joinedload(Habit.creator), \
      joinedload(Habit.daily_stamps)) \
      .one()
    habit_data = habit_schema.dump(habit)
    habit_data["color"] = color_schema.dump(habit.color)
    habit_data["stamp"] = stamp_schema.dump(habit.stamp)
    habit_data["program"] = program_schema.dump(habit.program)
    habit_data["creator"] = user_schema.dump(habit.creator)
    habit_data["daily_stamps"] = dailystamp_schema.dump(
        [stamp for stamp in habit.daily_stamps if stamp.member_id == mid])
    print("\nSINGLE HABIT DATA", habit_data)
    return jsonify(habit_data)
Example #5
0
def authenticate():
    """Authenticates a user"""
    user = User.query.options( \
      joinedload(User.color), \
      joinedload(User.stamp), \
      joinedload(User.memberships), \
      ).get(current_user.id)
    if user.is_authenticated:

        user_data = user_schema.dump(current_user)
        user_data["color"] = color_schema.dump(user.color)
        user_data["stamp"] = stamp_schema.dump(user.stamp)
        print("\nauthed user")
        user_data["memberships"] = {
            m["id"]: m
            for m in dump_data_list(user.memberships, member_schema)
        }
        print("\nUSER WITH MEMBERS")
        # pprint(user_data)
        return jsonify(user_data)
    return {'errors': ['Unauthorized']}, 401
Example #6
0
def edit_habit(hid):
    """Edit a habit's details by id."""
    form = HabitForm()
    form['csrf_token'].data = request.cookies['csrf_token']

    if form.validate():
        habit = Habit.query.get(hid)
        habit.habit = form.data['habit']
        habit.description = form.data['description']
        habit.frequency = form.data['frequency']
        habit.color_id = form.data['color']
        habit.stamp_id = form.data['stamp']
        db.session.commit()
        print("\nEDITED", habit)

        habit_data = habit_schema.dump(habit)
        habit_data["color"] = color_schema.dump(habit.color)
        habit_data["stamp"] = stamp_schema.dump(habit.stamp)
        print("\nEDITTED HABIT DUMP", habit_data)
        return jsonify(habit_data)
    return "Habit-edit fail :["
Example #7
0
def program_rewards(pid):
    """Get a list of a program's custom rewards."""
    rewards = Reward.query.filter(Reward.program_id == pid).options(
        joinedload(Reward.stamp), joinedload(Reward.color),
        joinedload(Reward.creator)).all()

    rewards_obj = {}
    rewards_data = dump_data_list(rewards, reward_schema)
    rewards_data = [reward for reward in rewards_data]
    i = 0
    for reward in rewards:
        rewards_data[i]["color"] = color_schema.dump(reward.color)
        rewards_data[i]["stamp"] = stamp_schema.dump(reward.stamp)
        rewards_data[i]["creator"] = user_schema.dump(reward.creator)
        rewards_obj[rewards_data[i]["id"]] = rewards_data[i]
        if rewards_data[i]["quantity"] == -1:
            rewards_data[i]["quantity"] = "∞"
        if rewards_data[i]["limit_per_member"] <= 0:
            rewards_data[i]["limit_per_member"] = "∞"
        i += 1
    print("\n\nPROGRAM REWARDS", rewards_obj)
    return jsonify(rewards_obj)
Example #8
0
def create_reward(pid):
    print("\nmaking reward")
    form = RewardForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    print("REWARD FORM", form.data, form.validate())

    if form.validate():
        print("VALIDATED")
        reward = Reward(
            reward=form['reward'].data,
            type='custom',
            description=form['description'].data,
            color_id=form['color'].data,
            stamp_id=form['stamp'].data,
            cost=form['cost'].data,
            limit_per_member=form['limit'].data,
            quantity=form['quantity'].data,
            creator_id=request.json['userId'],
            program_id=pid,
        )
        db.session.add(reward)
        db.session.commit()

        reward_data = reward_schema.dump(reward)
        reward_data["color"] = color_schema.dump(reward.color)
        reward_data["stamp"] = stamp_schema.dump(reward.stamp)
        reward_data["creator"] = user_schema.dump(reward.creator)
        reward_data["program"] = program_schema.dump(reward.program)

        if form['quantity'].data == -1:
            reward_data["quantity"] = "∞"
        if form['limit'].data == -1:
            reward_data["limit_per_member"] = "∞"

        print("\nCREATED REWARD")
        pprint(reward_data)
        return jsonify(reward_data)
    return "Oh nooo no reward made D: "
Example #9
0
def redeem_reward(rid, mid):
    """Redeem a reward for a member."""
    reward = Reward.query.filter(Reward.id == rid).one()
    member = Member.query.filter(Member.id == mid).one()

    if reward.limit_per_member > 0:
        redeemed_count = Redeemed.query.filter(
            Redeemed.reward_id == reward.id,
            Redeemed.user_id == member.member.id).count()
        if redeemed_count >= reward.limit_per_member:
            return f"You have too many, sorry T_T . Only {str(reward.limit_per_member)} per customer!"

    if reward.quantity == 0:
        return "There aren't any left, sorry T_T"

    if member.points < reward.cost:
        return "You need more points please TT_TT"

    if reward.quantity > 0:
        reward.quantity -= 1

    member.points -= reward.cost
    redeemed = Redeemed(
        user_id=member.member_id,
        reward_id=reward.id,
    )
    db.session.add(redeemed)
    db.session.commit()
    redeemed_data = redeemed_schema.dump(redeemed)
    redeemed_data["reward"] = reward_schema.dump(redeemed.reward)
    redeemed_data["reward"]["color"] = color_schema.dump(redeemed.reward.color)
    redeemed_data["reward"]["stamp"] = stamp_schema.dump(redeemed.reward.stamp)
    redeemed_data["user"] = user_schema.dump(redeemed.user)

    print("\n\nREDEEMED REWARD", redeemed_data)
    print("\n\nMEMBER NOW", member)
    return jsonify(points=member.points, redeemed_data=redeemed_data)
def user_programs(uid):
    """Get a user's subscribed programs."""
    current_date = date.today()
    past_week = [(current_date - timedelta(days=i)) for i in range(7)]
    past_week = [(day.strftime('%A')[0:3], day.strftime('%Y-%m-%d'))
                 for day in past_week]

    print("\n\nUID", uid)
    user_programs = Program.query \
        .join(Member.program).filter(Member.member_id == uid) \
        .options(joinedload(Program.rewards), \
            joinedload(Program.members), \
            joinedload(Program.stamp), \
            joinedload(Program.color), \
            joinedload(Program.habits).joinedload(Habit.daily_stamps), \
            joinedload(Program.habits).joinedload(Habit.stamp), \
            joinedload(Program.habits).joinedload(Habit.color)) \
        .all()
    programs_data = dump_data_list(user_programs, program_schema)

    for i in range(len(user_programs)):
        if user_programs[i].members:
            memberships = [m.id for m in current_user.memberships]
            print("\n\nmemberships", memberships)
            try:
                [mid] = [
                    m for m in programs_data[i]["members"] if m in memberships
                ]
                programs_data[i]["habits"] = []

                for j in range(len(user_programs[i].habits)):
                    programs_data[i]["habits"].append(
                        habit_schema.dump(user_programs[i].habits[j]))
                    habit = habit_schema.dump(user_programs[i].habits[j])
                    habit["stamp"] = stamp_schema.dump(
                        user_programs[i].habits[j].stamp)
                    habit["color"] = color_schema.dump(
                        user_programs[i].habits[j].color)
                    # Daily stamps for prev week for habit
                    habit["daily_stamps"] = DailyStamp.query.filter( \
                        DailyStamp.habit_id == habit["id"], \
                        DailyStamp.member_id == mid, \
                        DailyStamp.date <= past_week[0][1], \
                        DailyStamp.date >= past_week[6][1]).all()
                    habit["daily_stamps"] = dump_data_list(
                        habit["daily_stamps"], dailystamp_schema)
                    programs_data[i]["habits"][j] = habit
            except:
                print("\nno mid probs")
        programs_data[i]["stamp"] = stamp_schema.dump(user_programs[i].stamp)
        programs_data[i]["color"] = color_schema.dump(user_programs[i].color)

    programs_fin = {}
    habits_fin = {}
    dailies_fin = {}
    for program in programs_data:
        habits_fin.update({habit["id"]: habit for habit in program["habits"]})
        program["habits"] = [habit["id"] for habit in program["habits"]]
        programs_fin.update({program["id"]: program})

    for habit in habits_fin.values():
        dailies_fin.update(
            {stamp["id"]: stamp
             for stamp in habit["daily_stamps"]})
        habit["daily_stamps"] = [
            daily["id"] for daily in habit["daily_stamps"]
        ]

    print("\nPROGRAMS DATA")
    # pprint(programs_data)
    print("\nHABITS DATA")
    # pprint(habits_fin)
    print("\nDAILIES DATA")
    # pprint(dailies_fin)

    return jsonify(programs_data=programs_fin,
                   habits_data=habits_fin,
                   dailies_data=dailies_fin,
                   past_week=past_week)