Skip to content

Commit

Permalink
Merge pull request #6609 from hotosm/fastapi-refactor
Browse files Browse the repository at this point in the history
Teams managers and members assignment and retrieve query fixed
  • Loading branch information
prabinoid authored Nov 4, 2024
2 parents c4361e2 + eb9c68d commit 9ee86b5
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 22 deletions.
1 change: 0 additions & 1 deletion backend/api/teams/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ async def patch(
)
try:
if ("joinMethod" or "organisations_id") not in data.keys():
print("inside......")
await Team.update_team_members(team, team_dto, db)
else:
await TeamService.update_team(team_dto, db)
Expand Down
18 changes: 13 additions & 5 deletions backend/api/users/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

from databases import Database
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from loguru import logger


from backend.db import get_db, get_session
from backend.models.dtos.user_dto import AuthUserDTO, UserSearchQuery
Expand Down Expand Up @@ -59,9 +62,12 @@ async def get(
return user_dto


# class UsersAllAPI():
@router.get("/")
async def get(request: Request, db: Database = Depends(get_db)):
async def get(
request: Request,
user: AuthUserDTO = Depends(login_required),
db: Database = Depends(get_db),
):
"""
Get paged list of all usernames
---
Expand Down Expand Up @@ -124,9 +130,11 @@ async def get(request: Request, db: Database = Depends(get_db)):
query.mapping_level = request.query_params.get("level")
query.role = request.query_params.get("role")
except Exception:
# logger.error(f"Error validating request: {str(e)}")
return {"Error": "Unable to fetch user list", "SubCode": "InvalidData"}, 400

logger.error(f"Error validating request: {str(e)}")
return JSONResponse(
content={"Error": "Unable to fetch user list", "SubCode": "InvalidData"},
status_code=400,
)
users_dto = await UserService.get_all_users(query, db)
return users_dto

Expand Down
23 changes: 18 additions & 5 deletions backend/models/postgis/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,17 +508,29 @@ async def update(self, project_dto: ProjectDTO, db: Database):
self.osmcha_filter_id = None

if project_dto.organisation:
organisation_query = "SELECT * FROM organisations WHERE id = :id"
organization = await db.fetch_one(
"SELECT * FROM organisations WHERE id = :id",
values={"id": project_dto.organisation},
organisation_query, values={"id": project_dto.organisation}
)
org = Organisation(**organization)
if org is None:

if organization is None:
raise NotFound(
sub_code="ORGANISATION_NOT_FOUND",
organisation_id=project_dto.organisation,
)
self.organisation = org

update_organisation_query = """
UPDATE projects
SET organisation_id = :organisation_id
WHERE id = :project_id
"""
await db.execute(
update_organisation_query,
values={
"organisation_id": project_dto.organisation,
"project_id": project_dto.project_id,
},
)

# Cast MappingType strings to int array
type_array = []
Expand Down Expand Up @@ -725,6 +737,7 @@ async def update(self, project_dto: ProjectDTO, db: Database):
columns.pop("geometry", None)
columns.pop("centroid", None)
columns.pop("id", None)
columns.pop("organisation_id", None)
# Update the project in the database
await db.execute(
self.__table__.update().where(Project.id == self.id).values(**columns)
Expand Down
45 changes: 40 additions & 5 deletions backend/models/postgis/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,19 +122,54 @@ class Team(Base):
# organisation = relationship(Organisation, backref="teams", lazy="joined")
organisation = relationship(Organisation, backref="teams")

# async def create(self, db: Database):
# """Creates and saves the current model to the DB"""
# print(self.members)

# team = await db.execute(
# insert(Team.__table__).values(
# organisation_id=self.organisation_id,
# name=self.name,
# logo=self.logo,
# description=self.description,
# join_method=self.join_method,
# visibility=self.visibility,
# )
# )
# return team if team else None

async def create(self, db: Database):
"""Creates and saves the current model to the DB"""
team = await db.execute(
insert(Team.__table__).values(
"""Creates and saves the current model to the DB, including members if they exist."""

# Create the Team and get the generated team_id
team_id = await db.execute(
insert(Team.__table__)
.values(
organisation_id=self.organisation_id,
name=self.name,
logo=self.logo,
description=self.description,
join_method=self.join_method,
visibility=self.visibility,
)
.returning(Team.__table__.c.id)
)
return team if team else None

if team_id and self.members:
members_to_insert = [
{
"team_id": team_id,
"user_id": member.user_id,
"function": member.function,
"active": member.active,
"join_request_notifications": member.join_request_notifications,
}
for member in self.members
]

await db.execute_many(insert(TeamMembers.__table__), members_to_insert)

return team_id

@classmethod
async def create_from_dto(cls, new_team_dto: NewTeamDTO, db: Database):
Expand All @@ -155,7 +190,7 @@ async def create_from_dto(cls, new_team_dto: NewTeamDTO, db: Database):
new_member.user_id = new_team_dto.creator
new_member.function = TeamMemberFunctions.MANAGER.value
new_member.active = True
new_team.members.append(new_member)
new_member.join_request_notifications = False

team = await Team.create(new_team, db)
return team
Expand Down
7 changes: 5 additions & 2 deletions backend/models/postgis/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,17 @@ async def get_all_users(query: UserSearchQuery, db) -> UserSearchDTO:
base_query += " WHERE " + " AND ".join(filters)

base_query += " ORDER BY username"

if query.pagination:
base_query += " LIMIT :limit OFFSET :offset"
base_params = params.copy()
base_params["limit"] = query.per_page
base_params["offset"] = (query.page - 1) * query.per_page

results = await db.fetch_all(base_query, base_params)
results = await db.fetch_all(base_query, base_params)

else:
results = await db.fetch_all(base_query, params)

dto = UserSearchDTO()
for result in results:
Expand All @@ -231,7 +235,6 @@ async def get_all_users(query: UserSearchQuery, db) -> UserSearchDTO:
listed_user.username = result["username"]
listed_user.picture_url = result["picture_url"]
listed_user.role = UserRole(result["role"]).name

dto.users.append(listed_user)

if query.pagination:
Expand Down
8 changes: 4 additions & 4 deletions backend/services/team_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,19 +282,19 @@ async def get_all_teams(search_dto: TeamSearchDTO, db: Database) -> TeamsListDTO
query_parts.append("t.organisation_id = :organisation_id")
params["organisation_id"] = search_dto.organisation

if search_dto.manager and search_dto.manager == search_dto.user_id:
if search_dto.manager and int(search_dto.manager) == int(search_dto.user_id):
manager_teams_query = """
SELECT t.id FROM teams t
JOIN team_members tm ON t.id = tm.team_id
WHERE tm.user_id = :manager_id AND tm.active = true AND tm.function = :manager_function
"""
params["manager_id"] = search_dto.manager
params["manager_id"] = int(search_dto.manager)
params["manager_function"] = TeamMemberFunctions.MANAGER.value

orgs_teams_query = """
SELECT t.id FROM teams t
WHERE t.organisation_id IN (
SELECT id FROM organisations WHERE user_id = :manager_id
WHERE t.organisation_id = ANY(
SELECT organisation_id FROM organisation_managers WHERE user_id = :manager_id
)
"""

Expand Down

0 comments on commit 9ee86b5

Please sign in to comment.