def get(self):
        """ Gets all events that have been created.

        URL Args:
            category (str): The category you want the events for. If category
                is 'all', then this will return all events. Any sub_categories
                will also be queried for events.
        """
        category = request.args.get("category", "all")
        if category == 'all':
            events = Event.query(ancestor=Event.root_key())
        else:
            category = PointCategory.get_from_name(category)
            if category is None:
                response = jsonify(message="Category does not exist")
                response.status_code = 404
                return response

            keys = []
            keys.append(category.key)
            keys.extend(category.sub_categories)

            events = Event.query(Event.point_category.IN(keys), ancestor=Event.root_key())

        events = events.order(Event.date)

        out = {'events': []}
        for event in events:
            out['events'].append({
                "name": event.name,
                "date": event.date.strftime('%m/%d/%Y'),
                "point-category": event.point_category.get().name,
            })

        return jsonify(**out)
    def post(self):
        """ Creates a new event. """
        data = request.form

        # Don't allow duplicate events
        event = Event.get_from_name(data['name'])
        if event is not None:
            response = jsonify(message="Duplicate resource")
            response.status_code = 409
            return response

        # Get the point category by name
        point_category = PointCategory.get_from_name(data['point-category'])
        if point_category is None:
            raise Exception("Unknonwn point category: " + data['point-category'])

        new_event = Event(parent=Event.root_key())
        new_event.date = datetime.strptime(data['date'], "%Y-%m-%d")
        new_event.name = data['name']
        new_event.point_category = point_category.key
        new_event.put()

        # Make sure there are point records for this event
        new_event.populate_records()

        response = jsonify()
        response.status_code = 201
        response.headers['location'] = "/api/events/" + new_event.name.replace(" ", "")
        return response
Example #3
0
def event_create(data):
    if data["menu_choice"] in [1, 2, 3]:
        data["client_id"] = get_jwt_identity()
        new_event = Event(data)
        try:
            new_event.save()
            message = f'New event successfully created: {data["title"]}'
            return message, 200
        except Exception as e:
            return str(e), 400
    else:
        message = "Select a menu choice 1-3."
    return message
    def get(self):
        event_name = request.args.get("event_name", "all")
        username = request.args.get("username", "all")

        records = PointRecord.query()
        # TODO (phillip): probably shouldn't make these special cases?
        if event_name != "all":
            records = records.filter(PointRecord.event_name == event_name)

        if username != "all":
            records = records.filter(PointRecord.username == username)

        records = records.order(PointRecord.username)

        out = {'records': []}
        for record in records:
            event = Event.get_from_name(record.event_name)
            if event is None:
                logging.error("Tried to get a point record with an invalid event name: " + record.event_name)
                record.key.delete()
                continue

            point_cat = event.point_category.get().name
            out['records'].append({
                'event_name': record.event_name,
                'username': record.username,
                'points-earned': record.points_earned,
                'point-category': point_cat,
            })

        return jsonify(**out)
    def put(self):
        data = request.form

        user_data = UserData.get_from_username(data['username'])
        if not user_data:
            raise Exception("I don't know that person")

        event = Event.get_from_name(data['event_name'])
        if not event:
            raise Exception("I don't know that event")

        point_record = PointRecord.query(PointRecord.event_name == event.name,
                                         PointRecord.username == user_data.username).get()
        # TODO (phillip): this might allow me to not create new records every time a
        # new event or user is created because a record will be created when
        # the client tries to modify a record that should exist
        # Create a point record if one does not exist
        if not point_record:
            # TODO (phillip): does this work with the user key as the ancestor?
            point_record = PointRecord(parent=user_data.key)

        point_record.event_name = event.name
        point_record.username = user_data.username
        point_record.points_earned = float(data['points-earned'])
        point_record.put()

        # TODO (phillip): A put request (and really any other request that creates or
        # updates an object) should return the new representation of that
        # object so clients don't need to make more API calls

        response = jsonify()
        response.status_code = 204
        return response
