Ejemplo n.º 1
0
def eventIdAction(id):
  if request.method == 'DELETE':
    try:
      event = Event.get(Event.id == id)
      event.delete_instance()
    except DoesNotExist:
      abort(404)

    return jsonify(success=1)
  elif request.method == 'PUT':
    data = request.json
    data['source'] = data['source']['id']
    data['target'] = data['target']['id']
    data.pop('type', None)

    if data['source'] != current_user.id and current_user.elder == 0:
      abort(403)

    target = None
    try:
      target = User.get(User.id == data['target'])
    except DoesNotExist:
      abort(403)

    if target.disabled and current_user.elder == 0:
      abort(403)

    data['amount'] = max(min(current_user.max_points, data['amount']), 1)

    event = Event(**data)
    event.save()

    return jsonify(success=1)

  abort(404)
Ejemplo n.º 2
0
    def get_user(user_id, include_points=False):
        from chalicepoints.models.event import Event

        given_query = Event.select(Event.target,
                                   fn.Sum(
                                       Event.amount).alias('total')).group_by(
                                           Event.target).alias('GIVEN')
        received_query = Event.select(
            Event.source,
            fn.Sum(Event.amount).alias('total')).group_by(
                Event.source).alias('RECEIVED')

        query = User.select()

        if include_points:
            query = User.select(User, given_query.c.total.alias('given'),
                                received_query.c.total.alias('received'))

            query = query.join(
                given_query,
                on=(User.id == given_query.c.target)).switch(User).join(
                    received_query,
                    on=(User.id == received_query.c.source)).switch(User)

        query = query.where(User.id == user_id)

        return query.get()
Ejemplo n.º 3
0
def eventIdAction(id):
    if request.method == 'DELETE':
        try:
            event = Event.get(Event.id == id)
            event.delete_instance()
        except DoesNotExist:
            abort(404)

        return jsonify(success=1)
    elif request.method == 'PUT':
        data = request.json
        data['source'] = data['source']['id']
        data['target'] = data['target']['id']
        data.pop('type', None)

        if data['source'] != current_user.id and current_user.elder == 0:
            abort(403)

        target = None
        try:
            target = User.get(User.id == data['target'])
        except DoesNotExist:
            abort(403)

        if target.disabled and current_user.elder == 0:
            abort(403)

        data['amount'] = max(min(current_user.max_points, data['amount']), 1)

        event = Event(**data)
        event.save()

        return jsonify(success=1)

    abort(404)
Ejemplo n.º 4
0
def eventAction():
    if request.method == 'GET':
        return Event.do_get_events()
    elif request.method == 'POST':
        return Event.do_post_events(request.json)
    else:
        abort(404)
Ejemplo n.º 5
0
def mergeUser(id, target):
    Event.update(source=target).where(Event.source == id).execute()
    Event.update(target=target).where(Event.target == id).execute()

    try:
        user = User.get(User.id == id)
        user.delete_instance()
    except DoesNotExist:
        abort(404)

    return jsonify(success=1)
Ejemplo n.º 6
0
def mergeUser(id, target):
  Event.update(source=target).where(Event.source == id).execute()
  Event.update(target=target).where(Event.target == id).execute()

  try:
    user = User.get(User.id == id)
    user.delete_instance()
  except DoesNotExist:
    abort(404)

  return jsonify(success=1)
Ejemplo n.º 7
0
def digest_monthly():
  history = Event.select()

  now = datetime.now().date()

  start_date = now.replace(day = 1)
  start_text = start_date.strftime('%b %-d, %Y')

  end_date = now.replace(day = monthrange(now.year, now.month)[1])
  end_text = end_date.strftime('%b %-d, %Y')

  history = history.where(Event.created_at >= start_date)
  history = history.where(Event.created_at <= end_date)
  history = history.order_by(Event.created_at.desc())

  events = []
  for event in history:
    event.type = Event.types[event.type]
    events.append(event)

  recipients = User.get_digest_monthly()

  text_body = render_template('digest_monthly.txt', events=events, start_date=start_text, end_date=end_text, base_url=app.config['SITE_URL'])
  html_body = render_template('digest_monthly.html', events=events, start_date=start_text, end_date=end_text, base_url=app.config['SITE_URL'])

  send_email('[CHALICEPOINTS] Monthly Digest', ('Chalice Points', app.config['SENDER_EMAIL']), recipients, text_body, html_body, ('Chalice Points', app.config['REPLY_EMAIL']))
