def create_user_car(id):
    data = request.get_json()
    logger.info(f"Recieved data {data}")

    user = get_user_by_id(id)

    if user is None:
        return create_response(message=f"No user with id {id} was found.",
                               status=404)

    car = Car()

    for key in Car.getAllKeys():
        if key in Car.getRequiredKeys() and key not in data:
            msg = f"Car not created, missing field '{key}''."
            logger.info(msg)
            return create_response(status=442, message=msg)
        if key in data:
            car[key] = data[key]

    car.save()

    user.cars.append(car)

    user.save()

    return create_response(
        message=
        f"Successfully created car with id {car.id} for user with id {user.id}.",
        data={"car_id": str(car.id)},
        status=201,
    )
Example #2
0
def return_visualizations():
    data = request.get_json()
    logger.info("Data recieved: %s", data)
    if "user_id" not in data:
        msg = "No user ID provided for visualizations."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "visualization_id" not in data:
        visualizations = db.session.query(Visualization).filter(
            Visualization.id.in_(
                db.session.query(Access.model_id).filter(Access.user_id == data["user_id"], Access.model=='visualization').all()
            )
        ).all()
        # return visualizations 
        return create_response(data={"visualizations": serialize_list(visualizations)})
    # If there was a specific visualization requested, fetch it and return it
    visualization = db.session.query(Visualization).filter(
        Visualization.id == data["visualization_id"],
        Visualization.id.in_(
            db.session.query(Access.model_id).filter(Access.user_id == data["user_id"], Access.model=='visualization').all()
        )
    ).first()
    visualization_details = visualization.get_fields()
    # visualization_details.pop('_sa_instance_state', None)
    return create_response(data={"visualization": visualization_details})
Example #3
0
def create_person():
    data = request.get_json()

    logger.info("Data received: %s", data)
    if "name" not in data:
        msg = "No name provided for person."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "email" not in data:
        msg = "No email provided for person."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "password" not in data:
        msg = "No password provided for person."
        logger.info(msg)
        return create_response(status=422, message=msg)

    if db.session.query(
            User.id).filter_by(email=data["email"]).scalar() is not None:
        msg = "!!!!"
        logger.info(msg)
        return create_response(status=422, message=msg)
    new_user = User(name=data["name"],
                    email=data["email"],
                    password=generate_password_hash(data["password"]),
                    isAdmin=False)

    db.session.add(new_user)
    db.session.commit()
    return create_response(
        message=
        f"Successfully created person {new_user.name} with id: {new_user.id}")
Example #4
0
def create_message():
    data = request.get_json()

    try:
        message = DirectMessage(
            body=data["message"],
            message_read=False,
            sender_id=data["user_id"],
            recipient_id=data["recipient_id"],
            created_at=data.get("time"),
        )
    except Exception as e:
        msg = "Invalid parameter provided"
        logger.info(e)
        return create_response(status=422, message=msg)
    try:
        message.save()
    except:
        msg = "Failed to save message"
        logger.info(msg)
        return create_response(status=422, message=msg)

    socketio.emit(data["recipient_id"], json.loads(message.to_json()))
    return create_response(
        status=201,
        message=f"Successfully saved message",
    )
def populate_db():
    data = request.get_json()
    if "parent_link" not in data:
        msg = "No parent link."
        logger.info(msg)
        return create_response(status=442, message=msg)

    parent_link = data["parent_link"]
    logger.info("Populating Census Response Data from {}".format(parent_link))

    files = extract_data_links(parent_link)

    parse2000 = True
    for file, date in files.items():
        responses = parse_census_data(file, date, parse2000)
        parse2000 = False
        for r in responses:
            existing = CensusResponse.objects(tract_id=r.tract_id)
            if len(existing) > 0:
                existing = existing[0]
                existing.update(r)
                existing.save()
            else:
                r.save()

    return create_response(
        message=f"Successfully added {len(responses)} new Census Responses")
