Workspace member (#552)

* fix: clean small back-end issues

* fix: apollo factory causing infinite loop on token renew

* feat: small refactor and add ability to remove workspace member

* fix: test
This commit is contained in:
Jérémy M
2023-07-10 11:25:11 +02:00
committed by GitHub
parent f2c49907a8
commit c529c49ea6
14 changed files with 316 additions and 97 deletions

View File

@ -1112,7 +1112,8 @@ export type EnumPipelineProgressableTypeFilter = {
}; };
export enum FileFolder { export enum FileFolder {
ProfilePicture = 'ProfilePicture' ProfilePicture = 'ProfilePicture',
WorkspaceLogo = 'WorkspaceLogo'
} }
export type IntNullableFilter = { export type IntNullableFilter = {
@ -1160,6 +1161,7 @@ export type Mutation = {
deleteManyCompany: AffectedRows; deleteManyCompany: AffectedRows;
deleteManyPerson: AffectedRows; deleteManyPerson: AffectedRows;
deleteManyPipelineProgress: AffectedRows; deleteManyPipelineProgress: AffectedRows;
deleteWorkspaceMember: WorkspaceMember;
renewToken: AuthTokens; renewToken: AuthTokens;
updateOneCommentThread: CommentThread; updateOneCommentThread: CommentThread;
updateOneCompany?: Maybe<Company>; updateOneCompany?: Maybe<Company>;
@ -1232,6 +1234,11 @@ export type MutationDeleteManyPipelineProgressArgs = {
}; };
export type MutationDeleteWorkspaceMemberArgs = {
where: WorkspaceMemberWhereUniqueInput;
};
export type MutationRenewTokenArgs = { export type MutationRenewTokenArgs = {
refreshToken: Scalars['String']; refreshToken: Scalars['String'];
}; };
@ -2430,6 +2437,7 @@ export type Query = {
findManyPipelineProgress: Array<PipelineProgress>; findManyPipelineProgress: Array<PipelineProgress>;
findManyPipelineStage: Array<PipelineStage>; findManyPipelineStage: Array<PipelineStage>;
findManyUser: Array<User>; findManyUser: Array<User>;
findManyWorkspaceMember: Array<WorkspaceMember>;
findUniqueCompany: Company; findUniqueCompany: Company;
findUniquePerson: Person; findUniquePerson: Person;
}; };
@ -2510,6 +2518,16 @@ export type QueryFindManyUserArgs = {
}; };
export type QueryFindManyWorkspaceMemberArgs = {
cursor?: InputMaybe<WorkspaceMemberWhereUniqueInput>;
distinct?: InputMaybe<Array<WorkspaceMemberScalarFieldEnum>>;
orderBy?: InputMaybe<Array<WorkspaceMemberOrderByWithRelationInput>>;
skip?: InputMaybe<Scalars['Int']>;
take?: InputMaybe<Scalars['Int']>;
where?: InputMaybe<WorkspaceMemberWhereInput>;
};
export type QueryFindUniqueCompanyArgs = { export type QueryFindUniqueCompanyArgs = {
id: Scalars['String']; id: Scalars['String'];
}; };
@ -2930,6 +2948,23 @@ export type WorkspaceMemberCreateWithoutWorkspaceInput = {
user: UserCreateNestedOneWithoutWorkspaceMemberInput; user: UserCreateNestedOneWithoutWorkspaceMemberInput;
}; };
export type WorkspaceMemberOrderByWithRelationInput = {
createdAt?: InputMaybe<SortOrder>;
id?: InputMaybe<SortOrder>;
updatedAt?: InputMaybe<SortOrder>;
user?: InputMaybe<UserOrderByWithRelationInput>;
userId?: InputMaybe<SortOrder>;
};
export enum WorkspaceMemberScalarFieldEnum {
CreatedAt = 'createdAt',
DeletedAt = 'deletedAt',
Id = 'id',
UpdatedAt = 'updatedAt',
UserId = 'userId',
WorkspaceId = 'workspaceId'
}
export type WorkspaceMemberScalarWhereInput = { export type WorkspaceMemberScalarWhereInput = {
AND?: InputMaybe<Array<WorkspaceMemberScalarWhereInput>>; AND?: InputMaybe<Array<WorkspaceMemberScalarWhereInput>>;
NOT?: InputMaybe<Array<WorkspaceMemberScalarWhereInput>>; NOT?: InputMaybe<Array<WorkspaceMemberScalarWhereInput>>;
@ -2983,6 +3018,17 @@ export type WorkspaceMemberUpsertWithWhereUniqueWithoutWorkspaceInput = {
where: WorkspaceMemberWhereUniqueInput; where: WorkspaceMemberWhereUniqueInput;
}; };
export type WorkspaceMemberWhereInput = {
AND?: InputMaybe<Array<WorkspaceMemberWhereInput>>;
NOT?: InputMaybe<Array<WorkspaceMemberWhereInput>>;
OR?: InputMaybe<Array<WorkspaceMemberWhereInput>>;
createdAt?: InputMaybe<DateTimeFilter>;
id?: InputMaybe<StringFilter>;
updatedAt?: InputMaybe<DateTimeFilter>;
user?: InputMaybe<UserRelationFilter>;
userId?: InputMaybe<StringFilter>;
};
export type WorkspaceMemberWhereUniqueInput = { export type WorkspaceMemberWhereUniqueInput = {
id?: InputMaybe<Scalars['String']>; id?: InputMaybe<Scalars['String']>;
userId?: InputMaybe<Scalars['String']>; userId?: InputMaybe<Scalars['String']>;
@ -3330,10 +3376,10 @@ export type RemoveProfilePictureMutationVariables = Exact<{
export type RemoveProfilePictureMutation = { __typename?: 'Mutation', updateUser: { __typename?: 'User', id: string } }; export type RemoveProfilePictureMutation = { __typename?: 'Mutation', updateUser: { __typename?: 'User', id: string } };
export type GetCurrentWorkspaceQueryVariables = Exact<{ [key: string]: never; }>; export type GetWorkspaceMembersQueryVariables = Exact<{ [key: string]: never; }>;
export type GetCurrentWorkspaceQuery = { __typename?: 'Query', currentWorkspace: { __typename?: 'Workspace', id: string, workspaceMember?: Array<{ __typename?: 'WorkspaceMember', id: string, user: { __typename?: 'User', id: string, email: string, avatarUrl?: string | null, firstName?: string | null, lastName?: string | null } }> | null } }; export type GetWorkspaceMembersQuery = { __typename?: 'Query', workspaceMembers: Array<{ __typename?: 'WorkspaceMember', id: string, user: { __typename?: 'User', id: string, email: string, avatarUrl?: string | null, firstName?: string | null, lastName?: string | null } }> };
export type UpdateWorkspaceMutationVariables = Exact<{ export type UpdateWorkspaceMutationVariables = Exact<{
data: WorkspaceUpdateInput; data: WorkspaceUpdateInput;
@ -3354,6 +3400,13 @@ export type RemoveWorkspaceLogoMutationVariables = Exact<{ [key: string]: never;
export type RemoveWorkspaceLogoMutation = { __typename?: 'Mutation', updateWorkspace: { __typename?: 'Workspace', id: string } }; export type RemoveWorkspaceLogoMutation = { __typename?: 'Mutation', updateWorkspace: { __typename?: 'Workspace', id: string } };
export type RemoveWorkspaceMemberMutationVariables = Exact<{
where: WorkspaceMemberWhereUniqueInput;
}>;
export type RemoveWorkspaceMemberMutation = { __typename?: 'Mutation', deleteWorkspaceMember: { __typename?: 'WorkspaceMember', id: string } };
export const CreateEventDocument = gql` export const CreateEventDocument = gql`
mutation CreateEvent($type: String!, $data: JSON!) { mutation CreateEvent($type: String!, $data: JSON!) {
@ -5041,50 +5094,47 @@ export function useRemoveProfilePictureMutation(baseOptions?: Apollo.MutationHoo
export type RemoveProfilePictureMutationHookResult = ReturnType<typeof useRemoveProfilePictureMutation>; export type RemoveProfilePictureMutationHookResult = ReturnType<typeof useRemoveProfilePictureMutation>;
export type RemoveProfilePictureMutationResult = Apollo.MutationResult<RemoveProfilePictureMutation>; export type RemoveProfilePictureMutationResult = Apollo.MutationResult<RemoveProfilePictureMutation>;
export type RemoveProfilePictureMutationOptions = Apollo.BaseMutationOptions<RemoveProfilePictureMutation, RemoveProfilePictureMutationVariables>; export type RemoveProfilePictureMutationOptions = Apollo.BaseMutationOptions<RemoveProfilePictureMutation, RemoveProfilePictureMutationVariables>;
export const GetCurrentWorkspaceDocument = gql` export const GetWorkspaceMembersDocument = gql`
query GetCurrentWorkspace { query GetWorkspaceMembers {
currentWorkspace { workspaceMembers: findManyWorkspaceMember {
id id
workspaceMember { user {
id id
user { email
id avatarUrl
email firstName
avatarUrl lastName
firstName
lastName
}
} }
} }
} }
`; `;
/** /**
* __useGetCurrentWorkspaceQuery__ * __useGetWorkspaceMembersQuery__
* *
* To run a query within a React component, call `useGetCurrentWorkspaceQuery` and pass it any options that fit your needs. * To run a query within a React component, call `useGetWorkspaceMembersQuery` and pass it any options that fit your needs.
* When your component renders, `useGetCurrentWorkspaceQuery` returns an object from Apollo Client that contains loading, error, and data properties * When your component renders, `useGetWorkspaceMembersQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI. * you can use to render your UI.
* *
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
* *
* @example * @example
* const { data, loading, error } = useGetCurrentWorkspaceQuery({ * const { data, loading, error } = useGetWorkspaceMembersQuery({
* variables: { * variables: {
* }, * },
* }); * });
*/ */
export function useGetCurrentWorkspaceQuery(baseOptions?: Apollo.QueryHookOptions<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>) { export function useGetWorkspaceMembersQuery(baseOptions?: Apollo.QueryHookOptions<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions} const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>(GetCurrentWorkspaceDocument, options); return Apollo.useQuery<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>(GetWorkspaceMembersDocument, options);
} }
export function useGetCurrentWorkspaceLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>) { export function useGetWorkspaceMembersLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions} const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>(GetCurrentWorkspaceDocument, options); return Apollo.useLazyQuery<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>(GetWorkspaceMembersDocument, options);
} }
export type GetCurrentWorkspaceQueryHookResult = ReturnType<typeof useGetCurrentWorkspaceQuery>; export type GetWorkspaceMembersQueryHookResult = ReturnType<typeof useGetWorkspaceMembersQuery>;
export type GetCurrentWorkspaceLazyQueryHookResult = ReturnType<typeof useGetCurrentWorkspaceLazyQuery>; export type GetWorkspaceMembersLazyQueryHookResult = ReturnType<typeof useGetWorkspaceMembersLazyQuery>;
export type GetCurrentWorkspaceQueryResult = Apollo.QueryResult<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>; export type GetWorkspaceMembersQueryResult = Apollo.QueryResult<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>;
export const UpdateWorkspaceDocument = gql` export const UpdateWorkspaceDocument = gql`
mutation UpdateWorkspace($data: WorkspaceUpdateInput!) { mutation UpdateWorkspace($data: WorkspaceUpdateInput!) {
updateWorkspace(data: $data) { updateWorkspace(data: $data) {
@ -5183,4 +5233,37 @@ export function useRemoveWorkspaceLogoMutation(baseOptions?: Apollo.MutationHook
} }
export type RemoveWorkspaceLogoMutationHookResult = ReturnType<typeof useRemoveWorkspaceLogoMutation>; export type RemoveWorkspaceLogoMutationHookResult = ReturnType<typeof useRemoveWorkspaceLogoMutation>;
export type RemoveWorkspaceLogoMutationResult = Apollo.MutationResult<RemoveWorkspaceLogoMutation>; export type RemoveWorkspaceLogoMutationResult = Apollo.MutationResult<RemoveWorkspaceLogoMutation>;
export type RemoveWorkspaceLogoMutationOptions = Apollo.BaseMutationOptions<RemoveWorkspaceLogoMutation, RemoveWorkspaceLogoMutationVariables>; export type RemoveWorkspaceLogoMutationOptions = Apollo.BaseMutationOptions<RemoveWorkspaceLogoMutation, RemoveWorkspaceLogoMutationVariables>;
export const RemoveWorkspaceMemberDocument = gql`
mutation RemoveWorkspaceMember($where: WorkspaceMemberWhereUniqueInput!) {
deleteWorkspaceMember(where: $where) {
id
}
}
`;
export type RemoveWorkspaceMemberMutationFn = Apollo.MutationFunction<RemoveWorkspaceMemberMutation, RemoveWorkspaceMemberMutationVariables>;
/**
* __useRemoveWorkspaceMemberMutation__
*
* To run a mutation, you first call `useRemoveWorkspaceMemberMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useRemoveWorkspaceMemberMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [removeWorkspaceMemberMutation, { data, loading, error }] = useRemoveWorkspaceMemberMutation({
* variables: {
* where: // value for 'where'
* },
* });
*/
export function useRemoveWorkspaceMemberMutation(baseOptions?: Apollo.MutationHookOptions<RemoveWorkspaceMemberMutation, RemoveWorkspaceMemberMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<RemoveWorkspaceMemberMutation, RemoveWorkspaceMemberMutationVariables>(RemoveWorkspaceMemberDocument, options);
}
export type RemoveWorkspaceMemberMutationHookResult = ReturnType<typeof useRemoveWorkspaceMemberMutation>;
export type RemoveWorkspaceMemberMutationResult = Apollo.MutationResult<RemoveWorkspaceMemberMutation>;
export type RemoveWorkspaceMemberMutationOptions = Apollo.BaseMutationOptions<RemoveWorkspaceMemberMutation, RemoveWorkspaceMemberMutationVariables>;

View File

@ -1,4 +1,4 @@
import { useMemo, useRef } from 'react'; import { useEffect, useMemo, useRef } from 'react';
import { InMemoryCache, NormalizedCacheObject } from '@apollo/client'; import { InMemoryCache, NormalizedCacheObject } from '@apollo/client';
import { useRecoilState } from 'recoil'; import { useRecoilState } from 'recoil';
@ -38,6 +38,8 @@ export function useApolloFactory() {
fetchPolicy: 'cache-first', fetchPolicy: 'cache-first',
}, },
}, },
// We don't want to re-create the client on token change or it will cause infinite loop
initialTokenPair: tokenPair,
onTokenPairChange(tokenPair) { onTokenPairChange(tokenPair) {
setTokenPair(tokenPair); setTokenPair(tokenPair);
}, },
@ -46,11 +48,17 @@ export function useApolloFactory() {
}, },
extraLinks: [], extraLinks: [],
isDebugMode, isDebugMode,
tokenPair,
}); });
return apolloRef.current.getClient(); return apolloRef.current.getClient();
}, [setTokenPair, isDebugMode, tokenPair]); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [setTokenPair, isDebugMode]);
useEffect(() => {
if (apolloRef.current) {
apolloRef.current.updateTokenPair(tokenPair);
}
}, [tokenPair]);
return apolloClient; return apolloClient;
} }