Ejemplo n.º 8
0
def digest_weekly():
  history = Event.select()

  now = datetime.now().date()
  dow = now.weekday()

  start_delta = timedelta(days=dow)
  start_date = now - start_delta
  start_text = start_date.strftime('%b %-d, %Y')

  end_delta = timedelta(days=6 - dow)
  end_date = now + end_delta
  end_text = end_date.strftime('%b %-d, %Y')

  history = history.where(Event.created_at >= start_date)
  history = history.where(Event.created_at <= end_date)
  history = history.order_by(Event.created_at.desc())

  events = []
  for event in history:
    event.type = Event.types[event.type]
    events.append(event)

  recipients = User.get_digest_weekly()

  text_body = render_template('digest_weekly.txt', events=events, start_date=start_text, end_date=end_text, base_url=app.config['SITE_URL'])
  html_body = render_template('digest_weekly.html', events=events, start_date=start_text, end_date=end_text, base_url=app.config['SITE_URL'])

  send_email('[CHALICEPOINTS] Weekly Digest', ('Chalice Points', app.config['SENDER_EMAIL']), recipients, text_body, html_body, ('Chalice Points', app.config['REPLY_EMAIL']))
Ejemplo n.º 9
0
def history_all():
    query = request.json

    Source = User.alias()
    Target = User.alias()

    history = Event.select(
        Event.id, Event.source, Event.target, Event.type, Event.amount,
        Event.created_at, Source.name.alias('source_name'),
        Target.name.alias('target_name')).join(
            Source, on=(Event.source == Source.id)).switch(Event).join(
                Target, on=(Event.target == Target.id)).switch(Event)

    # Process Query Parameters
    history = process_history_query(history, query)

    # Order By
    order_by = Event.created_at.desc()

    if 'sort' in query and query['sort'] is not None:
        field = query['sort']['field'] if 'field' in query[
            'sort'] else 'created_at'

        if field == 'source':
            field = 'source_name'
        elif field == 'target':
            field = 'target_name'

        order_by = SQL('%s %s' % (field, query['sort']['direction']))

    history = history.order_by(order_by)

    # Get Result Count
    count = history.count()

    # Paginate
    page = 1
    limit = 10

    if 'page' in query and query['page'] is not None:
        page = query['page']

    if 'limit' in query and query['limit'] is not None:
        limit = query['limit']

    history = history.paginate(page, limit)

    # Query and return as dictionary
    history = history.dicts()

    # Process results
    events = []
    for event in history:
        event['type'] = event['type'] if event['type'] != '' else 'other'
        events.append(event)

    result = {'history': events, 'count': count}

    return Response(json.dumps(result, cls=Encoder, use_decimal=True),
                    mimetype='application/json')
Ejemplo n.º 10
0
def leaderboard(type):
  points = Event.get_points(type)

  given = []
  received = []

  for id, user in points.iteritems():
    givenEntry = {
      'user': user,
      'amount': user.given
    }
    given.append(givenEntry)

    receivedEntry = {
      'user': user,
      'amount': user.received
    }
    received.append(receivedEntry)

  response = {
    'success': 1,
    'given': given,
    'received': received
  }

  return Response(json.dumps(response, cls=Encoder), mimetype='application/json')
