From d6c35fc4e3816eccb021a98a3823c35cf6aa6ac9 Mon Sep 17 00:00:00 2001 From: sultanofcardio <14842108+sultanofcardio@users.noreply.github.com> Date: Thu, 9 Jan 2025 08:35:21 -0500 Subject: [PATCH] Add roles property to details object in each returned respondent --- .../workspaces/crud/user_applet_access.py | 35 +++++++++++++++++++ src/apps/workspaces/domain/workspace.py | 2 ++ 2 files changed, 37 insertions(+) diff --git a/src/apps/workspaces/crud/user_applet_access.py b/src/apps/workspaces/crud/user_applet_access.py index 793caead9f0..40ccadc903b 100644 --- a/src/apps/workspaces/crud/user_applet_access.py +++ b/src/apps/workspaces/crud/user_applet_access.py @@ -457,6 +457,31 @@ async def get_workspace_respondents( .exists() ) + # Subquery to get the list of roles for each user and applet + roles_subquery = ( + select( + UserAppletAccessSchema.user_id, + UserAppletAccessSchema.applet_id, + func.array_agg( + aggregate_order_by( + UserAppletAccessSchema.role, + case( + (UserAppletAccessSchema.role == Role.OWNER, 1), + (UserAppletAccessSchema.role == Role.MANAGER, 2), + (UserAppletAccessSchema.role == Role.COORDINATOR, 3), + (UserAppletAccessSchema.role == Role.EDITOR, 4), + (UserAppletAccessSchema.role == Role.REVIEWER, 5), + (UserAppletAccessSchema.role == Role.RESPONDENT, 6), + else_=10, + ).asc(), + ) + ).label("roles"), + ) + .where(UserAppletAccessSchema.soft_exists()) + .group_by(UserAppletAccessSchema.applet_id, UserAppletAccessSchema.user_id) + .subquery() + ) + query: Query = select( # fmt: off UserSchema.id, @@ -518,6 +543,8 @@ async def get_workspace_respondents( SubjectSchema.last_name, text("'subject_created_at'"), SubjectSchema.created_at, + text("'roles'"), + func.coalesce(roles_subquery.c.roles, []), ) ).label("details"), ) @@ -534,6 +561,14 @@ async def get_workspace_respondents( ), isouter=True, ) + query = query.join( + roles_subquery, + and_( + roles_subquery.c.user_id == SubjectSchema.user_id, + roles_subquery.c.applet_id == SubjectSchema.applet_id, + ), + isouter=True, + ) query = query.where( has_access, diff --git a/src/apps/workspaces/domain/workspace.py b/src/apps/workspaces/domain/workspace.py index 286316cbd2c..e3240c3b863 100644 --- a/src/apps/workspaces/domain/workspace.py +++ b/src/apps/workspaces/domain/workspace.py @@ -89,6 +89,7 @@ class WorkspaceRespondentDetails(InternalModel): subject_last_name: str subject_created_at: datetime.datetime invitation: InvitationDetail | None = None + roles: list[Role] @validator("respondent_nickname", "subject_first_name", "subject_last_name", pre=True) def decrypt_fields(cls, value): @@ -202,6 +203,7 @@ class PublicWorkspaceRespondentDetails(PublicModel): subject_last_name: str subject_created_at: datetime.datetime invitation: InvitationResponse | None = None + roles: list[Role] class PublicWorkspaceRespondent(PublicModel):