Skip to content

Commit

Permalink
Ryan/epic2/userstory6 (#318)
Browse files Browse the repository at this point in the history
* Add /:id/users endpoint

* Linting Fix

* Lint Fix

* Lint Fix

* Remove explicit ID declarations from dev_seeds.
Corrects and issue where the SQLAlchemy Autoincrement
collides with already used IDs.

---------

Co-authored-by: Darrell Malone Jr <[email protected]>
  • Loading branch information
RyEggGit and DMalone87 authored Jan 20, 2024
1 parent 2f891cc commit e99bcaa
Show file tree
Hide file tree
Showing 4 changed files with 173 additions and 70 deletions.
15 changes: 8 additions & 7 deletions alembic/dev_seeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from backend.database.models.partner import Partner
from backend.database.models.use_of_force import UseOfForce


def create_user(user):
user_exists = (
db.session.query(User).filter_by(email=user.email).first() is not None
Expand All @@ -14,6 +15,7 @@ def create_user(user):
if not user_exists:
user.create()


def create_partner(partner):
partner_exists = (
db.session.query(Partner).filter_by(id=partner.id).first() is not None
Expand All @@ -22,14 +24,12 @@ def create_partner(partner):
if not partner_exists:
partner.create()


def create_incident(key=1, date="10-01-2019", lon=84, lat=34):
base_id = 10000000
id = base_id + key
mpv = db.session.query(Partner).filter_by(
name="Mapping Police Violence").first()
incident = Incident(
id=id,
source_id="1",
source_id=mpv.id,
date_record_created=f"{date} 00:00:00",
time_of_incident=f"{date} 00:00:00",
time_confidence="1",
Expand All @@ -55,11 +55,12 @@ def create_incident(key=1, date="10-01-2019", lon=84, lat=34):
],
use_of_force=[UseOfForce(item=f"gunshot {key}")]
)
exists = db.session.query(Incident).filter_by(id=id).first() is not None
exists = db.session.query(Incident).filter_by(id=key).first() is not None

if not exists:
incident.create()


def create_seeds():
create_user(
User(
Expand Down Expand Up @@ -103,7 +104,6 @@ def create_seeds():
)
create_partner(
Partner(
id="1",
name="Mapping Police Violence",
url="https://mappingpoliceviolence.us",
contact_email="[email protected]"
Expand All @@ -118,4 +118,5 @@ def create_seeds():
create_incident(key=7, date="10-01-2020", lon=-118.40853, lat=33.9415889)
create_incident(key=8, date="10-15-2020", lon=-84.032149, lat=33.967774)

create_seeds()

create_seeds()
83 changes: 66 additions & 17 deletions backend/routes/partners.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
from flask import Blueprint, abort, current_app, request
from flask_jwt_extended import get_jwt
from flask_jwt_extended.view_decorators import jwt_required

from flask_sqlalchemy import Pagination
from ..database import Partner, PartnerMember, MemberRole, db
from ..schemas import (
CreatePartnerSchema,
AddMemberSchema,
partner_orm_to_json,
partner_member_orm_to_json,
user_orm_to_json,
partner_member_to_orm,
partner_to_orm,
validate,
Expand Down Expand Up @@ -54,10 +55,14 @@ def create_partner():
)
make_admin.create()

track_to_mp(request, "create_partner", {
"partner_name": partner.name,
"partner_contact": partner.contact_email
})
track_to_mp(
request,
"create_partner",
{
"partner_name": partner.name,
"partner_contact": partner.contact_email,
},
)
return partner_orm_to_json(created)


Expand Down Expand Up @@ -107,12 +112,12 @@ def get_partner_members(partner_id: int):
PartnerMember.partner_id == partner_id
)
results = all_members.paginate(
page=q_page, per_page=q_per_page, max_per_page=100)
page=q_page, per_page=q_per_page, max_per_page=100
)

return {
"results": [
partner_member_orm_to_json(member)
for member in results.items
partner_member_orm_to_json(member) for member in results.items
],
"page": results.page,
"totalPages": results.pages,
Expand All @@ -136,6 +141,42 @@ class Config:
} """


@bp.route("/<int:partner_id>/users", methods=["GET"])
@jwt_required() # type: ignore
@min_role_required(UserRole.PUBLIC)
@validate() # type: ignore
def get_partner_users(partner_id: int):
# Get the page number from the query parameters (default to 1)
page = request.args.get("page", 1, type=int)

# Get the number of items per page from the query parameters (default to 20)
per_page = request.args.get("per_page", 20, type=int)

# Query the PartnerMember table for records with
# the given partner_id and paginate the results
pagination: Pagination = PartnerMember.query.filter_by(
partner_id=partner_id
).paginate(page=page, per_page=per_page, error_out=False)

# If the partner_id is invalid, return a 404 error
if pagination.total == 0:
return {"message": "Partner not found"}, 404

# Get the User objects associated with the members on the current page
users: list[User] = [
User.query.get(member.user_id) for member in pagination.items
] # type: ignore

# Convert the User objects to dictionaries and return them as JSON

return {
"results": [user_orm_to_json(user) for user in users],
"page": pagination.page,
"totalPages": pagination.pages,
"totalResults": pagination.total,
}


@bp.route("/<int:partner_id>/members/add", methods=["POST"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
Expand All @@ -157,10 +198,14 @@ def add_member_to_partner(partner_id: int):
jwt_decoded = get_jwt()

current_user = User.get(jwt_decoded["sub"])
association = db.session.query(PartnerMember).filter(
PartnerMember.user_id == current_user.id,
PartnerMember.partner_id == partner_id,
).first()
association = (
db.session.query(PartnerMember)
.filter(
PartnerMember.user_id == current_user.id,
PartnerMember.partner_id == partner_id,
)
.first()
)

if (
association is None
Expand All @@ -187,9 +232,13 @@ def add_member_to_partner(partner_id: int):

created = partner_member.create()

track_to_mp(request, "add_partner_member", {
"partner_id": partner_id,
"user_id": partner_member.user_id,
"role": partner_member.role,
})
track_to_mp(
request,
"add_partner_member",
{
"partner_id": partner_id,
"user_id": partner_member.user_id,
"role": partner_member.role,
},
)
return partner_member_orm_to_json(created)
15 changes: 12 additions & 3 deletions backend/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,7 @@ class CreatePartnerMemberSchema(BaseModel):


AddMemberSchema = sqlalchemy_to_pydantic(
PartnerMember,
exclude=["id", "date_joined", "partner", "user"]
PartnerMember, exclude=["id", "date_joined", "partner", "user"]
)


Expand Down Expand Up @@ -298,7 +297,8 @@ def partner_orm_to_json(partner: Partner) -> dict:


def partner_member_to_orm(
partner_member: CreatePartnerMemberSchema) -> PartnerMember:
partner_member: CreatePartnerMemberSchema,
) -> PartnerMember:
"""Convert the JSON partner member into an ORM instance"""
orm_attrs = partner_member.dict()
return PartnerMember(**orm_attrs)
Expand All @@ -308,3 +308,12 @@ def partner_member_orm_to_json(partner_member: PartnerMember) -> dict:
return PartnerMemberSchema.from_orm(partner_member).dict(
exclude_none=True,
)


def user_orm_to_json(user: User) -> Dict[str, Any]:
return UserSchema.from_orm(user).dict(
exclude={
"password",
"email_confirmed_at",
}
)
Loading

0 comments on commit e99bcaa

Please sign in to comment.