View File

@ -28,9 +28,9 @@ export interface Options<TCacheShape> extends ApolloClientOptions<TCacheShape> {
onNetworkError?: (err: Error | ServerParseError | ServerError) => void; onNetworkError?: (err: Error | ServerParseError | ServerError) => void;
onTokenPairChange?: (tokenPair: AuthTokenPair) => void; onTokenPairChange?: (tokenPair: AuthTokenPair) => void;
onUnauthenticatedError?: () => void; onUnauthenticatedError?: () => void;
initialTokenPair: AuthTokenPair | null;
extraLinks?: ApolloLink[]; extraLinks?: ApolloLink[];
isDebugMode?: boolean; isDebugMode?: boolean;
tokenPair: AuthTokenPair | null;
} }
export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> { export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> {
@ -44,13 +44,13 @@ export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> {
onNetworkError, onNetworkError,
onTokenPairChange, onTokenPairChange,
onUnauthenticatedError, onUnauthenticatedError,
initialTokenPair,
extraLinks, extraLinks,
isDebugMode, isDebugMode,
tokenPair,
...options ...options
} = opts; } = opts;
this.tokenPair = tokenPair; this.tokenPair = initialTokenPair;
const buildApolloLink = (): ApolloLink => { const buildApolloLink = (): ApolloLink => {
const httpLink = createUploadLink({ const httpLink = createUploadLink({

View File

@ -15,14 +15,14 @@ type Size = 'medium' | 'small';
type Props = { type Props = {
icon?: React.ReactNode; icon?: React.ReactNode;
title: string; title?: string;
fullWidth?: boolean; fullWidth?: boolean;
variant?: Variant; variant?: Variant;
size?: Size; size?: Size;
} & React.ComponentProps<'button'>; } & React.ComponentProps<'button'>;
const StyledButton = styled.button< const StyledButton = styled.button<
Pick<Props, 'fullWidth' | 'variant' | 'size'> Pick<Props, 'fullWidth' | 'variant' | 'size' | 'title'>
>` >`
align-items: center; align-items: center;
background: ${({ theme, variant, disabled }) => { background: ${({ theme, variant, disabled }) => {
@ -33,8 +33,10 @@ const StyledButton = styled.button<
} else { } else {
return theme.color.blue; return theme.color.blue;
} }
default: case 'secondary':
return theme.background.primary; return theme.background.primary;
default:
return 'transparent';
} }
}}; }};
border: ${({ theme, variant }) => { border: ${({ theme, variant }) => {
@ -93,7 +95,13 @@ const StyledButton = styled.button<
gap: ${({ theme }) => theme.spacing(2)}; gap: ${({ theme }) => theme.spacing(2)};
height: ${({ size }) => (size === 'small' ? '24px' : '32px')}; height: ${({ size }) => (size === 'small' ? '24px' : '32px')};
justify-content: flex-start; justify-content: flex-start;
padding: ${({ theme }) => theme.spacing(2)} ${({ theme }) => theme.spacing(3)}; padding: ${({ theme, title }) => {
if (!title) {
return `${theme.spacing(1)}`;
}
return `${theme.spacing(2)} ${theme.spacing(3)}`;
}};
transition: background 0.1s ease; transition: background 0.1s ease;
@ -143,6 +151,7 @@ export function Button({
fullWidth={fullWidth} fullWidth={fullWidth}
variant={variant} variant={variant}
size={size} size={size}
title={title}
{...props} {...props}
> >
{icon} {icon}

View File

@ -6,5 +6,6 @@ export function getImageAbsoluteURIOrBase64(imageUrl?: string | null) {
if (imageUrl?.startsWith('data:')) { if (imageUrl?.startsWith('data:')) {
return imageUrl; return imageUrl;
} }
return `${process.env.REACT_APP_FILES_URL}/${imageUrl}`; return `${process.env.REACT_APP_FILES_URL}/${imageUrl}`;
} }

View File

@ -12,21 +12,15 @@ const StyledContainer = styled.div`
flex-direction: row; flex-direction: row;
margin-bottom: ${({ theme }) => theme.spacing(0)}; margin-bottom: ${({ theme }) => theme.spacing(0)};
margin-top: ${({ theme }) => theme.spacing(4)}; margin-top: ${({ theme }) => theme.spacing(4)};
padding: ${({ theme }) => theme.spacing(3)};
`; `;
const AvatarContainer = styled.div` const Content = styled.div`
margin: ${({ theme }) => theme.spacing(3)};
`;
const TextContainer = styled.div`
display: flex; display: flex;
flex: 1;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
`; margin-left: ${({ theme }) => theme.spacing(3)};
const NameAndEmailContainer = styled.div`
display: flex;
flex-direction: column;
`; `;
const NameText = styled.span` const NameText = styled.span`
@ -41,29 +35,26 @@ type OwnProps = {
workspaceMember: { workspaceMember: {
user: Pick<User, 'firstName' | 'lastName' | 'avatarUrl' | 'email'>; user: Pick<User, 'firstName' | 'lastName' | 'avatarUrl' | 'email'>;
}; };
accessory?: React.ReactNode;
}; };
export function WorkspaceMemberCard({ workspaceMember }: OwnProps) { export function WorkspaceMemberCard({ workspaceMember, accessory }: OwnProps) {
return ( return (
<StyledContainer> <StyledContainer>
<AvatarContainer> <Avatar
<Avatar avatarUrl={getImageAbsoluteURIOrBase64(workspaceMember.user.avatarUrl)}
avatarUrl={getImageAbsoluteURIOrBase64( placeholder={workspaceMember.user.firstName || ''}
workspaceMember.user.avatarUrl, type="squared"
)} size={40}
placeholder={workspaceMember.user.firstName || ''} />
type="squared" <Content>
size={40} <NameText>
/> {workspaceMember.user.firstName} {workspaceMember.user.lastName}{' '}
</AvatarContainer> </NameText>
<TextContainer> <EmailText>{workspaceMember.user.email}</EmailText>
<NameAndEmailContainer> </Content>
<NameText>
{workspaceMember.user.firstName} {workspaceMember.user.lastName}{' '} {accessory}
</NameText>
<EmailText>{workspaceMember.user.email}</EmailText>
</NameAndEmailContainer>
</TextContainer>
</StyledContainer> </StyledContainer>
); );
} }

View File

@ -1,18 +1,15 @@
import { gql } from '@apollo/client'; import { gql } from '@apollo/client';
export const GET_CURRENT_WORKSPACE = gql` export const GET_WORKSPACE_MEMBERS = gql`
query GetCurrentWorkspace { query GetWorkspaceMembers {
currentWorkspace { workspaceMembers: findManyWorkspaceMember {
id id
workspaceMember { user {
id id
user { email
id avatarUrl
email firstName
avatarUrl lastName
firstName
lastName
}
} }
} }
} }

View File

@ -24,3 +24,11 @@ export const REMOVE_WORKSPACE_LOGO = gql`
} }
} }
`; `;
export const REMOVE_WORKSPACE_MEMBER = gql`
mutation RemoveWorkspaceMember($where: WorkspaceMemberWhereUniqueInput!) {
deleteWorkspaceMember(where: $where) {
id
}
}
`;

View File

@ -1,10 +1,17 @@
import styled from '@emotion/styled'; import styled from '@emotion/styled';
import { useRecoilState } from 'recoil';
import { currentUserState } from '@/auth/states/currentUserState';
import { Button } from '@/ui/components/buttons/Button';
import { MainSectionTitle } from '@/ui/components/section-titles/MainSectionTitle'; import { MainSectionTitle } from '@/ui/components/section-titles/MainSectionTitle';
import { SubSectionTitle } from '@/ui/components/section-titles/SubSectionTitle'; import { SubSectionTitle } from '@/ui/components/section-titles/SubSectionTitle';
import { IconTrash } from '@/ui/icons';
import { NoTopBarContainer } from '@/ui/layout/containers/NoTopBarContainer'; import { NoTopBarContainer } from '@/ui/layout/containers/NoTopBarContainer';
import { WorkspaceMemberCard } from '@/workspace/components/WorkspaceMemberCard'; import { WorkspaceMemberCard } from '@/workspace/components/WorkspaceMemberCard';
import { useGetCurrentWorkspaceQuery } from '~/generated/graphql'; import {
useGetWorkspaceMembersQuery,
useRemoveWorkspaceMemberMutation,
} from '~/generated/graphql';
const StyledContainer = styled.div` const StyledContainer = styled.div`
display: flex; display: flex;
@ -16,8 +23,52 @@ const StyledContainer = styled.div`
} }
`; `;
const ButtonContainer = styled.div`
align-items: center;
display: flex;
flex-direction: row;
margin-left: ${({ theme }) => theme.spacing(3)};
`;
export function SettingsWorkspaceMembers() { export function SettingsWorkspaceMembers() {
const { data } = useGetCurrentWorkspaceQuery(); const [currentUser] = useRecoilState(currentUserState);
const { data } = useGetWorkspaceMembersQuery();
const [removeWorkspaceMember] = useRemoveWorkspaceMemberMutation();
const handleRemoveWorkspaceMember = async (userId: string) => {
await removeWorkspaceMember({
variables: {
where: {
userId,
},
},
optimisticResponse: {
__typename: 'Mutation',
deleteWorkspaceMember: {
__typename: 'WorkspaceMember',
id: userId,
},
},
update: (cache, { data: responseData }) => {
if (!responseData) {
return;
}
const normalizedId = cache.identify({
id: responseData.deleteWorkspaceMember.id,
__typename: 'WorkspaceMember',
});
// Evict object from cache
cache.evict({ id: normalizedId });
// Clean up relation to this object
cache.gc();
},
});
};
return ( return (
<NoTopBarContainer> <NoTopBarContainer>
@ -27,10 +78,22 @@ export function SettingsWorkspaceMembers() {
title="Members" title="Members"
description="Manage the members of your space here" description="Manage the members of your space here"
/> />
{data?.currentWorkspace?.workspaceMember?.map((member) => ( {data?.workspaceMembers?.map((member) => (
<WorkspaceMemberCard <WorkspaceMemberCard
key={member.user.id} key={member.user.id}
workspaceMember={{ user: member.user }} workspaceMember={{ user: member.user }}
accessory={
currentUser?.id !== member.user.id && (
<ButtonContainer>
<Button
onClick={() => handleRemoveWorkspaceMember(member.user.id)}
variant="tertiary"
size="small"
icon={<IconTrash size={16} />}
/>
</ButtonContainer>
)
}
/> />
))} ))}
</StyledContainer> </StyledContainer>

View File

@ -58,7 +58,9 @@ export class AbilityFactory {
can(AbilityAction.Update, 'Workspace', { id: workspace.id }); can(AbilityAction.Update, 'Workspace', { id: workspace.id });
// Workspace Member // Workspace Member
can(AbilityAction.Read, 'WorkspaceMember', { userId: user.id }); can(AbilityAction.Read, 'WorkspaceMember', { workspaceId: workspace.id });
can(AbilityAction.Delete, 'WorkspaceMember', { workspaceId: workspace.id });
cannot(AbilityAction.Delete, 'WorkspaceMember', { userId: user.id });
// Company // Company
can(AbilityAction.Read, 'Company', { workspaceId: workspace.id }); can(AbilityAction.Read, 'Company', { workspaceId: workspace.id });

View File

@ -1,12 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from '@nestjs/testing';
import { WorkspaceMemberResolver } from './workspace-member.resolver'; import { WorkspaceMemberResolver } from './workspace-member.resolver';
import { WorkspaceMemberService } from '../services/workspace-member.service';
import { AbilityFactory } from 'src/ability/ability.factory';
describe('WorkspaceMemberResolver', () => { describe('WorkspaceMemberResolver', () => {
let resolver: WorkspaceMemberResolver; let resolver: WorkspaceMemberResolver;
beforeEach(async () => { beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({ const module: TestingModule = await Test.createTestingModule({
providers: [WorkspaceMemberResolver], providers: [
WorkspaceMemberResolver,
{
provide: WorkspaceMemberService,
useValue: {},
},
{
provide: AbilityFactory,
useValue: {},
},
],
}).compile(); }).compile();
resolver = module.get<WorkspaceMemberResolver>(WorkspaceMemberResolver); resolver = module.get<WorkspaceMemberResolver>(WorkspaceMemberResolver);

View File

@ -1,5 +1,62 @@
import { Resolver } from '@nestjs/graphql'; import { Args, Query, Resolver, Mutation } from '@nestjs/graphql';
import { WorkspaceMember } from '../../@generated/workspace-member/workspace-member.model'; import { WorkspaceMember } from '../../@generated/workspace-member/workspace-member.model';
import { UseGuards } from '@nestjs/common';
import { AbilityGuard } from 'src/guards/ability.guard';
import { CheckAbilities } from 'src/decorators/check-abilities.decorator';
import {
DeleteWorkspaceMemberAbilityHandler,
ReadWorkspaceMemberAbilityHandler,
} from 'src/ability/handlers/workspace-member.ability-handler';
import { FindManyWorkspaceMemberArgs } from 'src/core/@generated/workspace-member/find-many-workspace-member.args';
import { UserAbility } from 'src/decorators/user-ability.decorator';
import { AppAbility } from 'src/ability/ability.factory';
import {
PrismaSelect,
PrismaSelector,
} from 'src/decorators/prisma-select.decorator';
import { WorkspaceMemberService } from '../services/workspace-member.service';
import { accessibleBy } from '@casl/prisma';
import { DeleteOneWorkspaceMemberArgs } from 'src/core/@generated/workspace-member/delete-one-workspace-member.args';
import { JwtAuthGuard } from 'src/guards/jwt.auth.guard';
@UseGuards(JwtAuthGuard)
@Resolver(() => WorkspaceMember) @Resolver(() => WorkspaceMember)
export class WorkspaceMemberResolver {} export class WorkspaceMemberResolver {
constructor(
private readonly workspaceMemberService: WorkspaceMemberService,
) {}
@Query(() => [WorkspaceMember])
@UseGuards(AbilityGuard)
@CheckAbilities(ReadWorkspaceMemberAbilityHandler)
async findManyWorkspaceMember(
@Args() args: FindManyWorkspaceMemberArgs,
@UserAbility() ability: AppAbility,
@PrismaSelector({ modelName: 'WorkspaceMember' })
prismaSelect: PrismaSelect<'WorkspaceMember'>,
): Promise<Partial<WorkspaceMember>[]> {
return this.workspaceMemberService.findMany({
...args,
where: args.where
? {
AND: [args.where, accessibleBy(ability).WorkspaceMember],
}
: accessibleBy(ability).WorkspaceMember,
select: prismaSelect.value,
});
}
@Mutation(() => WorkspaceMember)
@UseGuards(AbilityGuard)
@CheckAbilities(DeleteWorkspaceMemberAbilityHandler)
async deleteWorkspaceMember(
@Args() args: DeleteOneWorkspaceMemberArgs,
@PrismaSelector({ modelName: 'WorkspaceMember' })
prismaSelect: PrismaSelect<'WorkspaceMember'>,
): Promise<Partial<WorkspaceMember>> {
return this.workspaceMemberService.delete({
where: args.where,
select: prismaSelect.value,
});
}
}

View File

@ -50,8 +50,8 @@ export class WorkspaceResolver {
@Query(() => Workspace) @Query(() => Workspace)
async currentWorkspace( async currentWorkspace(
@AuthWorkspace() workspace: Workspace, @AuthWorkspace() workspace: Workspace,
@PrismaSelector({ modelName: 'User' }) @PrismaSelector({ modelName: 'Workspace' })
prismaSelect: PrismaSelect<'User'>, prismaSelect: PrismaSelect<'Workspace'>,
) { ) {
const selectedWorkspace = await this.workspaceService.findUnique({ const selectedWorkspace = await this.workspaceService.findUnique({
where: { where: {

View File

@ -1,12 +0,0 @@
import { CanActivate, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/database/prisma.service';
@Injectable()
export class ShowOneGuard implements CanActivate {
constructor(private prismaService: PrismaService) {}
async canActivate(): Promise<boolean> {
// TODO
return true;
}
}