Ejemplo n.º 11
0
    def get_users(include_self=True,
                  include_points=False,
                  exclude_disabled=False):
        from chalicepoints.models.event import Event

        given_query = Event.select(Event.target,
                                   fn.Sum(
                                       Event.amount).alias('total')).group_by(
                                           Event.target).alias('GIVEN')
        received_query = Event.select(
            Event.source,
            fn.Sum(Event.amount).alias('total')).group_by(
                Event.source).alias('RECEIVED')

        query = User.select()

        if include_points:
            query = User.select(User, given_query.c.total.alias('given'),
                                received_query.c.total.alias('received'))

            query = query.join(
                given_query,
                on=(User.id == given_query.c.target)).switch(User).join(
                    received_query,
                    on=(User.id == received_query.c.source)).switch(User)

        if not include_self:
            query = query.where(User.id != current_user.id)

        if exclude_disabled:
            query = query.where(User.disabled == False)

        query = query.order_by(User.name.desc())

        users = []

        for user in query:
            users.append(user)

        return users
Ejemplo n.º 12
0
def eventAction():
  data = request.json
  data.pop('id', None)

  if data['target'] == current_user.id:
    abort(403)

  target = User()
  try:
    target = User.get(User.id == data['target'])
  except DoesNotExist:
    abort(403)

  if target.disabled:
    abort(403)

  data['amount'] = max(min(current_user.max_points, int(data['amount'])), 1)

  event = Event(**data)
  event.source = current_user.id
  event.add()

  return jsonify(success=1)
Ejemplo n.º 13
0
    def get_timeline(self):
        from chalicepoints.models.event import Event

        query = Event.select()
        query = query.where((Event.source == self.id)
                            | (Event.target == self.id))
        query = query.order_by(Event.created_at.desc())

        timeline = []

        for event in query:
            timeline.append(event)

        return timeline
Ejemplo n.º 14
0
def eventAction():
    data = request.json
    data.pop('id', None)

    if data['target'] == current_user.id:
        abort(403)

    target = User()
    try:
        target = User.get(User.id == data['target'])
    except DoesNotExist:
        abort(403)

    if target.disabled:
        abort(403)

    data['amount'] = max(min(current_user.max_points, int(data['amount'])), 1)

    event = Event(**data)
    event.source = current_user.id
    event.add()

    return jsonify(success=1)
Ejemplo n.º 15
0
def history_by_source():
  query = request.json

  Source = User.alias()
  Target = User.alias()

  history = Event.select(
    Event.id, Event.source, Source.name.alias('source_name'), fn.Sum(Event.amount).alias('amount')
  ).join(
    Source, on=(Event.source == Source.id)
  ).switch(Event)

  # Group by Giver
  history = history.group_by(Event.source)

  # Process Query Parameters
  history = process_history_query(history, query)

  # Order By
  history = history.order_by(SQL('amount DESC'))

  # Get Result Count
  count = history.count()

  # Paginate
  page = 1
  limit = 5

  if 'page' in query and query['page'] is not None:
    page = query['page']

  if 'limit' in query and query['limit'] is not None:
    limit = query['limit']

  history = history.paginate(page, limit)

  # Query and return as dictionary
  history = history.dicts()

  # Process results
  events = []
  for event in history:
    events.append(event)

  result = {
    'history': events,
    'count': count
  }

  return Response(json.dumps(result, cls=Encoder, use_decimal=True), mimetype='application/json')
Ejemplo n.º 16
0
    def get_points(week=False):
        points = {}

        users = User.get_users()
        for source in users:
            sourceUser = users[source]
            if not sourceUser:
                continue

            if sourceUser['disabled']:
                continue

            events = Event.get_events(source, False, week)
            for event in events:
                target = event['user']
                targetUser = User.get_user(target)
                if not targetUser:
                    continue

                if targetUser['disabled']:
                    continue

                if source not in points:
                    points[source] = {
                        'givenTotal': 0,
                        'receivedTotal': 0,
                        'given': {},
                        'received': {},
                    }

                amount = int(event['amount'])

                if event['type'] == 'give':
                    points[source]['givenTotal'] += amount

                    if target not in points[source]['given']:
                        points[source]['given'][target] = 0

                    points[source]['given'][target] += amount
                else:
                    points[source]['receivedTotal'] += amount

                    if target not in points[source]['received']:
                        points[source]['received'][target] = 0

                    points[source]['received'][target] += amount

        return points