Example #6
0
def print_calendar_table(events):
    '''
    Prints upcoming events in form of a table

    Paramaters
    ----------
    events = list of Event objects

    Returns
    -------saa
    None
    '''
    table = PrettyTable(['', 'Name', 'Date', 'Type'])
    for event in events:
        ev_date = event[1].date
        ev_name = event[1].name
        ev_type = event[1].ev_type
        is_past2 = Event.check_if_passed(event[1])dsadas
        if is_past:
            ev_name = Bcolors.RED + event[1].name + Bcolors.ENDC
            ev_date = Bcolors.RED + str(event[1].date) + Bcolors.ENDC
            ev_type = Bcolors.RED + event[1].ev_type + Bcolors.ENDC

        table.add_row([event[0], ev_name, ev_date, ev_type])
    print(table)
Example #7
0
def fill_student_calendar(login):
    '''
    Using three assingments with nearest deadline, creates
    objects out of them.
    '''
    coming_assingments = Assingment.get_coming_assingments()
    for assingment in coming_assingments:
        Event(assingment.title, assingment.date, login, 'Assingment')
    def delete(self, event):
        event = Event.get_from_name(event)
        if event is None:
            # TODO (phillip): this code is duplicated, maybe make some sort of default
            # handler that can be called for any resource that doesn't exist?
            response = jsonify(message="Resource does not exist")
            response.status_code = 404
            return response

        event.delete()
def create_and_add_events_objects(events):
    '''
    Create events objects
    '''

    NAME = 0
    DATE = 1
    LOGIN = 2
    EVENT_TYPE = 3

    for ev in events:
        Event(ev[NAME], ev[DATE], ev[LOGIN], ev[EVENT_TYPE])
    def put(self, event):
        data = request.form

        new_event_name = data['name']
        dup_event = Event.get_from_name(new_event_name)
        # Don't allow duplicate events
        if dup_event is not None and new_event_name.replace(" ", "") != event.replace(" ", ""):
            response = jsonify(message="Duplicate resource")
            response.status_code = 409
            return response

        event = Event.get_from_name(event)
        if event is None:
            # TODO (phillip): this code is duplicated, maybe make some sort of default
            # handler that can be called for any resource that doesn't exist?
            response = jsonify(message="Resource does not exist")
            response.status_code = 404
            return response

        # Get the point category by name
        point_category = PointCategory.get_from_name(data['point-category'])
        if point_category is None:
            raise Exception("Unknonwn point category: " + data['point-category'])

        records = PointRecord.query(PointRecord.event_name == event.name)
        for record in records:
            record.event_name = data['name']
            record.put()

        event.name = data['name']
        event.date = datetime.strptime(data['date'], "%Y-%m-%d")
        event.point_category = point_category.key
        event.put()

        response = jsonify()
        response.status_code = 201
        response.headers['location'] = "/api/events/" + event.name.replace(" ", "")
        return response
    def get(self, event):
        event = Event.get_from_name(event)
        if event is None:
            # TODO (phillip): this code is duplicated, maybe make some sort of default
            # handler that can be called for any resource that doesn't exist?
            response = jsonify(message="Resource does not exist")
            response.status_code = 404
            return response

        out = {
            u'name': event.name,
            u'date': event.date.strftime('%m/%d/%Y'),
            u'point-category': event.point_category.get().name,
        }
        return jsonify(**out)
 def post(self):
     #request.json.headers.add( "Access-Control-Allow-Origin", "*" )
     new_event = Event(
         name=request.json["name"],
         category=request.json["category"],
         place=request.json["place"],
         address=request.json["address"],
         start_date=datetime.datetime.strptime(request.json["start_date"],
                                               '%Y-%m-%d %H:%M:%S'),
         end_date=datetime.datetime.strptime(request.json["end_date"],
                                             '%Y-%m-%d %H:%M:%S'),
         is_virtual=request.json["is_virtual"],
         user_id=request.json["user_id"])
     db.session.add(new_event)
     db.session.commit()
     return self.post_schema.dump(new_event)
Example #13
0
def add_event():
    employee_view.print_add_event()
    title = employee_view.get_string('title')
    date = employee_view.get_date()

    Event(title, date)
Example #14
0
def is_event(event_id):
    return Event.event_get(event_id)
def event(event):
    event = Event.get_from_name(event)
    template_values = {
        'target_event': event,
    }
    return render_jinja_template('event.html', template_values)