Example #6
0
def edit_visualization():
    data = request.get_json()
    logger.info("Data recieved: %s", data)
    if "visualization_id" not in data:
        msg = "No ID provided for visualization."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "name" not in data:
        msg = "No name provided for visualization."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "sentence_id" not in data:
        msg = "No sentence ID provided for visualization."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "comment" not in data:
        data["comment"] = ""
    # create SQLAlchemy Object
    if "params" not in data:
        msg = "No params provided for line chart visualization."
        logger.info(msg)
        return create_response(status=422, message=msg)
    visual = Visualization.query.get(data["visualization_id"])
    visual.name = data["name"]
    visual.sentence_id = data["sentence_id"]
    visual.comment = data["comment"]
    visual.params = data["params"]
    visual.type = data["type"]
    # commit it to database
    db.session.commit()
    return create_response(
        message=f"Successfully edited visualization {visual.name} with id: {visual.id}"
    )
Example #7
0
def create_access():
    data = request.get_json()
    logger.info("Data recieved: %s", data)
    if "user_id" not in data:
        msg = "No user ID provided for access."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "model" not in data:
        msg = "No model provided for access."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "model_id" not in data:
        msg = "No model ID provided for access."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "level" not in data:
        msg = "No access level provided for access."
        logger.info(msg)
        return create_response(status=422, message=msg)
    # Create SQLAlchemy Object
    new_access = Access(
        user_id = data["user_id"], 
        model = data["model"],
        model_id = data["model_id"],
        level = data["level"])
    # Commit it to database
    db.session.add(new_access)
    db.session.commit()
    return create_response(
        message=f"Successfully created access with id: {new_access.id}"
    )
Example #8
0
def refresh_token():
    data = request.json
    token = data.get("token")

    claims = firebase_admin_auth.verify_id_token(token)
    firebase_uid = claims.get("uid")
    role = claims.get("role")

    profile_model = get_profile_model(role)
    profile_id = None

    try:
        profile = profile_model.objects.get(firebase_uid=firebase_uid)
        profile_id = str(profile.id)
    except:
        msg = "Could not find profile"
        logger.info(msg)
        return create_response(status=422, message=msg)

    return create_response(
        status=200,
        data={
            "token":
            firebase_admin_auth.create_custom_token(firebase_uid, {
                "role": role,
                "profileId": profile_id
            }).decode("utf-8"),
        },
    )
Example #9
0
def generate_sheet(sheet_name, row_data, columns):
    df = pd.DataFrame(row_data, columns=columns)
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine="xlsxwriter")

    df.to_excel(writer,
                startrow=0,
                merge_cells=False,
                sheet_name=sheet_name,
                index=False)
    workbook = writer.book
    worksheet = writer.sheets[sheet_name]
    format = workbook.add_format()
    format.set_bg_color("#eeeeee")
    worksheet.set_column(0, len(row_data[0]), 28)

    writer.close()
    output.seek(0)

    try:
        return send_file(
            output,
            mimetype=
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            attachment_filename="{0}.xlsx".format(sheet_name),
            as_attachment=True,
        )
    except FileNotFoundError:
        msg = "Download failed"
        logger.info(msg)
        return create_response(status=422, message=msg)