Ejemplo n.º 17
0
def history_by_source():
    query = request.json

    Source = User.alias()
    Target = User.alias()

    history = Event.select(Event.id, Event.source,
                           Source.name.alias('source_name'),
                           fn.Sum(Event.amount).alias('amount')).join(
                               Source,
                               on=(Event.source == Source.id)).switch(Event)

    # Group by Giver
    history = history.group_by(Event.source)

    # Process Query Parameters
    history = process_history_query(history, query)

    # Order By
    history = history.order_by(SQL('amount DESC'))

    # Get Result Count
    count = history.count()

    # Paginate
    page = 1
    limit = 5

    if 'page' in query and query['page'] is not None:
        page = query['page']

    if 'limit' in query and query['limit'] is not None:
        limit = query['limit']

    history = history.paginate(page, limit)

    # Query and return as dictionary
    history = history.dicts()

    # Process results
    events = []
    for event in history:
        events.append(event)

    result = {'history': events, 'count': count}

    return Response(json.dumps(result, cls=Encoder, use_decimal=True),
                    mimetype='application/json')
Ejemplo n.º 18
0
def history_by_type():
  query = request.json

  history = Event.select(
    Event.id, Event.type, fn.Sum(Event.amount).alias('amount')
  )

  # Group by Type
  history = history.group_by(Event.type)

  # Process Query Parameters
  history = process_history_query(history, query)

  # Order By
  history = history.order_by(SQL('amount DESC'))

  # Get Result Count
  count = history.count()

  # Paginate
  page = 1
  limit = 5

  if 'page' in query and query['page'] is not None:
    page = query['page']

  if 'limit' in query and query['limit'] is not None:
    limit = query['limit']

  history = history.paginate(page, limit)

  # Query and return as dictionary
  history = history.dicts()

  # Process results
  events = []
  for event in history:
    event['type'] = event['type'] if event['type'] != '' else 'other'
    events.append(event)

  result = {
    'history': events,
    'count': count
  }

  return Response(json.dumps(result, cls=Encoder, use_decimal=True), mimetype='application/json')
Ejemplo n.º 19
0
def leaderboard(type):
    points = Event.get_points(type)

    given = []
    received = []

    for id, user in points.iteritems():
        givenEntry = {'user': user, 'amount': user.given}
        given.append(givenEntry)

        receivedEntry = {'user': user, 'amount': user.received}
        received.append(receivedEntry)

    response = {'success': 1, 'given': given, 'received': received}

    return Response(json.dumps(response, cls=Encoder),
                    mimetype='application/json')
Ejemplo n.º 20
0
def history_by_type():
    query = request.json

    history = Event.select(Event.id, Event.type,
                           fn.Sum(Event.amount).alias('amount'))

    # Group by Type
    history = history.group_by(Event.type)

    # Process Query Parameters
    history = process_history_query(history, query)

    # Order By
    history = history.order_by(SQL('amount DESC'))

    # Get Result Count
    count = history.count()

    # Paginate
    page = 1
    limit = 5

    if 'page' in query and query['page'] is not None:
        page = query['page']

    if 'limit' in query and query['limit'] is not None:
        limit = query['limit']

    history = history.paginate(page, limit)

    # Query and return as dictionary
    history = history.dicts()

    # Process results
    events = []
    for event in history:
        event['type'] = event['type'] if event['type'] != '' else 'other'
        events.append(event)

    result = {'history': events, 'count': count}

    return Response(json.dumps(result, cls=Encoder, use_decimal=True),
                    mimetype='application/json')
Ejemplo n.º 21
0
def userNameAction(name):
    name = name.encode('ascii')

    if name == 'list':
        return userAction(False)

    users = User.get_users()
    if name not in users:
        abort(404)

    user = users[name]
    user['events'] = Event.get_events(name)
    user['given'] = 0
    user['received'] = 0

    points = Point.get_points()
    if name in points:
        user['given'] = points[name]['givenTotal']
        user['received'] = points[name]['receivedTotal']

    return Response(json.dumps(user), mimetype='application/json')