Example #16
0
def remove_event(login):
    events = event_controller.get_calendar(login)
    event_index = employee_view.get_event(events)
    Event.remove_event(events[1][event_index])
    def get(self, user_id):
        output = {u"categories": {}}

        user = UserData.get_user_from_id(user_id)

        point_exceptions = {exc.point_category: exc.points_needed for exc in user.point_exceptions}
        categories = PointCategory.query(ancestor=PointCategory.root_key())
        for cat in categories:
            # TODO (phillip): Write tests to test the behavior when calculating requirement for
            # a category with children having a higher requirement. (i.e. max(self, children))

            # TODO (phillip): remove some of the ugly repeated code below
            # Add each category and the required number of points
            if user.is_baby():
                requirement = cat.baby_requirement
                if requirement is None:
                    requirement = 0

                sub_req_list = []
                for sub in cat.sub_categories:
                    req = sub.get().member_requirement
                    if req is None:
                        sub_req_list.append(0)
                    else:
                        sub_req_list.append(req)
                sub_req = sum(sub_req_list)
                requirement = max(requirement, sub_req)
            else:
                requirement = cat.member_requirement
                if requirement is None:
                    requirement = 0

                # TODO (phillip): add test when one of the requirements is None
                sub_req_list = []
                for sub in cat.sub_categories:
                    req = sub.get().member_requirement
                    if req is None:
                        sub_req_list.append(0)
                    else:
                        sub_req_list.append(req)
                sub_req = sum(sub_req_list)
                requirement = max(requirement, sub_req)

            if cat.name in point_exceptions:
                requirement = point_exceptions[cat.name]

            output["categories"][cat.name] = {u"required": requirement}

            output["categories"][cat.name]["received"] = 0
            if cat.parent is not None:
                output["categories"][cat.name]["level"] = 2
            else:
                output["categories"][cat.name]["level"] = 1

        # NOTE: At this point I am assuming each category has been added to
        # the output. If this is not true, the following code will fail
        # miserably.
        records = PointRecord.query()
        # username = user.username
        records = records.filter(PointRecord.username == user.username)
        for record in records:
            event = Event.get_from_name(record.event_name)
            if event is None:
                logging.error("Uknown event " + record.event_name + " requested for point record: " + str(record))
                record.key.delete()
                continue

            category = event.point_category.get()
            if record.points_earned is None:
                record.points_earned = 0
                record.put()
            output["categories"][category.name]["received"] += record.points_earned

            # Make sure to also count the points for the parent category
            if category.parent is not None:
                output["categories"][category.parent.name]["received"] += record.points_earned
                output["categories"][category.name]["level"] = 2

        output = self.reshape_categories(output)

        return jsonify(**output)
Example #18
0
    def create_event():
        user_id = request.json.get('user_id')
        name = request.json.get('name')
        related_to = request.json.get('related_to')
        related_pros = request.json.get("related_pros")
        related_clients = request.json.get("related_clients")
        status = request.json.get("status")

        if not user_id:
            return jsonify({"data": {"msg": "user_id field is required"}}), 400
        elif not name:
            return jsonify({"data": {"msg": "Nome é obrigatório"}}), 400

        admin = db.session.query(User).filter_by(id = user_id).first()

        new_event = Event(
            name,
            user_id,
            str(related_clients if related_clients else []),
            str([user_id] if admin.account_type == "mentor" else related_pros if related_pros else []),
            str([user_id] if admin.account_type == "admin" else related_pros if related_pros else []),
            time.time(),
            status if status else "agendado",
            related_to
        )


        try:
            db.session.add(new_event)
            db.session.commit()
        except:
            return jsonify({"data": {"msg": "an error occured"}}), 400

        json = EventSchema(strict=True).dump(new_event).data

        request_data = db.session.query(Request).filter_by(id = json['related_to']).first()
        client = db.session.query(User).filter_by(id = request_data.client_id).first() if request_data else None

        def get_user_details(user_type):
            output = []
            for user_index in ast.literal_eval(user_type):
                try:
                    temp_user = db.session.query(User).filter_by(id = user_index).first()
                    media = db.session.query(Avatar).filter_by(user_id = user_index).first()
                    avatar = media.avatar_name if media.avatar_name else None

                    output.append({
                        "id": temp_user.id,
                        "name": temp_user.name,
                        "avatar_name": avatar,
                    })
                except:
                    None

            return output

        data = {
            "id": json['id'],
            "name": json['name'],
            "created_by": json['created_by'],
            "created_at": json['created_at'],
            "current_status": json['status'],
            "images": [],
            "related_to": json['related_to'],
            "related": {
                "admins": get_user_details(str([json['id']])),
                "clients": get_user_details(json['related_clients']),
                "pros": get_user_details(json['related_pros'])
            },
            "request": {
                "id": request_data.id,
                "duration": request_data.duration,
                "level": request_data.level,
                "type": request_data.type,
                "client_id": request_data.client_id,
                "result": request_data.result,
                "client_name": client.name,
                "client_email": client.email,
                "client_phone": client.phone_number,
                "set": ast.literal_eval(request_data.set),
                "status": request_data.status,
                "discount": request_data.discount,
                "date": request_data.date,
                "hour": request_data.hour,
                "total": {
                    "sub": request_data.total,
                    "outros": request_data.total_outros,
                    "servicos": request_data.total_servicos,
                    "eventos": request_data.total_eventos
                }
            } if request_data else None
        }
        db.session.close()
        return jsonify({"data": data})