Example #10
0
def create_widget():
    def missing_data(field):
        msg = "No %s provided for widget." % field
        logger.info(msg)
        return create_response(status=422, message=msg)

    data = request.get_json()
    logger.info("Data recieved: %s", data)
    if "background_colour_r" not in data:
        return missing_data("background_colour_r")
    if "background_colour_b" not in data:
        return missing_data("background_colour_b")
    if "background_colour_g" not in data:
        return missing_data("background_colour_g")
    if "background_colour_a" not in data:
        return missing_data("background_colour_a")
    if "background_image" not in data:
        return missing_data("background_image")
    if "height" not in data:
        return missing_data("height")
    if "content_background_colour_r" not in data:
        return missing_data("content_background_colour_r")
    if "content_background_colour_b" not in data:
        return missing_data("content_background_colour_b")
    if "content_background_colour_g" not in data:
        return missing_data("content_background_colour_g")
    if "content_background_colour_a" not in data:
        return missing_data("content_background_colour_a")
    if "border_radius" not in data:
        return missing_data("border_radius")
    if "content_body_text" not in data:
        return missing_data("content_body_text")

    # create SQLAlchemy Objects
    background_colour = ",".join([
        str(data["background_colour_r"]),
        str(data["background_colour_g"]),
        str(data["background_colour_b"]),
        str(data["background_colour_a"]),
    ])
    content_background_colour = ",".join([
        str(data["content_background_colour_r"]),
        str(data["content_background_colour_g"]),
        str(data["content_background_colour_b"]),
        str(data["content_background_colour_a"]),
    ])
    assert len(background_colour.split(",")) == 4
    assert len(content_background_colour.split(",")) == 4
    new_widget = Widget(
        background_colour=background_colour,
        background_image=data["background_image"],
        height=data["height"],
        content_background_colour=content_background_colour,
        border_radius=data["border_radius"],
        content_body_text=data["content_body_text"],
    )
    # commit it to database
    db.session.add(new_widget)
    db.session.commit()
    return jsonify({"id": new_widget.id})
Example #11
0
def create_dashboard():
    data = request.get_json()
    logger.info("Data recieved: %s", data)
    if "name" not in data:
        msg = "No name provided for dashboard."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "comment" not in data:
        data["comment"] = ""
    # create SQLAlchemy Object
    new_dash = Dashboard(
        name = data["name"], 
        comment = data["comment"])
    # commit it to database
    new_dash.visualizations=[]
    for vis in data["visualizations"]:
        dash_vis = DashboardsVisualizations(
            visualization = Visualization.query.get(vis["_id"]),
            order = vis["order"]
        )
        new_dash.visualizations.append(dash_vis)
    db.session.add(new_dash)
    db.session.commit()
    db.session.add(Access(user_id = data["user_id"], model = 'dashboard', model_id = new_dash.id, level = 'admin'))
    db.session.commit()
    return create_response(
        message=f"Successfully created dashboard {new_dash.name} with id: {new_dash.id}"
    )
Example #12
0
def edit_mentor(id):
    data = request.get_json()

    try:
        account_type = int(request.args["account_type"])
    except:
        msg = "Level param doesn't exist or isn't an int"
        return create_response(status=422, message=msg)

    # Try to retrieve account profile from database
    account = None
    try:
        if account_type == Account.MENTEE:
            account = MenteeProfile.objects.get(id=id)
        elif account_type == Account.MENTOR:
            account = MentorProfile.objects.get(id=id)
        else:
            msg = "Level param doesn't match existing account types"
            return create_response(status=422, message=msg)
    except:
        msg = ""
        if account_type == Account.MENTEE:
            msg = "No mentee with that id"
        elif account_type == Account.MENTOR:
            msg = "No mentor with that id"
        logger.info(msg)
        return create_response(status=422, message=msg)

    if not edit_profile(data, account):
        msg = "Couldn't update profile"
        return create_response(status=500, message=msg)

    account.save()

    return create_response(status=200, message=f"Success")
Example #13
0
def delete_request(appointment_id):
    try:
        request = AppointmentRequest.objects.get(id=appointment_id)
        mentor = MentorProfile.objects.get(id=request.mentor_id)
        mentee = MenteeProfile.objects.get(id=appointment.mentee_id)
    except:
        msg = "No appointment or account found with that id"
        logger.info(msg)
        return create_response(status=422, message=msg)

    if mentee.email_notifications:
        start_time = appointment.timeslot.start_time.strftime(
            f"{APPT_TIME_FORMAT} GMT")
        res_email = send_email(
            recipient=mentee.email,
            subject="Mentee Appointment Notification",
            data={
                "name": mentor.name,
                "date": start_time,
                "approved": False
            },
            template_id=MENTEE_APPT_TEMPLATE,
        )
        if not res_email:
            logger.info("Failed to send email")

    request.status = APPT_STATUS["REJECTED"]
    request.save()
    return create_response(status=200, message=f"Success")