Ejemplo n.º 22
0
def history_all():
  query = request.json

  Source = User.alias()
  Target = User.alias()

  history = Event.select(
    Event.id, Event.source, Event.target, Event.type, Event.amount, Event.created_at, Source.name.alias('source_name'), Target.name.alias('target_name')
  ).join(
    Source, on=(Event.source == Source.id)
  ).switch(Event).join(
    Target, on=(Event.target == Target.id)
  ).switch(Event)

  # Process Query Parameters
  history = process_history_query(history, query)

  # Order By
  order_by = Event.created_at.desc()

  if 'sort' in query and query['sort'] is not None:
    field = query['sort']['field'] if 'field' in query['sort'] else 'created_at'

    if field == 'source':
      field = 'source_name'
    elif field == 'target':
      field = 'target_name'

    order_by = SQL('%s %s' % (field, query['sort']['direction']))

  history = history.order_by(order_by)

  # Get Result Count
  count = history.count()

  # Paginate
  page = 1
  limit = 10

  if 'page' in query and query['page'] is not None:
    page = query['page']

  if 'limit' in query and query['limit'] is not None:
    limit = query['limit']

  history = history.paginate(page, limit)

  # Query and return as dictionary
  history = history.dicts()

  # Process results
  events = []
  for event in history:
    event['type'] = event['type'] if event['type'] != '' else 'other'
    events.append(event)

  result = {
    'history': events,
    'count': count
  }

  return Response(json.dumps(result, cls=Encoder, use_decimal=True), mimetype='application/json')
Ejemplo n.º 23
0
def timeline():
    timeline = Event.get_timeline()
    return Response(json.dumps(timeline.values()), mimetype='application/json')
Ejemplo n.º 24
0
def winners():
    totals = {}
    leaders = {}
    highest = {}

    current_week = datetime.now().strftime('%U %y 0')
    current_date = datetime.strptime(current_week, '%U %y %w').strftime('%Y-%m-%dT%H:%M:%S')

    users = User.get_users()
    for source in users:
        events = Event.get_events(source)
        for event in events:
            target = event['user']
            amount = int(event['amount'])

            week = datetime.strptime(event['date'], '%Y-%m-%dT%H:%M:%SZ').strftime('%U %y 0')
            date = datetime.strptime(week, '%U %y %w').strftime('%Y-%m-%dT%H:%M:%S')

            if not date in totals:
                totals[date] = {}

            if not source in totals[date]:
                totals[date][source] = {
                    'given': 0,
                    'received': 0,
                }

            if not target in totals[date]:
                totals[date][target] = {
                    'given': 0,
                    'received': 0,
                }

            if event['type'] == 'give':
                totals[date][source]['given'] += amount
                totals[date][target]['received'] += amount

    for date in totals:
        leaders[date] = {
            'date': date,
            'current': 0,
            'given': [],
            'received': [],
        }

        if current_date == date:
            leaders[date]['current'] = 1

        highest[date] = {
            'given': 0,
            'received': 0,
        }

        for person in totals[date]:
            if totals[date][person]['given'] > highest[date]['given']:
                leaders[date]['given'] = [{
                    'name': person,
                    'amount': totals[date][person]['given'],
                }]

                highest[date]['given'] = totals[date][person]['given']
            elif totals[date][person]['given'] == highest[date]['given']:
                leaders[date]['given'].append({
                    'name': person,
                    'amount': totals[date][person]['given'],
                })

            if totals[date][person]['received'] > highest[date]['received']:
                leaders[date]['received'] = [{
                    'name': person,
                    'amount': totals[date][person]['received'],
                }]

                highest[date]['received'] = totals[date][person]['received']
            elif totals[date][person]['received'] == highest[date]['received']:
                leaders[date]['received'].append({
                    'name': person,
                    'amount': totals[date][person]['received'],
                })

    return Response(json.dumps(leaders.values()), mimetype='application/json')