Example #19
0
def event_get_all(client):
    events = Event.event_get_all(client)
    schema_dump = event_schema.dump(events, many=True)
    response = custom_response(schema_dump, 200)
    return response
Example #20
0
def is_event_owner(client, event_id):
    return True if client == Event.event_get_owner(event_id) else False
Example #21
0
    def post_request():
        type = request.json.get('type')
        duration = request.json.get('duration')
        level = request.json.get('level')
        client_id = request.json.get('client_id')
        set = request.json.get('set')
        total = request.json.get('total')
        discount = request.json.get('discount')
        total_outros = request.json.get('total_outros')
        total_servicos = request.json.get('total_servicos')
        total_eventos = request.json.get('total_eventos')
        date = request.json.get('date')
        hour = request.json.get('hour')
        result = request.json.get('result')
        event_id = request.json.get('eventId')

        user = db.session.query(User).filter_by(id = client_id).first()

        def get_user_details(user_type):
            output = []
            for user_index in ast.literal_eval(user_type):
                try:
                    temp_user = db.session.query(User).filter_by(id = user_index).first()
                    media = db.session.query(Avatar).filter_by(user_id = user_index).first()
                    avatar = media.avatar_name if media.avatar_name else None

                    output.append({
                        "id": temp_user.id,
                        "name": temp_user.name,
                        "avatar_name": avatar,
                    })
                except:
                    None

            return output

        if user: 
            event_request = Request(type, duration, level, client_id, str(set), total, discount, total_outros, total_servicos, total_eventos, "accepted" if event_id else "pending", date, hour, "pending", result)
            db.session.add(event_request)
            db.session.commit()
            
            json_dump = RequestSchema(strict=True).dump(event_request).data

            if not event_id:
                event = Event(
                    None, 
                    user.id, 
                    str([user.id]), 
                    str([]), 
                    str([]), 
                    time.time(), 
                    "pendente",
                    json_dump['id']
                )
            else:
                event = db.session.query(Event).filter_by(id = event_id).first()

                event.related_to = json_dump['id']

            event_dump = EventSchema(strict=True).dump(event).data

            db.session.add(event)
            db.session.commit()

            output = {
                "id": event_dump['id'],
                "name": event_dump['name'],
                "created_by": event_dump['created_by'],
                "created_at": event_dump['created_at'],
                "current_status": event_dump['status'],
                "images": [],
                "related_to": event_dump['related_to'],
                "related": {
                    "admins": get_user_details(str([event_dump['id']])),
                    "clients": get_user_details(event_dump['related_clients']),
                    "pros": get_user_details(event_dump['related_pros'])
                },
                "request": {
                    "id": json_dump['id'],
                    "duration": json_dump['duration'],
                    "level": json_dump['level'],
                    "type": json_dump['type'],
                    "client_id": json_dump['client_id'],
                    "client_name": user.name,
                    "client_email": user.email,
                    "client_phone": user.phone_number,
                    "set": ast.literal_eval(json_dump['set']),
                    "status": json_dump['status'],
                    "result": json_dump['result'],
                    "discount": json_dump['discount'],
                    "date": json_dump['date'],
                    "hour": json_dump['hour'],
                    "total": {
                        "sub": json_dump['total'],
                        "outros": json_dump['total_outros'],
                        "servicos": json_dump['total_servicos'],
                        "eventos": json_dump['total_eventos']
                    }
                }
            }

            db.session.close()
            return jsonify({"data": output})
        else:
            db.session.close()
            return jsonify({"data": {"msg": "Nenhum usuário encontrado"}}), 400