Example #14
0
def get_replies(flyer_id):
    data = request.get_json()
    logger.info("Data recieved: %s", data)

    if "sender" not in data:
        msg = "No sender provided for reply."
        logger.info(msg)
        return create_response(status=422, message=msg)

    flyer = SearchFlyer.query.get(flyer_id)
    sender = data['sender']
    data['content'] = f'{sender} se quiere contactar con vos por tu aviso.'
    data['flyer_id'] = flyer_id
    data['recipient'] = flyer.created_by
    data['status'] = 'sent'

    # create SQLAlchemy Object
    message = Message(**data)

    # commit it to database
    db.session.add_all([message])
    db.session.commit()

    submit_notification(
        flyer.created_by, {
            'title': '¡Respondieron tu aviso!',
            'body': f'{sender} se quiere contactar con vos por tu aviso.',
            'flyer_id': flyer_id
        })

    return create_response(
        message=f"Successfully created message with id: {message.id}",
        data={"message": message.to_dict()})
Example #15
0
def edit_sentence():
    data = request.get_json()
    logger.info("Data recieved: %s", data)
    if "sentence_id" not in data:
        msg = "No sentence ID provided for sentence."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "name" not in data:
        msg = "No name provided for sentence."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "sql_query" not in data:
        msg = "No SQL query provided for sentence."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "connection_id" not in data:
        msg = "No connection ID provided for sentence."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "comment" not in data:
        data["comment"] = ""
    # Fetch Sentence
    sentence = Sentence.query.get(data["sentence_id"])
    # Perform edit
    sentence.connection_id = data["connection_id"]
    sentence.name = data["name"]
    sentence.sql_query = data["sql_query"]
    sentence.comment = data["comment"]
    sentence.visual_query_params = data["visual_query_params"]
    # Commit it to database
    db.session.commit()
    return create_response(
        message=f"Successfully edited sentence {sentence.name} with id: {sentence.id}"
    )
Example #16
0
def post_user_data():
    data = request.get_json()
    logger.info("Data recieved: %s", data)

    if "email" not in data:
        msg = "No email provided."
        logger.info(msg)
        return create_response(status=422, message=msg)

    email = data['email']
    
    user_data = UserData.query.filter_by(email= email).first()
    
    if user_data:
        user_data.push_token = data['push_token']
    else:
        user_data = UserData(**data)
        # commit it to database
        db.session.add_all([user_data])

    db.session.commit()

    return create_response(
        message=f"Successfully update user data",
        data={ "message": user_data.to_dict() }
    )
Example #17
0
def get_account(id):
    try:
        account_type = int(request.args["account_type"])
    except:
        msg = "Missing account_type param or account_type param is not an int"
        return create_response(status=422, message=msg)

    account = None
    try:
        if account_type == Account.MENTEE:
            account = MenteeProfile.objects.get(id=id)
        elif account_type == Account.MENTOR:
            account = MentorProfile.objects.get(id=id)
        else:
            msg = "Level param doesn't match existing account types"
            return create_response(status=422, message=msg)
    except:
        msg = ""
        if account_type == Account.MENTEE:
            msg = "No mentee with that id"
        elif account_type == Account.MENTOR:
            msg = "No mentor with that id"
        logger.info(msg)
        return create_response(status=422, message=msg)

    return create_response(data={"account": account})
Example #18
0
def download_accounts_info():
    data = request.args
    account_type = int(data.get("account_type", 0))
    accounts = None

    try:
        admins = Admin.objects()
        admin_ids = [admin.firebase_uid for admin in admins]

        if account_type == Account.MENTOR:
            accounts = MentorProfile.objects(firebase_uid__nin=admin_ids)
        elif account_type == Account.MENTEE:
            accounts = MenteeProfile.objects(firebase_uid__nin=admin_ids)
    except:
        msg = "Failed to get accounts"
        logger.info(msg)
        return create_response(status=422, message=msg)

    if account_type == Account.MENTOR:
        return download_mentor_accounts(accounts)
    elif account_type == Account.MENTEE:
        return download_mentee_accounts(accounts)

    msg = "Invalid input"
    logger.info(msg)
    return create_response(status=422, message=msg)
def create_locations_in_trip(id):
    info = request.get_json()
    logger.info(f"Recieved info {info}")

    trip = get_trip_by_id(id)

    if trip is None:
        return create_response(message=f"No trip with id {id} was found.",
                               status=404)

    location = Location()

    for key in Location.get_elements():
        if key in Location.get_elements() and key not in info:
            msg = f"Checkpoint was not created because missing required Location field '{key}'."
            logger.info(msg)
            return create_response(message=msg, status=442)
        elif key in Location.get_elements() and key in info:
            location[key] = info[key]

    location.save()

    trip.checkpoints.append(location)
    trip.save()

    return create_response(
        message=
        f"Successfully created location with id {location.id} for trip with driver id {trip.driver.id} and id {trip.id}.",
        status=201,
    )
Example #20
0
def get_crime():
    """
    GET function for retrieving Crime objects
    """
    response = [crime.to_mongo() for crime in Crime.objects]
    response = {"crimes": response}
    logger.info("CRIMES: %s", response)
    return create_response(data=response)
Example #21
0
def get_streetlight():
    """
    GET function for retrieving Streetlight objects
    """
    response = [streetlight.to_mongo() for streetlight in Streetlight.objects]
    response = {"streetlights": response}
    logger.info("STREETLIGHTS: %s", response)
    return create_response(data=response)
Example #22
0
def get_busStop():
    """
    GET function for retrieving BusStop objects
    """
    response = [busStop.to_mongo() for busStop in BusStop.objects]
    response = {"busStops": response}
    logger.info("BUSSTOPS: %s", response)
    return create_response(data=response)
def get_user_by_id(user_id):
    user = User.objects(id=user_id)

    if not user:
        logger.info(f"There are no users with id {user_id}.")
        return None

    return user.get(id=user_id)
Example #24
0
def get_users():
    """
    GET function for retrieving User objects
    """
    response = [user.to_mongo() for user in User.objects]
    response = {"users": response}
    logger.info("USERS: %s", response)
    return create_response(data=response)
def get_trip_by_id(trip_id):
    trip = Trip.objects(id=trip_id)

    if not trip:
        logger.info(f"There are no trips with id {trip_id}.")
        return None

    return trip.get(id=trip_id)
Example #26
0
def get_application_by_id(id):
    try:
        application = MentorApplication.objects.get(id=id)
    except:
        msg = "No application currently exist with this id " + id
        logger.info(msg)
        return create_response(status=422, message=msg)

    return create_response(data={"mentor_application": application})
def get_car_by_id(user, car_id):
    car = Car.objects(id=car_id)

    if not car:
        logger.info(
            f"There are no cars with id {car_id} belonging to user {user.id}.")
        return None

    return car.get(id=car_id)
Example #28
0
def get_availability(id):

    try:
        availability = MentorProfile.objects.get(id=id).availability
    except:
        msg = "No mentor found with that id"
        logger.info(msg)
        return create_response(status=422, message=msg)

    return create_response(data={"availability": availability})
Example #29
0
def get_police_stations():
    """
    GET function for retrieving Police Station objects
    """
    response = [
        policeStation.to_mongo() for policeStation in PoliceStation.objects
    ]
    response = {"policeStations": response}
    logger.info("POLICESTATIONS: %s", response)
    return create_response(data=response)
Example #30
0
def get_business():
    """
    GET function for retrieving Business objects
    """
    response = [business.to_mongo() for business in Business.objects]
    response = {"businesses": response}
    logger.info("BUSINESSES: %s", response)
    return create_response(
        data=response, status=200, message="Returning all businesses."
    )